<commit_before>'use strict';

treeherder.directive('personaButtons', [
    '$http', '$q', '$log', '$rootScope',
    'thServiceDomain', 'BrowserId', 'ThUserModel', 'thNotify',
    function(
        $http, $q, $log, $rootScope, thServiceDomain,
        BrowserId, ThUserModel, thNotify) {

        return {
            restrict: "E",
            link: function(scope, element, attrs) {
                scope.initialized = ThUserModel.get().then(function(user){
                    $rootScope.user = {};
                    // if the user.email value is null, it means that he's not logged in
                    $rootScope.user.email = user.email || null;
                    $rootScope.user.loggedin = $rootScope.user.email !== null;

                    if ($rootScope.user.loggedin) {
                        angular.extend($rootScope.user, user);
                    }
                }).then(function(){
                    navigator.id.watch({
                        /*
                         * loggedinUser is all that we know about the user before
                         * the interaction with persona. This value could come from a cookie to persist the authentication
                         * among page reloads. If the value is null, the user is considered logged out.
                         */
                        loggedInUser: $rootScope.user.email,
                        /*
                         * We need a watch call to interact with persona.
                         * onLogin is called when persona provides an assertion
                         * This is the only way we can know the assertion from persona,
                         * so we resolve BrowserId.requestDeferred with the assertion retrieved
                         */
                        onlogin: function(assertion){
                            if (BrowserId.requestDeferred) {
                                BrowserId.requestDeferred.resolve(assertion);
                            }
                        },
                        /*
                         * Resolve BrowserId.logoutDeferred once the user is logged out from persona
                         */
                        onlogout: function(){
                            if (BrowserId.logoutDeferred) {
                                BrowserId.logoutDeferred.resolve();
                            }
                        }
                    });
                });

                scope.login = function(){
                    /*
                     * BrowserID.login returns a promise of the verification.
                     * If successful, we will find the user email in the response
                     */
                    scope.initialized.then(function(){
                        BrowserId.login()
                            .then(function(response){
                                $rootScope.user.loggedin = true;
                                $rootScope.user.email = response.data.email;
                                // retrieve the current user's info from the api
                                ThUserModel.get().then(function(user){
                                    angular.extend($rootScope.user, user);
                                }, null);
                            },function(response){
                                var message = "Login failed: " + response.status + " " + response.statusText;
                                thNotify.send(message, "danger", true);

                                // logout if the verification failed
                                scope.logout();
                            });
                    });
                };
                scope.logout = function(){
                    scope.initialized.then(function(){
                        BrowserId.logout().then(function(response){
                            $rootScope.user = {loggedin: false, email:null};
                        });
                    });
                };
            },
            templateUrl: 'partials/main/persona_buttons.html'
        };
    }]);
<commit_msg>Bug 1197550 - Fix csrf token validation on first persona login<commit_after>'use strict';

treeherder.directive('personaButtons', [
    '$http', '$q', '$log', '$rootScope',
    'thServiceDomain', 'BrowserId', 'ThUserModel', 'thNotify',
    function(
        $http, $q, $log, $rootScope, thServiceDomain,
        BrowserId, ThUserModel, thNotify) {

        return {
            restrict: "E",
            link: function(scope, element, attrs) {
                scope.initialized = $q.all([
                    ThUserModel.get().then(function(user){
                        $rootScope.user = {};
                        // if the user.email value is null, it means that he's not logged in
                        $rootScope.user.email = user.email || null;
                        $rootScope.user.loggedin = $rootScope.user.email !== null;

                        if ($rootScope.user.loggedin) {
                            angular.extend($rootScope.user, user);
                        }
                    }),
                    $http.get('/browserid/csrf/')
                ]).then(function(){
                    navigator.id.watch({
                        /*
                         * loggedinUser is all that we know about the user before
                         * the interaction with persona. This value could come from a cookie to persist the authentication
                         * among page reloads. If the value is null, the user is considered logged out.
                         */
                        loggedInUser: $rootScope.user.email,
                        /*
                         * We need a watch call to interact with persona.
                         * onLogin is called when persona provides an assertion
                         * This is the only way we can know the assertion from persona,
                         * so we resolve BrowserId.requestDeferred with the assertion retrieved
                         */
                        onlogin: function(assertion){
                            if (BrowserId.requestDeferred) {
                                BrowserId.requestDeferred.resolve(assertion);
                            }
                        },
                        /*
                         * Resolve BrowserId.logoutDeferred once the user is logged out from persona
                         */
                        onlogout: function(){
                            if (BrowserId.logoutDeferred) {
                                BrowserId.logoutDeferred.resolve();
                            }
                        }
                    });
                });

                scope.login = function(){
                    /*
                     * BrowserID.login returns a promise of the verification.
                     * If successful, we will find the user email in the response
                     */
                    scope.initialized.then(function(){
                        BrowserId.login()
                            .then(function(response){
                                $rootScope.user.loggedin = true;
                                $rootScope.user.email = response.data.email;
                                // retrieve the current user's info from the api
                                ThUserModel.get().then(function(user){
                                    angular.extend($rootScope.user, user);
                                }, null);
                            },function(response){
                                var message = "Login failed: " + response.status + " " + response.statusText;
                                thNotify.send(message, "danger", true);

                                // logout if the verification failed
                                scope.logout();
                            });
                    });
                };
                scope.logout = function(){
                    scope.initialized.then(function(){
                        BrowserId.logout().then(function(response){
                            $rootScope.user = {loggedin: false, email:null};
                        });
                    });
                };
            },
            templateUrl: 'partials/main/persona_buttons.html'
        };
    }]);
<|endoftext|>


<commit_before><commit_msg>Shorter, cleaner syntax<commit_after><|endoftext|>


<commit_before>/**
 * Gen 1 mechanics were fairly different, so we need to make a lot of changes to battle.js
 * using this.
 */
exports.BattleScripts = {
	gen: 1,
	init: function() {
		// We check for everything that didn't exist back in gen 1 and make it Illegal
		for (var i in this.data.Pokedex) {
			var template = this.getTemplate(i);
			if (template.gen > 1) template.isNonstandard = true;
			delete template.abilities['DW'];
		}
		for (var i in this.data.Movedex) {
			var move = this.getMove(i);
			if (move.gen > 1) move.isNonstandard = true;
		}
		for (var i in this.data.Abilities) {
			var ability = this.getAbility(i);
			if (ability.gen > 1) ability.isNonstandard = true;
		}
		for (var i in this.data.Items) {
			var item = this.getItem(i);
			if (item.gen > 1) item.isNonstandard = true;
		}
	},
	runMove: function(move, pokemon, target, sourceEffect) {
		/**
		 * runMove event needs to be reviewed for gen 1
		 */
		move = this.getMove(move);
		if (!target) target = this.resolveTarget(pokemon, move);

		this.setActiveMove(move, pokemon, target);

		if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) {
			this.debug(''+pokemon.id+' move interrupted; movedThisTurn: '+pokemon.movedThisTurn);
			this.clearActiveMove(true);
			return;
		}
		if (move.beforeMoveCallback) {
			if (move.beforeMoveCallback.call(this, pokemon, target, move)) {
				this.clearActiveMove(true);
				return;
			}
		}
		pokemon.lastDamage = 0;
		var lockedMove = this.runEvent('LockMove', pokemon);
		if (lockedMove === true) lockedMove = false;
		if (!lockedMove) pokemon.deductPP(move, null, target);
		this.useMove(move, pokemon, target, sourceEffect);
		this.runEvent('AfterMove', target, pokemon, move);
		this.runEvent('AfterMoveSelf', pokemon, target, move);
	},
	getDamage: function(pokemon, target, move, suppressMessages) {
		if (typeof move === 'string') move = this.getMove(move);
		if (typeof move === 'number') move = {
			basePower: move,
			type: '???',
			category: 'Physical'
		};

		if (move.affectedByImmunities) {
			if (!target.runImmunity(move.type, true)) {
				return false;
			}
		}

		if (move.ohko) {
			if (target.speed > pokemon.speed) {
				this.add('-failed', target);
				return false;
			}
			return target.maxhp;
		}

		if (move.damageCallback) {
			return move.damageCallback.call(this, pokemon, target);
		}

		if (move.damage === 'level') {
			return pokemon.level;
		}

		if (move.damage) {
			return move.damage;
		}

		if (!move) {
			move = {};
		}

		if (!move.category) move.category = 'Physical';
		if (!move.defensiveCategory) move.defensiveCategory = move.category;
		// '???' is typeless damage: used for Struggle and Confusion etc
		if (!move.type) move.type = '???';
		var type = move.type;

		// In Gen 1 category deppends on attacking type
		var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
		var category = (type in specialTypes)? 'Special' : 'Physical';
		console.log(move.name + ': Using ' + category + ' type of attack for ' + type + '-type move.');

		var basePower = move.basePower;
		if (move.basePowerCallback) {
			basePower = move.basePowerCallback.call(this, pokemon, target, move);
		}
		if (!basePower) return 0;
		basePower = clampIntRange(basePower, 1);

		// We check if it's a 100% crit move
		move.critRatio = clampIntRange(move.critRatio, 0, 5);
		var critMult = [0, 16, 8, 4, 3, 2];
		move.crit = move.willCrit || false;
		var critRatio = 0;
		// Otherwise, we calculate the critical hit chance
		if (typeof move.willCrit === 'undefined') {
			// In gen 1, the critical chance is based on speed
			switch (move.critRatio) {
			case 1:
				// Normal crit-rate: BaseSpeed * 100 / 512.
				critRatio = pokemon.baseStats['spe'] * 100 / 512;
				console.log('Using normal crit-rate: BaseSpeed * 100 / 512');
				break;
			case 2:
				// High crit-rate: BaseSpeed * 100 / 64
				critRatio = pokemon.baseStats['spe'] * 100 / 64;
				console.log('Using high crit-rate: BaseSpeed * 100 / 64');
				break;
			case -2:
				// Crit rate destroyed by Focus Energy (dumb trainer is dumb)
				// 1 - 3 = -2, this is a normal move
				critRatio = (pokemon.baseStats['spe'] * 100 / 64) * 0.25;
				console.log('Using ruined normal crit-rate: (pokemon.baseStats[\'spe\'] * 100 / 64) * 0.25');
				break;
			case -1:
				// 2 - 3 = -1, this is a high crit move. Deppends on speed
				if (pokemon.speed > target.speed) {
					// Critical rate not decreased
					critRatio = pokemon.baseStats['spe'] * 100 / 64;
					console.log('Using ruined high crit-rate: pokemon.baseStats[\'spe\'] * 100 / 64');
				} else {
					// If you are slower you can't crit
					console.log('Ruined crit rate, too slow, cannnot crit');
					critRatio = false;
				}
				break;
			}

			if (critRatio) {
				critRatio = critRatio.floor();
				var random = Math.random() * 100;
				move.crit = (random.floor() <= critRatio);
			}
		}

		if (move.crit) {
			move.crit = this.runEvent('CriticalHit', target, null, move);
		}

		// happens after crit calculation
		if (basePower) {
			basePower = this.runEvent('BasePower', pokemon, target, move, basePower);

			if (move.basePowerModifier) {
				basePower *= move.basePowerModifier;
			}
		}
		if (!basePower) return 0;
		basePower = clampIntRange(basePower, 1);

		var level = pokemon.level;

		var attacker = pokemon;
		var defender = target;
		if (move.useTargetOffensive) attacker = target;
		if (move.useSourceDefensive) defender = pokemon;

		var attack = attacker.getStat(move.category==='Physical'?'atk':'spa');
		var defense = defender.getStat(move.defensiveCategory==='Physical'?'def':'spd');

		if (move.crit) {
			move.ignoreNegativeOffensive = true;
			move.ignorePositiveDefensive = true;
		}
		if (move.ignoreNegativeOffensive && attack < attacker.getStat(move.category==='Physical'?'atk':'spa', true)) {
			move.ignoreOffensive = true;
		}
		if (move.ignoreOffensive) {
			console.log('Negating (sp)atk boost/penalty.');
			attack = attacker.getStat(move.category==='Physical'?'atk':'spa', true);
		}
		if (move.ignorePositiveDefensive && defense > target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true)) {
			move.ignoreDefensive = true;
		}
		if (move.ignoreDefensive) {
			console.log('Negating (sp)def boost/penalty.');
			defense = target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true);
		}

		// Gen 1 damage formula (((((min(((((2L/5 + 2)*A*P)/max(1, D))/50), 997) + 2)*S)*T)/10)*R)/255
		// Where: L: user level, A: current attack, P: move power, D: opponent current defense,
		// S is the Stab modifier, T is the type effectiveness modifier, R is random between 217 and 255
		// The max damage is 999
		console.log('Using formula: int(int(int(2*L/5+2)*A*P/D)/50) for base damage');
		var baseDamage = Math.floor(Math.floor(Math.floor(2*level/5+2) * basePower * attack/defense)/50) + 2;

		// crit
		if (move.crit) {
			if (!suppressMessages) this.add('-crit', target);
			baseDamage = this.modify(baseDamage, move.critModifier || 2);
		}

		// randomizer
		// this is not a modifier
		// gen 1-2
		var randFactor = Math.floor(Math.random()*39)+217;
		baseDamage *= Math.floor(randFactor * 100 / 255) / 100;
		console.log('Randomizing base damage as to gen 1: Math.floor(randFactor * 100 / 255) / 100, rand factor is ' + randFactor);

		// STAB
		if (type !== '???' && pokemon.hasType(type)) {
			// The "???" type never gets STAB
			// Not even if you Roost in Gen 4 and somehow manage to use
			// Struggle in the same turn.
			// (On second thought, it might be easier to get a Missingno.)
			baseDamage = this.modify(baseDamage, move.stab || 1.5);
		}

		// Types
		var totalTypeMod = this.getEffectiveness(type, target);
		if (totalTypeMod > 0) {
			if (!suppressMessages) this.add('-supereffective', target);
			baseDamage *= 2;
			if (totalTypeMod >= 2) {
				baseDamage *= 2;
			}
		}

		if (totalTypeMod < 0) {
			if (!suppressMessages) this.add('-resisted', target);
			baseDamage = Math.floor(baseDamage/2);
			if (totalTypeMod <= -2) {
				baseDamage = Math.floor(baseDamage/2);
			}
		}

		if (basePower && !Math.floor(baseDamage)) {
			return 1;
		}

		return Math.floor(baseDamage);
	}
}<commit_msg>Override rollMoveHit to add 1/256 miss chance<commit_after>/**
 * Gen 1 mechanics were fairly different, so we need to make a lot of changes to battle.js
 * using this.
 */
