text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.web.server.impl;

import java.io.File;
import java.util.HashMap;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import org.modeshape.common.logging.Logger;
import org.modeshape.jcr.JcrRepository;
import org.modeshape.jcr.api.RepositoryManager;
import org.modeshape.web.client.RemoteException;
import org.modeshape.web.server.LRepository;

/**
 *
 * @author kulikov
 */
public class LRepositoryImpl implements LRepository {
    private Credentials creds;
    private JcrRepository repository;
    private HashMap<String, Session> sessions = new HashMap<>();
    private String[] workspaces;
    private final static Logger logger = Logger.getLogger(LRepositoryImpl.class);

    public LRepositoryImpl(JcrRepository repository, Credentials creds) throws RepositoryException {
        this.creds = creds;
        assert repository != null;
        this.repository = repository;
        logger.debug("Logging to repository " + repository + " as " + creds);
        Session session = creds != null ?
                repository.login(creds) : repository.login();
        sessions.put(session.getWorkspace().getName(), session);
        workspaces = session.getWorkspace().getAccessibleWorkspaceNames();
        logger.debug("[" + this.repository.getName() + "] available workspaces " + wsnames());
    }

    @Override
    public String name() {
        return repository.getName();
    }

    @Override
    public String[] getWorkspaces() {
        logger.debug("[" + this.repository.getName() + "] Requested workspaces " + wsnames());
        return workspaces;
    }

    private String wsnames() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        for (int i = 0; i < workspaces.length - 1; i++) {
            builder.append(workspaces[i]);
            builder.append(",");
        }
        builder.append(workspaces[workspaces.length - 1]);
        builder.append("}");
        return builder.toString();
    }

    @Override
    public Session session(String workspace) throws RemoteException {
        if (sessions.containsKey(workspace)) {
            logger.debug("[" + this.repository.getName() + "] has already session to " + workspace);
            return sessions.get(workspace);
        }

        try {
            logger.debug("[" + this.repository.getName() + "] has not yet session to " + workspace);
            Session session = creds != null ?
                    repository.login(creds, workspace) :
                    repository.login(workspace);
            sessions.put(workspace, session);
            return session;
        } catch (RepositoryException e) {
            throw new RemoteException(e.getMessage());
        }
    }

    @Override
    public Repository repository() {
        return repository;
    }

    @Override
    public void backup(String workspace, String name) throws RemoteException {
        try {
/*            Properties conf = new Properties();
            InputStream in = getClass().getResourceAsStream("/config/connector.properties");
            if (in == null) {
                System.out.println("------- Input is null");
            }
            conf.load(in);
            */
            File backupDir = new File(name);
            RepositoryManager mgr = ((org.modeshape.jcr.api.Session)session(workspace)).getWorkspace().getRepositoryManager();
            mgr.backupRepository(backupDir);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RemoteException(e.getMessage());
        }
    }

    @Override
    public void restore(String workspace, String name) throws RemoteException {
        try {
            File backupDir = new File(name);
            RepositoryManager mgr = ((org.modeshape.jcr.api.Session)session(workspace)).getWorkspace().getRepositoryManager();
            mgr.restoreRepository(backupDir);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RemoteException(e.getMessage());
        }
    }

    public void importXML(String workspace) throws RemoteException {
        try {
            Workspace ws = ((org.modeshape.jcr.api.Session)session(workspace)).getWorkspace();
            ws.importXML(workspace, null, 0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RemoteException(e.getMessage());
        }
    }

}


text:
@implementation IKCell
@synthesize imageView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
}

@end

redpajama_set_name: RedPajamaGithub


text:
(function() {
	/**
	 * Error notification to show any unexpected error that
	 * has occurred.
	 */
	MiniRox.TestNotificationView = MiniRox.NotificationView.extend({
		// Additional class
		additionalClassName: 'alert-info',

		events: {
			'click .test-notification': 'showTestDetails'
		},

		ui: {
			key: 'code'
		},

		/**
		 * Build the notification title
		 *
		 * @param data The data to fill the template
		 * @returns {string} The template ready to render
		 */
		title: function(data) {
			var title = ' Test ' + data.k + ' {statusText}';

			title = title.replace('{statusText}', data.p ? 'passed' : 'failed').replace('{icon}', data.p ? 'icon-thumbs-up' : 'icon-thumbs-down');
			if (data.f == 1) {
				title = title.replace('{testNotificationClass}', 'test-notification-inactive');
			}
			else {
				title = title.replace('{testNotificationClass}', data.p ? 'test-notification-passed' : 'test-notification-failed');
			}
			return '
' + title + '
';
		},

		/**
		 * Build the notification content
		 *
		 * @param {Object} data The data to fill the template
		 * @returns {string} The template ready to render
		 */
		contentTemplate: function(data) {
			return '
' + data.n + '
';
		},

		/**
		 * Handle the event to add the test details to the details list
		 *
		 * @param {Event} event The click event
		 */
		showTestDetails: function(event) {
			event.preventDefault();
			event.stopPropagation();

			// Differentiate the action to add a key filter or to show the test details
			if (event.altKey) {
				this.trigger('filter', 'key:' + this.ui.key.text());
			}
			else {
				this.trigger('show:details', this.ui.key.text());
			}
		}
	});
}).call(this);


text:
class Product < ActiveRecord::Base
  belongs_to :discount

  validates :price, numericality: { greater_than: 0 }
end


text:
function init() {
    tinyMCEPopup.resizeToInnerSize();
    var inst = tinyMCEPopup.editor;
    var dom = inst.dom;
    var elm = inst.selection.getNode();
    var f = document.forms[0];
    var onclick = dom.getAttrib(elm, 'onclick');

    setFormValue('title', dom.getAttrib(elm, 'title'));
    setFormValue('id', dom.getAttrib(elm, 'id'));
    setFormValue('style', dom.getAttrib(elm, "style"));
    setFormValue('dir', dom.getAttrib(elm, 'dir'));
    setFormValue('lang', dom.getAttrib(elm, 'lang'));
    setFormValue('tabindex', dom.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : ""));
    setFormValue('accesskey', dom.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : ""));
    setFormValue('onfocus', dom.getAttrib(elm, 'onfocus'));
    setFormValue('onblur', dom.getAttrib(elm, 'onblur'));
    setFormValue('onclick', onclick);
    setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick'));
    setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown'));
    setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup'));
    setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover'));
    setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove'));
    setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout'));
    setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress'));
    setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown'));
    setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup'));
    className = dom.getAttrib(elm, 'class');

    addClassesToList('classlist', 'advlink_styles');
    selectByValue(f, 'classlist', className, true);

    TinyMCE_EditableSelects.init();
}

function setFormValue(name, value) {
    if(value && document.forms[0].elements[name]){
        document.forms[0].elements[name].value = value;
    }
}

function insertAction() {
    var inst = tinyMCEPopup.editor;
    var elm = inst.selection.getNode();

    setAllAttribs(elm);
    tinyMCEPopup.execCommand("mceEndUndoLevel");
    tinyMCEPopup.close();
}

function setAttrib(elm, attrib, value) {
    var formObj = document.forms[0];
    var valueElm = formObj.elements[attrib.toLowerCase()];
    var inst = tinyMCEPopup.editor;
    var dom = inst.dom;

    if (typeof(value) == "undefined" || value == null) {
        value = "";

        if (valueElm)
            value = valueElm.value;
    }

    dom.setAttrib(elm, attrib.toLowerCase(), value);
}

function setAllAttribs(elm) {
    var f = document.forms[0];

    setAttrib(elm, 'title');
    setAttrib(elm, 'id');
    setAttrib(elm, 'style');
    setAttrib(elm, 'class', getSelectValue(f, 'classlist'));
    setAttrib(elm, 'dir');
    setAttrib(elm, 'lang');
    setAttrib(elm, 'tabindex');
    setAttrib(elm, 'accesskey');
    setAttrib(elm, 'onfocus');
    setAttrib(elm, 'onblur');
    setAttrib(elm, 'onclick');
    setAttrib(elm, 'ondblclick');
    setAttrib(elm, 'onmousedown');
    setAttrib(elm, 'onmouseup');
    setAttrib(elm, 'onmouseover');
    setAttrib(elm, 'onmousemove');
    setAttrib(elm, 'onmouseout');
    setAttrib(elm, 'onkeypress');
    setAttrib(elm, 'onkeydown');
    setAttrib(elm, 'onkeyup');

    // Refresh in old MSIE
//    if (tinyMCE.isMSIE5)
//        elm.outerHTML = elm.outerHTML;
}

function insertAttribute() {
    tinyMCEPopup.close();
}

tinyMCEPopup.onInit.add(init);
tinyMCEPopup.requireLangPack();


text:
<?php

namespace backend\tests\functional;

use backend\tests\FunctionalTester;
use common\fixtures\User as UserFixture;
use Yii;

/**
 * Class LoginCest
 */
class LoginCest
{
	public function _before(FunctionalTester $I)
	{
		$I->haveFixtures([
			'user' => [
				'class'    => UserFixture::className(),
				'dataFile' => codecept_data_dir() . 'login_data.php',
			],
		]);
	}

