text:
var PartyGame = require('./PartyGame.js');
var GLOBAL = require('../../global.js');
var LANG = require('../../language.js');
var util = require('../../utils.js');
var Cover = require('../../objects/Cover.js');
var Mouse = require('../../characters/agents/Mouse.js');

module.exports = PartyInvitationGame;

PartyInvitationGame.prototype = Object.create(PartyGame.prototype);
PartyInvitationGame.prototype.constructor = PartyInvitationGame;
function PartyInvitationGame () {
	PartyGame.call(this); // Call parent constructor.
}

// Right now only two rounds are used, and it is a 50% chance to get more than one.
// If you raise the max rounds, the percentage will be to the power of rounds (that is extra 1: 0.5, extra 2: 0.5^2, extra 3: 0.5^3...).
var maxCardRounds = 2;
var morePercentage = 0.5;
var difficultySpritePercentages = [[10, 90], [20, 80], [30, 70], [40, 60], [40, 50], [40, 40], [30, 30], [20, 20], [10, 10], [10, 0]];
var trollChance = 40;
var trollChanceAnother = 25;

PartyInvitationGame.prototype.pos = {
	helper1: { x: 580, y: 520 },
	helper2: { x: 370, y: 540 },
	troll: { x: 480, y: 650 },
	stack: { x: -30, y: 490, scale: 0.7 },
	arm: { x: 840, y: 540, scale: 1.4, angle: 45 },
	choices: [300, 500, 700], // NOTE: This is actually shuffled in code, do not rely on these positions.
	choiceY: 685
};

// Tell the PartyGame to create guests with these scales (see createGuests).
PartyInvitationGame.prototype.guestScales = [0.5, 0.4, 0.7, 0.2, 0.2];

PartyInvitationGame.prototype.preload = function () {
	PartyGame.prototype.preload.call(this);
	this.load.atlasJSONHash('invitation', 'img/partygames/invitationGame/atlas.png', 'img/partygames/invitationGame/atlas.json');
};