exports.BattleScripts = {
	gen: 1,
	init: function() {
		// We check for everything that didn't exist back in gen 1 and make it Illegal
		for (var i in this.data.Pokedex) {
			var template = this.getTemplate(i);
			if (template.gen > 1) template.isNonstandard = true;
			delete template.abilities['DW'];
		}
		for (var i in this.data.Movedex) {
			var move = this.getMove(i);
			if (move.gen > 1) move.isNonstandard = true;
		}
		for (var i in this.data.Abilities) {
			var ability = this.getAbility(i);
			if (ability.gen > 1) ability.isNonstandard = true;
		}
		for (var i in this.data.Items) {
			var item = this.getItem(i);
			if (item.gen > 1) item.isNonstandard = true;
		}
	},
	runMove: function(move, pokemon, target, sourceEffect) {
		/**
		 * runMove event needs to be reviewed for gen 1
		 */
		move = this.getMove(move);
		if (!target) target = this.resolveTarget(pokemon, move);

		this.setActiveMove(move, pokemon, target);

		if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) {
			this.debug(''+pokemon.id+' move interrupted; movedThisTurn: '+pokemon.movedThisTurn);
			this.clearActiveMove(true);
			return;
		}
		if (move.beforeMoveCallback) {
			if (move.beforeMoveCallback.call(this, pokemon, target, move)) {
				this.clearActiveMove(true);
				return;
			}
		}
		pokemon.lastDamage = 0;
		var lockedMove = this.runEvent('LockMove', pokemon);
		if (lockedMove === true) lockedMove = false;
		if (!lockedMove) pokemon.deductPP(move, null, target);
		this.useMove(move, pokemon, target, sourceEffect);
		this.runEvent('AfterMove', target, pokemon, move);
		this.runEvent('AfterMoveSelf', pokemon, target, move);
	},
	getDamage: function(pokemon, target, move, suppressMessages) {
		if (typeof move === 'string') move = this.getMove(move);
		if (typeof move === 'number') move = {
			basePower: move,
			type: '???',
			category: 'Physical'
		};

		if (move.affectedByImmunities) {
			if (!target.runImmunity(move.type, true)) {
				return false;
			}
		}

		if (move.ohko) {
			if (target.speed > pokemon.speed) {
				this.add('-failed', target);
				return false;
			}
			return target.maxhp;
		}

		if (move.damageCallback) {
			return move.damageCallback.call(this, pokemon, target);
		}

		if (move.damage === 'level') {
			return pokemon.level;
		}

		if (move.damage) {
			return move.damage;
		}

		if (!move) {
			move = {};
		}

		if (!move.category) move.category = 'Physical';
		if (!move.defensiveCategory) move.defensiveCategory = move.category;
		// '???' is typeless damage: used for Struggle and Confusion etc
		if (!move.type) move.type = '???';
		var type = move.type;

		// In Gen 1 category deppends on attacking type
		var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
		var category = (type in specialTypes)? 'Special' : 'Physical';
		console.log(move.name + ': Using ' + category + ' type of attack for ' + type + '-type move.');

		var basePower = move.basePower;
		if (move.basePowerCallback) {
			basePower = move.basePowerCallback.call(this, pokemon, target, move);
		}
		if (!basePower) return 0;
		basePower = clampIntRange(basePower, 1);

		// We check if it's a 100% crit move
		move.critRatio = clampIntRange(move.critRatio, 0, 5);
		var critMult = [0, 16, 8, 4, 3, 2];
		move.crit = move.willCrit || false;
		var critRatio = 0;
		// Otherwise, we calculate the critical hit chance
		if (typeof move.willCrit === 'undefined') {
			// In gen 1, the critical chance is based on speed
			switch (move.critRatio) {
			case 1:
				// Normal crit-rate: BaseSpeed * 100 / 512.
				critRatio = pokemon.baseStats['spe'] * 100 / 512;
				console.log('Using normal crit-rate: BaseSpeed * 100 / 512');
				break;
			case 2:
				// High crit-rate: BaseSpeed * 100 / 64
				critRatio = pokemon.baseStats['spe'] * 100 / 64;
				console.log('Using high crit-rate: BaseSpeed * 100 / 64');
				break;
			case -2:
				// Crit rate destroyed by Focus Energy (dumb trainer is dumb)
				// 1 - 3 = -2, this is a normal move
				critRatio = (pokemon.baseStats['spe'] * 100 / 64) * 0.25;
				console.log('Using ruined normal crit-rate: (pokemon.baseStats[\'spe\'] * 100 / 64) * 0.25');
				break;
			case -1:
				// 2 - 3 = -1, this is a high crit move. Deppends on speed
				if (pokemon.speed > target.speed) {
					// Critical rate not decreased
					critRatio = pokemon.baseStats['spe'] * 100 / 64;
					console.log('Using ruined high crit-rate: pokemon.baseStats[\'spe\'] * 100 / 64');
				} else {
					// If you are slower you can't crit
					console.log('Ruined crit rate, too slow, cannnot crit');
					critRatio = false;
				}
				break;
			}

			if (critRatio) {
				critRatio = critRatio.floor();
				var random = Math.random() * 100;
				move.crit = (random.floor() <= critRatio);
			}
		}

		if (move.crit) {
			move.crit = this.runEvent('CriticalHit', target, null, move);
		}

		// happens after crit calculation
		if (basePower) {
			basePower = this.runEvent('BasePower', pokemon, target, move, basePower);

			if (move.basePowerModifier) {
				basePower *= move.basePowerModifier;
			}
		}
		if (!basePower) return 0;
		basePower = clampIntRange(basePower, 1);

		var level = pokemon.level;

		var attacker = pokemon;
		var defender = target;
		if (move.useTargetOffensive) attacker = target;
		if (move.useSourceDefensive) defender = pokemon;

		var attack = attacker.getStat(move.category==='Physical'?'atk':'spa');
		var defense = defender.getStat(move.defensiveCategory==='Physical'?'def':'spd');

		if (move.crit) {
			move.ignoreNegativeOffensive = true;
			move.ignorePositiveDefensive = true;
		}
		if (move.ignoreNegativeOffensive && attack < attacker.getStat(move.category==='Physical'?'atk':'spa', true)) {
			move.ignoreOffensive = true;
		}
		if (move.ignoreOffensive) {
			console.log('Negating (sp)atk boost/penalty.');
			attack = attacker.getStat(move.category==='Physical'?'atk':'spa', true);
		}
		if (move.ignorePositiveDefensive && defense > target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true)) {
			move.ignoreDefensive = true;
		}
		if (move.ignoreDefensive) {
			console.log('Negating (sp)def boost/penalty.');
			defense = target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true);
		}

		// Gen 1 damage formula (((((min(((((2L/5 + 2)*A*P)/max(1, D))/50), 997) + 2)*S)*T)/10)*R)/255
		// Where: L: user level, A: current attack, P: move power, D: opponent current defense,
		// S is the Stab modifier, T is the type effectiveness modifier, R is random between 217 and 255
		// The max damage is 999
		console.log('Using formula: int(int(int(2*L/5+2)*A*P/D)/50) for base damage');
		var baseDamage = Math.floor(Math.floor(Math.floor(2*level/5+2) * basePower * attack/defense)/50) + 2;

		// crit
		if (move.crit) {
			if (!suppressMessages) this.add('-crit', target);
			baseDamage = this.modify(baseDamage, move.critModifier || 2);
		}

		// randomizer
		// this is not a modifier
		// gen 1-2
		var randFactor = Math.floor(Math.random()*39)+217;
		baseDamage *= Math.floor(randFactor * 100 / 255) / 100;
		console.log('Randomizing base damage as to gen 1: Math.floor(randFactor * 100 / 255) / 100, rand factor is ' + randFactor);

		// STAB
		if (type !== '???' && pokemon.hasType(type)) {
			// The "???" type never gets STAB
			// Not even if you Roost in Gen 4 and somehow manage to use
			// Struggle in the same turn.
			// (On second thought, it might be easier to get a Missingno.)
			baseDamage = this.modify(baseDamage, move.stab || 1.5);
		}

		// Types
		var totalTypeMod = this.getEffectiveness(type, target);
		if (totalTypeMod > 0) {
			if (!suppressMessages) this.add('-supereffective', target);
			baseDamage *= 2;
			if (totalTypeMod >= 2) {
				baseDamage *= 2;
			}
		}

		if (totalTypeMod < 0) {
			if (!suppressMessages) this.add('-resisted', target);
			baseDamage = Math.floor(baseDamage/2);
			if (totalTypeMod <= -2) {
				baseDamage = Math.floor(baseDamage/2);
			}
		}

		if (basePower && !Math.floor(baseDamage)) {
			return 1;
		}

		return Math.floor(baseDamage);
	},
	rollMoveHit: function(target, pokemon, move, spreadHit) {
		if (move.selfdestruct && spreadHit) {
			pokemon.hp = 0;
		}

		var boostTable = [1, 4/3, 5/3, 2, 7/3, 8/3, 3];

		// calculate true accuracy
		var accuracy = move.accuracy;
		if (accuracy !== true) {
			if (!move.ignoreAccuracy) {
				if (pokemon.boosts.accuracy > 0) {
					accuracy *= boostTable[pokemon.boosts.accuracy];
				} else {
					accuracy /= boostTable[-pokemon.boosts.accuracy];
				}
			}
			if (!move.ignoreEvasion) {
				if (target.boosts.evasion > 0 && !move.ignorePositiveEvasion) {
					accuracy /= boostTable[target.boosts.evasion];
				} else if (target.boosts.evasion < 0) {
					accuracy *= boostTable[-target.boosts.evasion];
				}
			}
		}
		if (move.ohko) { // bypasses accuracy modifiers
			if (!target.volatiles['bounce'] && !target.volatiles['dig'] && !target.volatiles['dive'] && !target.volatiles['fly'] && !target.volatiles['shadowforce'] && !target.volatiles['skydrop']) {
				accuracy = 30;
				if (pokemon.level > target.level) accuracy += (pokemon.level - target.level);
			}
		}
		if (move.alwaysHit) accuracy = true; // bypasses ohko accuracy modifiers
		accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy);
		if (accuracy !== true && this.random(100 + (1/256)) >= accuracy) {
			if (!spreadHit) this.attrLastMove('[miss]');
			this.add('-miss', pokemon, target);
			return false;
		}

		if ((move.affectedByImmunities && !target.runImmunity(move.type, true)) || (move.isSoundBased && (pokemon !== target || this.gen <= 4) && !target.runImmunity('sound', true))) {
			return false;
		}

		var damage = 0;
		pokemon.lastDamage = 0;
		if (move.multihit) {
			var hits = move.multihit;
			if (hits.length) {
				// yes, it's hardcoded... meh
				if (hits[0] === 2 && hits[1] === 5) {
					var roll = this.random(6);
					hits = [2,2,3,3,4,5][roll];
				} else {
					hits = this.random(hits[0],hits[1]+1);
				}
			}
			hits = Math.floor(hits);
			for (var i=0; i<hits && target.hp && pokemon.hp; i++) {
				var moveDamage = this.moveHit(target, pokemon, move);
				if (moveDamage === false) break;
				// Damage from each hit is individually counted for the
				// purposes of Counter, Metal Burst, and Mirror Coat.
				damage = (moveDamage || 0);
			}
			if (i === 0) return true;
			this.add('-hitcount', target, i);
		} else {
			damage = this.moveHit(target, pokemon, move);
		}

		if (move.category !== 'Status') target.gotAttacked(move, damage, pokemon);

		if (!damage && damage !== 0) return false;

		if (move.selfdestruct) {
			this.faint(pokemon, pokemon, move);
		}

		if (!move.negateSecondary) {
			this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move);
			this.runEvent('AfterMoveSecondary', target, pokemon, move);
		}

		return damage;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2016-2017 The Thingsboard Authors
 *
 * 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.
 */