	/**
	 * @param FunctionalTester $I
	 */
	public function loginUser(FunctionalTester $I)
	{
		$I->amOnPage('/user/login');
		$I->fillField(Yii::t('user', 'Username'), 'admin');
		$I->fillField(Yii::t('user', 'Password'), 'password_0');
		$I->click('login-button');

		$I->see(Yii::t('user', 'Logout ({username})', ['username' => 'admin']), 'form button[type = submit]');
		$I->dontSeeLink(Yii::t('user', 'Login'));
		$I->dontSeeLink(Yii::t('user', 'Signup'));
	}
}


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_OXCFXICS.S06_SyncICSContentsDeletion_TestSuite.MSOXCFXICS_S06_SyncICSContentsDeletion_TestSuite3 /testcontainer:..\..\MS-OXCFXICS\TestSuite\bin\Debug\MS-OXCFXICS_TestSuite.dll /runconfig:..\..\MS-OXCFXICS\MS-OXCFXICS.testsettings /unique
pause


text:
package com.contained.game.handler;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;

import com.contained.game.Contained;
import com.contained.game.ContainedRegistry;
import com.contained.game.Settings;
import com.contained.game.data.Data;
import com.contained.game.data.DataItemStack;
import com.contained.game.data.DataLogger;
import com.contained.game.data.Data.OccupationRank;
import com.contained.game.entity.ExtendedPlayer;
import com.contained.game.item.BlockInteractItem;
import com.contained.game.item.DowsingRod;
import com.contained.game.item.ItemTerritory;
import com.contained.game.item.SurveyClipboard;
import com.contained.game.network.ClientPacketHandlerUtil;
import com.contained.game.ui.survey.SurveyData;
import com.contained.game.user.PlayerMiniGame;
import com.contained.game.user.PlayerTeam;
import com.contained.game.user.PlayerTeamIndividual;
import com.contained.game.user.PlayerTeamInvitation;
import com.contained.game.util.MiniGameUtil;
import com.contained.game.util.Resources;
import com.contained.game.util.Util;
import com.contained.game.world.GameTeleporter;
import com.contained.game.world.block.AntiTerritoryMachine;
import com.contained.game.world.block.TerritoryMachine;
import com.contained.game.world.block.TerritoryMachineTE;

import codechicken.lib.packet.PacketCustom;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import cpw.mods.fml.relauncher.ReflectionHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemMonsterPlacer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent;
import net.minecraftforge.event.entity.player.PlayerUseItemEvent;
import net.minecraftforge.event.entity.player.PlayerEvent.Clone;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;

public class PlayerEvents {

	@SubscribeEvent
	//When a player joins the server, send their client the territory & team data.
	public void onJoin(EntityJoinWorldEvent event) {
		if (event.entity instanceof EntityPlayer && !event.world.isRemote) {
			EntityPlayer joined = (EntityPlayer)event.entity;
			boolean completedSurvey = false;

			if (PlayerTeamIndividual.get(joined) == null) {
				// Server has no info about this player, this must be their first
				// time joining. Initialize their custom data.
				Contained.teamMemberData.add(new PlayerTeamIndividual(joined.getDisplayName()));
				Contained.channel.sendToAll(ClientPacketHandlerUtil.packetNewPlayer(joined.getDisplayName()).toPacket());
			}
			else {
				PlayerTeamIndividual pdata = PlayerTeamIndividual.get(joined);

				//If player has not completed the survey, give them a reminder.
				if (pdata.surveyResponses.progress <= SurveyData.getSurveyLength())
					Util.displayMessage(joined, "§a§l(Reminder: Please take a moment to fill out §a§lyour §a§lsurvey)");
				else
					completedSurvey = true;

				//If the player has pending invitations, let them know.
				if (PlayerTeamInvitation.getInvitations(pdata).size() > 0)
					Util.displayMessage(joined, "§d§lYou have pending inviations in your guild §d§lmenu!");

				// If the player got accepted into a team since last time they
				// were online, let them know.
				if (pdata.teamID != null && pdata.joinTime > pdata.lastOnline) {
					PlayerTeam newTeam = PlayerTeam.get(pdata.teamID, joined.dimension);
					if (newTeam != null)
						Util.displayMessage(joined, "§d§lYou are now a member of "+newTeam.getFormatCode()+"§l"+newTeam.displayName+"§d§l!");
					pdata.lastOnline = System.currentTimeMillis();
				}
			}

			//If player does not have a survey in their inventory, give them one.
			if (!completedSurvey && !joined.inventory.hasItem(SurveyClipboard.instance)
					&& joined.inventory.getFirstEmptyStack() > -1){
				joined.inventory.addItemStackToInventory(new ItemStack(SurveyClipboard.instance, 1));
				PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM);
				itemPacket.writeItemStack(new ItemStack(SurveyClipboard.instance, 1));
				Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined);
			}