PartyInvitationGame.prototype.create = function () {
	// The invitation game uses helper1, it should be Panda or Mouse as backup.
	if (this.birthdayType === Mouse) {
		this.switchAgents();
	}

	PartyGame.prototype.create.call(this);

	this.troll.visible = true;
	this.troll.changeShape('stone');

	this.mailbox = this.gladeIntro.create(800, 360, 'glade', 'mailbox');

	this.gameGroup.create(0, 0, 'invitation', 'background');

	this.guestThought = this.add.group(this.gameGroup);
	this.guestThought.x = 740;
	this.guestThought.y = 110;
	this.guestThought.visible = false;
	var bubble = this.guestThought.create(-10, 5, 'objects', 'thought_bubble');
	bubble.anchor.set(0.5);
	bubble.scale.set(-1);
	bubble.angle = -30;
	this.thoughtGroup = this.add.group(this.guestThought); // This will be filled with the decor.

	this.stackHighlight = new Cover(this.game, 0x0000aa, 0);
	this.stackHighlight.x = this.pos.stack.x;
	this.stackHighlight.y = this.pos.stack.y;
	this.stackHighlight.anchor.set(0.5);
	this.stackHighlight.scale.x *= 0.45;
	this.stackHighlight.scale.y *= 0.45;
	this.stackHighlight.flash = TweenMax.to(this.stackHighlight, 0.8, { alpha: 0.3, ease: Power1.easeInOut, repeat: -1, yoyo: true, paused: true });
	this.gameGroup.add(this.stackHighlight);

	this.cardStack = this.add.group(this.gameGroup);
	this.cardStack.x = this.pos.stack.x;
	this.cardStack.y = this.pos.stack.y;

	this.choices = [];
	for (var i = 0; i < 3; i++) {
		var choice = new Tray(this.game, 0, this.world.height);
		choice.scale.set(0);
		choice.handle.events.onInputDown.add(this.pickDecor, this);
		this.gameGroup.add(choice);
		this.choices.push(choice);
	}

	this.arm = this.gameGroup.create(this.pos.arm.x, this.pos.arm.y, 'invitation', this.helper1 instanceof Mouse ? 'mousearm' : 'pandaarm');
	this.arm.anchor.y = 0.3;
	this.arm.angle = this.pos.arm.angle;
	this.arm.scale.set(this.pos.arm.scale);

	this.gladeIntro.parent.bringToTop(this.gladeIntro);
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                           Start round functions                           */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
/**
 * @param {Number} max - The max value of a number in the array.
 * @returns {Array} An array with 3 specific amounts.
 */
PartyInvitationGame.prototype.getAmounts = function (max) {
	var amountsArray = util.growingArray(1, max);
	this.rnd.shuffle(amountsArray);
	return amountsArray.splice(0, 3);
};

/**
 * @returns {Array} An array with 3 unspecific amounts (two many, one few, or vice versa).
 */
PartyInvitationGame.prototype.getAmountsMany = function () {
	var many = this.game.rnd.between(10, 20);
	var few = this.game.rnd.between(2, 3);

	return this.game.rnd.pick([[many, few, few], [few, many, many]]);
};

/**
 * Get the decor sprites to use. One sprite variant will be used if none of the percentages are fulfilled.
 * @param {Number} chanceTwo - The percentage (0-100) of two sprites.
 * @param {Number} chanceThree - The percentage (0-100) of three sprites.
 * @returns {Array} An array with three sprites.
 */
PartyInvitationGame.prototype.getSprites = function (chanceTwo, chanceThree) {
	chanceTwo += chanceThree;
	var chance = this.game.rnd.between(1, 100);
	var variants = chance <= chanceThree ? 3 : (chance <= chanceTwo ? 2 : 1);

	var sprites = this.rnd.shuffle(['decor1', 'decor2', 'decor3', 'decor4', 'decor5']);
	sprites.splice(variants);
	while (sprites.length < 3) {
		sprites.push(sprites[0]);
	}
	return sprites;
};

PartyInvitationGame.prototype.generateRound = function () {
	var pileType;
	if (this.difficulty < 4) {
		pileType = 'piles';
	} else if (this.difficulty < 6) {
		pileType = 'singles';
	} else if (this.difficulty < 8) {
		pileType = 'manyNumber';
	} else  {
		pileType = 'singleNumber';
	}

	var amounts;
	if (this.difficulty < 4) {
		amounts = this.getAmountsMany();
	} else {
		// NOTE: Difficulty can go up to ten.
		amounts = this.getAmounts(this.difficulty | 0); // "|" is a fast way to round down.
	}

	var sprites = this.getSprites.apply(this, difficultySpritePercentages[this.difficulty | 0]);

	var xPos = this.rnd.shuffle(this.pos.choices);

	for (var i = 0; i < this.choices.length; i++) {
		this.choices[i].setup(pileType, amounts[i], sprites[i], xPos[i]);
	}

	this.correctAmount = amounts[0];
	this.correctSprite = sprites[0];

	this.thoughtGroup.removeAll();
	for (i = 0; i < this.correctAmount; i++) {
		this.thoughtGroup.create(0, 0, 'invitation', this.correctSprite).anchor.set(0.5);
	}

	// Randomize position of the decor and make sure they do not overlap.
	for (i = 0; i < this.correctAmount; i++) {
		var decor = this.thoughtGroup.children[i];

		var angle = this.game.rnd.angle();
		decor.x = Math.cos(angle)*Math.random()*50;
		decor.y = Math.sin(angle)*Math.random()*50;

		if (this.correctAmount < 10) {
			for (var j = 0; j < i; j++) {
				if (decor.position.distance(this.thoughtGroup.children[j].position) < 30) {
					i--;
					break;
				}
			}
		}
	}
};

/** Set up new card for next round */
PartyInvitationGame.prototype.newCard = function () {
	this.playCard = new Card(this.game, this.game.width / 2, 395);
	this.playCard.scale.set(0);
	this.gameGroup.add(this.playCard);
	this.playCard.handle.events.onInputDown.add(this.pickDecor, this);
};

/** Set up new guest for next round */
PartyInvitationGame.prototype.newGuest = function () {
	this.guest = this.guests[this.cardStack.children.length];
	if (this.guest.name === LANG.TEXT.lizardName) {
		this.guest.x = this.game.width / 2 - 100;
		this.guest.y = 55;
	} else {
		this.guest.x = this.game.width / 2;
		this.guest.y = 75;
	}
	this.gameGroup.add(this.guest);
};

PartyInvitationGame.prototype.newRound = function (add) {
	this.generateRound();

	var t = new TimelineMax();

	if (!add) {
		this.moreDecor = 0;
		this.newCard();
		this.newGuest();

		var correct = this.choices[0];
		t.addSound(this.helper1.speech, this.helper1, correct.type === 'piles' ? (correct.decorGroup.length > 5 ? 'manyOfThese' : 'someOfThese') : 'thisManyOfThese', 0.3);
	}
	this.moreDecor++;

	t.add(util.fade(this.guest, true, 0.2), 0);
	t.add(util.fade(this.guestThought, true, 0.5), 0.5);
	t.add(util.popin(this.playCard, true, 0.5), 1);
	t.addCallback(this.slideChoices, 1.5, [true], this);
	return t;
};

PartyInvitationGame.prototype.slideChoices = function (into) {
	var t = new TimelineMax();
	for (var i = 0; i < this.choices.length; i++) {
		var choice = this.choices[i];
		t.add(TweenMax.to(choice, 0.5, { y: into ? this.pos.choiceY : this.world.height }), 0);
		t.add(TweenMax.to(choice.scale, 0.5, { x: into ? 1 : 0, y: into ? 1 : 0 }), 0);
	}
	return t;
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                             Troll functions                               */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
PartyInvitationGame.prototype.trolling = function (chance) {
	// Always return a timeline from this function.
	var t = new TimelineMax();

	// Randomize troll appearance.
	if (this.game.rnd.between(1, 100) <= chance) {
		var target = this.choices[this.rnd.integerInRange(1, 2)];
		t.add(this.troll.appear(target.x, this.pos.choiceY));

		if (Math.random() <= 0.5) {
			// Change places of two piles.
			var otherPile;
			do {
				otherPile = this.game.rnd.pick(this.choices);
			} while (target === otherPile);

			t.addLabel('changePlace');
			t.to(target, 1, { x: otherPile.x, ease: Power2.easeOut });
			t.to(otherPile, 1, { x: target.x, ease: Power2.easeOut }, 'changePlace');
		} else {
			// Change decor on one of the piles (not the correct one).
			t.addCallback(function () {
				var newName = target.decorGroup.children[0].frameName === 'decor5' ? 'decor3' : 'decor5';
				for (var i = 0; i < target.decorGroup.length; i++) {
					target.decorGroup.children[i].frameName = newName;
				}
			}, null, null, this);
		}

		t.addSound(this.helper1.speech, this.helper1, 'ohNo');
		t.addSound(this.helper1.speech, this.helper1, (Math.random() < 0.5 ? 'aBitWeird' : 'helpMeCorrect'));
	}
	return t;
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                    Picked pile and feedback functions                     */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
/** Run this function when picking up one of the piles. */
PartyInvitationGame.prototype.pickDecor = function (origin) {
	if (!this.playCard.decorGroup.length || this.game.input.activePointer.y < 550) {
		var choice = origin.parent;
		origin.events.onInputUp.add(this.dropDecor, this);
		this.gameGroup.bringToTop(choice);
		choice.follow(this.game.input.activePointer);
	}
};

/** Run this function when dropping one of the piles. */
PartyInvitationGame.prototype.dropDecor = function (origin) {
	origin.events.onInputUp.remove(this.dropDecor, this);

	var choice = origin.parent;
	choice.follow();

	if (this.game.input.activePointer.y < 550) {
		if (choice instanceof Tray) {
			this.playCard.transferFrom(choice);
			this.checkDecor();
		}
	} else {
		if (choice instanceof Card) {
			for (var i = 0; i < this.choices.length; i++) {
				if (!this.choices[i].decorGroup.length) {
					this.choices[i].transferFrom(choice);
					break;
				}
			}
		}
	}
};

/** Check if dropped decor is correct */
PartyInvitationGame.prototype.checkDecor = function () {
	if (this.checking) {
		this.checking.kill();
	}

	this.checking = new TimelineMax();
	if (this.playCard.decorGroup.children.length === this.correctAmount) { // Correct :)
		this.checking.addCallback(this.disable, null, [true], this);

		this.checking.add(util.fade(this.guestThought, false, 0.5), 0);
		this.checking.add(this.slideChoices(false), 0);

		var more = Math.random();
		if (this.moreDecor < maxCardRounds && more > Math.pow(morePercentage, this.moreDecor)) {
			// The card will get another round.
			this.playCard.stashDecor();

			this.checking.addSound(this.helper1.speech, this.helper1, 'rightButMore', 0);
			this.checking.addCallback(function () {
				this.guest.setNeutral();
				var t = this.newRound(true);
				t.add(this.trolling(trollChanceAnother));
				t.addCallback(this.disable, null, [false], this);
			}, null, null, this);

		} else {
			// We are done with this card!
			this.setupDragCard();

			this.checking.addCallback(this.guest.setHappy, null, null, this.guest);
			this.checking.addSound(this.helper1.speech, this.helper1, 'looksNice');
			this.checking.addCallback(this.disable, null, [false], this);
			this.checking.addSound(this.helper1.speech, this.helper1, 'dragCard');
		}

	} else if (this.playCard.decorGroup.children.length > this.correctAmount) { // Incorrect, too many.
		this.checking.addCallback(this.guest.setSad, null, null, this.guest);
		this.checking.addSound(this.helper1.speech, this.helper1, 'tryLess');
		this.checking.addSound(this.helper1.speech, this.helper1, 'dragStickersBack', '+=0.5');

	} else { // Incorrect, too few.
		this.checking.addCallback(this.guest.setSad, null, null, this.guest);
		this.checking.addSound(this.helper1.speech, this.helper1, 'tryMore');
		this.checking.addSound(this.helper1.speech, this.helper1, 'dragStickersBack', '+=0.5');
	}
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                  Card functions after decor is done                       */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
/** Setup the dragging of the card to the stack. */
PartyInvitationGame.prototype.setupDragCard = function () {
	this.playCard.parent.bringToTop(this.playCard);
	this.playCard.handle.events.destroy();
	this.playCard.handle.events.onInputDown.add(function () {
		this.playCard.update = function () {
			this.x = this.game.input.activePointer.x;
			this.y = this.game.input.activePointer.y;
		};
	}, this);
	this.playCard.handle.events.onInputUp.add(function () {
		this.playCard.update = function () {}; // Overwriting the follow.
		this.addCardToStack().addCallback(this.nextRound, null, null, this);
	}, this);

	this.stackHighlight.flash.play();
};

/** Add the finished card to stack. */
PartyInvitationGame.prototype.addCardToStack = function () {
	this.disable(true);
	this.stackHighlight.flash.pause(0);
	this.playCard.handle.events.destroy();

	var t = new TimelineMax();
	var offset = this.cardStack.length * 5;
	t.to(this.playCard, 1, { x: this.cardStack.x + offset, y: this.cardStack.y + offset, ease: Power0.easeInOut }, 0);
	t.to(this.playCard.scale, 1, { x: this.pos.stack.scale, y: this.pos.stack.scale, ease: Power0.easeInOut }, 0);
	t.addCallback(function () {
		this.cardStack.add(this.playCard);
		this.playCard.x = offset;
		this.playCard.y = offset;
	}, null, null, this);

	t.add(util.fade(this.guest, false, 0.5), 0);
	return t;
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                 Overshadowing Subgame mode functions                      */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
PartyInvitationGame.prototype.modeIntro = function () {
	var t = new TimelineMax();
	t.skippable();

	t.add(this.helper2.wave(1, -1));
	t.addSound(this.helper2.speech, this.helper2, 'hi', 0);
	t.addSound(this.helper2.speech, this.helper2, 'niceYoureHere', '+=0.5');
	if (this.birthdayType === Mouse) { // Special case for the speech to be correct.
		t.addSound(this.helper2.speech, this.helper2, 'soonBirthday', '+=1');
	} else {
		t.addSound(this.helper1.speech, this.helper1, 'soonBirthday', '+=1');
	}
	t.addSound(this.helper1.speech, this.helper1, 'wereHavingParty', '+=0.5');

	t.add(this.troll.transform('troll'), '+=1');
	t.addSound(this.sfx, null, 'pop', '-=1');

	t.addCallback(function () {
		this.helper1.eyesFollowObject(this.troll);
		this.helper2.eyesFollowObject(this.troll);
	}, null, null, this);

	t.addSound(this.troll.speech, this.troll, 'laugh');
	t.addSound(this.troll.speech, this.troll, 'iCanDo', '+=0.6');

	t.addCallback(function () {
		this.helper1.eyesFollowObject(this.troll.emitter);
		this.helper2.eyesFollowObject(this.troll.emitter);
	}, null, null, this);

	t.add(this.troll.swish(this.mailbox.x + 30, this.mailbox.y + 30));

	var bear = this.gladeIntro.create(this.mailbox.x, this.mailbox.y + 60, 'glade', 'decor5');
	bear.alpha = 0;
	bear.scale.set(1.5);

	t.addLabel('gone', '-=0.5');
	t.addLabel('gone2');
	t.addSound(this.sfx, null, 'pop', 'gone');
	t.add(new TweenMax(this.mailbox, 0.1, { alpha: 0 }), 'gone');
	t.add(new TweenMax(bear, 0.1, { alpha: 1 }), 'gone');
	t.to(this.troll.leftArm, 0.3, { rotation: -1.1, ease: Power4.easeIn });
	t.addSound(this.troll.speech, this.troll, 'oops1', 'gone2');

	t.addCallback(function () {
		this.helper1.eyesStopFollow();
		this.helper2.eyesStopFollow();
	}, null, null, this);
	t.addSound(this.troll.speech, this.troll, 'iNeedHelp', '+=0.5');

	t.addSound(this.helper1.speech, this.helper1, 'gottaInvite', '+=1');
	t.addLabel('maker');
	t.add(this.helper1.move({ x: '+=' + 170, y: '+=' + 20 }, 2), 'maker');
	t.addSound(this.helper1.speech, this.helper1, 'makeCards', 'maker');
	t.to(this.gladeIntro, 3.5, { x: -2700, y: -1800, ease: Power2.easeInOut }, 'maker');
	t.to(this.gladeIntro.scale, 3.5, { x: 4, y: 4, ease: Power2.easeInOut }, 'maker');

	t.add(util.fade(this.gladeIntro, false, 2));

	t.addCallback(function () {
		bear.destroy();

		this._counter.value++; // We run one card and because this part is in the intro, manually increase counter.

		this.gladeIntro.x = 0;
		this.gladeIntro.y = 0;
		this.gladeIntro.scale.set(1);

		this.troll.visible = false;
		this.troll.scale.set(0.22);
		this.gameGroup.add(this.troll);

		var t = new TimelineMax();
		t.skippable();
		t.addSound(this.helper1.speech, this.helper1, 'allGuestsGet');
		t.add(this.newRound(), '+=1');

		var correctPile = this.choices[0];
		this.gameGroup.bringToTop(correctPile);
		this.gameGroup.bringToTop(this.arm);

		t.to(this.arm, 3, { x: correctPile.x, y: this.pos.choiceY, ease: Power1.easeIn }); // Cannot go to choice y, since it is too low.
		t.addSound(this.helper1.speech, this.helper1, 'imTrying');
		t.addCallback(function () { correctPile.follow(this.arm); }, null, null, this);
		t.to(this.arm, 2, { x: this.playCard.x, y: this.playCard.y, ease: Power1.easeIn });
		t.addCallback(function () {
			this.playCard.transferFrom(correctPile);
			correctPile.follow();
			this.guest.setHappy();
		}, null, null, this);
		t.addSound(this.helper1.speech, this.helper1, 'looksNice');

		t.add(util.fade(this.guestThought, false, 0.5));
		t.add(this.slideChoices(false));

		t.addSound(this.helper1.speech, this.helper1, 'imPutting');
		t.addLabel('drag');
		t.add(this.addCardToStack());
		t.to(this.arm, 1, { x: this.cardStack.x, y: this.cardStack.y, ease: Power0.easeIn }, 'drag');
		t.to(this.arm, 2, { x: this.pos.arm.x, y: this.pos.arm.y, ease: Power1.easeIn });

		t.addCallback(function () {
			// Don't know why this is necessary, but otherwise the card will not go to the correct positions when skipping the instructions.
			this.playCard.x = 0;
			this.playCard.y = 0;
		}, null, null, this);

		t.addCallback(this.nextRound, null, null, this);
	}, null, null, this);
};

PartyInvitationGame.prototype.modePlayerDo = function (intro) {
	var t = new TimelineMax();
	t.add(this.newRound());

	if (intro) {
		t.addSound(this.helper1.speech, this.helper1, 'helpMeStickers', '+=0.5');
	} else {
		t.add(this.trolling(trollChance));
	}
	t.addCallback(this.disable, null, [false], this);
};

PartyInvitationGame.prototype.modeOutro = function () {
	var t = new TimelineMax();
	t.addSound(this.helper1.speech, this.helper1, 'madeNiceCards');
	t.to(this.arm, 2, { x: this.cardStack.x, y: this.cardStack.y, ease: Power1.easeIn });
	t.to([this.arm, this.cardStack], 1, { x: this.world.width, y: this.world.height + this.cardStack.height, ease: Power1.easeIn });
	t.add(this.troll.water(400, this));

	t.addCallback(function () {
		this.gameGroup.bringToTop(this.gladeIntro);

		this.helper1.x = this.pos.helper2.x;
		this.helper1.y = this.pos.helper2.y;
		this.helper1.scale.set(0.15);
		this.gladeIntro.add(this.helper1);

		this.troll.x = this.pos.helper1.x;
		this.troll.y = this.pos.helper1.y;
		this.troll.scale.set(0.12);
		this.gladeIntro.add(this.troll);

		this.troll.rightArm.add(this.cardStack);
		this.cardStack.x = this.troll.rightArm.width / 2;
		this.cardStack.y = 0;
		this.cardStack.scale.set(1);

		this.helper2.visible = false;
		this.mailbox.alpha = 1;
	}, null, null, this);
	t.add(util.fade(this.gladeIntro, true, 2));

	t.addSound(this.troll.speech, this.troll, 'isGood', '+=0.3');
	t.addCallback(this.troll.eyesFollowObject, null, [this.mailbox], this.troll);
	t.add(this.troll.move({ x: this.mailbox.x - 50, y: this.mailbox.y + 90, ease: Power0.easeNone }, 2));
	t.to(this.troll.rightArm, 0.8,  { rotation: -0.3, ease: Power1.easeIn });
	t.addCallback(function () { this.mailbox.frameName = 'mailbox_open'; }, null, null, this);
	t.to(this.cardStack.scale, 0.5, { x: 0, y: 0, ease: Power0.easeNone });
	t.to(this.troll.rightArm, 1, { rotation: 1.1, ease: Power1.easeIn});
	t.addCallback(function () {
		this.mailbox.frameName = 'mailbox';
		this.troll.eyesStopFollow();
	}, null, null, this);

	t.add(this.troll.move({ x: this.pos.helper1.x, y: this.pos.helper1.y, ease: Power0.easeNone }, 2));
	t.addSound(this.troll.speech, this.troll, 'continue', '-=1');
	t.addSound(this.helper1.speech, this.helper1, 'thanksForHelp', '+=0.5');

	t.addCallback(this.nextRound, null, null, this); // Ending game.
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                            Container object                               */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
Container.prototype = Object.create(Phaser.Group.prototype);
Container.prototype.constructor = Container;
function Container (game, x, y, handle, handleDecor) {
	Phaser.Group.call(this, game, null); // Parent constructor.
	this.x = x;
	this.y = y;

	this.handle = this.create(0, 0, handle, handleDecor);
	this.handle.inputEnabled = true;
	this.handle.anchor.set(0.5);

	this.decorGroup = this.game.add.group(this);
}

Container.prototype.transferFrom = function (container) {
	while (container.decorGroup.children.length) {
		this.decorGroup.add(container.decorGroup.children[0]);
	}
};

Container.prototype.follow = function (what) {
	this.decorGroup.x = 0;
	this.decorGroup.y = 0;

	if (!what) {
		this.decorGroup.update = function () {};
	} else {
		this.decorGroup.update = function () {
			this.x = what.x - this.parent.x;
			this.y = what.y - this.parent.y;
		};
	}
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                                Tray object                                */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
Tray.prototype = Object.create(Container.prototype);
Tray.prototype.constructor = Tray;
function Tray (game, x, y) {
	Container.call(this, game, x, y, 'invitation', 'tray'); // Parent constructor.
}

Tray.prototype.setup = function (type, amount, decor, xPos) {
	this.type = type;
	this.x = xPos;

	this.decorGroup.removeAll();
	for (var i = 0; i < amount; i++) {
		this.decorGroup.create(0, 0, 'invitation', decor).anchor.set(0.5);
	}
	this.decorPositions();
};

Tray.prototype.transferFrom = function (container) {
	Container.prototype.transferFrom.call(this, container);

	this.decorPositions();
};

Tray.prototype.decorPositions = function () {
	var i, j, decor, angle, radius;
	if (this.type === 'piles' || this.type === 'singles' || this.type === 'manyNumber') {
		for (i = 0; i < this.decorGroup.children.length; i++) {
			decor = this.decorGroup.children[i];
			angle = this.game.rnd.angle();
			radius = (this.handle.width - 60) / 2;
			decor.x = Math.cos(angle) * Math.random() * radius;
			decor.y = Math.sin(angle) * Math.random() * radius;

			if (this.decorGroup.children.length < 10) {
				for (j = 0; j < i; j++) {
					if (decor.position.distance(this.decorGroup.children[j].position) < 20) {
						i--;
						break;
					}
				}
			}
		}
	} else if (this.type === 'singleNumber') {
		for (i = 0; i < this.decorGroup.children.length; i++) {
			decor = this.decorGroup.children[i];
			decor.x = 0;
			decor.y = 0;
		}
	}

	if (this.nr) {
		this.nr.destroy();
	}
	if (this.type === 'manyNumber' || this.type === 'singleNumber') {
		this.nr = this.game.add.text(0, -87, this.decorGroup.children.length, { font: '30pt ' + GLOBAL.FONT });
		this.nr.anchor.set(0.5);
		this.add(this.nr);
		this.nr.sendToBack();
	}
};

/*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
/*                                Card object                                */
/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/
Card.prototype = Object.create(Container.prototype);
Card.prototype.constructor = Card;
function Card (game, x, y) {
	Container.call(this, game, x, y, 'invitation', 'card'); // Parent constructor.

	this.moreDecorGroup = this.game.add.group(this);
}

Card.prototype.transferFrom = function (container) {
	Container.prototype.transferFrom.call(this, container);

	for (var i = 0; i < this.decorGroup.children.length; i++) {
		var decor = this.decorGroup.children[i];
		decor.x = this.game.rnd.between(-150, 150);
		decor.y = this.game.rnd.between(-100, 100);

		var j;
		if (this.decorGroup.children.length < 10) {
			for (j = 0; j < i; j++) {
				if (decor.position.distance(this.decorGroup.children[j].position) < 40) {
					i--;
					break;
				}
			}
		}

		if (this.moreDecorGroup.length && (this.decorGroup.children.length + this.moreDecorGroup.children.length) < 20) {
			for (j = 0; j < i; j++) {
				if (decor.position.distance(this.decorGroup.children[j].position) < 30) {
					i--;
					break;
				}
			}
		}
	}
};

Card.prototype.stashDecor = function () {
	this.decorGroup.moveAll(this.moreDecorGroup);
};


text:
import BaseScene from './base'
import Composer from '../composer'
import Context from '../context'
import d from 'debug'
import { SessionContext } from '../session'
const debug = d('telegraf:scenes:context')

const noop = () => Promise.resolve()
const now = () => Math.floor(Date.now() / 1000)

export interface SceneContext<D extends SceneSessionData = SceneSessionData>
  extends Context {
  session: SceneSession<D>
  scene: SceneContextScene<SceneContext<D>, D>
}

export interface SceneSessionData {
  current?: string
  expires?: number
  state?: object
}

export interface SceneSession<S extends SceneSessionData = SceneSessionData> {
  __scenes: S
}

export interface SceneContextSceneOptions<D extends SceneSessionData> {
  ttl?: number
  default?: string
  defaultSession: D
}

export default class SceneContextScene<
  C extends SessionContext<SceneSession<D>>,
  D extends SceneSessionData = SceneSessionData
> {
  private readonly options: SceneContextSceneOptions<D>

  constructor(
    private readonly ctx: C,
    private readonly scenes: Map<string, BaseScene<C>>,
    options: Partial<SceneContextSceneOptions<D>>
  ) {
    // @ts-expect-error {} might not be assignable to D
    const fallbackSessionDefault: D = {}

    this.options = { defaultSession: fallbackSessionDefault, ...options }
  }

  get session(): D {
    const defaultSession = Object.assign({}, this.options.defaultSession)

    let session = this.ctx.session?.__scenes ?? defaultSession
    if (session.expires !== undefined && session.expires < now()) {
      session = defaultSession
    }
    if (this.ctx.session === undefined) {
      this.ctx.session = { __scenes: session }
    } else {
      this.ctx.session.__scenes = session
    }
    return session
  }

  get state() {
    return (this.session.state ??= {})
  }

  set state(value) {
    this.session.state = { ...value }
  }

  get current() {
    const sceneId = this.session.current ?? this.options.default
    return sceneId === undefined || !this.scenes.has(sceneId)
      ? undefined
      : this.scenes.get(sceneId)
  }

  reset() {
    if (this.ctx.session !== undefined)
      this.ctx.session.__scenes = Object.assign({}, this.options.defaultSession)
  }

  async enter(sceneId: string, initialState: object = {}, silent = false) {
    if (!this.scenes.has(sceneId)) {
      throw new Error(`Can't find scene: ${sceneId}`)
    }
    if (!silent) {
      await this.leave()
    }
    debug('Entering scene', sceneId, initialState, silent)
    this.session.current = sceneId
    this.state = initialState
    const ttl = this.current?.ttl ?? this.options.ttl
    if (ttl !== undefined) {
      this.session.expires = now() + ttl
    }
    if (this.current === undefined || silent) {
      return
    }
    const handler =
      'enterMiddleware' in this.current &&
      typeof this.current.enterMiddleware === 'function'
        ? this.current.enterMiddleware()
        : this.current.middleware()
    return await handler(this.ctx, noop)
  }

  reenter() {
    return this.session.current === undefined
      ? undefined
      : this.enter(this.session.current, this.state)
  }

  private leaving = false
  async leave() {
    if (this.leaving) return
    debug('Leaving scene')
    try {
      this.leaving = true
      if (this.current === undefined) {
        return
      }
      const handler =
        'leaveMiddleware' in this.current &&
        typeof this.current.leaveMiddleware === 'function'
          ? this.current.leaveMiddleware()
          : Composer.passThru()
      await handler(this.ctx, noop)
      return this.reset()
    } finally {
      this.leaving = false
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Skyhub\Resources;

class Freights extends \Skyhub\Marketplace {

	private $params;

	public function __construct($data) {
		$this->conf = $data->conf;
	}

	public function __set($var, $val) {

		if ($var=='saleSystems')
			$this->params['filters[sale_systems]'] = $val;
			return;

		$this->params[$this->fromCamelCase($var)] = $val;
	}

	public function get() {
		return $this->apiCall('GET', '/freights', $this->params);
	}

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;

//^ using Microsoft.Contracts;

namespace Microsoft.Cci.Ast {

  /// <summary>
  /// Represents a .NET assembly.
  /// </summary>
  public abstract class Assembly : Module, IAssembly {

    /// <summary>
    /// Allocates an object that represents a .NET assembly.
    /// </summary>
    /// <param name="name">The name of the unit.</param>
    /// <param name="location">An indication of the location where the unit is or will be stored. This need not be a file system path and may be empty.
    /// The interpretation depends on the IMetadataHost instance used to resolve references to this unit.</param>
    /// <param name="moduleName">The name of the module containing the assembly manifest. This can be different from the name of the assembly itself.</param>
    /// <param name="assemblyReferences">A list of the assemblies that are referenced by this module.</param>
    /// <param name="moduleReferences">A list of the modules that are referenced by this module.</param>
    /// <param name="resources">A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes.</param>
    /// <param name="files">
    /// A list of the files that constitute the assembly. These are not the source language files that may have been
    /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well
    /// as any external resources. It corresonds to the File table of the .NET assembly file format.
    /// </param>
    protected Assembly(IName name, string location, IName moduleName, IEnumerable<IAssemblyReference> assemblyReferences, IEnumerable<IModuleReference> moduleReferences,
      IEnumerable<IResourceReference> resources, IEnumerable<IFileReference> files)
      : base(name, location, Dummy.Assembly, assemblyReferences, moduleReferences) {
      this.moduleName = moduleName;
      this.resources = resources;
      this.files = files;
    }

    /// <summary>
    /// A list of aliases for the root namespace of the referenced assembly.
    /// </summary>
    public IEnumerable<IName> Aliases {
      get { return Enumerable<IName>.Empty; }
    }

    /// <summary>
    /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
    /// with this assembly.
    /// </summary>
    public IEnumerable<ICustomAttribute> AssemblyAttributes {
      get {
        if (this.assemblyAttributes == null) {
          var assemblyAttributes = this.GetAssemblyAttributes();
          assemblyAttributes.TrimExcess();
          this.assemblyAttributes = assemblyAttributes.AsReadOnly();
        }
        return this.assemblyAttributes;
      }
    }
    IEnumerable<ICustomAttribute> assemblyAttributes;

    /// <summary>
    /// The identity of the assembly.
    /// </summary>
    public AssemblyIdentity AssemblyIdentity {
      get {
        if (this.assemblyIdentity == null)
          this.assemblyIdentity = UnitHelper.GetAssemblyIdentity(this);
        return this.assemblyIdentity;
      }
    }
    AssemblyIdentity/*?*/ assemblyIdentity;

    /// <summary>
    /// The assembly that contains this module.
    /// </summary>
    public override IAssembly/*?*/ ContainingAssembly {
      get { return this; }
    }

    /// <summary>
    /// Identifies the culture associated with the assembly. Typically specified for sattelite assemblies with localized resources.
    /// Empty if not specified.
    /// </summary>
    public virtual string Culture {
      get { return string.Empty; }
    }

    /// <summary>
    /// Calls visitor.Visit(IAssembly).
    /// </summary>
    public override void Dispatch(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// Calls visitor.Visit(IAssemblyReference).
    /// </summary>
    public override void DispatchAsReference(IMetadataVisitor visitor) {
      visitor.Visit((IAssemblyReference)this);
    }

    /// <summary>
    /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly.
    /// </summary>
    public virtual IEnumerable<IAliasForType> ExportedTypes {
      get { return Enumerable<IAliasForType>.Empty; }
    }

    /// <summary>
    /// A list of the files that constitute the assembly. These are not the source language files that may have been
    /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well
    /// as any external resources. It corresonds to the File table of the .NET assembly file format.
    /// </summary>
    public IEnumerable<IFileReference> Files {
      get { return this.files; }
    }
    readonly IEnumerable<IFileReference> files;

    /// <summary>
    /// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set
    /// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform.
    /// </summary>
    public virtual uint Flags {
      get { return 0; } //TODO: get from options or an attribute
    }

    /// <summary>
    /// Returns a list of custom attributes that describes this type declaration member.
    /// Typically, these will be derived from this.SourceAttributes. However, some source attributes
    /// might instead be persisted as metadata bits and other custom attributes may be synthesized
    /// from information not provided in the form of source custom attributes.
    /// The list is not trimmed to size, since an override of this method may call the base method
    /// and then add more attributes.
    /// </summary>
    protected virtual List<ICustomAttribute> GetAssemblyAttributes() {
      List<ICustomAttribute> result = new List<ICustomAttribute>();
      bool sawTypeWithExtensions = false;
      this.UnitNamespaceRoot.FillInWithAssemblyAttributes(result, ref sawTypeWithExtensions);
      if (sawTypeWithExtensions) {
        var eattr = new Microsoft.Cci.MutableCodeModel.CustomAttribute();
        eattr.Constructor = this.Compilation.ExtensionAttributeCtor;
        result.Add(eattr);
      }
      return result;
    }

    /// <summary>
    /// The encrypted SHA1 hash of the persisted form of the referenced assembly.
    /// </summary>
    public IEnumerable<byte> HashValue {
      get { return Enumerable<byte>.Empty; }
    }

    /// <summary>
    /// True if the implementation of the referenced assembly used at runtime is not expected to match the version seen at compile time.
    /// </summary>
    public virtual bool IsRetargetable {
      get { return false; } //TODO: get from options or an attribute
    }

    /// <summary>
    /// The kind of metadata stored in the module. For example whether the module is an executable or a manifest resource file.
    /// </summary>
    public override ModuleKind Kind {
      get { return this.EntryPoint.ResolvedMethod is Dummy ? ModuleKind.DynamicallyLinkedLibrary : ModuleKind.ConsoleApplication; } //TODO: obtain it from the compiler options
    }

    /// <summary>
    /// A list of the modules that constitute the assembly.
    /// </summary>
    public IEnumerable<IModule> MemberModules {
      get { return Enumerable<IModule>.Empty; }
    }

    /// <summary>
    /// The identity of the module.
    /// </summary>
    public override ModuleIdentity ModuleIdentity {
      get { return this.AssemblyIdentity; }
    }

    /// <summary>
    /// The name of the module containing the assembly manifest. This can be different from the name of the assembly itself.
    /// </summary>
    public override IName ModuleName {
      get { return this.moduleName; }
    }
    readonly IName moduleName;

    /// <summary>
    /// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly . Empty if not specified.
    /// This value is used by the loader to decrypt HashValue which it then compares with a freshly computed hash value to verify the
    /// integrity of the assembly.
    /// </summary>
    public virtual IEnumerable<byte> PublicKey {
      get { return Enumerable<byte>.Empty; } //TODO: get this from an option or attribute
    }

    /// <summary>
    /// The hashed 8 bytes of the public key called public key token of the referenced assembly. This is non empty of the referenced assembly is strongly signed.
    /// </summary>
    public IEnumerable<byte> PublicKeyToken {
      get { return UnitHelper.ComputePublicKeyToken(this.PublicKey); }
    }

    /// <summary>
    /// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes.
    /// </summary>
    public IEnumerable<IResourceReference> Resources {
      get { return this.resources; }
    }
    readonly IEnumerable<IResourceReference> resources;

    /// <summary>
    /// A list of objects representing persisted instances of pairs of security actions and sets of security permissions.
    /// These apply by default to every method reachable from the module.
    /// </summary>
    public virtual IEnumerable<ISecurityAttribute> SecurityAttributes {
      get { return Enumerable<ISecurityAttribute>.Empty; } //TODO: compute this
    }

    /// <summary>
    /// The version of the assembly.
    /// </summary>
    public virtual Version Version {
      get { return new System.Version(0, 0, 0, 0); } //TODO: obtain from compiler options or custom attributes
    }

    #region IAssemblyReference Members

    IAssembly IAssemblyReference.ResolvedAssembly {
      get { return this; }
    }

    AssemblyIdentity IAssemblyReference.UnifiedAssemblyIdentity {
      get { return this.AssemblyIdentity; }
    }

    bool IAssemblyReference.ContainsForeignTypes {
      get { return false; }
    }

    #endregion

    #region IModuleReference Members

    IAssemblyReference/*?*/ IModuleReference.ContainingAssembly {
      get { return this; }
    }

    #endregion

  }

  /// <summary>
  /// A reference to a .NET assembly.
  /// </summary>
  public class ResolvedAssemblyReference : ResolvedModuleReference, IAssemblyReference {

    /// <summary>
    /// Allocates a reference to a .NET assembly.
    /// </summary>
    /// <param name="referencedAssembly">The assembly to reference.</param>
    public ResolvedAssemblyReference(IAssembly referencedAssembly)
      : base(referencedAssembly) {
      this.aliases = Enumerable<IName>.Empty;
    }

    /// <summary>
    /// A list of aliases for the root namespace of the referenced assembly.
    /// </summary>
    public IEnumerable<IName> Aliases {
      get { return this.aliases; }
    }
    IEnumerable<IName> aliases;

    /// <summary>
    /// The identity of the assembly reference.
    /// </summary>
    public AssemblyIdentity AssemblyIdentity {
      get { return this.ResolvedAssembly.AssemblyIdentity; }
    }

    /// <summary>
    /// Identifies the culture associated with the assembly reference. Typically specified for sattelite assemblies with localized resources.
    /// Empty if not specified.
    /// </summary>
    public string Culture {
      get { return this.ResolvedAssembly.Culture; }
    }

    /// <summary>
    /// Calls the visitor.Visit(IAssemblyReference) method.
    /// </summary>
    public override void Dispatch(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// Calls the visitor.Visit(IAssemblyReference) method.
    /// </summary>
    public override void DispatchAsReference(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// The encrypted SHA1 hash of the persisted form of the referenced assembly.
    /// </summary>
    public IEnumerable<byte> HashValue {
      get { return this.ResolvedAssembly.HashValue; }
    }

    /// <summary>
    /// True if the implementation of the referenced assembly used at runtime is not expected to match the version seen at compile time.
    /// </summary>
    public virtual bool IsRetargetable {
      get { return this.ResolvedAssembly.IsRetargetable; }
    }

    /// <summary>
    /// The public part of the key used to encrypt the SHA1 hash over the persisted form of the referenced assembly. Empty if not specified.
    /// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value
    /// in order to verify the integrity of the assembly.
    /// </summary>
    public IEnumerable<byte> PublicKey {
      get { return this.ResolvedAssembly.PublicKey; }
    }

    /// <summary>
    /// The hashed 8 bytes of the public key called public key token of the referenced assembly. This is non empty of the referenced assembly is strongly signed.
    /// </summary>
    public IEnumerable<byte> PublicKeyToken {
      get { return this.ResolvedAssembly.PublicKeyToken; }
    }

    /// <summary>
    /// The referenced assembly.
    /// </summary>
    public IAssembly ResolvedAssembly {
      get {
        IAssembly/*?*/ result = this.ResolvedUnit as IAssembly;
        //^ assume result != null; //The constructor + immutability guarantees this.
        return result;
      }
    }

    /// <summary>
    /// Returns the identity of the assembly reference to which this assembly reference has been unified.
    /// </summary>
    public AssemblyIdentity UnifiedAssemblyIdentity {
      get { return this.ResolvedAssembly.AssemblyIdentity; }
    }

    /// <summary>
    /// The identity of the unit reference.
    /// </summary>
    public override UnitIdentity UnitIdentity {
      get {
        return this.AssemblyIdentity;
      }
    }

    /// <summary>
    /// The version of the assembly reference.
    /// </summary>
    public Version Version {
      get { return this.ResolvedAssembly.Version; }
    }

    #region IAssemblyReference Members

    bool IAssemblyReference.ContainsForeignTypes {
      get { return false; }
    }

    #endregion

    #region IModuleReference Members

    IAssemblyReference/*?*/ IModuleReference.ContainingAssembly {
      get { return this; }
    }

    #endregion

  }

  /// <summary>
  /// An object that represents a .NET module.
  /// </summary>
  public abstract class Module : Unit, IModule {

    /// <summary>
    /// Allocates an object that represents a .NET module.
    /// </summary>
    /// <param name="name">The name of the unit.</param>
    /// <param name="location">An indication of the location where the unit is or will be stored. This need not be a file system path and may be empty.
    /// The interpretation depends on the ICompilationHostEnviroment instance used to resolve references to this unit.</param>
    /// <param name="containingAssembly">The assembly that contains this module.</param>
    /// <param name="assemblyReferences">A list of the assemblies that are referenced by this module.</param>
    /// <param name="moduleReferences">A list of the modules that are referenced by this module.</param>
    protected Module(IName name, string location, IAssembly containingAssembly, IEnumerable<IAssemblyReference> assemblyReferences, IEnumerable<IModuleReference> moduleReferences)
      : base(name, location) {
      this.containingAssembly = containingAssembly;
      this.assemblyReferences = assemblyReferences;
      this.moduleReferences = moduleReferences;
    }

    /// <summary>
    /// A list of the assemblies that are referenced by this module.
    /// </summary>
    public IEnumerable<IAssemblyReference> AssemblyReferences {
      get { return this.assemblyReferences; }
    }
    readonly IEnumerable<IAssemblyReference> assemblyReferences;

    /// <summary>
    /// The preferred memory address at which the module is to be loaded at runtime.
    /// </summary>
    public ulong BaseAddress {
      get { return 0x400000; } //TODO: allow this to be specified via a compilation flag
    }

    /// <summary>
    /// The assembly that contains this module.
    /// </summary>
    public virtual IAssembly/*?*/ ContainingAssembly {
      get { return this.containingAssembly; }
    }
    IAssembly containingAssembly;

    /// <summary>
    /// Returns a root namepace object that is language specific.
    /// </summary>
    /// <remarks>Most languages will probably just use the base method, but some languages may want to
    /// allocate a root namespace that has added behavior that, for example, helps with language specific name lookup rules.</remarks>
    protected virtual RootUnitNamespace CreateRootNamespace()
      //^ ensures result.RootOwner == this;
    {
      return new RootUnitNamespace(this.Compilation.NameTable.EmptyName, this);
    }

    /// <summary>
    /// Calls visitor.Visit(IModule).
    /// </summary>
    public override void Dispatch(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// Calls visitor.Visit(IModuleReference).
    /// </summary>
    public override void DispatchAsReference(IMetadataVisitor visitor) {
      visitor.Visit((IModuleReference)this);
    }

    /// <summary>
    /// A path to the debug information corresponding to this module. Can be absolute or relative to the file path of the module. Empty if not specified.
    /// </summary>
    public string DebugInformationLocation {
      get {
        return System.IO.Path.ChangeExtension(this.Location, "pdb");
      }
    }

    /// <summary>
    /// A hexadecimal string that is used to store and retrieve the debugging symbols from a symbol store.
    /// </summary>
    public string DebugInformationVersion {
      get {
        return string.Empty;
      }
    }

    /// <summary>
    /// Flags that control the behavior of the target operating system. CLI implementations are supposed to ignore this, but some operating system pay attention.
    /// </summary>
    public virtual ushort DllCharacteristics {
      get { return 0; } //TODO: provide compilation flag or attribute to control this
    }

    /// <summary>
    /// The method that will be called to start execution of this executable module.
    /// </summary>
    public abstract IMethodReference EntryPoint {
      get;
    }

    /// <summary>
    /// The alignment of sections in the module's image file.
    /// </summary>
    public virtual uint FileAlignment {
      get { return 512; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// Returns a list of custom attributes that describes this type declaration member.
    /// Typically, these will be derived from this.SourceAttributes. However, some source attributes
    /// might instead be persisted as metadata bits and other custom attributes may be synthesized
    /// from information not provided in the form of source custom attributes.
    /// The list is not trimmed to size, since an override of this method may call the base method
    /// and then add more attributes.
    /// </summary>
    protected override List<ICustomAttribute> GetAttributes() {
      List<ICustomAttribute> result = new List<ICustomAttribute>();
      this.UnitNamespaceRoot.FillInWithModuleAttributes(result);
      return result;
    }

    /// <summary>
    /// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents
    /// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a
    /// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a
    /// prefix of the user string heap when writing out a module as a PE file.
    /// </summary>
    public IEnumerable<string> GetStrings() {
      return Enumerable<string>.Empty;
    }

    /// <summary>
    /// Returns all of the types in the current module.
    /// </summary>
    public IEnumerable<INamedTypeDefinition> GetAllTypes() {
      if (this.allTypes == null) {
        List<INamedTypeDefinition> result = new List<INamedTypeDefinition>();
        result.Add(this.Compilation.ModuleClass);
        result.Add(this.Compilation.GlobalsClass);
        UnitNamespace.FillInWithTypes(this.UnitNamespaceRoot, result);
        this.allTypes = result.AsReadOnly();
      }
      return this.allTypes;
    }
    IEnumerable<INamedTypeDefinition>/*?*/ allTypes;

    /// <summary>
    /// True if the module contains only IL and is processor independent.
    /// </summary>
    public virtual bool ILOnly {
      get { return true; }
    }

    /// <summary>
    /// The kind of metadata stored in the module. For example whether the module is an executable or a manifest resource file.
    /// </summary>
    public virtual ModuleKind Kind {
      get { return ModuleKind.DynamicallyLinkedLibrary; }
    }

    /// <summary>
    /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 8 in 8.0.
    /// </summary>
    public virtual byte LinkerMajorVersion {
      get { return 6; }
    }

    /// <summary>
    /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 0 in 8.0.
    /// </summary>
    public virtual byte LinkerMinorVersion {
      get { return 0; }
    }

    /// <summary>
    /// Specifies the target CPU.
    /// </summary>
    public Machine Machine {
      get { return Machine.Unknown; } //TODO: get from compilation host
    }

    /// <summary>
    /// The first part of a two part version number indicating the version of the format used to persist this module. For example, the 1 in 1.0.
    /// </summary>
    public byte MetadataFormatMajorVersion {
      get { return this.metadataFormatMajorVersion; }
    }
    readonly byte metadataFormatMajorVersion = 2; //TODO: get from compilation host

    /// <summary>
    /// The second part of a two part version number indicating the version of the format used to persist this module. For example, the 0 in 1.0.
    /// </summary>
    public byte MetadataFormatMinorVersion {
      get { return this.metadataFormatMinorVersion; }
    }
    readonly byte metadataFormatMinorVersion = 0; //TODO: get from compilation host

    /// <summary>
    /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
    /// with this module.
    /// </summary>
    public IEnumerable<ICustomAttribute> ModuleAttributes {
      get { return this.attributes.AsReadOnly(); }
      //TODO: run through the namespaces and collect together all of their attributes that
      //specify their target to be a module
    }
    readonly List<ICustomAttribute> attributes = new List<ICustomAttribute>();

    /// <summary>
    /// The identity of the module.
    /// </summary>
    public abstract ModuleIdentity ModuleIdentity {
      get;
    }

    /// <summary>
    /// The name of the module. This can be different from the name if this module is also an assembly.
    /// </summary>
    public virtual IName ModuleName {
      get { return this.Name; }
    }

    /// <summary>
    /// A list of the modules that are referenced by this module.
    /// </summary>
    public IEnumerable<IModuleReference> ModuleReferences {
      get { return this.moduleReferences; }
    }
    readonly IEnumerable<IModuleReference> moduleReferences;

    /// <summary>
    /// If set, the module is platform independent but prefers to be loaded in a 32-bit process for performance reasons.
    /// </summary>
    public bool Prefers32bits {
      get { return false; }
    }

    /// <summary>
    /// A globally unique persistent identifier for this module.
    /// </summary>
    public Guid PersistentIdentifier {
      get { return this.persistentIdentifier; }
    }
    readonly Guid persistentIdentifier = Guid.NewGuid();

    /// <summary>
    /// If set, the module contains instructions or assumptions that are specific to the AMD 64 bit instruction set. Setting this flag to
    /// true also sets Requires64bits to true.
    /// </summary>
    public virtual bool RequiresAmdInstructionSet {
      get { return false; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// If set, the module contains instructions that assume a 32 bit instruction set. For example it may depend on an address being 32 bits.
    /// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop.
    /// </summary>
    public virtual bool Requires32bits {
      get { return false; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// If set, the module contains instructions that assume a 64 bit instruction set. For example it may depend on an address being 64 bits.
    /// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop.
    /// </summary>
    public virtual bool Requires64bits {
      get { return false; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// If set, the module must include a machine code stub that transfers control to the virtual execution system.
    /// </summary>
    public virtual bool RequiresStartupStub {
      get { return true; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The size of the virtual memory initially committed for the initial process heap.
    /// </summary>
    public virtual ulong SizeOfHeapCommit {
      get { return 0x1000; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The size of the virtual memory to reserve for the initial process heap.
    /// </summary>
    public virtual ulong SizeOfHeapReserve {
      get { return 0x100000; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The size of the virtual memory to reserve for the initial thread's stack.
    /// </summary>
    public virtual ulong SizeOfStackReserve {
      get { return 0x100000; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The size of the virtual memory initially committed for the initial thread's stack.
    /// </summary>
    public virtual ulong SizeOfStackCommit {
      get { return 0x1000; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// True if the module contains a hash of its contents, encrypted with the private key of an assembly strong name.
    /// </summary>
    public virtual bool StrongNameSigned {
      get { return false; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The first part of a two part version number indicating the operating subsystem that is expected to be the target environment for this module.
    /// </summary>
    public ushort SubsystemMajorVersion {
      get { return 4; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// The second part of a two part version number indicating the operating subsystem that is expected to be the target environment for this module.
    /// </summary>
    public ushort SubsystemMinorVersion {
      get { return 0; } //TODO: provide an option for setting this
    }

    /// <summary>
    /// Identifies the version of the CLR that is required to load this module or assembly.
    /// </summary>
    public string TargetRuntimeVersion {
      get {
        if (this.targetRuntimeVersion == null) {
          IModule/*?*/ mscorlib = TypeHelper.GetDefiningUnit(this.Compilation.PlatformType.SystemObject.ResolvedType) as IModule;
          if (mscorlib == null)
            this.targetRuntimeVersion = "bad target runtime";
          else
            this.targetRuntimeVersion = mscorlib.TargetRuntimeVersion;
        }
        return this.targetRuntimeVersion;
      }
    }
    string/*?*/ targetRuntimeVersion;

    /// <summary>
    /// True if the instructions in this module must be compiled in such a way that the debugging experience is not compromised.
    /// To set the value of this property, add an instance of System.Diagnostics.DebuggableAttribute to the MetadataAttributes list.
    /// </summary>
    public virtual bool TrackDebugData {
      get { return false; } //TODO: get this from an option or an attribute
    }

    /// <summary>
    /// The identity of the unit.
    /// </summary>
    public override UnitIdentity UnitIdentity {
      get { return this.ModuleIdentity; }
    }

    /// <summary>
    /// A root namespace that contains nested namespaces as well as top level types and anything else that implements INamespaceMember.
    /// </summary>
    public override RootUnitNamespace UnitNamespaceRoot {
      get {
        if (this.unitNamespaceRoot == null) {
          lock (GlobalLock.LockingObject) {
            if (this.unitNamespaceRoot == null) {
              RootUnitNamespace nsRoot = this.unitNamespaceRoot = this.CreateRootNamespace();
              foreach (CompilationPart compilationPart in this.Compilation.Parts)
                nsRoot.AddNamespaceDeclaration(compilationPart.RootNamespace);
            }
          }
        }
        return this.unitNamespaceRoot;
      }
    }
    RootUnitNamespace/*?*/ unitNamespaceRoot;
    //^ invariant this.unitNamespaceRoot == null || this.unitNamespaceRoot.RootOwner == this;

    /// <summary>
    /// A list of other units that are referenced by this unit.
    /// </summary>
    public override IEnumerable<IUnitReference> UnitReferences {
      get {
        foreach (IAssemblyReference assemblyReference in this.AssemblyReferences)
          yield return assemblyReference;
        foreach (IModuleReference moduleReference in this.ModuleReferences)
          yield return moduleReference;
      }
    }

    /// <summary>
    /// True if the module will be persisted with a list of assembly references that include only tokens derived from the public keys
    /// of the referenced assemblies, rather than with references that include the full public keys of referenced assemblies as well
    /// as hashes over the contents of the referenced assemblies. Setting this property to true is appropriate during development.
    /// When building for deployment it is safer to set this property to false.
    /// </summary>
    public virtual bool UsePublicKeyTokensForAssemblyReferences {
      get { return true; } //TODO: get the value from an option
    }

    /// <summary>
    /// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API.
    /// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools
    /// and not typically use the data in its own code.
    /// </summary>
    public IEnumerable<IWin32Resource> Win32Resources {
      get { return this.win32Resources.AsReadOnly(); }
    }
    readonly List<IWin32Resource> win32Resources = new List<IWin32Resource>();

    #region IModule Members

    IEnumerable<ITypeReference> IModule.GetTypeReferences() {
      return Enumerable<ITypeReference>.Empty;
    }

    IEnumerable<IGenericMethodInstanceReference> IModule.GetGenericMethodInstances() {
      return Enumerable<IGenericMethodInstanceReference>.Empty;
    }

    IEnumerable<ITypeReference> IModule.GetStructuralTypeInstances() {
      return Enumerable<ITypeReference>.Empty;
    }

    IEnumerable<ITypeMemberReference> IModule.GetStructuralTypeInstanceMembers() {
      return Enumerable<ITypeMemberReference>.Empty;
    }

    IEnumerable<ITypeMemberReference> IModule.GetTypeMemberReferences() {
      return Enumerable<ITypeMemberReference>.Empty;
    }

    #endregion

    #region IModuleReference Members

    IAssemblyReference/*?*/ IModuleReference.ContainingAssembly {
      get { return this.ContainingAssembly; }
    }

    IModule IModuleReference.ResolvedModule {
      get { return this; }
    }

    #endregion
  }

  /// <summary>
  /// A reference to a .NET module.
  /// </summary>
  public class ResolvedModuleReference : ResolvedUnitReference, IModuleReference {

    /// <summary>
    /// Allocates a reference to a .NET module.
    /// </summary>
    /// <param name="referencedModule">The module to reference.</param>
    internal ResolvedModuleReference(IModule referencedModule)
      : base(referencedModule) {
    }

    /// <summary>
    /// The Assembly that contains this module. May be null if the module is not part of an assembly.
    /// </summary>
    public IAssemblyReference/*?*/ ContainingAssembly {
      get { return this.ResolvedModule.ContainingAssembly; }
    }

    /// <summary>
    /// Calls the visitor.Visit(IModuleReference) method.
    /// </summary>
    public override void Dispatch(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// Calls the visitor.Visit(IModuleReference) method.
    /// </summary>
    public override void DispatchAsReference(IMetadataVisitor visitor) {
      visitor.Visit(this);
    }

    /// <summary>
    /// Returns the identity of the module reference.
    /// </summary>
    public ModuleIdentity ModuleIdentity {
      get { return this.ResolvedModule.ModuleIdentity; }
    }

    /// <summary>
    /// The referenced module.
    /// </summary>
    public IModule ResolvedModule {
      get {
        IModule/*?*/ result = this.ResolvedUnit as IModule;
        //^ assume result != null; //The constructor+immutability guarantees this.
        return result;
      }
    }

    /// <summary>
    /// The identity of the unit reference.
    /// </summary>
    public override UnitIdentity UnitIdentity {
      get { return this.ModuleIdentity; }
    }

  }

  /// <summary>
  /// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units.
  /// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers.
  /// </summary>
  public abstract class Unit : IUnit {

    /// <summary>
    /// Initializes a unit of metadata stored as a single artifact and potentially produced and revised independently from other units.
    /// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers.
    /// </summary>
    /// <param name="name">The name of the unit.</param>
    /// <param name="location">An indication of the location where the unit is or will be stored. This need not be a file system path and may be empty.
    /// The interpretation depends on the ICompilationHostEnviroment instance used to resolve references to this unit.</param>
    protected Unit(IName name, string location) {
      this.name = name;
      this.location = location;
    }

    /// <summary>
    /// The identity of the assembly corresponding to the target platform contract assembly at the time this unit was compiled.
    /// This property will be used to implement IMetadataHost.ContractAssemblySymbolicIdentity and its implementation must
    /// consequently not use the latter.
    /// </summary>
    public AssemblyIdentity ContractAssemblySymbolicIdentity {
      get {
        AssemblyIdentity/*?*/ result = null;
        foreach (IUnit unit in this.UnitReferences) {
          AssemblyIdentity contractId = unit.ContractAssemblySymbolicIdentity;
          if (contractId.Name.Value.Length == 0) continue;
          if (result == null || result.Version < contractId.Version) result = contractId;
        }
        if (result != null) return result;
        Assembly/*?*/ assem = this as Assembly;
        if (assem != null) {
          foreach (INamespaceMember member in assem.UnitNamespaceRoot.GetMembersNamed(this.NameTable.GetNameFor("Microsoft"), false)) {
            INestedUnitNamespace/*?*/ microsoft = member as INestedUnitNamespace;
            if (microsoft == null) continue;
            foreach (INamespaceMember mem in microsoft.GetMembersNamed(this.NameTable.GetNameFor("Contracts"), false)) {
              INestedUnitNamespace/*?*/ microsoftContracts = mem as INestedUnitNamespace;
              if (microsoftContracts == null) continue;
              foreach (INamespaceMember m in microsoftContracts.GetMembersNamed(this.NameTable.GetNameFor("Contract"), false)) {
                if (m is INamespaceTypeDefinition) return assem.AssemblyIdentity;
              }
            }
          }
        }
        return Dummy.Assembly.AssemblyIdentity;
      }
    }

    /// <summary>
    /// An assembly reference corresponding to the target platform core assembly at the time this unit was compiled.
    /// This property will be used to implement IMetadataHost.CoreAssemblySymbolicIdentity and its implementation must
    /// consequently not use the latter.
    /// </summary>
    public AssemblyIdentity CoreAssemblySymbolicIdentity {
      get {
        AssemblyIdentity/*?*/ result = null;
        foreach (IUnit unit in this.UnitReferences) {
          AssemblyIdentity coreId = unit.CoreAssemblySymbolicIdentity;
          if (coreId.Name.Value.Length == 0) continue;
          if (result == null || result.Version < coreId.Version) result = coreId;
        }
        if (result != null) return result;
        Assembly/*?*/ assem = this as Assembly;
        if (assem != null) {
          foreach (INamespaceMember member in assem.UnitNamespaceRoot.GetMembersNamed(this.NameTable.System, false)) {
            INestedUnitNamespace/*?*/ system = member as INestedUnitNamespace;
            if (system == null) continue;
            foreach (INamespaceMember mem in system.GetMembersNamed(this.NameTable.Object, false)) {
              if (mem is INamespaceTypeDefinition) return assem.AssemblyIdentity;
            }
          }
        }
        return Dummy.Assembly.AssemblyIdentity;
      }
    }

    /// <summary>
    /// The compilation that produces this unit of metadata.
    /// </summary>
    public abstract Compilation Compilation {
      get;
    }

    /// <summary>
    /// An indication of the location where the unit is or will be stored. This need not be a file system path and may be empty.
    /// The interpretation depends on the ICompilationHostEnviroment instance used to resolve references to unit.
    /// </summary>
    public string Location {
      get { return this.location; }
    }
    readonly string location;

    /// <summary>
    /// The name of the entity.
    /// </summary>
    public IName Name {
      get {
        return this.name;
        //TODO: if name is the empty name, then look for the main routine and use the name of the source file in which it appears.
        //otherwise just use the name of the first compilation part making up the compilation that resulted in this unit.
        //(Call an abstract helper to do that).
      }
    }
    IName name;

    /// <summary>
    /// A table used to intern strings used as names. This table is obtained from the host environment.
    /// It is mutuable, in as much as it is possible to add new names to the table.
    /// </summary>
    public INameTable NameTable {
      get { return this.Compilation.NameTable; }
    }

    /// <summary>
    /// A collection of well known types that must be part of every target platform and that are fundamental to modeling compiled code.
    /// The types are obtained by querying the unit set of the compilation and thus can include types that are defined by the compilation itself.
    /// </summary>
    public IPlatformType PlatformType {
      get { return this.Compilation.PlatformType; }
    }

    /// <summary>
    /// A root namespace that contains nested namespaces as well as top level types and anything else that implements INamespaceMember.
    /// </summary>
    public abstract RootUnitNamespace UnitNamespaceRoot {
      get;
      //^ ensures result.RootOwner == this;
    }

    /// <summary>
    /// A list of other units that are referenced by this unit.
    /// </summary>
    public abstract IEnumerable<IUnitReference> UnitReferences {
      get;
    }

    /// <summary>
    /// Calls visitor.Visit(IUnit).
    /// </summary>
    public abstract void Dispatch(IMetadataVisitor visitor);

    /// <summary>
    /// Calls visitor.Visit(IUnitReference).
    /// </summary>
    public abstract void DispatchAsReference(IMetadataVisitor visitor);

    /// <summary>
    /// Returns the identity of the unit reference.
    /// </summary>
    public abstract UnitIdentity UnitIdentity {
      get;
    }

    /// <summary>
    /// A sequence of PE sections that are not well known to PE readers and thus have not been decompiled into
    /// other parts of the Metadata Model. These sections may have meaning to other tools.
    /// </summary>
    public IEnumerable<IPESection> UninterpretedSections {
      get { return Enumerable<IPESection>.Empty; }
    }

    #region IUnit Members

    IRootUnitNamespace IUnit.UnitNamespaceRoot {
      get { return this.UnitNamespaceRoot; }
    }

    #endregion

    #region IUnitReference Members

    /// <summary>
    /// The referenced unit, or Dummy.Unit if the reference cannot be resolved.
    /// </summary>
    /// <value></value>
    public IUnit ResolvedUnit {
      get { return this; }
    }

    #endregion

    #region INamespaceRootOwner Members

    INamespaceDefinition INamespaceRootOwner.NamespaceRoot {
      get { return this.UnitNamespaceRoot; }
    }

    #endregion

    #region IReference Members

    /// <summary>
    /// A collection of metadata custom attributes that are associated with this definition.
    /// </summary>
    public IEnumerable<ICustomAttribute> Attributes {
      get {
        if (this.attributes == null) {
          var attributes = this.GetAttributes();
          attributes.TrimExcess();
          this.attributes = attributes.AsReadOnly();
        }
        return this.attributes;
      }
    }
    IEnumerable<ICustomAttribute>/*?*/ attributes;

    /// <summary>
    /// Returns a list of custom attributes that describes this type declaration member.
    /// Typically, these will be derived from this.SourceAttributes. However, some source attributes
    /// might instead be persisted as metadata bits and other custom attributes may be synthesized
    /// from information not provided in the form of source custom attributes.
    /// The list is not trimmed to size, since an override of this method may call the base method
    /// and then add more attributes.
    /// </summary>
    protected virtual List<ICustomAttribute> GetAttributes() {
      List<ICustomAttribute> result = new List<ICustomAttribute>();
      return result;
    }

    /// <summary>
    /// A potentially empty collection of locations that correspond to this instance.
    /// </summary>
    /// <value></value>
    public IEnumerable<ILocation> Locations {
      get {
        foreach (CompilationPart compilationPart in this.Compilation.Parts)
          yield return compilationPart.SourceLocation;
      }
    }

    #endregion

  }

  /// <summary>
  /// A reference to a instance of <see cref="IUnit"/>.
  /// </summary>
  public abstract class ResolvedUnitReference : IUnitReference {

    /// <summary>
    /// Initializes a reference to a instance of <see cref="IUnit"/>.
    /// </summary>
    /// <param name="referencedUnit">The unit to reference.</param>
    internal ResolvedUnitReference(IUnit referencedUnit)
      // ^ ensures this.ResolvedUnit == referencedUnit; //Spec# problem with delayed receiver
    {
      this.resolvedUnit = referencedUnit;
    }

    /// <summary>
    /// A collection of metadata custom attributes that are associated with this definition.
    /// </summary>
    public IEnumerable<ICustomAttribute> Attributes {
      get { return Enumerable<ICustomAttribute>.Empty; }
    }

    /// <summary>
    /// Calls visitor.Visit(IUnitReference).
    /// </summary>
    public abstract void Dispatch(IMetadataVisitor visitor);

    /// <summary>
    /// Calls visitor.Visit(IUnitReference).
    /// </summary>
    public abstract void DispatchAsReference(IMetadataVisitor visitor);

    /// <summary>
    /// A potentially empty collection of locations that correspond to this IReference instance.
    /// </summary>
    public IEnumerable<ILocation> Locations {
      get { return Enumerable<ILocation>.Empty; }
    }

    /// <summary>
    /// The name of the unit.
    /// </summary>
    public IName Name {
      get { return this.UnitIdentity.Name; }
    }

    /// <summary>
    /// The referenced unit.
    /// </summary>
    public IUnit ResolvedUnit {
      get {
        return this.resolvedUnit;
      }
    }
    readonly IUnit resolvedUnit;

    /// <summary>
    /// The identity of the unit reference.
    /// </summary>
    public abstract UnitIdentity UnitIdentity {
      get;
    }

  }

}


text:
soco.services module
====================

.. automodule:: soco.services


text:
#include "widget.hpp"
#include <cppdevtk/base/logger.hpp>
#include <cppdevtk/base/cassert.hpp>
#include <cppdevtk/base/verify.h>
#include <cppdevtk/base/dbc.hpp>
#include <cppdevtk/base/info_tr.hpp>

#include <QtGui/QIcon>
#include <QtCore/QDir>

#define CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY 0

namespace cppdevtk {
namespace test_disk_space_widget {

Widget::Widget(QWidget* pParent): QWidget(pParent), WidgetBase(), Ui::Widget() {
	CPPDEVTK_LOG_TRACE_FUNCTION();

	setupUi(this);

	SetStyleSheetFromFileCross(":/cppdevtk/test_disk_space_widget/res/qss", "widget");
	setWindowIcon(QIcon(":/cppdevtk/test_disk_space_widget/res/ico/application.ico"));

	pDiskSpaceWidget_->SetDiskNameColor(Qt::darkRed);
	pDiskSpaceWidget_->SetSpaceInfoColor(Qt::darkBlue);
	pDiskSpaceWidget_->SetBold(true);
#	if (!CPPDEVTK_DETAIL_TEST_DISK_SPACE_WIDGET_PATH_EMPTY)
	const QString kPath = QDir::currentPath();
	CPPDEVTK_LOG_DEBUG("setting path to: " << kPath);
	pDiskSpaceWidget_->SetPath(kPath);
#	endif

	pSpinBoxAutoRefreshInterval_->setValue(pDiskSpaceWidget_->GetAutoRefreshInterval());

	CPPDEVTK_VERIFY(connect(pPushButtonRefresh_, SIGNAL(clicked()),
			pDiskSpaceWidget_, SLOT(Refresh())));
	CPPDEVTK_VERIFY(connect(pGroupBoxAutoRefresh_, SIGNAL(toggled(bool)),
			pDiskSpaceWidget_, SLOT(SetAutoRefreshEnabled(bool))));
	CPPDEVTK_VERIFY(connect(pSpinBoxAutoRefreshInterval_, SIGNAL(valueChanged(int)),
			SLOT(SetAutoRefreshInterval(int))));

	adjustSize();
}

Widget::~Widget() {
	CPPDEVTK_LOG_TRACE_FUNCTION();
}

void Widget::SetAutoRefreshInterval(int sec) {
	pDiskSpaceWidget_->SetAutoRefreshInterval(sec);
}

void Widget::changeEvent(QEvent* pEvent) {
	CPPDEVTK_DBC_CHECK_NON_NULL_ARGUMENT(pEvent);

	QWidget::changeEvent(pEvent);
	switch (pEvent->type()) {
		case QEvent::LanguageChange:
			retranslateUi(this);
			break;
		default:
			break;
	}
}

}	// namespace test_disk_space_widget
}	// namespace cppdevtk


text:
\hypertarget{struct_mesh}{\section{Mesh Struct Reference}
\label{struct_mesh}\index{Mesh@{Mesh}}
}
\subsection*{Public Types}
\begin{DoxyCompactItemize}
\item
typedef std\+::vector$<$ \hyperlink{struct_group}{Group} $>$ \hyperlink{struct_mesh_aac2eabb5152e121bbb4b1652afe568a0}{Group\+Array}
\end{DoxyCompactItemize}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
void \hyperlink{struct_mesh_a59a2c14a5dfd063dd579261b4ea2359a}{load} (bx\+::\+Reader\+Seeker\+I $\ast$\+\_\+reader)
\item
void \hyperlink{struct_mesh_ad85261cc7c136eb6feb3078de1462c18}{unload} ()
\item
void \hyperlink{struct_mesh_a565eb4332bbc51daf34ef88651caf593}{submit} (uint8\+\_\+t \+\_\+id, bgfx\+::\+Program\+Handle \+\_\+program, float $\ast$\+\_\+mtx, uint64\+\_\+t \+\_\+state)
\end{DoxyCompactItemize}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
bgfx\+::\+Vertex\+Decl \hyperlink{struct_mesh_ad8168b5956620ef2e61a6cc4889d8b55}{m\+\_\+decl}
\item
\hyperlink{struct_mesh_aac2eabb5152e121bbb4b1652afe568a0}{Group\+Array} \hyperlink{struct_mesh_abcfb049a965b104931860b2fd844dfcf}{m\+\_\+groups}
\end{DoxyCompactItemize}

\subsection{Detailed Description}

Definition at line 267 of file bgfx\+\_\+utils.\+cpp.

\subsection{Member Typedef Documentation}
\hypertarget{struct_mesh_aac2eabb5152e121bbb4b1652afe568a0}{\index{Mesh@{Mesh}!Group\+Array@{Group\+Array}}
\index{Group\+Array@{Group\+Array}!Mesh@{Mesh}}
\subsubsection[{Group\+Array}]{\setlength{\rightskip}{0pt plus 5cm}typedef std\+::vector$<${\bf Group}$>$ {\bf Mesh\+::\+Group\+Array}}}\label{struct_mesh_aac2eabb5152e121bbb4b1652afe568a0}

Definition at line 398 of file bgfx\+\_\+utils.\+cpp.

\subsection{Member Function Documentation}
\hypertarget{struct_mesh_a59a2c14a5dfd063dd579261b4ea2359a}{\index{Mesh@{Mesh}!load@{load}}
\index{load@{load}!Mesh@{Mesh}}
\subsubsection[{load}]{\setlength{\rightskip}{0pt plus 5cm}void Mesh\+::load (
\begin{DoxyParamCaption}
\item[{bx\+::\+Reader\+Seeker\+I $\ast$}]{\+\_\+reader}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_mesh_a59a2c14a5dfd063dd579261b4ea2359a}

Definition at line 269 of file bgfx\+\_\+utils.\+cpp.

\hypertarget{struct_mesh_a565eb4332bbc51daf34ef88651caf593}{\index{Mesh@{Mesh}!submit@{submit}}
\index{submit@{submit}!Mesh@{Mesh}}
\subsubsection[{submit}]{\setlength{\rightskip}{0pt plus 5cm}void Mesh\+::submit (
\begin{DoxyParamCaption}
\item[{uint8\+\_\+t}]{\+\_\+id, }
\item[{bgfx\+::\+Program\+Handle}]{\+\_\+program, }
\item[{float $\ast$}]{\+\_\+mtx, }
\item[{uint64\+\_\+t}]{\+\_\+state}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_mesh_a565eb4332bbc51daf34ef88651caf593}

Definition at line 369 of file bgfx\+\_\+utils.\+cpp.

\hypertarget{struct_mesh_ad85261cc7c136eb6feb3078de1462c18}{\index{Mesh@{Mesh}!unload@{unload}}
\index{unload@{unload}!Mesh@{Mesh}}
\subsubsection[{unload}]{\setlength{\rightskip}{0pt plus 5cm}void Mesh\+::unload (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_mesh_ad85261cc7c136eb6feb3078de1462c18}

Definition at line 354 of file bgfx\+\_\+utils.\+cpp.

\subsection{Member Data Documentation}
\hypertarget{struct_mesh_ad8168b5956620ef2e61a6cc4889d8b55}{\index{Mesh@{Mesh}!m\+\_\+decl@{m\+\_\+decl}}
\index{m\+\_\+decl@{m\+\_\+decl}!Mesh@{Mesh}}
\subsubsection[{m\+\_\+decl}]{\setlength{\rightskip}{0pt plus 5cm}bgfx\+::\+Vertex\+Decl Mesh\+::m\+\_\+decl}}\label{struct_mesh_ad8168b5956620ef2e61a6cc4889d8b55}

Definition at line 397 of file bgfx\+\_\+utils.\+cpp.

\hypertarget{struct_mesh_abcfb049a965b104931860b2fd844dfcf}{\index{Mesh@{Mesh}!m\+\_\+groups@{m\+\_\+groups}}
\index{m\+\_\+groups@{m\+\_\+groups}!Mesh@{Mesh}}
\subsubsection[{m\+\_\+groups}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Group\+Array} Mesh\+::m\+\_\+groups}}\label{struct_mesh_abcfb049a965b104931860b2fd844dfcf}

Definition at line 399 of file bgfx\+\_\+utils.\+cpp.

The documentation for this struct was generated from the following file\+:\begin{DoxyCompactItemize}
\item
/mnt/windows/data/programming/crapengine2/source/video/include/bgfx/\hyperlink{bgfx__utils_8cpp}{bgfx\+\_\+utils.\+cpp}\end{DoxyCompactItemize}


text:
using System;
using System.Collections.Generic;

using UML = TSF.UmlToolingFramework.UML;

namespace TSF.UmlToolingFramework.Wrappers.EA
{
    public class ParameterReturnType : Parameter
    {

        internal global::EA.Method wrappedOperation
        {
            get { return this._owner.wrappedOperation; }
        }

        internal Operation _owner;

        public ParameterReturnType(Model model, Operation operation)
          : base(model)
        {
            this._owner = operation;
            this.isDirty = true;
        }

        public override UML.Classes.Kernel.ParameterDirectionKind direction
        {
            get { return UML.Classes.Kernel.ParameterDirectionKind._return; }
            set { throw new NotImplementedException(); }
        }

        public override String _default
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        #region implemented abstract members of Parameter
        public override uint position
        {
            get
            {
                return 0;
            }
            set
            {
                //do nothing. position has no meaning in the return type
            }
        }
        #endregion
        public override UML.Classes.Kernel.ValueSpecification defaultValue
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override bool isOrdered
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override bool isUnique
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        public override UML.Classes.Kernel.Multiplicity multiplicity
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        public override UML.Classes.Kernel.UnlimitedNatural upper
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override uint lower
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override UML.Classes.Kernel.ValueSpecification upperValue
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
        public override UML.Classes.Kernel.ValueSpecification lowerValue
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override UML.Classes.Kernel.Type type
        {
            get
            {
                // for some strange reason the classifierid of the parameter is a
                // string, where all other id the the EA API are integers.
                int ClassifierID;
                UML.Classes.Kernel.Type type = null;
                if (int.TryParse(this.wrappedOperation.ClassifierID, out ClassifierID))
                {
                    type = this.EAModel.getElementWrapperByID(ClassifierID) as UML.Classes.Kernel.Type;
                }
                // check if the type is defined as an element in the model.
                if (type == null)
                {
                    // no element, create primitive type based on the name of the
                    // returntype
                    type = this.EAModel.factory.createPrimitiveType
                      (this.wrappedOperation.ReturnType);
                }
                return type;
            }
            set { throw new NotImplementedException(); }
        }

        public override String name
        {
            get { return "returntype of " + this.operation.name; }
            set { throw new NotImplementedException(); }
        }
        public override UML.Classes.Kernel.VisibilityKind visibility
        {
            get { return this._owner.visibility; }
            set { throw new NotImplementedException(); }
        }

        public override String qualifiedName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override UML.Classes.Kernel.Namespace owningNamespace
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override HashSet<UML.Classes.Kernel.Element> ownedElements
        {
            get { return new HashSet<UML.Classes.Kernel.Element>(); }
            set { /* do nothing */ }
        }

        public override UML.Classes.Kernel.Element owner
        {
            get { return this._owner; }
            set { throw new NotImplementedException(); }
        }

        public override HashSet<UML.Profiles.Stereotype> stereotypes
        {
            get { return new HashSet<UML.Profiles.Stereotype>(); }
            set { /* do nothing, no stereotypes on return types */ }
        }

        // save the return type to the case tool.
        // this return type is implemented as a primitive or as a parameter in EA
        internal override void saveElement()
        {
            // saving the parent operation saves the parameters as well.
            // now we don't have to worry wether this returntype is modelled in EA
            // as a parameter or as the type of the operation.
            this._owner.saveElement();
        }

        public override String notes
        {
            get { return String.Empty; }
            set { /* do nothing, returntypes do not have comments in EA */ }
        }

        public override TSF.UmlToolingFramework.UML.Extended.UMLItem getItemFromRelativePath(List<string> relativePath)
        {
            return null;
        }

        internal override global::EA.Collection eaTaggedValuesCollection
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public override string guid
        {
            get
            {

                //the return type doesn't have a guid, so we return closest thing, the guid of the operation
                return this.wrappedOperation.MethodGUID;
            }
        }

        #region implemented abstract members of Element

        public override void deleteOwnedElement(Element ownedElement)
        {
            throw new NotImplementedException();
        }

        public override bool makeWritable(bool overrideLocks)
        {
            return this.owner.makeWritable(overrideLocks);
        }

        public override string getLockedUser()
        {
            return this._owner.getLockedUser();
        }

        public override string getLockedUserID()
        {
            return this._owner.getLockedUserID();
        }

        #endregion

        #region implemented abstract members of Element

        protected override string getTaggedValueQuery(string taggedValueName)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


text:
var between = require('../').between;

module.exports = function(op, a, b) {
    var res = op(a, b);

    return !res || between(res, a, b);
};


text:
<?php
require_once(dirname(dirname(dirname(__FILE__))).'/OAuthModule.php');

class TwitterAuthenticationModule extends OAuthAuthenticationModule
{
	protected $userCredentialsClass = 'TwitterUserCredentials';

	public function __construct($oAuthConsumerKey, $oAuthConsumerSecret)
	{
		parent::__construct(
			'Twitter',
			'http://api.twitter.com',
			$oAuthConsumerKey,
			$oAuthConsumerSecret,
			'https://api.twitter.com/oauth/request_token',
			'https://api.twitter.com/oauth/access_token',
			'https://api.twitter.com/oauth/authenticate',
			array('HMAC-SHA1'),
			'http://api.twitter.com',
			UserConfig::$USERSROOTURL.'/modules/twitter/login-button.png',
			UserConfig::$USERSROOTURL.'/modules/twitter/login-button.png',
			UserConfig::$USERSROOTURL.'/modules/twitter/login-button.png',
			array(
				array(4001, "Logged in using Twitter account", 1),
				array(4002, "Added Twitter account", 1),
				array(4003, "Removed Twitter account", 0),
				array(4004, "Registered using Twitter account", 1),
			)
		);
	}

	public function getID()
	{
		return "twitter";
	}

	public function getLegendColor()
	{
		return "60bddc";
	}

	public function getTitle()
	{
		return "Twitter";
	}

	public function getIdentity($oauth_user_id) {
		// get twitter handle
		#$request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.xml', 'GET');
		$request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.json', 'GET');
		$result = $request->doRequest($oauth_user_id);

		if ($result['code'] == 200) {
			$data = json_decode($result['body'], true);
			if (is_null($data)) {
				switch(json_last_error())
				{
					case JSON_ERROR_DEPTH:
						error_log('JSON Error: Maximum stack depth exceeded');
					break;
					case JSON_ERROR_CTRL_CHAR:
						error_log('JSON Error: Unexpected control character found');
					break;
					case JSON_ERROR_SYNTAX:
						error_log('JSON Error: Syntax error, malformed JSON');
					break;
					case JSON_ERROR_NONE:
						error_log('JSON Error: No errors');
					break;
				}

				return null;
			}

			if (!is_null($data) && array_key_exists('id', $data) && array_key_exists('name', $data)) {
				return $data;
			}
		}

		return null;
	}

	protected function renderUserInfo($serialized_userinfo) {
		$user_info = unserialize($serialized_userinfo);
		?><a href="http://twitter.com/<?php echo UserTools::escape($user_info['screen_name']); ?>" target="_blank">@<?php echo UserTools::escape($user_info['screen_name']); ?>

		<a href="http://twitter.com/<?php echo UserTools::escape($user_info['screen_name']); ?>" target="_blank"><img src="<?php echo UserTools::escape($user_info['profile_image_url']); ?>" title="<?php echo UserTools::escape($user_info['name']); ?> (@<?php echo UserTools::escape($user_info['screen_name']); ?>)" style="max-width: 60px; max-height: 60px"/>
		<?php
	}
}

class TwitterUserCredentials extends OAuthUserCredentials {
	public function getHTML() {
		return 'userinfo['screen_name']).'" target="_blank">@'.$this->userinfo['screen_name'].'';
	}
}