const varsRegex = /\$\{([^\}]*)\}/g;

const linkActionRegex = /\<link-act name=['"]([^['"]*)['"]\>([^\<]*)\<\/link-act\>/g;
const buttonActionRegex = /\<button-act name=['"]([^['"]*)['"]\>([^\<]*)\<\/button-act\>/g;

export function processPattern(pattern, datasources, dsIndex) {
    var match = varsRegex.exec(pattern);
    var replaceInfo = {};
    replaceInfo.variables = [];
    while (match !== null) {
        var variableInfo = {};
        variableInfo.dataKeyIndex = -1;
        var variable = match[0];
        var label = match[1];
        var valDec = 2;
        var splitVals = label.split(':');
        if (splitVals.length > 1) {
            label = splitVals[0];
            valDec = parseFloat(splitVals[1]);
        }
        variableInfo.variable = variable;
        variableInfo.valDec = valDec;

        var keyIndex = -1;

        if (label.startsWith('#')) {
            var keyIndexStr = label.substring(1);
            var n = Math.floor(Number(keyIndexStr));
            if (String(n) === keyIndexStr && n >= 0) {
                keyIndex = n;
            }
        }
        var offset = 0;
        for (var i=0;i<datasources.length;i++) {
            var datasource = datasources[i];
            if (dsIndex == i) {
                if (keyIndex > -1) {
                    if (keyIndex < datasource.dataKeys.length) {
                        variableInfo.dataKeyIndex = offset + keyIndex;
                    }
                } else {
                    for (var k = 0; k < datasource.dataKeys.length; k++) {
                        var dataKey = datasource.dataKeys[k];
                        if (dataKey.label === label) {
                            variableInfo.dataKeyIndex = offset + k;
                            break;
                        }
                    }
                }
            }
            offset += datasource.dataKeys.length;
        }
        replaceInfo.variables.push(variableInfo);
        match = varsRegex.exec(pattern);
    }
    return replaceInfo;
}

export function fillPattern(pattern, replaceInfo, data) {
    var text = angular.copy(pattern);
    for (var v = 0; v < replaceInfo.variables.length; v++) {
        var variableInfo = replaceInfo.variables[v];
        var txtVal = '';
        if (variableInfo.dataKeyIndex > -1 && data[variableInfo.dataKeyIndex]) {
            var varData = data[variableInfo.dataKeyIndex].data;
            if (varData.length > 0) {
                var val = varData[varData.length - 1][1];
                if (isNumber(val)) {
                    txtVal = padValue(val, variableInfo.valDec, 0);
                } else {
                    txtVal = val;
                }
            }
        }
        text = text.split(variableInfo.variable).join(txtVal);
    }
    return text;
}

function createLink(actionName, actionText, actionCallbackName, additionalArgs) {
    var args = 'event,\''+actionName+'\'';
    if (additionalArgs && additionalArgs.length) {
        args += ','+additionalArgs.join();
    }
    return ''+actionText+'';
}

function createButton(actionName, actionText, actionCallbackName, additionalArgs) {
    var args = 'event,\''+actionName+'\'';
    if (additionalArgs && additionalArgs.length) {
        args += ','+additionalArgs.join();
    }
    return '<button onclick="angular.element(this).scope().'+actionCallbackName+'('+args+'); return false;">'+actionText+'</button>';
}

export function fillPatternWithActions(pattern, actionCallbackName, additionalArgs) {
    var text = angular.copy(pattern);
    var match = linkActionRegex.exec(pattern);
    var actionTags;
    var actionName;
    var actionText;
    var actionHtml;
    while (match !== null) {
        actionTags = match[0];
        actionName = match[1];
        actionText = match[2];
        actionHtml = createLink(actionName, actionText, actionCallbackName, additionalArgs);
        text = text.split(actionTags).join(actionHtml);
        match = linkActionRegex.exec(pattern);
    }
    match = buttonActionRegex.exec(pattern);
    while (match !== null) {
        actionTags = match[0];
        actionName = match[1];
        actionText = match[2];
        actionHtml = createButton(actionName, actionText, actionCallbackName, additionalArgs);
        text = text.split(actionTags).join(actionHtml);
        match = buttonActionRegex.exec(pattern);
    }
    return text;
}

export function toLabelValueMap(data, datasources) {
    var dataMap = {};
    var dsDataMap = [];
    for (var d=0;d<datasources.length;d++) {
        dsDataMap[d] = {};
    }
    for (var i = 0; i < data.length; i++) {
        var dataKey = data[i].dataKey;
        var label = dataKey.label;
        var keyData = data[i].data;
        var val = null;
        if (keyData.length > 0) {
            val = keyData[keyData.length-1][1];
        }
        dataMap[label] = val;
        var dsIndex = datasources.indexOf(data[i].datasource);
        dsDataMap[dsIndex][label] = val;
    }
    return {
        dataMap: dataMap,
        dsDataMap: dsDataMap
    };
}