			//If dowsing is enabled, give the player a dowsing rod.
			if (Contained.configs.enableDowsing[Settings.getDimConfig(joined.dimension)]
					&& !joined.inventory.hasItem(DowsingRod.instance)
					&& joined.inventory.getFirstEmptyStack() > -1) {
				joined.inventory.addItemStackToInventory(new ItemStack(DowsingRod.instance, 1));
				PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM);
				itemPacket.writeItemStack(new ItemStack(DowsingRod.instance, 1));
				Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined);
			}

			//Tutorial book
			if (!joined.inventory.hasItem(ContainedRegistry.book)
					&& joined.inventory.getFirstEmptyStack() > -1){
				joined.inventory.addItemStackToInventory(new ItemStack(ContainedRegistry.book, 1));
				PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM);
				itemPacket.writeItemStack(new ItemStack(ContainedRegistry.book, 1));
				Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined);
			}

			//Update PlayerMiniGame When Joining Server
			if(!ExtendedPlayer.get(joined).isAdmin()
					&& (MiniGameUtil.isPvP(joined.dimension) || MiniGameUtil.isTreasure(joined.dimension))){
				PlayerMiniGame miniGame = PlayerMiniGame.get(joined.dimension);
				if(miniGame != null && ExtendedPlayer.get(joined).gameID == miniGame.getGameID()){
					PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_STARTED);
					miniGamePacket.writeInt(miniGame.getGameMode());
					miniGamePacket.writeInt(miniGame.getGameID());

					NBTTagCompound miniGameTag = new NBTTagCompound();
					miniGame.writeToNBT(miniGameTag);
					miniGamePacket.writeNBTTagCompound(miniGameTag);

					miniGamePacket.writeInt(miniGame.getGameDimension());
					miniGamePacket.writeInt(Contained.getTeamList(miniGame.getGameDimension()).size());
					for(PlayerTeam team : Contained.getTeamList(miniGame.getGameDimension())){
						NBTTagCompound teamTag = new NBTTagCompound();
						team.writeToNBT(teamTag);
						miniGamePacket.writeNBTTagCompound(teamTag);
					}

					Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) joined);
				} else {
					//If MiniGame Does Not Exist, Send Back To Lobby
					//Do not reward player and do not update stats
					int dim = joined.dimension;

					Util.travelToDimension(Resources.OVERWORLD, joined, true);

					PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED);
					miniGamePacket.writeInt(dim);
					Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) joined);
				}
			}

			// Players should get a short period of invincibility upon respawning
			// to prevent spawn camping
			joined.addPotionEffect(new PotionEffect(Potion.resistance.id, 20*15, 5));

			if (joined instanceof EntityPlayerMP) {
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTeams(Contained.getTeamList(joined.dimension)).toPacket(), (EntityPlayerMP) joined);
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTerritories(Contained.getTerritoryMap(joined.dimension)).toPacket(), (EntityPlayerMP) joined);
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncLocalPlayer((EntityPlayer)joined).toPacket(), (EntityPlayerMP)joined);
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetPlayerList(Contained.teamMemberData).toPacket(), (EntityPlayerMP)joined);
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncRelevantInvites(joined).toPacket(), (EntityPlayerMP)joined);
				Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTrades(Contained.getTradeList(joined.dimension)).toPacket(), (EntityPlayerMP) joined);
				ClientPacketHandlerUtil.syncPlayerStats(ExtendedPlayer.get(joined), (EntityPlayerMP) joined);

				if (MiniGameUtil.isTreasure(joined.dimension))
					Contained.channel.sendTo(ClientPacketHandlerUtil.packetAddTreasures(Contained.getActiveTreasures(joined.dimension), true).toPacket(), (EntityPlayerMP)joined);

				//Class Perks
				ArrayList<Integer> perks = ExtendedPlayer.get(joined).perks;
				PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PERK_INFO);
				for(int i = 0; i < 5; i++){
					if(i < perks.size())
						perkPacket.writeInt(perks.get(i));
					else
						perkPacket.writeInt(-1);
				}
				perkPacket.writeInt(ExtendedPlayer.get(joined).occupationClass);
				perkPacket.writeInt(ExtendedPlayer.get(joined).occupationLevel);
				Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) joined);
			}
		}
	}

	@SubscribeEvent
	public void onLeave(PlayerEvent.PlayerLoggedOutEvent event) {
		PlayerTeamIndividual pdata = PlayerTeamIndividual.get(event.player);
		pdata.lastOnline = System.currentTimeMillis();
	}

	@SubscribeEvent
	public void onRespawn(Clone event) {
		if(event.entityPlayer != null) {
			ExtendedPlayer newClone = ExtendedPlayer.get(event.entityPlayer);
			ExtendedPlayer oldPlayer = ExtendedPlayer.get(event.original);
			NBTTagCompound ntc = new NBTTagCompound();
			oldPlayer.saveNBTData(ntc);
			newClone.loadNBTData(ntc);

			int dim = event.entityPlayer.dimension;
			if (MiniGameUtil.isPvP(dim) && event.wasDeath) {
				ExtendedPlayer properties = ExtendedPlayer.get(event.entityPlayer);
				PacketCustom syncLifePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_LIVES);
				syncLifePacket.writeInt(properties.lives);
				Contained.channel.sendTo(syncLifePacket.toPacket(), (EntityPlayerMP) event.entityPlayer);

				if(properties.lives == 0){
					PacketCustom spectatorPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_SPECTATOR);
					Contained.channel.sendTo(spectatorPacket.toPacket(), (EntityPlayerMP) event.entityPlayer);
				}
			}

			if((MiniGameUtil.isPvP(dim) ||
					MiniGameUtil.isTreasure(dim)) && event.wasDeath){
				boolean endGame = false;
				if(PlayerMiniGame.get(dim) == null)
					endGame = true;
				else if(PlayerMiniGame.get(dim).getGameID() != oldPlayer.gameID)
					endGame = true;

				if(endGame) {
					PlayerTeamIndividual pdata = PlayerTeamIndividual.get(event.entityPlayer.getDisplayName());
					ExtendedPlayer properties = ExtendedPlayer.get(event.entityPlayer);

					int playerScore = 0;
					int winScore = DataLogger.findGameWinScore(properties.gameID, pdata.teamID);
					String winCondition = DataLogger.findGameWinCondition(properties.gameID);
					String teamID = DataLogger.findGameWinTeamID(properties.gameID);
					if(MiniGameUtil.isPvP(dim) && pdata.teamID != null){
						playerScore = properties.curKills - properties.curDeaths + properties.curAntiTerritory;
						DataLogger.insertPVPScore(Util.getServerID(), properties.gameID, event.entityPlayer.getDisplayName(),
								pdata.teamID, properties.curKills, properties.curDeaths,
								properties.curAntiTerritory, Util.getDate());
						if(!winCondition.equals("TIE")){
							if(pdata.teamID.equalsIgnoreCase(teamID))
								properties.pvpWon++;
							else if (!teamID.equals("Debug") && !teamID.equals("Kicked"))
								properties.pvpLost++;
						}

						properties.kills+=properties.curKills;
						properties.deaths+=properties.curDeaths;
						properties.antiTerritory+=properties.curAntiTerritory;
					}else if(MiniGameUtil.isTreasure(dim) && pdata.teamID != null){
						playerScore = properties.curTreasuresOpened + properties.curAltersActivated;
						DataLogger.insertTreasureScore(Util.getServerID(),
								properties.gameID, event.entityPlayer.getDisplayName(), pdata.teamID,
								properties.curTreasuresOpened, properties.curAltersActivated, Util.getDate());
						if(!winCondition.equals("TIE")){
							if(pdata.teamID.equalsIgnoreCase(teamID))
								properties.treasureWon++;
							else if (!teamID.equals("Debug") && !teamID.equals("Kicked"))
								properties.treasureLost++;
						}

						properties.treasuresOpened+=properties.curTreasuresOpened;
						properties.altersActivated+=properties.curAltersActivated;
					}

					//Reward XP Points To Player
					String teamMiniGame = pdata.teamID;
					if(teamID != null && winCondition != null){
						boolean emptySlot = false;
						int index = -1;
						for(int i = 0; i < pdata.inventory.length; i++){
							ItemStack item = pdata.inventory[i];
							if(item == null){
								emptySlot = true;
								index = i;
								break;
							}
						}

						if(!emptySlot)
							PlayerMiniGame.rewardXP(event.entityPlayer, pdata, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, pdata.teamID.equals(teamID));
					}

					Util.travelToDimension(Resources.OVERWORLD, event.entityPlayer, true);

					//Reward Item To Player
					if(teamID != null && teamMiniGame != null && winCondition != null){
						if(event.entityPlayer.inventory.getFirstEmptyStack() > -1)
							PlayerMiniGame.rewardItem(event.entityPlayer, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, pdata.teamID.equals(teamID));
					}

					if(MiniGameUtil.isPvP(dim)){
						PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS);
						syncScore.writeInt(properties.pvpWon);
						syncScore.writeInt(properties.pvpLost);
						syncScore.writeInt(properties.kills);
						syncScore.writeInt(properties.deaths);
						syncScore.writeInt(properties.antiTerritory);
						Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) event.entityPlayer);
					}else if(MiniGameUtil.isTreasure(dim)){
						PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS);
						syncScore.writeInt(properties.treasureWon);
						syncScore.writeInt(properties.treasureLost);
						syncScore.writeInt(properties.treasuresOpened);
						syncScore.writeInt(properties.altersActivated);
						Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) event.entityPlayer);
					}

					PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED);
					miniGamePacket.writeInt(dim);
					Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP)event.entityPlayer);
				}else{
					ExtendedPlayer properties = ExtendedPlayer.get(event.entityPlayer);
					event.entityPlayer.setPositionAndUpdate(properties.spawnMiniGameX, properties.spawnMiniGameZ, properties.spawnMiniGameY);
				}
			}
		}
	}

	@SubscribeEvent
	public void onEntityLiving(LivingUpdateEvent event) {
		if (event.entity != null && event.entity instanceof EntityPlayer
				&& !event.entity.worldObj.isRemote) {
			EntityPlayer player = (EntityPlayer)event.entity;
			ExtendedPlayer properties = ExtendedPlayer.get(player);

			// Handle nether portal override
			boolean wasInPortal = ReflectionHelper.getPrivateValue(Entity.class, player, "inPortal", "field_71087_bX");
			if (wasInPortal) {
				ReflectionHelper.setPrivateValue(Entity.class, player, false, "inPortal", "field_71087_bX");

				for(int i=-3; i<=3; i+=1) {
					for(int j=-3; j<=3; j+=1) {
						for(int k=-3; k<=3; k+=1) {
							if (player.worldObj.getBlock((int)player.posX+i, (int)player.posY+k, (int)player.posZ+j).equals(Blocks.portal))
								player.worldObj.setBlock((int)player.posX+i, (int)player.posY+k, (int)player.posZ+j, Blocks.air);
						}
					}
				}
				player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, 1, false);
				player.worldObj.spawnEntityInWorld(new EntityLightningBolt(player.worldObj, player.posX, player.posY+1, player.posZ));
				EntityLiving mobSpawn = (EntityLiving)EntityList.createEntityByName(Util.choose("PigZombie", "PigZombie", "Blaze", "LavaSlime"), player.worldObj);
				mobSpawn.setLocationAndAngles(player.posX, player.posY, player.posZ, MathHelper.wrapAngleTo180_float(player.worldObj.rand.nextFloat() * 360.0F), 0f);
				player.worldObj.spawnEntityInWorld(mobSpawn);

				if (Math.random() < 0.5) {
					player.worldObj.spawnEntityInWorld(new EntityItem(player.worldObj, player.posX, player.posY+1, player.posZ,
							Util.choose(new ItemStack(Items.quartz, 8)
									,new ItemStack(Blocks.obsidian, 2)
									,new ItemStack(Items.nether_wart, 4)
									,new ItemStack(Items.netherbrick, 32)
									,new ItemStack(Blocks.netherrack, 16)
									,new ItemStack(Blocks.soul_sand, 8))));
				}

				mobSpawn.playLivingSound();
			}

			// Update Admin Rights When Logging Back In Or Changing Dimensions
			if(properties.isAdmin()){
				if(!player.isInvisible() ||
						!player.capabilities.allowFlying ||
						!player.capabilities.disableDamage){
					player.setInvisible(true);
					player.capabilities.allowFlying = true;
					player.capabilities.disableDamage = true;

					PacketCustom adminPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_ADMIN);
					Contained.channel.sendTo(adminPacket.toPacket(), (EntityPlayerMP)player);
				}
			}

			//Check If Player Is In A Valid MiniGame Dimension
			if(!properties.isAdmin()
					&& (MiniGameUtil.isPvP(player.dimension) || MiniGameUtil.isTreasure(player.dimension))){
				int dim = player.dimension;
				PlayerMiniGame miniGame = PlayerMiniGame.get(player.dimension);

				if(miniGame == null
						|| (miniGame != null && miniGame.getGameID() != properties.gameID)){
					PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player.getDisplayName());
					Util.displayMessage(player, "The MiniGame You Were In Has Ended, We Are Sending You Back To Where You Belong!");
					Util.travelToDimension(Resources.OVERWORLD, player, true);

					PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED);
					miniGamePacket.writeInt(dim);
					Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) player);

					//Update Player Stats
					if(MiniGameUtil.isPvP(dim)){
						PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS);
						syncScore.writeInt(properties.pvpWon);
						syncScore.writeInt(properties.pvpLost);
						syncScore.writeInt(properties.kills);
						syncScore.writeInt(properties.deaths);
						Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
					}else if(MiniGameUtil.isTreasure(dim)){
						PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS);
						syncScore.writeInt(properties.treasureWon);
						syncScore.writeInt(properties.treasureLost);
						syncScore.writeInt(properties.treasuresOpened);
						Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
					}
				}
			}

			//Intermittently sync data logging information with the client
			//so the visualizations can be updated.
			if (player != null && Math.random() <= 1.0/20.0) {
				int[] occupationData = ExtendedPlayer.get(player).getOccupationValues();

				if (player instanceof EntityPlayerMP) {
					PacketCustom occPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.OCCUPATIONAL_DATA);
					for(int i=0; i<occupationData.length; i++)
						occPacket.writeInt(occupationData[i]);
					Contained.channel.sendTo(occPacket.toPacket(), (EntityPlayerMP)player);

					PacketCustom usePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ITEM_USAGE_DATA);
					usePacket.writeInt(ExtendedPlayer.get(player).usedOwnItems);
					usePacket.writeInt(ExtendedPlayer.get(player).usedOthersItems);
					usePacket.writeInt(ExtendedPlayer.get(player).usedByOthers);
					Contained.channel.sendTo(usePacket.toPacket(), (EntityPlayerMP)player);

					PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
					if(pdata.surveyResponses.progress < SurveyData.getSurveyLength() && Resources.MANDATORY_SURVEY){
						if(!player.isInvisible() || !player.capabilities.disableDamage){
							player.setInvisible(true);
							player.capabilities.disableDamage = true;
						}

						PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.START_SURVEY);
						Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) player);
					} else if(!ExtendedPlayer.get(player).isAdmin()
							&& (player.isInvisible() || player.capabilities.disableDamage)){
						player.setInvisible(false);
						player.capabilities.disableDamage = false;

						PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_NORMAL);
						Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) player);
					}
				}
			}

			//Update items in a player's inventory which
			//have no owner to be owned by them
			if (player != null) {
				ItemStack[] inventory = player.inventory.mainInventory;
				for(int i=0; i<inventory.length; i++)
					if (inventory[i] != null) {
						if (processNewOwnership(player, inventory[i], false)) {
							event.entity.worldObj.spawnEntityInWorld(new EntityItem(event.entity.worldObj,
									event.entity.posX, event.entity.posY+1, event.entity.posZ,
									inventory[i]));
							inventory[i] = null;
						}
					}
			}
		}
	}

	@SubscribeEvent
	public void onEntityDeath(LivingDeathEvent event) {
		Entity source = event.source.getSourceOfDamage();
		if (event.entityLiving == null || source == null || event.entityLiving.worldObj.isRemote)
			return;

		// Players in teams should drop anti-territory gems when they are killed by other players.
		if (event.entityLiving instanceof EntityPlayer && source instanceof EntityPlayer) {
			EntityPlayer killed = (EntityPlayer)event.entityLiving;
			EntityPlayer killer = (EntityPlayer)source;
			PlayerTeamIndividual playerData = PlayerTeamIndividual.get(killed);
			if (playerData.teamID != null) {
				int amount = 1;
				if (MiniGameUtil.isPvP(event.entityLiving.dimension)) {
					int territoryCount = (int)Math.pow(Contained.configs.pvpTerritorySize*2+1, 2);
					amount = Util.randomRange(
							(int)Math.ceil(Math.sqrt(territoryCount/2D)),
							(int)Math.sqrt(territoryCount));
				}
				else {
					if (playerData.isLeader) //Leaders drop more anti-gems on death.
						amount = 4;
				}
				ItemStack toDrop = new ItemStack(ItemTerritory.removeTerritory, amount);
				NBTTagCompound itemData = Data.getTagCompound(toDrop);
				itemData.setString("teamOwner", playerData.teamID);
				toDrop.setTagCompound(itemData);
				processNewOwnership(killer, toDrop, true);
				killed.worldObj.spawnEntityInWorld(new EntityItem(killed.worldObj, killed.posX, killed.posY+1, killed.posZ, toDrop));
			}
		}

		//Players should drop only a small portion of their inventory on death.
		if (event.entityLiving instanceof EntityPlayer && source instanceof EntityLivingBase) {
			EntityPlayer killed = (EntityPlayer)event.entityLiving;
			ArrayList<Integer> definedSlots = new ArrayList<Integer>();
			for(int i=0; i<killed.inventory.mainInventory.length; i++) {
				if (killed.inventory.mainInventory[i] != null)
					definedSlots.add(i);
			}
			Collections.shuffle(definedSlots);
			int numStacksToRemove = (int)Math.ceil((float)definedSlots.size()/8F);
			for (int i=0; i<numStacksToRemove; i++) {
				ItemStack toDrop = killed.inventory.mainInventory[definedSlots.get(i)];
				if (source instanceof EntityPlayer)
					processNewOwnership((EntityPlayer)source, toDrop, true);
				killed.worldObj.spawnEntityInWorld(new EntityItem(killed.worldObj, killed.posX, killed.posY+1, killed.posZ, toDrop));
				killed.inventory.mainInventory[definedSlots.get(i)] = null;
			}
		}
	}

	@SubscribeEvent
	// For players that are in teams, only allow them to sleep in beds that are
	// within their team's territory.
	public void onBedSleep(PlayerSleepInBedEvent ev) {
		if (ev.entityPlayer != null && !ev.entityPlayer.worldObj.isRemote) {
			PlayerTeamIndividual playerData = PlayerTeamIndividual.get(ev.entityPlayer);
			if (playerData.teamID != null) {
				Point probe = new Point(ev.x, ev.z);
				int dimID = ev.entityPlayer.worldObj.provider.dimensionId;
				if (!Contained.getTerritoryMap(dimID).containsKey(probe)
						|| !Contained.getTerritoryMap(dimID).get(probe).equals(playerData.teamID)) {
					ev.result = EntityPlayer.EnumStatus.OTHER_PROBLEM;
					Util.displayError(ev.entityPlayer, "You can only sleep within your team's territory.");
				}
			}
		}
	}

	@SubscribeEvent
	public void onEntityConstructing(EntityConstructing event) {
		if (event.entity instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer) event.entity) == null)
			ExtendedPlayer.register((EntityPlayer) event.entity);
	}

	/*
	 * =====================================================================
	 *  ITEM USAGE FUNCTIONS
	 * =====================================================================
	 */

	//Handle all data collection for a player using (consuming) an item.
	public void processItemUsage(EntityPlayer user, ItemStack item) {
		if (!user.worldObj.isRemote) {
			NBTTagCompound itemData = Data.getTagCompound(item);
			String ownerName = itemData.getString("owner");
			EntityPlayer owner = user.worldObj.getPlayerEntityByName(ownerName);

			//Use own item
			if (ownerName.equals(user.getDisplayName())) {
				ExtendedPlayer.get(user).usedOwnItems += 1;
			}
			//Use other person's item
			else {
				ExtendedPlayer.get(user).usedOthersItems += 1;
				if (owner != null)
					//Note: Data logging here may be flawed, as I don't
					//think it will be able to update this parameter
					//if the owner of the item is not currently online.
					ExtendedPlayer.get(owner).usedByOthers += 1;
			}
		}
	}

	@SubscribeEvent
	//When an item is used, if it is consumed by the usage, log it.
	public void onItemUsed(PlayerUseItemEvent.Finish event) {
		if (event.entityPlayer != null && event.item != null)
			processItemUsage(event.entityPlayer, event.item);
	}

	@SubscribeEvent
	//Handle firing the functionality of BlockInteractItems when right-clicked on a block.
	public void onItemUse(PlayerInteractEvent event) {
		if (!event.world.isRemote) {
			ItemStack usedItem = event.entityPlayer.getHeldItem();
			if (usedItem == null)
				return;
			if (usedItem.getItem() instanceof BlockInteractItem
					&& event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) {
				BlockInteractItem intItem = (BlockInteractItem)usedItem.getItem();
				intItem.onBlockInteract(event.entityPlayer, event.x, event.y, event.z, usedItem);
			}
		}
	}

    @SubscribeEvent
    //Transfer player's team to a territory machine when placed.
    public void onBlockPlacement(BlockEvent.PlaceEvent ev) {
    	if (ev.player != null &&
    			(ev.block instanceof TerritoryMachine.BlockClaimTerritory
    		  || ev.block instanceof AntiTerritoryMachine.BlockAntiTerritory)) {
    		TileEntity te = ev.world.getTileEntity(ev.x, ev.y, ev.z);
    		if (te != null && te instanceof TerritoryMachineTE) {
    			TerritoryMachineTE machine = (TerritoryMachineTE)te;

    			if (!ev.world.isRemote && ev.block instanceof TerritoryMachine.BlockClaimTerritory) {
    				PlayerTeamIndividual playerData = PlayerTeamIndividual.get(ev.player);
    				machine.teamID = playerData.teamID;
    				machine.sendInfoPacket();
    			}
    			if (ev.block instanceof AntiTerritoryMachine.BlockAntiTerritory && ev.itemInHand != null) {
    				NBTTagCompound itemData = Data.getTagCompound(ev.itemInHand);
    				String teamID = itemData.getString("teamOwner");
    				if (teamID == null || teamID.equals(""))
    					machine.teamID = null;
    				else {
    					machine.teamID = teamID;
    					machine.sendInfoPacket();
    				}
    			}
    		}
    	}
    }

	/*
	 * =====================================================================
	 *  ITEM OWNERSHIP FUNCTIONS
	 * =====================================================================
	 */

	//Handle all data collection procedures for when a player becomes
	//the owner of a new item.
	public boolean processNewOwnership(EntityPlayer newOwner, ItemStack item, boolean forceOwner) {
		//First make sure this item isn't owned by someone already...
		NBTTagCompound itemData = Data.getTagCompound(item);
		String owner = itemData.getString("owner");
		if ((owner == null || owner.equals("") || forceOwner) && newOwner != null) {
			//Check if this item corresponds to an "occupation", and update
			//player's values accordingly
			OccupationRank occ = Data.occupationMap.get(new DataItemStack(item));
			if (occ != null) {
				ExtendedPlayer.get(newOwner)
					.increaseOccupation(occ.occupationID, occ.rank*item.stackSize);
			}

			//Set this player as the new owner of the item
			itemData.setString("owner", newOwner.getDisplayName());
			item.setTagCompound(itemData);

			//If the item is a spawn egg, set its display name to match the owner.
			if (item.getItem() instanceof ItemMonsterPlacer)
				item.setStackDisplayName(newOwner.getDisplayName());

			return true;
		}
		return false;
	}

	@SubscribeEvent
	//When an unowned item is collected, it is owned by the collector.
	public void onItemCollected(EntityItemPickupEvent event) {
		if (event.entityPlayer != null)
			processNewOwnership(event.entityPlayer, event.item.getEntityItem(), false);
	}

	@SubscribeEvent
	//When a block is harvested, the dropped items are owned by the harvester.
	public void onItemHarvested(HarvestDropsEvent event) {
		ArrayList<ItemStack> drops = event.drops;
		for (ItemStack stack : drops)
			processNewOwnership(event.harvester, stack, false);
	}

	@SubscribeEvent
	//When a creature is killed, the dropped items are owned by the killer.
	public void onCreatureDropItems(LivingDropsEvent event) {
		DamageSource ds = event.source;
		if (ds != null && ds.getEntity() != null
				&& ds.getEntity() instanceof EntityPlayer)
		{
			EntityPlayer killer = (EntityPlayer)ds.getEntity();
			ArrayList<EntityItem> drops = event.drops;
			for (EntityItem item : drops)
				processNewOwnership(killer, item.getEntityItem(), false);
		}
	}

	@SubscribeEvent
	//Show the owner of an item in the item's mouse-over tooltip.
	public void itemInformation(ItemTooltipEvent event) {
		ItemStack stack = event.itemStack;
		NBTTagCompound itemData = Data.getTagCompound(stack);
		String owner = itemData.getString("owner");

		if (owner == null || owner.equals(""))
			event.toolTip.add("Not Owned");
		else
			event.toolTip.add("Owner: "+owner);
	}

	@SubscribeEvent
	//Make a player wait a little longer to loot an item if it belongs
	//to someone else.
	public void onItemPickup(EntityItemPickupEvent event) {
		int secondsToWait = 10;
		ItemStack stack = event.item.getEntityItem();
		NBTTagCompound itemData = Data.getTagCompound(stack);
		String owner = itemData.getString("owner");

		if (event.entityPlayer != null && !(owner == null || owner.equals("")
				|| owner.equals(event.entityPlayer.getDisplayName()))) {
			if (event.item.ticksExisted < 20*secondsToWait)
				event.setCanceled(true);
		}
	}
}