export function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

export function padValue(val, dec, int) {
    var i = 0;
    var s, strVal, n;

    val = parseFloat(val);
    n = (val < 0);
    val = Math.abs(val);

    if (dec > 0) {
        strVal = val.toFixed(dec).toString().split('.');
        s = int - strVal[0].length;

        for (; i < s; ++i) {
            strVal[0] = '0' + strVal[0];
        }

        strVal = (n ? '-' : '') + strVal[0] + '.' + strVal[1];
    }

    else {
        strVal = Math.round(val).toString();
        s = int - strVal.length;

        for (; i < s; ++i) {
            strVal = '0' + strVal;
        }

        strVal = (n ? '-' : '') + strVal;
    }

    return strVal;
}

export function arraysEqual(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length != b.length) return false;

    for (var i = 0; i < a.length; ++i) {
        if (!a[i].equals(b[i])) return false;
    }
    return true;
}
<commit_msg>UI: Map widgets - Add ts to dataMap.<commit_after>/*
 * Copyright © 2016-2017 The Thingsboard Authors
 *
 * 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.
 */

const varsRegex = /\$\{([^\}]*)\}/g;

const linkActionRegex = /\<link-act name=['"]([^['"]*)['"]\>([^\<]*)\<\/link-act\>/g;
const buttonActionRegex = /\<button-act name=['"]([^['"]*)['"]\>([^\<]*)\<\/button-act\>/g;

export function processPattern(pattern, datasources, dsIndex) {
    var match = varsRegex.exec(pattern);
    var replaceInfo = {};
    replaceInfo.variables = [];
    while (match !== null) {
        var variableInfo = {};
        variableInfo.dataKeyIndex = -1;
        var variable = match[0];
        var label = match[1];
        var valDec = 2;
        var splitVals = label.split(':');
        if (splitVals.length > 1) {
            label = splitVals[0];
            valDec = parseFloat(splitVals[1]);
        }
        variableInfo.variable = variable;
        variableInfo.valDec = valDec;

        var keyIndex = -1;

        if (label.startsWith('#')) {
            var keyIndexStr = label.substring(1);
            var n = Math.floor(Number(keyIndexStr));
            if (String(n) === keyIndexStr && n >= 0) {
                keyIndex = n;
            }
        }
        var offset = 0;
        for (var i=0;i<datasources.length;i++) {
            var datasource = datasources[i];
            if (dsIndex == i) {
                if (keyIndex > -1) {
                    if (keyIndex < datasource.dataKeys.length) {
                        variableInfo.dataKeyIndex = offset + keyIndex;
                    }
                } else {
                    for (var k = 0; k < datasource.dataKeys.length; k++) {
                        var dataKey = datasource.dataKeys[k];
                        if (dataKey.label === label) {
                            variableInfo.dataKeyIndex = offset + k;
                            break;
                        }
                    }
                }
            }
            offset += datasource.dataKeys.length;
        }
        replaceInfo.variables.push(variableInfo);
        match = varsRegex.exec(pattern);
    }
    return replaceInfo;
}

export function fillPattern(pattern, replaceInfo, data) {
    var text = angular.copy(pattern);
    for (var v = 0; v < replaceInfo.variables.length; v++) {
        var variableInfo = replaceInfo.variables[v];
        var txtVal = '';
        if (variableInfo.dataKeyIndex > -1 && data[variableInfo.dataKeyIndex]) {
            var varData = data[variableInfo.dataKeyIndex].data;
            if (varData.length > 0) {
                var val = varData[varData.length - 1][1];
                if (isNumber(val)) {
                    txtVal = padValue(val, variableInfo.valDec, 0);
                } else {
                    txtVal = val;
                }
            }
        }
        text = text.split(variableInfo.variable).join(txtVal);
    }
    return text;
}

function createLink(actionName, actionText, actionCallbackName, additionalArgs) {
    var args = 'event,\''+actionName+'\'';
    if (additionalArgs && additionalArgs.length) {
        args += ','+additionalArgs.join();
    }
    return ''+actionText+'';
}

function createButton(actionName, actionText, actionCallbackName, additionalArgs) {
    var args = 'event,\''+actionName+'\'';
    if (additionalArgs && additionalArgs.length) {
        args += ','+additionalArgs.join();
    }
    return '<button onclick="angular.element(this).scope().'+actionCallbackName+'('+args+'); return false;">'+actionText+'</button>';
}

export function fillPatternWithActions(pattern, actionCallbackName, additionalArgs) {
    var text = angular.copy(pattern);
    var match = linkActionRegex.exec(pattern);
    var actionTags;
    var actionName;
    var actionText;
    var actionHtml;
    while (match !== null) {
        actionTags = match[0];
        actionName = match[1];
        actionText = match[2];
        actionHtml = createLink(actionName, actionText, actionCallbackName, additionalArgs);
        text = text.split(actionTags).join(actionHtml);
        match = linkActionRegex.exec(pattern);
    }
    match = buttonActionRegex.exec(pattern);
    while (match !== null) {
        actionTags = match[0];
        actionName = match[1];
        actionText = match[2];
        actionHtml = createButton(actionName, actionText, actionCallbackName, additionalArgs);
        text = text.split(actionTags).join(actionHtml);
        match = buttonActionRegex.exec(pattern);
    }
    return text;
}

export function toLabelValueMap(data, datasources) {
    var dataMap = {};
    var dsDataMap = [];
    for (var d=0;d<datasources.length;d++) {
        dsDataMap[d] = {};
    }
    for (var i = 0; i < data.length; i++) {
        var dataKey = data[i].dataKey;
        var label = dataKey.label;
        var keyData = data[i].data;
        var ts = null;
        var val = null;
        if (keyData.length > 0) {
            ts = keyData[keyData.length-1][0];
            val = keyData[keyData.length-1][1];
        }
        dataMap[label+'|ts'] = ts;
        dataMap[label] = val;
        var dsIndex = datasources.indexOf(data[i].datasource);
        dsDataMap[dsIndex][label+'|ts'] = ts;
        dsDataMap[dsIndex][label] = val;
    }
    return {
        dataMap: dataMap,
        dsDataMap: dsDataMap
    };
}

export function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

export function padValue(val, dec, int) {
    var i = 0;
    var s, strVal, n;

    val = parseFloat(val);
    n = (val < 0);
    val = Math.abs(val);

    if (dec > 0) {
        strVal = val.toFixed(dec).toString().split('.');
        s = int - strVal[0].length;

        for (; i < s; ++i) {
            strVal[0] = '0' + strVal[0];
        }

        strVal = (n ? '-' : '') + strVal[0] + '.' + strVal[1];
    }

    else {
        strVal = Math.round(val).toString();
        s = int - strVal.length;

        for (; i < s; ++i) {
            strVal = '0' + strVal;
        }

        strVal = (n ? '-' : '') + strVal;
    }

    return strVal;
}

export function arraysEqual(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length != b.length) return false;

    for (var i = 0; i < a.length; ++i) {
        if (!a[i].equals(b[i])) return false;
    }
    return true;
}
<|endoftext|>


<commit_before><commit_msg>Use different service for storing chosen education paths<commit_after><|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All rights reserved.
//
// 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.

import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';
import Queue from 'axiom/fs/stream/queue';
import ReadableMemoryStream from 'axiom/fs/stream/readable_memory_stream';
import WritableMemoryStream from 'axiom/fs/stream/writable_memory_stream';

/** @typedef ReadableStream$$module$axiom$fs$stream$readable_stream */
var ReadableStream;

/** @typedef WritableStream$$module$axiom$fs$stream$writable_stream */
var WritableStream;

/** @typedef function():void */
var EventCallback;

/**
 * Event value + associated callback
 * @constructor
 * @param {!*} value
 * @param {!EventCallback} callback
 */
var EventWithCallback = function(value, callback) {
  this.value = value;
  this.callback = callback;
};

/**
 * @constructor
 */
export var MemoryStreamBuffer = function() {
  /** @private @type {boolean} */
  this.paused_ = true;
  /** @const @private @type {Queue} */
  this.events_ = new Queue();
  /** @type {!AxiomEvent} */
  this.onData = new AxiomEvent();
  /** @type {!AxiomEvent} */
  this.onReadable = new AxiomEvent();
  /** @const @type {!ReadableStream} */
  this.readableStream = new ReadableMemoryStream(this);
  /** @const @type {!WritableStream} */
  this.writableStream = new WritableMemoryStream(this);
};

export default MemoryStreamBuffer;

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.pause = function() {
  this.paused_ = true;
};

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.resume = function() {
  this.paused_ = false;
  this.flushEvents_();
};

/**
 * Consume one event from the stream. Return undefined if the
 * stream is empty.
 *
 * @return {*}
 */
MemoryStreamBuffer.prototype.read = function() {
  if (!this.paused_) {
    throw new AxiomError.Runtime('Cannot read: stream must be paused');
  }
  return this.read_();
};

/**
 * Write data into the stream (for implementers of the stream only).
 * Invoke the "onData" callback for all pending events if the callback is set.
 *
 * @param {!*} value
 * @param {EventCallback=} opt_callback
 * @return {void}
 */
MemoryStreamBuffer.prototype.write = function(value, opt_callback) {
  var item = value;
  if (opt_callback) {
    item = new EventWithCallback(value, opt_callback);
  }
  this.events_.enqueue(item);
  if (this.paused_) {
    this.onReadable.fire();
  } else {
    this.flushEvents_();
  }
};

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.flushEvents_ = function() {
  while (!this.paused_) {
    var item = this.read_();
    if (!item)
      break;

    this.onData.fire(item);
  }
};

/**
 * Consume one event from the stream. Return undefined if the
 * stream is empty.
 *
 * @return {*}
 */
MemoryStreamBuffer.prototype.read_ = function() {
  var item = this.events_.dequeue();
  if (item instanceof EventWithCallback) {
    item.callback();
    return item.value;
  } else {
    return item;
  }
};
<commit_msg>Comment (test for drone.io)<commit_after>// Copyright 2015 Google Inc. All rights reserved.
//
// 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.

import AxiomError from 'axiom/core/error';
import AxiomEvent from 'axiom/core/event';
import Queue from 'axiom/fs/stream/queue';
import ReadableMemoryStream from 'axiom/fs/stream/readable_memory_stream';
import WritableMemoryStream from 'axiom/fs/stream/writable_memory_stream';

/** @typedef ReadableStream$$module$axiom$fs$stream$readable_stream */
var ReadableStream;

/** @typedef WritableStream$$module$axiom$fs$stream$writable_stream */
var WritableStream;

/** @typedef function():void */
var EventCallback;

/**
 * Event value + associated callback
 * @constructor
 * @param {!*} value
 * @param {!EventCallback} callback
 */
var EventWithCallback = function(value, callback) {
  this.value = value;
  this.callback = callback;
};

/**
 * Implementation of streams over an in-memory array.
 *
 * @constructor
 */
export var MemoryStreamBuffer = function() {
  /** @private @type {boolean} */
  this.paused_ = true;
  /** @const @private @type {Queue} */
  this.events_ = new Queue();
  /** @type {!AxiomEvent} */
  this.onData = new AxiomEvent();
  /** @type {!AxiomEvent} */
  this.onReadable = new AxiomEvent();
  /** @const @type {!ReadableStream} */
  this.readableStream = new ReadableMemoryStream(this);
  /** @const @type {!WritableStream} */
  this.writableStream = new WritableMemoryStream(this);
};

export default MemoryStreamBuffer;

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.pause = function() {
  this.paused_ = true;
};

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.resume = function() {
  this.paused_ = false;
  this.flushEvents_();
};

/**
 * Consume one event from the stream. Return undefined if the
 * stream is empty.
 *
 * @return {*}
 */
MemoryStreamBuffer.prototype.read = function() {
  if (!this.paused_) {
    throw new AxiomError.Runtime('Cannot read: stream must be paused');
  }
  return this.read_();
};

/**
 * Write data into the stream (for implementers of the stream only).
 * Invoke the "onData" callback for all pending events if the callback is set.
 *
 * @param {!*} value
 * @param {EventCallback=} opt_callback
 * @return {void}
 */
MemoryStreamBuffer.prototype.write = function(value, opt_callback) {
  var item = value;
  if (opt_callback) {
    item = new EventWithCallback(value, opt_callback);
  }
  this.events_.enqueue(item);
  if (this.paused_) {
    this.onReadable.fire();
  } else {
    this.flushEvents_();
  }
};

/**
 * @return {void}
 */
MemoryStreamBuffer.prototype.flushEvents_ = function() {
  while (!this.paused_) {
    var item = this.read_();
    if (!item)
      break;

    this.onData.fire(item);
  }
};

/**
 * Consume one event from the stream. Return undefined if the
 * stream is empty.
 *
 * @return {*}
 */
MemoryStreamBuffer.prototype.read_ = function() {
  var item = this.events_.dequeue();
  if (item instanceof EventWithCallback) {
    item.callback();
    return item.value;
  } else {
    return item;
  }
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule NavigationView
 * @flow
 */
'use strict';

const Animated = require('Animated');
const NavigationContainer = require('NavigationContainer');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const NavigationScenesReducer = require('NavigationScenesReducer');
const ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');

import type {
  NavigationActionCaller,
  NavigationAnimatedValue,
  NavigationLayout,
  NavigationParentState,
  NavigationScene,
  NavigationSceneRenderer,
  NavigationSceneRendererProps,
} from 'NavigationTypeDefinition';

type Props = {
  navigationState: NavigationParentState,
  onNavigate: NavigationActionCaller,
  renderScene: NavigationSceneRenderer,
  style: any,
};

type State = {
  scenes: Array<NavigationScene>,
};

const {PropTypes} = React;

/**
 * A simple view that will render a scene for the currently focused sub-state.
 * The most common use-case is for tabs, where no transition is needed
 */
class NavigationView extends React.Component<any, Props, any> {
  _layout: NavigationLayout;
  _onLayout: (event: any) => void;
  _position: NavigationAnimatedValue;

  props: Props;
  state: State;

  static propTypes = {
    navigationState: PropTypes.object.isRequired,
    onNavigate: PropTypes.func.isRequired,
    renderScene: PropTypes.func.isRequired,
  };

  constructor(props: Props, context: any) {
    super(props, context);

    this._layout = {
      initWidth: 0,
      initHeight: 0,
      width: new Animated.Value(0),
      height: new Animated.Value(0),
    };

    const {navigationState} = this.props;

    this._position = new Animated.Value(navigationState.index);

    this.state = {
      scenes: NavigationScenesReducer([], navigationState),
    };
  }

  shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
    return ReactComponentWithPureRenderMixin.shouldComponentUpdate.call(
      this,
      nextProps,
      nextState
    );
  }

  componentWillReceiveProps(nextProps: Props): void {
    if (nextProps.navigationState !== this.props.navigationState) {
      const {navigationState} = nextProps;
      this.setState(
        {
          scenes: NavigationScenesReducer(
            this.state.scenes,
            navigationState,
            null, // There will be no transtion.
          ),
        },
        () => {
          this._position.setValue(navigationState.index);
        },
      );
    }
  }

  componentWillMount(): void {
    this._onLayout = this._onLayout.bind(this);
  }

  render(): ReactElement {
    const {
      navigationState,
      onNavigate
    } = this.props;

    const {
      scenes,
    } = this.state;

    const sceneProps = {
      layout: this._layout,
      navigationState: navigationState,
      onNavigate: onNavigate,
      position: this._position,
      scene: scenes[navigationState.index],
      scenes,
    };

    return (
      <View
        onLayout={this._onLayout}
        style={this.props.style}>
        {this._renderScene(sceneProps)}
      </View>
    );
  }

  _renderScene(props: NavigationSceneRendererProps): ?ReactElement {

    const child = this.props.renderScene(props);
    if (child === null) {
      return null;
    }
    return <View key={props.scene.key} style={styles.scene}>{child}</View>;
  }

  _onLayout(event: any): void {
    const {height, width} = event.nativeEvent.layout;

    const layout = {
      ...this._layout,
      initHeight: height,
      initWidth: width,
    };

    this._layout = layout;
    layout.height.setValue(height);
    layout.width.setValue(width);
  }
}

const styles = StyleSheet.create({
  scene: {
    bottom: 0,
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
  },
});

module.exports = NavigationContainer.create(NavigationView);
<commit_msg>Fix NavigationView.<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule NavigationView
 * @flow
 */
'use strict';

const Animated = require('Animated');
const NavigationContainer = require('NavigationContainer');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const NavigationScenesReducer = require('NavigationScenesReducer');
const ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');

import type {
  NavigationActionCaller,
  NavigationAnimatedValue,
  NavigationLayout,
  NavigationParentState,
  NavigationScene,
  NavigationSceneRenderer,
  NavigationSceneRendererProps,
} from 'NavigationTypeDefinition';

type Props = {
  navigationState: NavigationParentState,
  onNavigate: NavigationActionCaller,
  renderScene: NavigationSceneRenderer,
  style: any,
};

type State = {
  layout: NavigationLayout,
  scenes: Array<NavigationScene>,
};

const {PropTypes} = React;

/**
 * A simple view that will render a scene for the currently focused sub-state.
 * The most common use-case is for tabs, where no transition is needed
 */
class NavigationView extends React.Component<any, Props, any> {
  _onLayout: (event: any) => void;
  _position: NavigationAnimatedValue;

  props: Props;
  state: State;

  static propTypes = {
    navigationState: PropTypes.object.isRequired,
    onNavigate: PropTypes.func.isRequired,
    renderScene: PropTypes.func.isRequired,
  };

  constructor(props: Props, context: any) {
    super(props, context);

    const layout = {
      initWidth: 0,
      initHeight: 0,
      isMeasured: false,
      width: new Animated.Value(0),
      height: new Animated.Value(0),
    };

    const {navigationState} = this.props;

    this._position = new Animated.Value(navigationState.index);

    this.state = {
      layout,
      scenes: NavigationScenesReducer([], navigationState),
    };
  }

  shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
    return ReactComponentWithPureRenderMixin.shouldComponentUpdate.call(
      this,
      nextProps,
      nextState
    );
  }

  componentWillReceiveProps(nextProps: Props): void {
    if (nextProps.navigationState !== this.props.navigationState) {
      const {navigationState} = nextProps;
      this.setState(
        {
          scenes: NavigationScenesReducer(
            this.state.scenes,
            navigationState,
            null, // There will be no transtion.
          ),
        },
        () => {
          this._position.setValue(navigationState.index);
        },
      );
    }
  }

  componentWillMount(): void {
    this._onLayout = this._onLayout.bind(this);
  }

  render(): ReactElement {
    const {
      navigationState,
      onNavigate
    } = this.props;

    const {
      layout,
      scenes,
    } = this.state;

    const sceneProps = {
      layout,
      navigationState: navigationState,
      onNavigate: onNavigate,
      position: this._position,
      scene: scenes[navigationState.index],
      scenes,
    };

    return (
      <View
        onLayout={this._onLayout}
        style={this.props.style}>
        {this._renderScene(sceneProps)}
      </View>
    );
  }

  _renderScene(props: NavigationSceneRendererProps): ?ReactElement {

    const child = this.props.renderScene(props);
    if (child === null) {
      return null;
    }
    return <View key={props.scene.key} style={styles.scene}>{child}</View>;
  }

  _onLayout(event: any): void {
    const {height, width} = event.nativeEvent.layout;

    const layout = {
      ...this.state.layout,
      initHeight: height,
      initWidth: width,
      isMeasured: true,
    };

    layout.height.setValue(height);
    layout.width.setValue(width);

    this.setState({ layout });
  }
}

const styles = StyleSheet.create({
  scene: {
    bottom: 0,
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
  },
});

module.exports = NavigationContainer.create(NavigationView);
<|endoftext|>


<commit_before>'use strict';

const Router = require('express').Router;
const parseJSON = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('inventory:cart order route');
const CartOrder = require('../model/cart-order.js');
const Customer = require('../model/customer.js');

const cartOrderRouter = module.exports = Router();

cartOrderRouter.post('/api/orders/:customerID/cartOrder', parseJSON, function(request, response, next) {
  debug('POST: /api/cartOrder');

  if (Object.getOwnPropertyNames(request.body).length === 0) next(createError(400, 'No body posted.'));

  Customer.addCartOrder(request.params.customerID, request.body)
  .then(order => response.status(201).json(order))
  .catch(err => next(createError(404, err.message)));
});

cartOrderRouter.get('/api/orders/:orderID', function(request, response, next) {
  debug('GET: /api/orders/:orderID');

  CartOrder.findById(request.params.orderID)
  .then(order => response.json(order))
  .catch(() => next(createError(404, 'Not found.')));
});
<commit_msg>Added PUT route.<commit_after>'use strict';