text:
class CMarkup
{
public:
	CMarkup() { SetDoc( NULL ); };
	CMarkup( LPCTSTR szDoc ) { SetDoc( szDoc ); };
	CMarkup( const CMarkup& markup ) { *this = markup; };
	void operator=( const CMarkup& markup );
	virtual ~CMarkup() {};

	// Create
	CString GetDoc() const { return m_csDoc; };
	bool AddElem( LPCTSTR szName, LPCTSTR szData=NULL ) { return x_AddElem(szName,szData,false,false); };
	bool AddChildElem( LPCTSTR szName, LPCTSTR szData=NULL ) { return x_AddElem(szName,szData,false,true); };
	bool AddAttrib( LPCTSTR szAttrib, LPCTSTR szValue ) { return x_SetAttrib(m_iPos,szAttrib,szValue); };
	bool AddChildAttrib( LPCTSTR szAttrib, LPCTSTR szValue ) { return x_SetAttrib(m_iPosChild,szAttrib,szValue); };
	bool SetAttrib( LPCTSTR szAttrib, LPCTSTR szValue ) { return x_SetAttrib(m_iPos,szAttrib,szValue); };
	bool SetChildAttrib( LPCTSTR szAttrib, LPCTSTR szValue ) { return x_SetAttrib(m_iPosChild,szAttrib,szValue); };