const Router = require('express').Router;
const parseJSON = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('inventory:cart order route');
const CartOrder = require('../model/cart-order.js');
const Customer = require('../model/customer.js');

const cartOrderRouter = module.exports = Router();

cartOrderRouter.post('/api/orders/:customerID/cartOrder', parseJSON, function(request, response, next) {
  debug('POST: /api/orders/:customerID/cartOrder');

  if (Object.getOwnPropertyNames(request.body).length === 0) next(createError(400, 'No body posted.'));

  Customer.addCartOrder(request.params.customerID, request.body)
  .then(order => response.status(201).json(order))
  .catch(err => next(createError(404, err.message)));
});

cartOrderRouter.get('/api/orders/:orderID', function(request, response, next) {
  debug('GET: /api/orders/:orderID');

  CartOrder.findById(request.params.orderID)
  .then(order => response.json(order))
  .catch(() => next(createError(404, 'Not found.')));
});

cartOrderRouter.put('/api/orders/:orderID', parseJSON, function(request, response, next) {
  debug('PUT: /api/orders/:orderID');

  if (Object.getOwnPropertyNames(request.body).length === 0) next(createError(400, 'No body posted.'));

  CartOrder.findByIdAndUpdate(request.params.orderID)
  .then(order => response.json(order))
  .catch(() => next(createError(404, 'Not found.')));
});
<|endoftext|>


<commit_before>var adapter = require(__dirname + '/../../modules/adapter.js')({

    name:           'yr',

    ready: function () {
        main();
    }

});

var http = 		require('http');
var xml2js = 	require('xml2js');

function main() {

    var tmp = adapter.config.location.split('/');
    var city = unescape(tmp.pop());

    adapter.setObject('yr_forecast', {
        type: 'channel',
        role: 'forecast',
        common: {
            name: 'yr.no forecast ' + city
        },
        native: {
            url: adapter.config.location,
            country: unescape(tmp[0]),
            state: unescape(tmp[1]),
            city: city
        }
    });

    var reqOptions = {
        hostname: 'www.yr.no',
        port: 80,
        path: '/place/' + adapter.config.location + '/forecast.xml',
        method: 'GET'
    };

    adapter.log.info('get http://' + reqOptions.hostname + reqOptions.path);

    var req = http.request(reqOptions, function (res) {

        var data = '';

        res.on('data', function (chunk) {
            data += chunk;
        });

        res.on('end', function () {
            adapter.log.info('received data from yr.no');
            parseData(data.toString());
        });

    });

    req.on('error', function(e) {
        adapter.log.error(e.message);
    });

    req.end();

    // Force terminate after 5min
    setTimeout(function () {
        adapter.log.error('force terminate');
        process.exit(1);
    }, 300000);

}

function parseData(xml) {

    var options = {
        explicitArray: false,
        mergeAttrs: true
    };
    var parser = new xml2js.Parser(options);
    parser.parseString(xml, function (err, result) {
        if (err) {
            adapter.log.error(err);
        } else {
            adapter.log.info('got weather data from yr.no');
            var forecastArr = result.weatherdata.forecast.tabular.time;

            for (var i = 0; i < forecastArr.length; i++) {
                var period = forecastArr[i];
                period.symbol.url = 'http://symbol.yr.no/grafikk/sym/b38/' + period.symbol.var + '.png';

            }

            var tableDay = '

';
            var tableHead = '

';
            var tableMiddle = '

';
            var tableBottom = '

';
            var dateObj = new Date();
            var dayEnd = dateObj.getFullYear() + '-' + ('0' + (dateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + dateObj.getDate()).slice(-2) + 'T24:00:00';
            var daySwitch = false;
            for (var i = 0; i < 8; i++) {
                var period = forecastArr[i];
                switch (i) {
                    case 0:
                        tableHead += 'jetzt	';
                        break;
                    default:
                        if (period.from > dayEnd) {
                            if (!daySwitch) {
                                daySwitch = true;
                                tableDay += 'Heute	Morgen	';
                                if (i < 3) {
                                    tableDay += 'Übermorgen	';
                                }
                                tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                            } else {
                                tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                            }

                        } else {
                            tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                        }
                }

                tableMiddle += '
';
                tableBottom += ''+period.temperature.value+'°C	';
                //console.log(period);
            }
            var style = ''
            var table = style + tableDay + tableHead + tableMiddle + tableBottom + '

';
            //console.log(JSON.stringify(result, null, "  "));

            if (forecastArr[0].precipitation.value != '0' || forecastArr[1].precipitation.value != '1' || forecastArr[2].precipitation.value != '2' || forecastArr[3].precipitation.value != '3') {
                var rain24 = true;
            } else {
                var rain24 = false;
            }
            if (forecastArr[0].precipitation.value != '4' || forecastArr[1].precipitation.value != '5' || forecastArr[2].precipitation.value != '6' || forecastArr[3].precipitation.value != '7') {
                var rain48 = true;
            } else {
                var rain48 = false;
            }

            var minTemp24 = 100;
            var maxTemp24 = -100;
            var minTemp48 = 100;
            var maxTemp48 = -100;
            for (var i = 0; i < 4; i++) {
                if (forecastArr[i].temperature.value > maxTemp24) {
                    maxTemp24 = forecastArr[i].temperature.value;
                }
                if (forecastArr[i].temperature.value < minTemp24) {
                    minTemp24 = forecastArr[i].temperature.value;
                }
                if (forecastArr[i + 4].temperature.value > maxTemp48) {
                    maxTemp48 = forecastArr[i+4].temperature.value;
                }
                if (forecastArr[i + 4].temperature.value < minTemp48) {
                    minTemp48 = forecastArr[i+4].temperature.value;
                }
            }

            adapter.log.info('data succesfully parsed. setting states');

            adapter.setState('rain_24',         {val: rain24, ack: true});
            adapter.setState('rain_48',         {val: rain48, ack: true});
            adapter.setState('temp_min_24',     {val: minTemp24, ack: true});
            adapter.setState('temp_max_24',     {val: maxTemp24, ack: true});
            adapter.setState('temp_min_48',     {val: minTemp48, ack: true});
            adapter.setState('temp_max_48',     {val: maxTemp48, ack: true});
            adapter.setState('forecast_html',   {val: table, ack: true}, function () {
                setTimeout(function () {
                    process.exit(0);
                }, 5000);
            });

        }
    });
}<commit_msg>renamed "modules" dir to "lib"<commit_after>var adapter = require(__dirname + '/../../lib/adapter.js')({

    name:           'yr',

    ready: function () {
        main();
    }

});

var http = 		require('http');
var xml2js = 	require('xml2js');

function main() {

    var tmp = adapter.config.location.split('/');
    var city = unescape(tmp.pop());

    adapter.setObject('yr_forecast', {
        type: 'channel',
        role: 'forecast',
        common: {
            name: 'yr.no forecast ' + city
        },
        native: {
            url: adapter.config.location,
            country: unescape(tmp[0]),
            state: unescape(tmp[1]),
            city: city
        }
    });

    var reqOptions = {
        hostname: 'www.yr.no',
        port: 80,
        path: '/place/' + adapter.config.location + '/forecast.xml',
        method: 'GET'
    };

    adapter.log.info('get http://' + reqOptions.hostname + reqOptions.path);

    var req = http.request(reqOptions, function (res) {

        var data = '';

        res.on('data', function (chunk) {
            data += chunk;
        });

        res.on('end', function () {
            adapter.log.info('received data from yr.no');
            parseData(data.toString());
        });

    });

    req.on('error', function(e) {
        adapter.log.error(e.message);
    });

    req.end();

    // Force terminate after 5min
    setTimeout(function () {
        adapter.log.error('force terminate');
        process.exit(1);
    }, 300000);

}

function parseData(xml) {

    var options = {
        explicitArray: false,
        mergeAttrs: true
    };
    var parser = new xml2js.Parser(options);
    parser.parseString(xml, function (err, result) {
        if (err) {
            adapter.log.error(err);
        } else {
            adapter.log.info('got weather data from yr.no');
            var forecastArr = result.weatherdata.forecast.tabular.time;

            for (var i = 0; i < forecastArr.length; i++) {
                var period = forecastArr[i];
                period.symbol.url = 'http://symbol.yr.no/grafikk/sym/b38/' + period.symbol.var + '.png';

            }

            var tableDay = '

';
            var tableHead = '

';
            var tableMiddle = '

';
            var tableBottom = '

';
            var dateObj = new Date();
            var dayEnd = dateObj.getFullYear() + '-' + ('0' + (dateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + dateObj.getDate()).slice(-2) + 'T24:00:00';
            var daySwitch = false;
            for (var i = 0; i < 8; i++) {
                var period = forecastArr[i];
                switch (i) {
                    case 0:
                        tableHead += 'jetzt	';
                        break;
                    default:
                        if (period.from > dayEnd) {
                            if (!daySwitch) {
                                daySwitch = true;
                                tableDay += 'Heute	Morgen	';
                                if (i < 3) {
                                    tableDay += 'Übermorgen	';
                                }
                                tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                            } else {
                                tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                            }

                        } else {
                            tableHead += '' + parseInt(period.from.substring(11,13),10).toString() + '-' + parseInt(period.to.substring(11,13),10).toString() + '	';
                        }
                }

                tableMiddle += '
';
                tableBottom += ''+period.temperature.value+'°C	';
                //console.log(period);
            }
            var style = ''
            var table = style + tableDay + tableHead + tableMiddle + tableBottom + '

';
            //console.log(JSON.stringify(result, null, "  "));

            if (forecastArr[0].precipitation.value != '0' || forecastArr[1].precipitation.value != '1' || forecastArr[2].precipitation.value != '2' || forecastArr[3].precipitation.value != '3') {
                var rain24 = true;
            } else {
                var rain24 = false;
            }
            if (forecastArr[0].precipitation.value != '4' || forecastArr[1].precipitation.value != '5' || forecastArr[2].precipitation.value != '6' || forecastArr[3].precipitation.value != '7') {
                var rain48 = true;
            } else {
                var rain48 = false;
            }

            var minTemp24 = 100;
            var maxTemp24 = -100;
            var minTemp48 = 100;
            var maxTemp48 = -100;
            for (var i = 0; i < 4; i++) {
                if (forecastArr[i].temperature.value > maxTemp24) {
                    maxTemp24 = forecastArr[i].temperature.value;
                }
                if (forecastArr[i].temperature.value < minTemp24) {
                    minTemp24 = forecastArr[i].temperature.value;
                }
                if (forecastArr[i + 4].temperature.value > maxTemp48) {
                    maxTemp48 = forecastArr[i+4].temperature.value;
                }
                if (forecastArr[i + 4].temperature.value < minTemp48) {
                    minTemp48 = forecastArr[i+4].temperature.value;
                }
            }

            adapter.log.info('data succesfully parsed. setting states');

            adapter.setState('rain_24',         {val: rain24, ack: true});
            adapter.setState('rain_48',         {val: rain48, ack: true});
            adapter.setState('temp_min_24',     {val: minTemp24, ack: true});
            adapter.setState('temp_max_24',     {val: maxTemp24, ack: true});
            adapter.setState('temp_min_48',     {val: minTemp48, ack: true});
            adapter.setState('temp_max_48',     {val: maxTemp48, ack: true});
            adapter.setState('forecast_html',   {val: table, ack: true}, function () {
                setTimeout(function () {
                    process.exit(0);
                }, 5000);
            });

        }
    });
}<|endoftext|>


<commit_before>PST$sortedCopyOfArray = function(n) {
	var a = n.concat([]);
	a.sort();
	return a;
};

PST$multiplyList = function(l, n) {
	var o = [];
	var s = l.length;
	var i;
	while (n-- > 0) {
		for (i = 0; i < s; ++i) {
			o.push(l[i]);
		}
	}
	return o;
};

PST$checksubstring = function(s, index, lookfor) { return s.substring(index, index + lookfor.length) === lookfor; };

PST$stringTrimOneSide = function(s, isLeft) {
	var i = isLeft ? 0 : s.length - 1;
	var end = isLeft ? s.length : -1;
	var step = isLeft ? 1 : -1;
	var c;
	var trimming = true;
	while (trimming && i != end) {
		c = s.charAt(i);
		switch (c) {
			case ' ':
			case '\n':
			case '\t':
			case '\r':
				i += step;
				break;
			default:
				trimming = false;
				break;
		}
	}

	return isLeft ? s.substring(i) : s.substring(0, i + 1);
};

PST$floatParseHelper = function(o, s) {
	var t = parseFloat(s);
	if (t + '' == 'NaN') {
		o[0] = -1;
	} else {
		o[0] = 1;
		o[1] = t;
	}
};

PST$createNewArray = function(s) {
	var o = [];
	while (s-- > 0) o.push(null);
	return o;
};

PST$dictionaryKeys = function(d) {
	var o = [];
	for (var k in d) {
		o.push(k);
	}
	return o;
};

PST$dictionaryValues = function(d) {
	var o = [];
	for (var k in d) {
		o.push(d[k]);
	}
	return o;
};

PST$is_valid_integer = function(n) {
	var t = parseInt(n);
	return t < 0 || t >= 0;
};

PST$clearList = function(v) {
	v.length = 0;
};

PST$shuffle = function(v) {
	var t;
	var len = v.length;
	var sw;
	for (i = len - 1; i >= 0; --i) {
		sw = Math.floor(Math.random() * len);
		t = v[sw];
		v[sw] = v[i];
		v[i] = t;
	}
};

PST$stringEndsWith = function(s, v) {
	return s.indexOf(v, s.length - v.length) !== -1;
};

PST$intBuffer16 = PST$multiplyList([0], 16);
PST$floatBuffer16 = PST$multiplyList([0.0], 16);
PST$stringBuffer16 = PST$multiplyList([''], 16);

var lib_zip_ensureValidArchiveInfo = function(vm, args) {
	var sc = 0;
	if ((args[0][0] != 5)) {
		sc = 1;
	}
	if (((sc == 0) && (lib_zip_validateByteList(args[1], false) != null))) {
		sc = 2;
	}
	return buildInteger(vm[13], sc);
};

var lib_zip_initializeZipReader = function(vm, args) {
	var sc = 0;
	var byteArray = lib_zip_validateByteList(args[1], true);
	if ((byteArray == null)) {
		sc = 1;
	} else {
		var obj = args[0][1];
		obj[3] = PST$createNewArray(1);
		obj[3][0] = lib_zip_createZipReaderImpl(byteArray);
		obj[3][1] = 0;
		if ((obj[3][0] == null)) {
			sc = 2;
		}
	}
	return buildInteger(vm[13], sc);
};

var lib_zip_readerPeekNextEntry = function(vm, args) {
	var obj = args[0][1];
	var nd = obj[3];
	var output = args[1][1];
	var boolOut = PST$createNewArray(3);
	var nameOut = PST$createNewArray(1);
	var integers = [];
	lib_zip_readNextZipEntryImpl(nd[0], nd[1], boolOut, nameOut, integers);
	var problemsEncountered = !boolOut[0];
	var foundAnything = boolOut[1];
	var isDirectory = boolOut[2];
	if (problemsEncountered) {
		return vm[16];
	}
	nd[1] = (1 + nd[1]);
	setItemInList(output, 0, buildBoolean(vm[13], foundAnything));
	if (!foundAnything) {
		return vm[15];
	}
	setItemInList(output, 1, buildString(vm[13], nameOut[0]));
	if (isDirectory) {
		setItemInList(output, 2, buildBoolean(vm[13], isDirectory));
		return vm[15];
	}
	var byteValues = getItemFromList(output, 3)[1];
	var length = integers.length;
	var i = 0;
	var positiveNumbers = vm[13][9];
	var valuesOut = byteValues[2];
	i = 0;
	while ((i < length)) {
		valuesOut.push(positiveNumbers[integers[i]]);
		i += 1;
	}
	byteValues[1] = length;
	return vm[15];
};

var lib_zip_validateByteList = function(byteListValue, convert) {
	if ((byteListValue[0] != 6)) {
		return null;
	}
	var output = null;
	var bytes = byteListValue[1];
	var length = bytes[1];
	if (convert) {
		output = PST$createNewArray(length);
	} else {
		output = PST$createNewArray(1);
		output[0] = 1;
	}
	var value = null;
	var b = 0;
	var i = 0;
	while ((i < length)) {
		value = bytes[2][i];
		if ((value[0] != 3)) {
			return null;
		}
		b = value[1];
		if ((b > 255)) {
			return null;
		}
		if ((b < 0)) {
			if ((b >= -128)) {
				b += 255;
			} else {
				return null;
			}
		}
		if (convert) {
			output[i] = b;
		}
		i += 1;
	}
	return output;
};
<commit_msg>Regnerated pastel files for JS for Zip library.<commit_after>PST$sortedCopyOfArray = function(n) {
	var a = n.concat([]);
	a.sort();
	return a;
};

PST$multiplyList = function(l, n) {
	var o = [];
	var s = l.length;
	var i;
	while (n-- > 0) {
		for (i = 0; i < s; ++i) {
			o.push(l[i]);
		}
	}
	return o;
};

PST$checksubstring = function(s, index, lookfor) { return s.substring(index, index + lookfor.length) === lookfor; };

PST$stringTrimOneSide = function(s, isLeft) {
	var i = isLeft ? 0 : s.length - 1;
	var end = isLeft ? s.length : -1;
	var step = isLeft ? 1 : -1;
	var c;
	var trimming = true;
	while (trimming && i != end) {
		c = s.charAt(i);
		switch (c) {
			case ' ':
			case '\n':
			case '\t':
			case '\r':
				i += step;
				break;
			default:
				trimming = false;
				break;
		}
	}

	return isLeft ? s.substring(i) : s.substring(0, i + 1);
};

PST$floatParseHelper = function(o, s) {
	var t = parseFloat(s);
	if (t + '' == 'NaN') {
		o[0] = -1;
	} else {
		o[0] = 1;
		o[1] = t;
	}
};

PST$createNewArray = function(s) {
	var o = [];
	while (s-- > 0) o.push(null);
	return o;
};

PST$dictionaryKeys = function(d) {
	var o = [];
	for (var k in d) {
		o.push(k);
	}
	return o;
};

PST$dictionaryValues = function(d) {
	var o = [];
	for (var k in d) {
		o.push(d[k]);
	}
	return o;
};

PST$is_valid_integer = function(n) {
	var t = parseInt(n);
	return t < 0 || t >= 0;
};

PST$clearList = function(v) {
	v.length = 0;
};

PST$shuffle = function(v) {
	var t;
	var len = v.length;
	var sw;
	for (i = len - 1; i >= 0; --i) {
		sw = Math.floor(Math.random() * len);
		t = v[sw];
		v[sw] = v[i];
		v[i] = t;
	}
};

PST$stringEndsWith = function(s, v) {
	return s.indexOf(v, s.length - v.length) !== -1;
};

PST$intBuffer16 = PST$multiplyList([0], 16);
PST$floatBuffer16 = PST$multiplyList([0.0], 16);
PST$stringBuffer16 = PST$multiplyList([''], 16);

var lib_zip_ensureValidArchiveInfo = function(vm, args) {
	var sc = 0;
	if ((args[0][0] != 5)) {
		sc = 1;
	}
	if (((sc == 0) && (lib_zip_validateByteList(args[1], false) != null))) {
		sc = 2;
	}
	return buildInteger(vm[13], sc);
};

var lib_zip_initializeZipReader = function(vm, args) {
	var sc = 0;
	var byteArray = lib_zip_validateByteList(args[1], true);
	if ((byteArray == null)) {
		sc = 1;
	} else {
		var obj = args[0][1];
		obj[3] = PST$createNewArray(2);
		obj[3][0] = lib_zip_createZipReaderImpl(byteArray);
		obj[3][1] = 0;
		if ((obj[3][0] == null)) {
			sc = 2;
		}
	}
	return buildInteger(vm[13], sc);
};

var lib_zip_readerPeekNextEntry = function(vm, args) {
	var obj = args[0][1];
	var nd = obj[3];
	var output = args[1][1];
	var boolOut = PST$createNewArray(3);
	var nameOut = PST$createNewArray(1);
	var integers = [];
	lib_zip_readNextZipEntryImpl(nd[0], nd[1], boolOut, nameOut, integers);
	var problemsEncountered = !boolOut[0];
	var foundAnything = boolOut[1];
	var isDirectory = boolOut[2];
	if (problemsEncountered) {
		return vm[16];
	}
	nd[1] = (1 + nd[1]);
	setItemInList(output, 0, buildBoolean(vm[13], foundAnything));
	if (!foundAnything) {
		return vm[15];
	}
	setItemInList(output, 1, buildString(vm[13], nameOut[0]));
	if (isDirectory) {
		setItemInList(output, 2, buildBoolean(vm[13], isDirectory));
		return vm[15];
	}
	var byteValues = getItemFromList(output, 3)[1];
	var length = integers.length;
	var i = 0;
	var positiveNumbers = vm[13][9];
	var valuesOut = byteValues[2];
	i = 0;
	while ((i < length)) {
		valuesOut.push(positiveNumbers[integers[i]]);
		i += 1;
	}
	byteValues[1] = length;
	return vm[15];
};

var lib_zip_validateByteList = function(byteListValue, convert) {
	if ((byteListValue[0] != 6)) {
		return null;
	}
	var output = null;
	var bytes = byteListValue[1];
	var length = bytes[1];
	if (convert) {
		output = PST$createNewArray(length);
	} else {
		output = PST$createNewArray(1);
		output[0] = 1;
	}
	var value = null;
	var b = 0;
	var i = 0;
	while ((i < length)) {
		value = bytes[2][i];
		if ((value[0] != 3)) {
			return null;
		}
		b = value[1];
		if ((b > 255)) {
			return null;
		}
		if ((b < 0)) {
			if ((b >= -128)) {
				b += 255;
			} else {
				return null;
			}
		}
		if (convert) {
			output[i] = b;
		}
		i += 1;
	}
	return output;
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/fetchPage', function(req, res, next) {
	res.render(req.params.page);
});

module.exports = router;
<commit_msg>forgot some things<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/fetchPage', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	if (req.params.page === undefined) {
		res.json({
			status: "error",
			error: "Missing or invalid page parameter!"
		});
		return;
	}

	// "why do you do this? why not just pass user input into res.render?"
	// "path traversal"
	var pages = {
		"testPage": "testPage"
	};

	if (pages.indexOf(req.params.page) == -1) {
		res.json({
			status: "error",
			error: "Missing or invalid page parameter!"
		});
		return;
	}

	var currentPage = pages[req.params.page];
	res.render("pages/" + currentPage);
});