	// Navigate
	bool SetDoc( LPCTSTR szDoc );
	bool IsWellFormed();
	bool FindElem( LPCTSTR szName=NULL );
	bool FindChildElem( LPCTSTR szName=NULL );
	bool IntoElem();
	bool OutOfElem();
	void ResetChildPos() { x_SetPos(m_iPosParent,m_iPos,0); };
	void ResetMainPos() { x_SetPos(m_iPosParent,0,0); };
	void ResetPos() { x_SetPos(0,0,0); };
	CString GetTagName() const;
	CString GetChildTagName() const { return x_GetTagName(m_iPosChild); };
	CString GetData() const { return x_GetData(m_iPos); };
	CString GetChildData() const { return x_GetData(m_iPosChild); };
	CString GetAttrib( LPCTSTR szAttrib ) const { return x_GetAttrib(m_iPos,szAttrib); };
	CString GetChildAttrib( LPCTSTR szAttrib ) const { return x_GetAttrib(m_iPosChild,szAttrib); };
	CString GetError() const { return m_csError; };

	enum MarkupNodeType
	{
		MNT_ELEMENT					= 1,  // 0x01
		MNT_TEXT					= 2,  // 0x02
		MNT_WHITESPACE				= 4,  // 0x04
		MNT_CDATA_SECTION			= 8,  // 0x08
		MNT_PROCESSING_INSTRUCTION	= 16, // 0x10
		MNT_COMMENT					= 32, // 0x20
		MNT_DOCUMENT_TYPE			= 64, // 0x40
		MNT_EXCLUDE_WHITESPACE		= 123,// 0x7b
	};

protected:

#ifdef _DEBUG
	LPCTSTR m_pMainDS;
	LPCTSTR m_pChildDS;
#endif

	CString m_csDoc;
	CString m_csError;

	struct ElemPos
	{
		ElemPos() { Clear(); };
		ElemPos( const ElemPos& pos ) { *this = pos; };
		bool IsEmptyElement() const { return (nStartR == nEndL + 1); };
		void Clear()
		{
			nStartL=0; nStartR=0; nEndL=0; nEndR=0; nReserved=0;
			iElemParent=0; iElemChild=0; iElemNext=0;
		};
		void AdjustStart( int n ) { nStartL+=n; nStartR+=n; };
		void AdjustEnd( int n ) { nEndL+=n; nEndR+=n; };
		int nStartL;
		int nStartR;
		int nEndL;
		int nEndR;
		int nReserved;
		int iElemParent;
		int iElemChild;
		int iElemNext;
	};

	CArray< ElemPos, ElemPos& > m_aPos;
	int m_iPosParent;
	int m_iPos;
	int m_iPosChild;
	int m_iPosFree;
	int m_nNodeType;

	struct TokenPos
	{
		TokenPos( LPCTSTR sz ) { Clear(); szDoc = sz; };
		bool IsValid() const { return (nL <= nR); };
		void Clear() { nL=0; nR=-1; nNext=0; bIsString=false; };
		bool Match( LPCTSTR szName )
		{
			int nLen = nR - nL + 1;
			return ( (_tcsnccmp( &szDoc[nL], szName, nLen ) == 0)
				&& ( szName[nLen] == _T('\0') || _tcschr(_T(" =/["),szName[nLen]) ) );
		};
		int nL;
		int nR;
		int nNext;
		LPCTSTR szDoc;
		bool bIsString;
	};

	void x_SetPos( int iPosParent, int iPos, int iPosChild )
	{
		m_iPosParent = iPosParent;
		m_iPos = iPos;
		m_iPosChild = iPosChild;
		m_nNodeType = iPos?MNT_ELEMENT:0;
		MARKUP_SETDEBUGSTATE;
	};

	int x_GetFreePos();
	int x_ReleasePos();
	int x_ParseElem( int iPos );
	int x_ParseError( LPCTSTR szError, LPCTSTR szName = NULL );
	static bool x_FindChar( LPCTSTR szDoc, int& nChar, _TCHAR c );
	static bool x_FindAny( LPCTSTR szDoc, int& nChar );
	static bool x_FindToken( TokenPos& token );
	CString x_GetToken( const TokenPos& token ) const;
	int x_FindElem( int iPosParent, int iPos, LPCTSTR szPath );
	CString x_GetTagName( int iPos ) const;
	CString x_GetData( int iPos ) const;
	CString x_GetAttrib( int iPos, LPCTSTR szAttrib ) const;
	bool x_AddElem( LPCTSTR szName, LPCTSTR szValue, bool bInsert, bool bAddChild );
	bool x_FindAttrib( TokenPos& token, LPCTSTR szAttrib=NULL ) const;
	bool x_SetAttrib( int iPos, LPCTSTR szAttrib, LPCTSTR szValue );
	void x_LocateNew( int iPosParent, int& iPosRel, int& nOffset, int nLength, int nFlags );
	int x_ParseNode( TokenPos& token );
	void x_DocChange( int nLeft, int nReplace, const CString& csInsert );
	void x_Adjust( int iPos, int nShift, bool bAfterPos = false );
	CString x_TextToDoc( LPCTSTR szText, bool bAttrib = false ) const;
	CString x_TextFromDoc( int nLeft, int nRight ) const;
};

#endif // !defined(AFX_MARKUP_H__948A2705_9E68_11D2_A0BF_00105A27C570__INCLUDED_)


text:
namespace btunnel {

class Service;

// Returns a vector of registered services of the specified type, such as
// "_daap._tcp".  The caller is responsible for freeing all of the returned
// Service objects.
void BrowseService(const std::string& service_type,
                   std::vector<Service*>* services);

}  // namespace btunnel

#endif  // __BTUNNEL_BROWSE_H__


text:
class Delegate {

  constructor(bag) {
    this.bag = bag;
  }

  columns() {
    const { bag } = this;
    return bag.columns;
  }

  rows(pagination, sorting, callback) {
    const { bag } = this;
    bag.callbacks.rows = { pagination, sorting, callback };
  }

}

module.exports = Delegate;


text:
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/unistd.h>
#include <errno.h>

__syscall3(int, chown, const char*, filename, uid_t, uid, gid_t, gid);


text:
require "spec_helper"
require "chef/cookbook_version"

describe Chef::Cookbook::FileVendor do

  let(:file_vendor_class) { Class.new(described_class) }

  context "when configured to fetch files over http" do

    let(:http) { double("Chef::ServerAPI") }

    # A manifest is a Hash of the format defined by Chef::CookbookVersion#manifest
    let(:manifest) do
      cbv = Chef::CookbookVersion.new("bob", Array(Dir.tmpdir))
      cbv.cookbook_manifest
    end

    before do
      file_vendor_class.fetch_from_remote(http)
    end

    it "sets the vendor class to RemoteFileVendor" do
      expect(file_vendor_class.vendor_class).to eq(Chef::Cookbook::RemoteFileVendor)
    end

    it "sets the initialization options to the given http object" do
      expect(file_vendor_class.initialization_options).to eq(http)
    end

    context "with a manifest from a cookbook version" do

      # # A manifest is a Hash of the format defined by Chef::CookbookVersion#manifest
      # let(:manifest) do
      #   cbv = Chef::CookbookVersion.new("bob", Array(Dir.tmpdir))
      #   cbv.cookbook_manifest
      # end

      it "creates a RemoteFileVendor for a given manifest" do
        file_vendor = file_vendor_class.create_from_manifest(manifest)
        expect(file_vendor).to be_a_kind_of(Chef::Cookbook::RemoteFileVendor)
        expect(file_vendor.rest).to eq(http)
        expect(file_vendor.cookbook_name).to eq("bob")
      end

    end

    context "with a manifest from a cookbook artifact" do

      it "creates a RemoteFileVendor for a given manifest" do
        file_vendor = file_vendor_class.create_from_manifest(manifest)
        expect(file_vendor).to be_a_kind_of(Chef::Cookbook::RemoteFileVendor)
        expect(file_vendor.rest).to eq(http)
        expect(file_vendor.cookbook_name).to eq("bob")
      end

    end
  end

  context "when configured to load files from disk" do

    let(:cookbook_path) { %w{/var/chef/cookbooks /var/chef/other_cookbooks} }

    let(:manifest) do
      cbv = Chef::CookbookVersion.new("bob", Array(Dir.tmpdir))
      cbv.cookbook_manifest
    end

    before do
      file_vendor_class.fetch_from_disk(cookbook_path)
    end

    it "sets the vendor class to FileSystemFileVendor" do
      expect(file_vendor_class.vendor_class).to eq(Chef::Cookbook::FileSystemFileVendor)
    end

    it "sets the initialization options to the given cookbook paths" do
      expect(file_vendor_class.initialization_options).to eq(cookbook_path)
    end

    it "creates a FileSystemFileVendor for a given manifest" do
      file_vendor = file_vendor_class.create_from_manifest(manifest)
      expect(file_vendor).to be_a_kind_of(Chef::Cookbook::FileSystemFileVendor)
      expect(file_vendor.cookbook_name).to eq("bob")
      expect(file_vendor.repo_paths).to eq(cookbook_path)
    end

  end

  context "when vendoring a cookbook with a name mismatch" do
    let(:cookbook_path) { File.join(CHEF_SPEC_DATA, "cookbooks") }

    let(:manifest) do
      cbv = Chef::CookbookVersion.new("name-mismatch", Array(Dir.tmpdir))
      cbv.cookbook_manifest
    end

    before do
      file_vendor_class.fetch_from_disk(cookbook_path)
    end

    it "retrieves the file from the correct location based on path to the cookbook that conatins the correct name metadata" do
      file_vendor = file_vendor_class.create_from_manifest(manifest)
      file_vendor.get_filename("metadata.rb")
    end
  end
end


text:
module Handlebarer

  module Serialize

    module ClassMethods

      # Enable serialization on ActiveModel classes
      # @param [Array<Symbol>] args model attribute names to serialize
      # @param [Hash] args options serializing mode
      # @option args [Boolean] :merge should serialized attributes be merged with `self.attributes`
      # @example
      #     class User < ActiveRecord::Base
      #       include Handlebarer::Serialize
      #       hbs_serializable :name, :email, :merge => false
      #     end
      def hbs_serializable(*args)
        serialize = {
          :attrs => [],
          :merge => true
        }
        args.each do |arg|
          if arg.is_a? Symbol
            serialize[:attrs] << arg
          elsif arg.is_a? Hash
            serialize[:merge] = arg[:merge] if arg.include?(:merge)
          end
        end
        class_variable_set(:@@serialize, serialize)
      end

    end

    #nodoc
    def self.included(base)
      base.extend ClassMethods
    end

    # Serialize instance attributes to a Hash based on serializable attributes defined on Model class.
    # @return [Hash] hash of model instance attributes
    def to_hbs
      h = {:model => self.class.name.downcase}
      self.hbs_attributes.each do |attr|
        h[attr] = self.send(attr)

        ans = h[attr].class.ancestors
        if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations)
          h[attr] = h[attr].to_hbs
        else
        end
      end
      h
    end

    # List of Model attributes that should be serialized when called `to_hbs` on Model instance
    # @return [Array] list of serializable attributes
    def hbs_attributes
      s = self.class.class_variable_get(:@@serialize)
      if s[:merge]
        attrs = s[:attrs] + self.attributes.keys
      else
        attrs = s[:attrs]
      end
      attrs.collect{|attr| attr.to_sym}.uniq
    end
  end

end

class Object
  # Serialize Object to Jade format. Invoke `self.to_hbs` if instance responds to `to_hbs`
  def to_hbs
    if self.respond_to? :to_a
      self.to_a.to_hbs
    else
      nil
    end
  end
end

#nodoc
[FalseClass, TrueClass, Numeric, String].each do |cls|
  cls.class_eval do
    def to_hbs
      self
    end
  end
end

class Array

  # Serialize Array to Handlebarer format. Invoke `to_hbs` on array members
  def to_hbs
    map {|a| a.respond_to?(:to_hbs) ? a.to_hbs : a }
  end
end

class Hash

  # Serialize Hash to Handlebarer format. Invoke `to_hbs` on members
  def to_hbs
    res = {}
    each_pair do |key, value|
      res[key] = (value.respond_to?(:to_hbs) ? value.to_hbs : value)
    end
    res
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.CodeAnalysis.Editor
{
    internal interface IBraceMatcher
    {
        Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken = default);
    }
}


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/equatorial-guinea/timetables/" />
</head></html>


text:
namespace PLT {

Bitmap::Bitmap(unsigned width_, unsigned height_)
{
   resize(width_, height_);
}

Bitmap::~Bitmap()
{
   delete[] buffer;
}

void Bitmap::resize(unsigned width_, unsigned height_)
{
   delete[] buffer;

   width  = width_;
   height = height_;
   pitch  = (width * Image::getPixelBits() + 7) / 8;
   buffer = new uint8_t[pitch * height];
}

void* Bitmap::getHandle() const
{
   // No acceleration possible
   return nullptr;
}

} // namespace PLT


text:
#
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_ARRAY_DETAIL_GET_DATA_HPP
# define BOOST_PREPROCESSOR_ARRAY_DETAIL_GET_DATA_HPP
#
# include <boost/preprocessor/config/config.hpp>
# include <boost/preprocessor/tuple/rem.hpp>
# include <boost/preprocessor/control/if.hpp>
# include <boost/preprocessor/control/iif.hpp>
# include <boost/preprocessor/facilities/is_1.hpp>
#
# /* BOOST_PP_ARRAY_DETAIL_GET_DATA */
#
# define BOOST_PP_ARRAY_DETAIL_GET_DATA_NONE(size, data)

# if BOOST_PP_VARIADICS && !(BOOST_PP_VARIADICS_MSVC && _MSC_VER <= 1400)
# 	 if BOOST_PP_VARIADICS_MSVC
# 		define BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY_VC_DEFAULT(size, data) BOOST_PP_TUPLE_REM(size) data
# 		define BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY_VC_CAT(size, data) BOOST_PP_TUPLE_REM_CAT(size) data
# 		define BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY(size, data) \
			BOOST_PP_IIF \
				( \
				BOOST_PP_IS_1(size), \
				BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY_VC_CAT, \
				BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY_VC_DEFAULT \
				) \
			(size,data) \
/**/
#    else
# 		define BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY(size, data) BOOST_PP_TUPLE_REM(size) data
#    endif
# else
# 	 define BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY(size, data) BOOST_PP_TUPLE_REM(size) data
# endif

# define BOOST_PP_ARRAY_DETAIL_GET_DATA(size, data) \
	BOOST_PP_IF \
		( \
		size, \
		BOOST_PP_ARRAY_DETAIL_GET_DATA_ANY, \
		BOOST_PP_ARRAY_DETAIL_GET_DATA_NONE \
		) \
	(size,data) \
/**/
#
# endif /* BOOST_PREPROCESSOR_ARRAY_DETAIL_GET_DATA_HPP */


text:
Persistent<FunctionTemplate> FieldDefn::constructor;

void FieldDefn::Initialize(Handle<Object> target) {
  HandleScope scope;

  constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(FieldDefn::New));
  constructor->InstanceTemplate()->SetInternalFieldCount(1);
  constructor->SetClassName(String::NewSymbol("FieldDefn"));

  NODE_SET_PROTOTYPE_METHOD(constructor, "toString", toString);
  NODE_SET_PROTOTYPE_METHOD(constructor, "getName", getName);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setName", setName);
  NODE_SET_PROTOTYPE_METHOD(constructor, "getType", getType);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setType", setType);
  NODE_SET_PROTOTYPE_METHOD(constructor, "getJustify", getJustify);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setJustify", setJustify);
  NODE_SET_PROTOTYPE_METHOD(constructor, "getWidth", getWidth);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setWidth", setWidth);
  NODE_SET_PROTOTYPE_METHOD(constructor, "getPrecision", getPrecision);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setPrecision", setPrecision);
  NODE_SET_PROTOTYPE_METHOD(constructor, "isIgnored", isIgnored);
  NODE_SET_PROTOTYPE_METHOD(constructor, "setIgnored", setIgnored);

  target->Set(String::NewSymbol("FieldDefn"), constructor->GetFunction());
}