module.exports = router;
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { run } from '@ember/runloop';
import NodeModel from 'nomad-ui/models/node';
import pushPayloadToStore from '../../utils/push-payload-to-store';
import { settled } from '@ember/test-helpers';

module('Unit | Serializer | Node', function(hooks) {
  setupTest(hooks);
  hooks.beforeEach(function() {
    this.store = this.owner.lookup('service:store');
    this.subject = () => this.store.serializerFor('node');
  });

  test('local store is culled to reflect the state of findAll requests', async function(assert) {
    const findAllResponse = [
      makeNode('1', 'One', '127.0.0.1:4646'),
      makeNode('2', 'Two', '127.0.0.2:4646'),
      makeNode('3', 'Three', '127.0.0.3:4646'),
    ];

    const payload = this.subject().normalizeFindAllResponse(this.store, NodeModel, findAllResponse);
    pushPayloadToStore(this.store, payload, NodeModel.modelName);

    assert.equal(
      payload.data.length,
      findAllResponse.length,
      'Each original record is returned in the response'
    );

    assert.equal(
      this.store
        .peekAll('node')
        .filterBy('id')
        .get('length'),
      findAllResponse.length,
      'Each original record is now in the store'
    );

    const newFindAllResponse = [
      makeNode('2', 'Two', '127.0.0.2:4646'),
      makeNode('3', 'Three', '127.0.0.3:4646'),
      makeNode('4', 'Four', '127.0.0.4:4646'),
    ];

    let newPayload;
    run(() => {
      newPayload = this.subject().normalizeFindAllResponse(
        this.store,
        NodeModel,
        newFindAllResponse
      );
    });
    pushPayloadToStore(this.store, newPayload, NodeModel.modelName);

    await settled();
    assert.equal(
      newPayload.data.length,
      newFindAllResponse.length,
      'Each new record is returned in the response'
    );

    assert.equal(
      this.store
        .peekAll('node')
        .filterBy('id')
        .get('length'),
      newFindAllResponse.length,
      'The node length in the store reflects the new response'
    );

    assert.notOk(this.store.peekAll('node').findBy('id', '1'), 'Record One is no longer found');
  });

  function makeNode(id, name, ip) {
    return { ID: id, Name: name, HTTPAddr: ip };
  }

  const normalizationTestCases = [
    {
      name: 'Normal',
      in: {
        ID: 'test-node',
        HTTPAddr: '867.53.0.9:4646',
        Drain: false,
        Drivers: {
          docker: {
            Detected: true,
            Healthy: false,
          },
        },
      },
      out: {
        data: {
          id: 'test-node',
          type: 'node',
          attributes: {
            isDraining: false,
            httpAddr: '867.53.0.9:4646',
            drivers: [
              {
                name: 'docker',
                detected: true,
                healthy: false,
              },
            ],
            hostVolumes: [],
          },
          relationships: {
            allocations: {
              links: {
                related: '/v1/node/test-node/allocations',
              },
            },
          },
        },
      },
    },

    {
      name: 'Dots in driver names',
      in: {
        ID: 'test-node',
        HTTPAddr: '867.53.0.9:4646',
        Drain: false,
        Drivers: {
          'my.driver': {
            Detected: true,
            Healthy: false,
          },
          'my.other.driver': {
            Detected: false,
            Healthy: false,
          },
        },
      },
      out: {
        data: {
          id: 'test-node',
          type: 'node',
          attributes: {
            isDraining: false,
            httpAddr: '867.53.0.9:4646',
            drivers: [
              {
                name: 'my.driver',
                detected: true,
                healthy: false,
              },
              {
                name: 'my.other.driver',
                detected: false,
                healthy: false,
              },
            ],
            hostVolumes: [],
          },
          relationships: {
            allocations: {
              links: {
                related: '/v1/node/test-node/allocations',
              },
            },
          },
        },
      },
    },
  ];

  normalizationTestCases.forEach(testCase => {
    test(`normalization: ${testCase.name}`, async function(assert) {
      assert.deepEqual(this.subject().normalize(NodeModel, testCase.in), testCase.out);
    });
  });
});
<commit_msg>Improve the node serializer tests<commit_after>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { run } from '@ember/runloop';
import NodeModel from 'nomad-ui/models/node';
import pushPayloadToStore from '../../utils/push-payload-to-store';
import { settled } from '@ember/test-helpers';

module('Unit | Serializer | Node', function(hooks) {
  setupTest(hooks);
  hooks.beforeEach(function() {
    this.store = this.owner.lookup('service:store');
    this.subject = () => this.store.serializerFor('node');
  });

  test('local store is culled to reflect the state of findAll requests', async function(assert) {
    const findAllResponse = [
      makeNode('1', 'One', '127.0.0.1:4646'),
      makeNode('2', 'Two', '127.0.0.2:4646'),
      makeNode('3', 'Three', '127.0.0.3:4646'),
    ];

    const payload = this.subject().normalizeFindAllResponse(this.store, NodeModel, findAllResponse);
    pushPayloadToStore(this.store, payload, NodeModel.modelName);

    assert.equal(
      payload.data.length,
      findAllResponse.length,
      'Each original record is returned in the response'
    );

    assert.equal(
      this.store
        .peekAll('node')
        .filterBy('id')
        .get('length'),
      findAllResponse.length,
      'Each original record is now in the store'
    );

    const newFindAllResponse = [
      makeNode('2', 'Two', '127.0.0.2:4646'),
      makeNode('3', 'Three', '127.0.0.3:4646'),
      makeNode('4', 'Four', '127.0.0.4:4646'),
    ];

    let newPayload;
    run(() => {
      newPayload = this.subject().normalizeFindAllResponse(
        this.store,
        NodeModel,
        newFindAllResponse
      );
    });
    pushPayloadToStore(this.store, newPayload, NodeModel.modelName);

    await settled();
    assert.equal(
      newPayload.data.length,
      newFindAllResponse.length,
      'Each new record is returned in the response'
    );

    assert.equal(
      this.store
        .peekAll('node')
        .filterBy('id')
        .get('length'),
      newFindAllResponse.length,
      'The node length in the store reflects the new response'
    );

    assert.notOk(this.store.peekAll('node').findBy('id', '1'), 'Record One is no longer found');
  });

  function makeNode(id, name, ip) {
    return { ID: id, Name: name, HTTPAddr: ip };
  }

  const normalizationTestCases = [
    {
      name: 'Normal',
      in: {
        ID: 'test-node',
        HTTPAddr: '867.53.0.9:4646',
        Drain: false,
        Drivers: {
          docker: {
            Detected: true,
            Healthy: false,
          },
        },
        HostVolumes: {
          one: {
            Name: 'one',
            ReadOnly: true,
          },
          two: {
            Name: 'two',
            ReadOnly: false,
          },
        },
      },
      out: {
        data: {
          id: 'test-node',
          type: 'node',
          attributes: {
            isDraining: false,
            httpAddr: '867.53.0.9:4646',
            drivers: [
              {
                name: 'docker',
                detected: true,
                healthy: false,
              },
            ],
            hostVolumes: [{ name: 'one', readOnly: true }, { name: 'two', readOnly: false }],
          },
          relationships: {
            allocations: {
              links: {
                related: '/v1/node/test-node/allocations',
              },
            },
          },
        },
      },
    },

    {
      name: 'Dots in driver names',
      in: {
        ID: 'test-node',
        HTTPAddr: '867.53.0.9:4646',
        Drain: false,
        Drivers: {
          'my.driver': {
            Detected: true,
            Healthy: false,
          },
          'my.other.driver': {
            Detected: false,
            Healthy: false,
          },
        },
      },
      out: {
        data: {
          id: 'test-node',
          type: 'node',
          attributes: {
            isDraining: false,
            httpAddr: '867.53.0.9:4646',
            drivers: [
              {
                name: 'my.driver',
                detected: true,
                healthy: false,
              },
              {
                name: 'my.other.driver',
                detected: false,
                healthy: false,
              },
            ],
          },
          relationships: {
            allocations: {
              links: {
                related: '/v1/node/test-node/allocations',
              },
            },
          },
        },
      },
    },
  ];

  normalizationTestCases.forEach(testCase => {
    test(`normalization: ${testCase.name}`, async function(assert) {
      assert.deepEqual(this.subject().normalize(NodeModel, testCase.in), testCase.out);
    });
  });
});
<|endoftext|>