FieldDefn::FieldDefn(OGRFieldDefn *layer)
: ObjectWrap(),
  this_(layer)
{}

FieldDefn::FieldDefn()
: ObjectWrap(),
  this_(0)
{
}

FieldDefn::~FieldDefn()
{
  if (owned_) {
    delete this_;
  }
}

Handle<Value> FieldDefn::New(const Arguments& args)
{
  HandleScope scope;

  if (!args.IsConstructCall())
    return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

  if (args[0]->IsExternal()) {
    Local<External> ext = Local<External>::Cast(args[0]);
    void* ptr = ext->Value();
    FieldDefn *f = static_cast<FieldDefn *>(ptr);
    f->Wrap(args.This());
    return args.This();
  } else {
    std::string field_name("");
    OGRFieldType field_type(OFTString);

    NODE_ARG_STR(0, "field name", field_name);
    NODE_ARG_ENUM(1, "field type", OGRFieldType, field_type);

    FieldDefn* def = new FieldDefn(new OGRFieldDefn(field_name.c_str(), field_type));
    def->owned_ = true;
    def->Wrap(args.This());
  }

  return args.This();
}

Handle<Value> FieldDefn::New(OGRFieldDefn *def) {
  v8::HandleScope scope;
  FieldDefn *wrapped = new FieldDefn(def);
  //wrapped->size_ = geom->WkbSize();
  //V8::AdjustAmountOfExternalAllocatedMemory(wrapped->size_);

  v8::Handle<v8::Value> ext = v8::External::New(wrapped);
  v8::Handle<v8::Object> obj = FieldDefn::constructor->GetFunction()->NewInstance(1, &ext);

  return scope.Close(obj);
}

Handle<Value> FieldDefn::New(OGRFieldDefn *def, bool owned) {
  v8::HandleScope scope;
  FieldDefn *wrapped = new FieldDefn(def);
  wrapped->owned_ = owned;
  v8::Handle<v8::Value> ext = v8::External::New(wrapped);
  v8::Handle<v8::Object> obj = FieldDefn::constructor->GetFunction()->NewInstance(1, &ext);
  return scope.Close(obj);
}

Handle<Value> FieldDefn::toString(const Arguments& args)
{
  HandleScope scope;
  return scope.Close(String::New("FieldDefn"));
}

NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, getName, String, GetNameRef);
NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, getType, Integer, GetType);
NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, isIgnored, Boolean, IsIgnored);
NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, getJustify, Integer, GetJustify);
NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, getWidth, Integer, GetWidth);
NODE_WRAPPED_METHOD_WITH_RESULT(FieldDefn, getPrecision, Integer, GetPrecision);
NODE_WRAPPED_METHOD_WITH_1_ENUM_PARAM(FieldDefn, setJustify, SetJustify, OGRJustification, "justification");
NODE_WRAPPED_METHOD_WITH_1_ENUM_PARAM(FieldDefn, setType, SetType, OGRFieldType, "field type");
NODE_WRAPPED_METHOD_WITH_1_INTEGER_PARAM(FieldDefn, setPrecision, SetPrecision, "field precision");
NODE_WRAPPED_METHOD_WITH_1_INTEGER_PARAM(FieldDefn, setWidth, SetWidth, "field width");
NODE_WRAPPED_METHOD_WITH_1_BOOLEAN_PARAM(FieldDefn, setIgnored, SetIgnored, "is ignored");
NODE_WRAPPED_METHOD_WITH_1_STRING_PARAM(FieldDefn, setName, SetName, "field name");


text:
package com.amazonaws.services.simpleworkflow.model;
import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow#getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest) GetWorkflowExecutionHistory operation}.
 *

 * Returns the history of the specified workflow execution. The results may be split into multiple pages. To retrieve subsequent pages, make the call
 * again using the nextPageToken returned by the initial call.
 *

 *

 * NOTE: This operation is eventually consistent. The results are best effort and may not exactly reflect recent updates and changes.
 *

 *
 * @see com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow#getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest)
 */
public class GetWorkflowExecutionHistoryRequest extends AmazonWebServiceRequest {

    /**
     * The name of the domain containing the workflow execution.
     *

     * Constraints:

     * Length: 1 - 256

     */
    private String domain;

    /**
     * Specifies the workflow execution for which to return the history.
     */
    private WorkflowExecution execution;

    /**
     * If a NextPageToken is returned, the result has more than
     * one pages. To get the next page, repeat the call and specify the
     * nextPageToken with all other arguments unchanged.
     *

     * Constraints:

     * Length: 0 - 2048

     */
    private String nextPageToken;

    /**
     * Specifies the maximum number of history events returned in one page.
     * The next page in the result is identified by the
     * NextPageToken returned. By default 100 history events are
     * returned in a page but the caller can override this value to a page
     * size smaller than the default. You cannot specify a page size
     * larger than 100.
     *

     * Constraints:

     * Range: 0 - 1000

     */
    private Integer maximumPageSize;

    /**
     * When set to true, returns the events in reverse order. By
     * default the results are returned in ascending order of the
     * eventTimeStamp of the events.
     */
    private Boolean reverseOrder;

    /**
     * The name of the domain containing the workflow execution.
     *

     * Constraints:

     * Length: 1 - 256

     *
     * @return The name of the domain containing the workflow execution.
     */
    public String getDomain() {
        return domain;
    }

    /**
     * The name of the domain containing the workflow execution.
     *

     * Constraints:

     * Length: 1 - 256

     *
     * @param domain The name of the domain containing the workflow execution.
     */
    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     * The name of the domain containing the workflow execution.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 256

     *
     * @param domain The name of the domain containing the workflow execution.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetWorkflowExecutionHistoryRequest withDomain(String domain) {
        this.domain = domain;
        return this;
    }

    /**
     * Specifies the workflow execution for which to return the history.
     *
     * @return Specifies the workflow execution for which to return the history.
     */
    public WorkflowExecution getExecution() {
        return execution;
    }

    /**
     * Specifies the workflow execution for which to return the history.
     *
     * @param execution Specifies the workflow execution for which to return the history.
     */
    public void setExecution(WorkflowExecution execution) {
        this.execution = execution;
    }

    /**
     * Specifies the workflow execution for which to return the history.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param execution Specifies the workflow execution for which to return the history.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetWorkflowExecutionHistoryRequest withExecution(WorkflowExecution execution) {
        this.execution = execution;
        return this;
    }

    /**
     * If a NextPageToken is returned, the result has more than
     * one pages. To get the next page, repeat the call and specify the
     * nextPageToken with all other arguments unchanged.
     *

     * Constraints:

     * Length: 0 - 2048

     *
     * @return If a NextPageToken is returned, the result has more than
     *         one pages. To get the next page, repeat the call and specify the
     *         nextPageToken with all other arguments unchanged.
     */
    public String getNextPageToken() {
        return nextPageToken;
    }

    /**
     * If a NextPageToken is returned, the result has more than
     * one pages. To get the next page, repeat the call and specify the
     * nextPageToken with all other arguments unchanged.
     *

     * Constraints:

     * Length: 0 - 2048

     *
     * @param nextPageToken If a NextPageToken is returned, the result has more than
     *         one pages. To get the next page, repeat the call and specify the
     *         nextPageToken with all other arguments unchanged.
     */
    public void setNextPageToken(String nextPageToken) {
        this.nextPageToken = nextPageToken;
    }

    /**
     * If a NextPageToken is returned, the result has more than
     * one pages. To get the next page, repeat the call and specify the
     * nextPageToken with all other arguments unchanged.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 0 - 2048

     *
     * @param nextPageToken If a NextPageToken is returned, the result has more than
     *         one pages. To get the next page, repeat the call and specify the
     *         nextPageToken with all other arguments unchanged.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetWorkflowExecutionHistoryRequest withNextPageToken(String nextPageToken) {
        this.nextPageToken = nextPageToken;
        return this;
    }

    /**
     * Specifies the maximum number of history events returned in one page.
     * The next page in the result is identified by the
     * NextPageToken returned. By default 100 history events are
     * returned in a page but the caller can override this value to a page
     * size smaller than the default. You cannot specify a page size
     * larger than 100.
     *

     * Constraints:

     * Range: 0 - 1000

     *
     * @return Specifies the maximum number of history events returned in one page.
     *         The next page in the result is identified by the
     *         NextPageToken returned. By default 100 history events are
     *         returned in a page but the caller can override this value to a page
     *         size smaller than the default. You cannot specify a page size
     *         larger than 100.
     */
    public Integer getMaximumPageSize() {
        return maximumPageSize;
    }

    /**
     * Specifies the maximum number of history events returned in one page.
     * The next page in the result is identified by the
     * NextPageToken returned. By default 100 history events are
     * returned in a page but the caller can override this value to a page
     * size smaller than the default. You cannot specify a page size
     * larger than 100.
     *

     * Constraints:

     * Range: 0 - 1000

     *
     * @param maximumPageSize Specifies the maximum number of history events returned in one page.
     *         The next page in the result is identified by the
     *         NextPageToken returned. By default 100 history events are
     *         returned in a page but the caller can override this value to a page
     *         size smaller than the default. You cannot specify a page size
     *         larger than 100.
     */
    public void setMaximumPageSize(Integer maximumPageSize) {
        this.maximumPageSize = maximumPageSize;
    }

    /**
     * Specifies the maximum number of history events returned in one page.
     * The next page in the result is identified by the
     * NextPageToken returned. By default 100 history events are
     * returned in a page but the caller can override this value to a page
     * size smaller than the default. You cannot specify a page size
     * larger than 100.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Range: 0 - 1000

     *
     * @param maximumPageSize Specifies the maximum number of history events returned in one page.
     *         The next page in the result is identified by the
     *         NextPageToken returned. By default 100 history events are
     *         returned in a page but the caller can override this value to a page
     *         size smaller than the default. You cannot specify a page size
     *         larger than 100.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetWorkflowExecutionHistoryRequest withMaximumPageSize(Integer maximumPageSize) {
        this.maximumPageSize = maximumPageSize;
        return this;
    }

    /**
     * When set to true, returns the events in reverse order. By
     * default the results are returned in ascending order of the
     * eventTimeStamp of the events.
     *
     * @return When set to true, returns the events in reverse order. By
     *         default the results are returned in ascending order of the
     *         eventTimeStamp of the events.
     */
    public Boolean isReverseOrder() {
        return reverseOrder;
    }

    /**
     * When set to true, returns the events in reverse order. By
     * default the results are returned in ascending order of the
     * eventTimeStamp of the events.
     *
     * @param reverseOrder When set to true, returns the events in reverse order. By
     *         default the results are returned in ascending order of the
     *         eventTimeStamp of the events.
     */
    public void setReverseOrder(Boolean reverseOrder) {
        this.reverseOrder = reverseOrder;
    }

    /**
     * When set to true, returns the events in reverse order. By
     * default the results are returned in ascending order of the
     * eventTimeStamp of the events.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param reverseOrder When set to true, returns the events in reverse order. By
     *         default the results are returned in ascending order of the
     *         eventTimeStamp of the events.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetWorkflowExecutionHistoryRequest withReverseOrder(Boolean reverseOrder) {
        this.reverseOrder = reverseOrder;
        return this;
    }

    /**
     * When set to true, returns the events in reverse order. By
     * default the results are returned in ascending order of the
     * eventTimeStamp of the events.
     *
     * @return When set to true, returns the events in reverse order. By
     *         default the results are returned in ascending order of the
     *         eventTimeStamp of the events.
     */
    public Boolean getReverseOrder() {
        return reverseOrder;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (domain != null) sb.append("Domain: " + domain + ", ");
        if (execution != null) sb.append("Execution: " + execution + ", ");
        if (nextPageToken != null) sb.append("NextPageToken: " + nextPageToken + ", ");
        if (maximumPageSize != null) sb.append("MaximumPageSize: " + maximumPageSize + ", ");
        if (reverseOrder != null) sb.append("ReverseOrder: " + reverseOrder + ", ");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDomain() == null) ? 0 : getDomain().hashCode());
        hashCode = prime * hashCode + ((getExecution() == null) ? 0 : getExecution().hashCode());
        hashCode = prime * hashCode + ((getNextPageToken() == null) ? 0 : getNextPageToken().hashCode());
        hashCode = prime * hashCode + ((getMaximumPageSize() == null) ? 0 : getMaximumPageSize().hashCode());
        hashCode = prime * hashCode + ((isReverseOrder() == null) ? 0 : isReverseOrder().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof GetWorkflowExecutionHistoryRequest == false) return false;
        GetWorkflowExecutionHistoryRequest other = (GetWorkflowExecutionHistoryRequest)obj;

        if (other.getDomain() == null ^ this.getDomain() == null) return false;
        if (other.getDomain() != null && other.getDomain().equals(this.getDomain()) == false) return false;
        if (other.getExecution() == null ^ this.getExecution() == null) return false;
        if (other.getExecution() != null && other.getExecution().equals(this.getExecution()) == false) return false;
        if (other.getNextPageToken() == null ^ this.getNextPageToken() == null) return false;
        if (other.getNextPageToken() != null && other.getNextPageToken().equals(this.getNextPageToken()) == false) return false;
        if (other.getMaximumPageSize() == null ^ this.getMaximumPageSize() == null) return false;
        if (other.getMaximumPageSize() != null && other.getMaximumPageSize().equals(this.getMaximumPageSize()) == false) return false;
        if (other.isReverseOrder() == null ^ this.isReverseOrder() == null) return false;
        if (other.isReverseOrder() != null && other.isReverseOrder().equals(this.isReverseOrder()) == false) return false;
        return true;
    }

}


text:
void ompl::geometric::FMTHeuristic::saveTree(const std::string &filename)
{
    std::ofstream ofs;
    ofs.open(filename.c_str(), std::ofstream::trunc);

    std::vector<Motion *> motions;
    nn_->list(motions);

    for (size_t i = 0; i < motions.size(); ++i)
    {
        if (motions[i]->getParent())
            ofs << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[0] << "\t"
                << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[1] << "\t"
                << motions[i]->getParent()->getState()->as<base::RealVectorStateSpace::StateType>()->values[0] << "\t"
                << motions[i]->getParent()->getState()->as<base::RealVectorStateSpace::StateType>()->values[1] << "\t"
                << motions[i]->getCost() << "\t" << motions[i]->getHeuristicCost() << std::endl << "\t"
                << opt_->combineCosts(motions[i]->getCost(), motions[i]->getHeuristicCost());
        else
            ofs << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[0] << "\t"
                << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[1] << "\t"
                << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[0] << "\t"
                << motions[i]->getState()->as<base::RealVectorStateSpace::StateType>()->values[1] << "\t"
                << 0 << opt_->motionCostHeuristic(motions[i]->getState(), goalState_) << "\t"
                << opt_->motionCostHeuristic(motions[i]->getState(), goalState_) << std::endl;
    }

    ofs.close();
}


text:
using System;
using System.IO;

namespace GenVScripting
{
    static class GenVScriptDecompiler
    {
        public static void ReadScriptsFromHeader(string scr)
        {
            // For more info about the script format of Gen V games (specifically B2W2), see
            // Kaphotic's and pichu2001's threads on scripting, accessible from here:
            // https://projectpokemon.org/forums/forums/topic/25852-b2w2-scripting-thread/
            // This program will also (hopefully) serve as documentation.

            using (BinaryReader reader = new BinaryReader(File.OpenRead(scr)))
            {
                // Sorry, all of you staring at this, horrified. Sorry.
                for (uint scriptOffset = reader.ReadUInt32(),
                        currentOffset = (uint)reader.BaseStream.Position;
                    (ushort)scriptOffset != 0xFD13;
                    scriptOffset = reader.ReadUInt32(),
                        currentOffset = (uint)reader.BaseStream.Position)
                {
                    // So we found a script to jump to, then.
                    Console.WriteLine($"Offset: 0x{scriptOffset:X8}");

                    // Seek forward, and read the script.
                    reader.BaseStream.Seek(scriptOffset, SeekOrigin.Current);
                    ReadScript(reader);

                    // After the script's been read, jump back and read the next offset.
                    reader.BaseStream.Seek(currentOffset, SeekOrigin.Begin);
                }
            }

            return;
        }

        private static void ReadScript(BinaryReader reader)
        {
            CommandInfo current = new CommandInfo(reader);
            for (current.Decompile(); true; current.Decompile())
            {
                Console.WriteLine(current.ToString());
                // or something along those lines. Possibly including a ScriptInfo to iterate thru.

                if (current.ID == 0x0002)
                    break;
            }

            Util.Log("Script ended. Returning...");
            return;
        }
    }
}


text:
@implementation BindingItem

@synthesize observedController = _observedController;
@synthesize observedKeyPath = _observedKeyPath;
@synthesize transformerName = _transformerName;
@synthesize identifier = _identifier;
@synthesize selector = _selector;
@synthesize valueClass = _valueClass;

#pragma mark Initializing
//-- init
-(id) init
{
	self = [super init];
    if(self != nil){
        _observedController = _observedKeyPath = _transformerName = nil;
	}
    return self;
}

//-- initWithSelector:valueClass:
-(id) initWithSelector:(SEL) selector
			valueClass:(Class) valueClass
			identifier:(NSString*) identifier
{
	self = [super init];
    if(self != nil){
		_observedController = _observedKeyPath = _transformerName = nil;
		_selector = selector;
		_valueClass = valueClass;
		_identifier = identifier;
	}
	return self;
}

//-- dealloc
-(void) dealloc
{
	[_observedController release];
	[_observedKeyPath release];
	[_transformerName release];
	[super dealloc];
}

//-- bingindItemFromSelector:valueClass:identifier:
//
+ (BindingItem*) bindingItemFromSelector : (SEL) selector
							  valueClass : (Class) valueClass
							   identifier: (NSString*) identifier
{
	return [[[BindingItem alloc] initWithSelector:selector
									   valueClass:valueClass
									   identifier:identifier] autorelease];
}

#pragma mark Interface
//-- infoForBinding
//
-(NSDictionary*) infoForBinding
{
	return [NSDictionary dictionaryWithObjectsAndKeys:
		_observedController,	NSObservedObjectKey,
		_observedKeyPath,	NSObservedKeyPathKey,
		[NSDictionary dictionaryWithObject:_transformerName forKey:@"NSValueTransformerName"], NSOptionsKey,
		nil];
}

//-- unbind
//
- (void) unbind
{
	[self setObservedController:nil];
	[self setObservedKeyPath:nil];
	[self setTransformerName:nil];
}

@end