<commit_before>var errors = require('./errors');
var types = require('./types');
var constants = require('./constants');

function Context() {
    //this.commandStructure = [];
    this.blockBranches = [[]];
    this.currentBranch = 0;

    this.executionTree = [];
    this.currentExecutionTree = { parent: null, children: this.executionTree };

    this.macros = {};
    // add constants
    for (var i = 0; i < constants.length; i++) {
        var constantList = constants[i];
        for (var name in constantList) {
            if (constantList.hasOwnProperty(name)) this.macros[name.toLowerCase()] = constantList[name];
        }
    }

    this.scopes = [];
    this.pushScope();
}

Context.prototype.executionTreeStart = function(data) {
    var children = [], newItem = {
        data: data,
        children: children,
        parent: this.currentExecutionTree,
        toJSON: function() {
            return { data: data, children: children };
        }
    };

    this.currentExecutionTree.children.push(newItem);
    this.currentExecutionTree = newItem;
};
Context.prototype.executionTreeStop = function() {
    if (this.currentExecutionTree.parent == null) return;
    var currentItem = this.currentExecutionTree;

    this.currentExecutionTree = currentItem.parent;
};

Context.prototype.pushToBranch = function(obj) {
    this.blockBranches[this.currentBranch].push(obj);
};
Context.prototype.pushCommand = function(name, params) {
    this.pushToBranch({
        type: "command",
        command: name,
        params: params
    });
};

Context.prototype.pushWait = function(duration) {
    this.pushToBranch({
        type: "wait",
        duration: duration
    });
};

Context.prototype.branchTo = function(id) {
    this.pushToBranch({
        type: "branch",
        id: id
    });
    this.currentBranch = id;
};

Context.prototype.fork = function() {
    return this.blockBranches.push([]) - 1;
};

Context.prototype.pushScope = function() {
    this.scopes.unshift({});
    this.executionTreeStart({
        type: "scope",
        id: this.scopes.length - 1
    });
};

Context.prototype.popScope = function() {
    this.scopes.shift();
    this.executionTreeStop();
    if (!this.scopes.length) this.pushScope();
};

Context.prototype.findVariableScope = function(name) {
    var scopeLength = this.scopes.length;
    if (scopeLength > 1 && this.scopes[0].hasOwnProperty(name)) return 0;
    if (this.scopes[scopeLength - 1].hasOwnProperty(name)) return scopeLength - 1;
    return false;
};

Context.prototype.getVariable = function(name, scope) {
    if (scope == null) scope = this.findVariableScope(name);
    if (scope === false) errors.referenceError(name + " is not defined");

    return this.getVariableIn(name, this.scopes[scope]);
};

Context.prototype.getVariableIn = function(name, scope) {
    var currentValue = scope[name];
    if (currentValue && currentValue.isAssignable) return currentValue.getValue(value);
    else return currentValue;
};

Context.prototype.setVariable = function(name, value, scope) {
    if (scope == null) scope = this.findVariableScope(name);
    if (scope === false) scope = 0;

    this.setVariableIn(name, value, this.scopes[scope]);
};

Context.prototype.setVariableIn = function(name, value, scope) {
    var currentValue = scope[name];
    if (currentValue && currentValue.isAssignable) currentValue.setValue(value);
    else scope[name] = value;
};

Context.prototype.strictEqual = function(value1, value2) {
    if (value1 == null && value2 == null) return true;
    if (value1 == null || value2 == null) return false;

    var type1 = this.findCastType(value1);
    var type2 = this.findCastType(value2);

    if (type1.type !== type2.type) return false;

    if (type1.isEqual) return type1.equal(value1, value2, this);
    return value1 === value2;
};

Context.prototype.notStrictEqual = function(value1, value2) {
    return !this.strictEqual(value1, value2);
};

Context.prototype.cast = function(preferences, value) {
    if (value == null) return value;
    if (typeof value === 'boolean') value = value ? 1 : 0;

    if (!Array.isArray(preferences)) preferences = [preferences];

    var type = this.findCastType(value);
    if (!type.cast) errors.valueError("Cannot cast " + type.type + " to " + preferences.join(", "));

    if (preferences.indexOf(type.type) !== -1) return value;

    for (var i = 0; i < preferences.length; i++) {
        var name = preferences[i];

        if (type.cast[name]) return type.cast[name](value);
    }
    errors.valueError("Cannot cast " + type.type + " to " + preferences.join(", "));
};

Context.prototype.findCastType = function(value) {
    for (var key in types) {
        if (!types.hasOwnProperty(key)) continue;

        var type = types[key];
        if (!type.matches) continue;
        if (type.matches(value)) return type;
    }
    throw new Error("Cannot match type for value");
};

Context.prototype.castNumber = function(value) {
    return this.cast(["number"], value);
};

Context.prototype.castString = function(value) {
    return this.cast(["string"], value);
};

Context.prototype.castBoolean = function(value) {
    return this.cast(["boolean"], value);
};

Context.prototype.castMap = function(value) {
    return this.cast(["map"], value);
};

Context.prototype.expectNumber = function(value) {
    if (!types.number.matches(value)) errors.typeError("Expected number");
};

Context.prototype.expectString = function(value) {
     if (!types.string.matches(value)) errors.typeError("Expected string");
};

Context.prototype.expectBoolean = function(value) {
    if (!types.boolean.matches(value)) errors.typeError("Expected boolean");
};

Context.prototype.expectMap = function(value) {
    if (!types.map.matches(value)) errors.typeError("Expected map");
};

Context.prototype.expectBlock = function(value) {
    if (!types.block.matches(value)) errors.typeError("Expected block");
};

Context.prototype.expect = function(param, match) {
    if (!match) errors.typeError("Invalid value for parameter " + param);
};

module.exports = Context;<commit_msg>add 'test' property to branch<commit_after>var errors = require('./errors');
var types = require('./types');
var constants = require('./constants');

function Context() {
    //this.commandStructure = [];
    this.blockBranches = [[]];
    this.currentBranch = 0;

    this.executionTree = [];
    this.currentExecutionTree = { parent: null, children: this.executionTree };

    this.macros = {};
    // add constants
    for (var i = 0; i < constants.length; i++) {
        var constantList = constants[i];
        for (var name in constantList) {
            if (constantList.hasOwnProperty(name)) this.macros[name.toLowerCase()] = constantList[name];
        }
    }

    this.scopes = [];
    this.pushScope();
}

Context.prototype.executionTreeStart = function(data) {
    var children = [], newItem = {
        data: data,
        children: children,
        parent: this.currentExecutionTree,
        toJSON: function() {
            return { data: data, children: children };
        }
    };

    this.currentExecutionTree.children.push(newItem);
    this.currentExecutionTree = newItem;
};
Context.prototype.executionTreeStop = function() {
    if (this.currentExecutionTree.parent == null) return;
    var currentItem = this.currentExecutionTree;

    this.currentExecutionTree = currentItem.parent;
};

Context.prototype.pushToBranch = function(obj) {
    this.blockBranches[this.currentBranch].push(obj);
};
Context.prototype.pushCommand = function(name, params) {
    this.pushToBranch({
        type: "command",
        command: name,
        params: params
    });
};

Context.prototype.pushWait = function(duration) {
    this.pushToBranch({
        type: "wait",
        duration: duration
    });
};

Context.prototype.branchTo = function(id, test) {
    this.pushToBranch({
        type: "branch",
        id: id,
        test: test
    });
    this.currentBranch = id;
};

Context.prototype.fork = function() {
    return this.blockBranches.push([]) - 1;
};

Context.prototype.pushScope = function() {
    this.scopes.unshift({});
    this.executionTreeStart({
        type: "scope",
        id: this.scopes.length - 1
    });
};

Context.prototype.popScope = function() {
    this.scopes.shift();
    this.executionTreeStop();
    if (!this.scopes.length) this.pushScope();
};

Context.prototype.findVariableScope = function(name) {
    var scopeLength = this.scopes.length;
    if (scopeLength > 1 && this.scopes[0].hasOwnProperty(name)) return 0;
    if (this.scopes[scopeLength - 1].hasOwnProperty(name)) return scopeLength - 1;
    return false;
};

Context.prototype.getVariable = function(name, scope) {
    if (scope == null) scope = this.findVariableScope(name);
    if (scope === false) errors.referenceError(name + " is not defined");

    return this.getVariableIn(name, this.scopes[scope]);
};

Context.prototype.getVariableIn = function(name, scope) {
    var currentValue = scope[name];
    if (currentValue && currentValue.isAssignable) return currentValue.getValue(value);
    else return currentValue;
};

Context.prototype.setVariable = function(name, value, scope) {
    if (scope == null) scope = this.findVariableScope(name);
    if (scope === false) scope = 0;

    this.setVariableIn(name, value, this.scopes[scope]);
};

Context.prototype.setVariableIn = function(name, value, scope) {
    var currentValue = scope[name];
    if (currentValue && currentValue.isAssignable) currentValue.setValue(value);
    else scope[name] = value;
};

Context.prototype.strictEqual = function(value1, value2) {
    if (value1 == null && value2 == null) return true;
    if (value1 == null || value2 == null) return false;

    var type1 = this.findCastType(value1);
    var type2 = this.findCastType(value2);

    if (type1.type !== type2.type) return false;

    if (type1.isEqual) return type1.equal(value1, value2, this);
    return value1 === value2;
};

Context.prototype.notStrictEqual = function(value1, value2) {
    return !this.strictEqual(value1, value2);
};

Context.prototype.cast = function(preferences, value) {
    if (value == null) return value;
    if (typeof value === 'boolean') value = value ? 1 : 0;

    if (!Array.isArray(preferences)) preferences = [preferences];

    var type = this.findCastType(value);
    if (!type.cast) errors.valueError("Cannot cast " + type.type + " to " + preferences.join(", "));

    if (preferences.indexOf(type.type) !== -1) return value;

    for (var i = 0; i < preferences.length; i++) {
        var name = preferences[i];

        if (type.cast[name]) return type.cast[name](value);
    }
    errors.valueError("Cannot cast " + type.type + " to " + preferences.join(", "));
};

Context.prototype.findCastType = function(value) {
    for (var key in types) {
        if (!types.hasOwnProperty(key)) continue;

        var type = types[key];
        if (!type.matches) continue;
        if (type.matches(value)) return type;
    }
    throw new Error("Cannot match type for value");
};

Context.prototype.castNumber = function(value) {
    return this.cast(["number"], value);
};

Context.prototype.castString = function(value) {
    return this.cast(["string"], value);
};

Context.prototype.castBoolean = function(value) {
    return this.cast(["boolean"], value);
};

Context.prototype.castMap = function(value) {
    return this.cast(["map"], value);
};

Context.prototype.expectNumber = function(value) {
    if (!types.number.matches(value)) errors.typeError("Expected number");
};

Context.prototype.expectString = function(value) {
     if (!types.string.matches(value)) errors.typeError("Expected string");
};

Context.prototype.expectBoolean = function(value) {
    if (!types.boolean.matches(value)) errors.typeError("Expected boolean");
};

Context.prototype.expectMap = function(value) {
    if (!types.map.matches(value)) errors.typeError("Expected map");
};

Context.prototype.expectBlock = function(value) {
    if (!types.block.matches(value)) errors.typeError("Expected block");
};

Context.prototype.expect = function(param, match) {
    if (!match) errors.typeError("Invalid value for parameter " + param);
};

module.exports = Context;<|endoftext|>


<commit_before>/*global MainGame*/
var UnitAI={
	takeTurn: function(unit){
		if (unit.target === null) {
			unit.target = UnitAI.findTarget(unit);
		}

		UnitAI.makeMove(unit,UnitAI.chooseMove());

		if(unit.isAttacking)
			UnitAI.attackTarget(unit);
	},

	findTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			if(unit.currentIndex === unit.origin && MainGame.board.at(unit.currentIndex).getBuilding().name !== 'rubble')
				return unit.origin;
			else
				return MainGame.board.findBuilding('palace',null,null,null)[0];
		} else if (unit.type === Unit.Army) { // Should never call findTarget with a homeless group, but just to be sure
			var riotIndecies = MainGame.board.findUnits(Unit.Riot);
			if (riotIndecies.length > 0) {
				var palaceIndex = MainGame.board.findBuilding('palace',null,null,null)[0];
				var armyDistance = MainGame.board.distanceOf(palaceIndex, unit.currentIndex);
				var minDistance = null;
				var minIndex = null;
				for (var i = 0; i < riotIndecies.length; ++i) {
					var totalDistance = MainGame.board.distanceOf(palaceIndex,riotIndecies[i]) + armyDistance;
					if (!minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					} else if (totalDistance < minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					}
				}

				return MainGame.board.at(minIndex).getUnit();
			}
		}
	},

	chooseMove: function(unit) {
		var targetIndex = null;
		if (unit.type === Unit.Army) {
			if (unit.target !== null) {
				if (MainGame.board.distanceOf(unit.currentIndex, unit.target.currentIndex) === 1) {
					unit.isAttacking = true;
					return null;
				}
				targetIndex = unit.target.currentIndex;
			} else {
				if (MainGame.board.at(unit.currentIndex).getBuilding().name === "road") {
					var adjacent = MainGame.board.allAdjacent(unit.currentIndex,1);
					var roads = [];
					for(var i=0; i<adjacent.length; ++i){
						if(MainGame.board.at(adjacent[i]).getBuilding().name)
							roads.push(adjacent[i]);
					}
					if(roads.length>0)
						return roads[Math.floor(Math.random()*roads.length)];
					else
						targetIndex = unit.origin;
				}else{
					targetIndex = unit.origin;
				}
			}
		} else {
			if (unit.currentIndex === unit.target) {
				unit.isAttacking = true;
				return null;
			}
			targetIndex = unit.target;
		}

		var adjacentTiles = MainGame.board.allAdjacent(unit.currentIndex, 1);
		var distances = [];
		var buildings = [];
		for(var i=0; i<adjacentTiles.length; ++i){
			var tile = MainGame.board.at(adjacentTiles[i]);
			if(tile.hasBuilding())
				buildings.push(tile.getBuilding().name);
			else
				buildings.push("");
			if(!tile.hasUnit())
				distances.push(MainGame.board.distanceOf(adjacentTiles[i],targetIndex));
			else{
				if(unit.type === Unit.Riot && tile.getUnit().type === Unit.Riot)
					UnitAI.mergeUnits(tile.getUnit(),unit);
			}
		}

		// targeting nearby buildings
		if(unit.type===Unit.Riot){
			// simple sorting of building names
			for(var i=0; i<buildings.length; ++i){
				for(var j=i+1; j<buildings.length; ++j){
					if(buildings[j]==="palace" || (buildings[i]!=="palace" && buildings[j]!=="road" && buildings[j]!=="")){
						var temp = distances[i];
						distances[i] = distances[j];
						distances[j] = temp;
						temp = adjacentTiles[i];
						adjacentTiles[i] = adjacentTiles[j];
						adjacentTiles[j] = temp;
						temp = buildings[i];
						buildings[i] = buildings[j];
						buildings[j] = temp;
					}
				}
			}

			if(buildings[0]!=="road" && buildings[0]!==""){
				unit.target = adjacentTiles[0];
				return adjacentTiles[0];
			}
		}

		// simple sorting of distances
		for(var i=0; i<distances.length; ++i){
			for(var j=i+1; j<distances.length; ++j){
				if(distances[j]<distances[i]){
					var temp = distances[i];
					distances[i] = distances[j];
					distances[j] = temp;
					temp = adjacentTiles[i];
					adjacentTiles[i] = adjacentTiles[j];
					adjacentTiles[j] = temp;
					temp = buildings[i];
					buildings[i] = buildings[j];
					buildings[j] = temp;
				}
			}
		}

		if(distances[0]===distances[1]){
			var tile0 = MainGame.board.at(adjacentTiles[0]);
			var tile1 = MainGame.board.at(adjacentTiles[1]);
			if(buildings[0]==="road" && buildings[1]!=="road")
				return adjacentTiles[0];
			else if(buildings[0]!=="road" && buildings[0]==="road")
				return adjacentTiles[1];
			if(buildings[0]==="road")
				return adjacentTiles[0];
			if(buildings[1]==="road")
				return adjacentTiles[1];
		}else{
			return adjacentTiles[0];
		}
		//if none of the above conditions are met, then randomly choose a tile
		return (Math.floor(Math.random()*2)===0?adjacentTiles[0]:adjacentTiles[1]);
	},

	makeMove: function(unit,destIndex){
		if(destIndex===null)
			return;

		MainGame.board.at(unit.currentIndex).setUnit(null);
		MainGame.board.at(destIndex).setUnit(unit);
		unit.currentIndex = destIndex;
	},

	attackTarget: function(unit){
		if (unit.type === Unit.Riot) {
			var targetTile = MainGame.board.at(unit.target);
			if(unit.heath >= targetTile.getBuilding().heath){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetTile.getBuilding().damage(unit.heath);
		} else {
			var targetUnit = unit.target;
			if(unit.health >= targetUnit.health){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetUnit.takeDamage(unit.heath);
		}
	},

	mergeUnits: function(unit1, unit2) {
		var transfer = Math.min(unit2.health, 5 - unit1.heath);
		unit1.addPeople(transfer);
		unit2.subtractPeople(transfer);
	}
};<commit_msg>prioritized merging from weaker riots into stronger riots<commit_after>/*global MainGame*/
var UnitAI={
	takeTurn: function(unit){
		if (unit.target === null) {
			unit.target = UnitAI.findTarget(unit);
		}

		UnitAI.makeMove(unit,UnitAI.chooseMove());

		if(unit.isAttacking)
			UnitAI.attackTarget(unit);
	},

	findTarget: function(unit) {
		if (unit.type === Unit.Riot) {
			if(unit.currentIndex === unit.origin && MainGame.board.at(unit.currentIndex).getBuilding().name !== 'rubble')
				return unit.origin;
			else
				return MainGame.board.findBuilding('palace',null,null,null)[0];
		} else if (unit.type === Unit.Army) { // Should never call findTarget with a homeless group, but just to be sure
			var riotIndecies = MainGame.board.findUnits(Unit.Riot);
			if (riotIndecies.length > 0) {
				var palaceIndex = MainGame.board.findBuilding('palace',null,null,null)[0];
				var armyDistance = MainGame.board.distanceOf(palaceIndex, unit.currentIndex);
				var minDistance = null;
				var minIndex = null;
				for (var i = 0; i < riotIndecies.length; ++i) {
					var totalDistance = MainGame.board.distanceOf(palaceIndex,riotIndecies[i]) + armyDistance;
					if (!minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					} else if (totalDistance < minDistance) {
						minDistance = totalDistance;
						minIndex = riotIndecies[i];
					}
				}

				return MainGame.board.at(minIndex).getUnit();
			}
		}
	},

	chooseMove: function(unit) {
		var targetIndex = null;
		if (unit.type === Unit.Army) {
			if (unit.target !== null) {
				if (MainGame.board.distanceOf(unit.currentIndex, unit.target.currentIndex) === 1) {
					unit.isAttacking = true;
					return null;
				}
				targetIndex = unit.target.currentIndex;
			} else {
				if (MainGame.board.at(unit.currentIndex).getBuilding().name === "road") {
					var adjacent = MainGame.board.allAdjacent(unit.currentIndex,1);
					var roads = [];
					for(var i=0; i<adjacent.length; ++i){
						if(MainGame.board.at(adjacent[i]).getBuilding().name)
							roads.push(adjacent[i]);
					}
					if(roads.length>0)
						return roads[Math.floor(Math.random()*roads.length)];
					else
						targetIndex = unit.origin;
				}else{
					targetIndex = unit.origin;
				}
			}
		} else {
			if (unit.currentIndex === unit.target) {
				unit.isAttacking = true;
				return null;
			}
			targetIndex = unit.target;
		}

		var adjacentTiles = MainGame.board.allAdjacent(unit.currentIndex, 1);
		var distances = [];
		var buildings = [];
		for(var i=0; i<adjacentTiles.length; ++i){
			var tile = MainGame.board.at(adjacentTiles[i]);
			if(tile.hasBuilding())
				buildings.push(tile.getBuilding().name);
			else
				buildings.push("");
			if(!tile.hasUnit())
				distances.push(MainGame.board.distanceOf(adjacentTiles[i],targetIndex));
			else{
				var adjacentUnit = tile.getUnit();
				if(unit.type === Unit.Riot && adjacentUnit.type === Unit.Riot && unit.heath <= adjacentUnit.heath)
					UnitAI.mergeUnits(adjacentUnit,unit);
			}
		}

		// targeting nearby buildings
		if(unit.type===Unit.Riot){
			// simple sorting of building names
			for(var i=0; i<buildings.length; ++i){
				for(var j=i+1; j<buildings.length; ++j){
					if(buildings[j]==="palace" || (buildings[i]!=="palace" && buildings[j]!=="road" && buildings[j]!=="")){
						var temp = distances[i];
						distances[i] = distances[j];
						distances[j] = temp;
						temp = adjacentTiles[i];
						adjacentTiles[i] = adjacentTiles[j];
						adjacentTiles[j] = temp;
						temp = buildings[i];
						buildings[i] = buildings[j];
						buildings[j] = temp;
					}
				}
			}

			if(buildings[0]!=="road" && buildings[0]!==""){
				unit.target = adjacentTiles[0];
				return adjacentTiles[0];
			}
		}

		// simple sorting of distances
		for(var i=0; i<distances.length; ++i){
			for(var j=i+1; j<distances.length; ++j){
				if(distances[j]<distances[i]){
					var temp = distances[i];
					distances[i] = distances[j];
					distances[j] = temp;
					temp = adjacentTiles[i];
					adjacentTiles[i] = adjacentTiles[j];
					adjacentTiles[j] = temp;
					temp = buildings[i];
					buildings[i] = buildings[j];
					buildings[j] = temp;
				}
			}
		}

		if(distances[0]===distances[1]){
			var tile0 = MainGame.board.at(adjacentTiles[0]);
			var tile1 = MainGame.board.at(adjacentTiles[1]);
			if(buildings[0]==="road" && buildings[1]!=="road")
				return adjacentTiles[0];
			else if(buildings[0]!=="road" && buildings[0]==="road")
				return adjacentTiles[1];
			if(buildings[0]==="road")
				return adjacentTiles[0];
			if(buildings[1]==="road")
				return adjacentTiles[1];
		}else{
			return adjacentTiles[0];
		}
		//if none of the above conditions are met, then randomly choose a tile
		return (Math.floor(Math.random()*2)===0?adjacentTiles[0]:adjacentTiles[1]);
	},

	makeMove: function(unit,destIndex){
		if(destIndex===null)
			return;

		MainGame.board.at(unit.currentIndex).setUnit(null);
		MainGame.board.at(destIndex).setUnit(unit);
		unit.currentIndex = destIndex;
	},

	attackTarget: function(unit){
		if (unit.type === Unit.Riot) {
			var targetTile = MainGame.board.at(unit.target);
			if(unit.heath >= targetTile.getBuilding().heath){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetTile.getBuilding().damage(unit.heath);
		} else {
			var targetUnit = unit.target;
			if(unit.health >= targetUnit.health){
				unit.target = null;
				unit.isAttacking = false;
			}
			targetUnit.takeDamage(unit.heath);
		}
	},

	mergeUnits: function(unit1, unit2) {
		var transfer = Math.min(unit2.health, 5 - unit1.heath);
		unit1.addPeople(transfer);
		unit2.subtractPeople(transfer);
	}
};<|endoftext|>


<commit_before>require('date-utils');
var config = require('./config'),
    fs = require('fs'),
    filename = process.argv[2] + Date.today().toFormat('-YYYY-MM-DD')+'.json',
    out = fs.createWriteStream(filename),
    mongoose = require('mongoose'),
    quotes = mongoose.model('quotes', {msg: String, src: String});

var escapeQuotes = function (str) {
  return str.replace(/"/g, '\\"');
};

out.on('open', function (fd) {
  mongoose.connect(config.db_uri);
  var q_stream = quotes.find().stream();
  out.write('[\n');
  q_stream.on('data', function (q) {
    out.write('{"msg": "' + escapeQuotes(q.msg) + '", "src": "' + escapeQuotes(q.src) +'"},\n');
  }).on('error', function (err) {
    throw err;
  }).on('close', function () {
    mongoose.disconnect();
    out.write(']\n');
    out.end();
    console.log('backup completed...');
    console.log('database contents have been written to ' + filename + '.');
  });
});
<commit_msg>Update backup.js to use util.format().<commit_after>require('date-utils');
var config = require('./config'),
    util = require('util'),
    fs = require('fs'),
    filename = process.argv[2] + Date.today().toFormat('-YYYY-MM-DD')+'.json',
    out = fs.createWriteStream(filename),
    mongoose = require('mongoose'),
    quotes = mongoose.model('quotes', {msg: String, src: String});

var escapeQuotes = function (str) {
  return str.replace(/"/g, '\\"');
};

out.on('open', function (fd) {
  mongoose.connect(config.db_uri);
  var q_stream = quotes.find().stream();
  out.write('[\n');
  q_stream.on('data', function (q) {
    out.write(util.format('{"msg": "%s", "src": "%s"},\n', escapeQuotes(q.msg), escapeQuotes(q.src)));
  }).on('error', function (err) {
    throw err;
  }).on('close', function () {
    mongoose.disconnect();
    out.write(']\n');
    out.end();
    console.log('backup completed...');
    console.log('database contents have been written to ' + filename + '.');
  });
});
<|endoftext|>


<commit_before>'use-strict'

const utils = require('./utils')

module.exports = function broken (utxos, output, feeRate) {
  if (!isFinite(output.value)) throw new TypeError('Expected Satoshi value, got ' + output.value)

  const inAccum = utils.sum(utxos)
  const outputBytes = utils.outputBytes(output)
  const value = output.value

  var bytesAccum = utils.transactionBytes(utxos, [])
  var outAccum = 0
  var outputs = []

  while (true) {
    const fee = feeRate * (bytesAccum + outputBytes)

    // did we bust?
    if (inAccum < (outAccum + fee + value)) {
      // premature?
      if (outAccum === 0) return { fee: fee }

      break
    }

    bytesAccum += outputBytes
    outAccum += value
    outputs.push(Object.assign({}, output))
  }

  return utils.finalize(utxos, outputs, feeRate)
}
<commit_msg>broken: no need to clone the output<commit_after>'use-strict'

const utils = require('./utils')

module.exports = function broken (utxos, output, feeRate) {
  if (!isFinite(output.value)) throw new TypeError('Expected Satoshi value, got ' + output.value)

  const inAccum = utils.sum(utxos)
  const outputBytes = utils.outputBytes(output)
  const value = output.value

  var bytesAccum = utils.transactionBytes(utxos, [])
  var outAccum = 0
  var outputs = []

  while (true) {
    const fee = feeRate * (bytesAccum + outputBytes)

    // did we bust?
    if (inAccum < (outAccum + fee + value)) {
      // premature?
      if (outAccum === 0) return { fee: fee }

      break
    }

    bytesAccum += outputBytes
    outAccum += value
    outputs.push(output)
  }

  return utils.finalize(utxos, outputs, feeRate)
}
<|endoftext|>


<commit_before>var inside = require('point-in-polygon');
var URI = require('uri-js');

var GeoJSON = module.exports = {

///////////////////////////////////////////////////////////////////// VALIDATION

    isGeoJSON: function ( x ) {
        // Validate a GeoJSON object.
        return (
            GeoJSON.isGeometry(x) ||
            GeoJSON.isFeature(x)  ||
            GeoJSON.isFeatureCollection(x)
        );
    },

    isGeometry: function ( x ) {
        // Validate a GeoJSON Geometry.
        return (
            GeoJSON.isPoint(x) ||
            GeoJSON.isMultiPoint(x) ||
            GeoJSON.isLineString(x) ||
            GeoJSON.isMultiLineString(x) ||
            GeoJSON.isPolygon(x) ||
            GeoJSON.isMultiPolygon(x) ||
            GeoJSON.isGeometryCollection(x)
        );
    },

    isPosition: function ( x ) {
        // Validate a GeoJSON Position.
        return (
            Array.isArray(x) &&
            x.length > 1 &&
            x.every(
                function ( element ) {
                    return (typeof element === 'number');
                }
            )
        );
    },

    isPointCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON Point.
        return GeoJSON.isPosition(x);
    },

    isMultiPointCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiPoint.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isPosition)
        );
    },

    isLineStringCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON LineString.
        return (
            Array.isArray(x) &&
            x.length > 1 &&
            GeoJSON.isMultiPointCoordinates(x)
        );
    },

    isLinearRingCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON LinearRing.
        return (
            Array.isArray(x) &&
            x.length > 3 &&
            GeoJSON.isLineStringCoordinates(x) &&
            GeoJSON.equalPositions(x[0],x[x.length-1])
        );
    },

    isMultiLineStringCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiLineString.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isLineStringCoordinates)
        );
    },

    isPolygonCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON Polygon.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isLinearRingCoordinates) &&
            x.every(
                function ( LinearRingPosition , i , PolygonPosition ) {
                    if (i == 0) return true;
                    else return GeoJSON.containedPolygon(
                        LinearRingPosition,
                        PolygonPosition[0]
                    );
                }
            )
        );
    },

    isMultiPolygonCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiPolygon.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isPolygonCoordinates)
        );
    },

    isPoint: function ( x ) {
        // Validate a GeoJSON Point.
        return (
            x != null &&
            x.type === 'Point' &&
            GeoJSON.isPointCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiPoint: function ( x ) {
        // Validate a GeoJSON MultiPoint.
        return (
            x != null &&
            x.type === 'MultiPoint' &&
            GeoJSON.isMultiPointCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isLineString: function ( x ) {
        // Validate a GeoJSON LineString.
        return (
            x != null &&
            x.type === 'LineString' &&
            GeoJSON.isLineStringCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiLineString: function ( x ) {
        // Validate a GeoJSON MultiLineString.
        return (
            x != null &&
            x.type === 'MultiLineString' &&
            GeoJSON.isMultiLineStringCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isPolygon: function ( x ) {
        // Validate a GeoJSON Polygon.
        return (
            x != null &&
            x.type === 'Polygon' &&
            GeoJSON.isPolygonCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiPolygon: function ( x ) {
        // Validate a GeoJSON MultiPolygon.
        return (
            x != null &&
            x.type === 'MultiPolygon' &&
            GeoJSON.isMultiPolygonCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isGeometryCollection: function ( x ) {
        // Validate a GeoJSON GeometryCollection.
        return (
            x != null &&
            x.type === 'GeometryCollection' &&
            Array.isArray(x.geometries) &&
            x.geometries.every(GeoJSON.isGeometry) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isFeature: function ( x ) {
        // Validate a GeoJSON Feature.
        return (
            x != null &&
            x.type === 'Feature' &&
            typeof x.properties === 'object' &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x) &&
            (
                x.geometry === null ||
                GeoJSON.isGeometry(x.geometry)
            )
        );
    },

    isFeatureCollection: function ( x ) {
        // Validate a GeoJSON FeatureCollection.
        return (
            x != null &&
            x.type === 'FeatureCollection' &&
            Array.isArray(x.features) &&
            x.features.every(GeoJSON.isFeature) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isCRS: function ( x ) {
        // Validate a GeoJSON Coordinate Reference System.
        return (
            x != null &&
            (
                (
                    x.type === 'name' &&
                    x.properties != null &&
                    typeof x.properties.name === 'string' &&
                    x.properties.name.length > 0
                ) ||
                (
                    x.type === 'link' &&
                    GeoJSON.isLink(x.properties)
                )
            )
        );
    },

    validCRS: function ( x ) {
        // Validate the CRS property of a GeoJSON object.
        return (
            x != null &&
            (
                typeof x.crs === 'undefined' ||
                x.crs === null ||
                GeoJSON.isCRS(x.crs)
            )
        )
    },

    isBbox: function ( x ) {
        throw 'Not Implemented'
    },

    validBbox: function ( x ) {
        // Validate the bbox property of a GeoJSON object.
        return (
            x != null &&
            (
                typeof x.bbox === 'undefined' ||
                (
                    Array.isArray(x.bbox) &&
                    x.bbox.length%2 === 0 &&
                    GeoJSON.isBbox()
                )
            )
        );
    },

    isLink: function ( x ) {
        // Validate a GeoJSON Link.
        try {
            return (
                x != null &&
                x.properties != null &&
                typeof x.properties.href === 'string' &&
                URI.parse(x.properties.href) &&
                (
                    typeof x.properties.type === 'undefined' ||
                    (
                        typeof x.properties.type === 'string' &&
                        x.properties.type.length > 0
                    )
                )
            );
        }
        catch (e) {
            return false;
        }
    },

//////////////////////////////////////////////////////////////////////// UTILITY

    equalPositions: function ( a , b ) {
        // Compare two GeoJSON Positions for equality.
        return (
            GeoJSON.isPosition(a) && GeoJSON.isPosition(b) &&
            a.length == b.length &&
            a.every(
                function ( element , index ) {
                    return (a[index] == b[index]);
                }
            )
        );
    },

    containedPolygon: function ( inner , outer ) {
        // Determine whether one GeoJSON LinearRing contains another.
        return inner.every(
            function ( Position ) {
                return inside(Position,outer);
            }
        );
    },

/////////////////////////////////////////////////////////////////////// TEMPLATE

    Point: function ( latitude , longitude , altitude ) {
        // Create a valid GeoJSON Point geometry.
        var Point = null;
        if (typeof longitude === 'number' && typeof latitude === 'number') {
            Point = {
                type: 'Point',
                coordinates: [longitude,latitude]
            };
            if (typeof altitude === 'number') Point.coordinates.push(altitude);
        }
        return Point;
    },

    Feature: function ( Geometry , properties ) {
        // Create a valid GeoJSON Feature.
        var Feature = {
            type: 'Feature',
            geometry: null,
            properties: (typeof properties === 'object') ? properties : {}
        };
        if (GeoJSON.isGeometry(Geometry)) Feature.geometry = Geometry;
        return Feature;
    },

    FeatureCollection: function ( Features ) {
        // Create a valid GeoJSON FeatureCollection.
        var FeatureCollection = {
            type: 'FeatureCollection',
            features: []
        };
        if (GeoJSON.isFeature(Features)) {
            FeatureCollection.features.push(Features);
        }
        else if (Array.isArray(Features)) Features.forEach(
            function ( Feature ) {
                if (GeoJSON.isFeature(Feature)) {
                    FeatureCollection.features.push(Feature);
                }
            }
        );
        return FeatureCollection;
    },

    GeometryCollection: function ( Geometries ) {
        // Create a valid GeoJSON GeometryCollection.
        var GeometryCollection = {
            type: 'GeometryCollection',
            geometries: []
        };
        if (GeoJSON.isGeometry(Geometries)) {
            GeometryCollection.geometries.push(Geometries);
        }
        else if (Array.isArray(Geometries)) Geometries.forEach(
            function ( Geometry ) {
                if (GeoJSON.isGeometry(Geometry)) {
                    GeometryCollection.geometries.push(Geometry);
                }
            }
        );
        return GeometryCollection;
    },

///////////////////////////////////////////////////////////////////// EXTRACTION

    positionsOf: function ( geojson ) {
        // Find all the Positions in a valid GeoJSON object.
        var positions = [];
        var extractLineStringPositions = function ( LineStringPosition ) {
            LineStringPosition.forEach(
                function ( Position ) {
                    positions.push(Position);
                }
            );
        };
        var extractPolygonPositions = function ( PolygonPosition ) {
            PolygonPosition.forEach(extractLineStringPositions);
        };
        switch (geojson.type) {
            case 'Point':
                positions.push(geojson.coordinates);
                break;
            case 'MultiPoint':
            case 'LineString':
                extractLineStringPositions(geojson.coordinates);
                break;
            case 'MultiLineString':
            case 'Polygon':
                extractPolygonPositions(geojson.coordinates);
                break;
            case 'MultiPolygon':
                geojson.coordinates.forEach(extractPolygonPositions);
                break;
            case 'GeometryCollection':
                extractLineStringPositions(
                    GeoJSON.positionsOf(geojson.geometries)
                );
                break;
            case 'Feature':
                extractLineStringPositions(
                    GeoJSON.positionsOf(geojson.geometry)
                );
                break;
            case 'FeatureCollection':
                geojson.features.forEach(
                    function ( Feature ) {
                        extractLineStringPositions(
                            GeoJSON.positionsOf(Feature.geometry)
                        );
                    }
                );
                break;
        }
        return positions;
    },

    featuresOf: function ( geojson ) {
        // Find all Features in a valid GeoJSON object.
        var features = [];
        switch (geojson.type) {
            case 'Feature':
                features.push(geojson);
                break;
            case 'FeatureCollection':
                geojson.features.forEach(
                    function ( Feature ) {
                        GeoJSON.featuresOf(Feature).forEach(
                            function ( Feature ) {
                                features.push(Feature);
                            }
                        );
                    }
                );
                break;
        }
        return features;
    },

    geometriesOf: function ( geojson ) {
        // Find all Geometries in a valid GeoJSON object.
        var geometries = [];
        var extractFeatureGeometries = function ( Feature ) {
            GeoJSON.geometriesOf(Feature.geometry).forEach(
                function ( Geometry ) {
                    geometries.push(Geometry);
                }
            );
        };
        switch (geojson.type) {
            case 'Point':
            case 'MultiPoint':
            case 'LineString':
            case 'MultiLineString':
            case 'Polygon':
            case 'MultiPolygon':
                geometries.push(geojson);
                break;
            case 'GeometryCollection':
                geojson.geometries.forEach(
                    function ( Geometry ) {
                        GeoJSON.geometriesOf(Geometry).forEach(
                            function ( Geometry ) {
                                geometries.push(Geometry);
                            }
                        );
                    }
                );
                break;
            case 'Feature':
                extractFeatureGeometries(geojson);
                break;
            case 'FeatureCollection':
                geojson.features.forEach(extractFeatureGeometries);
                break;
        }
        return geometries;
    }

};
<commit_msg>Throw an Error object instead of just a string.<commit_after>var inside = require('point-in-polygon');
var URI = require('uri-js');

var GeoJSON = module.exports = {

///////////////////////////////////////////////////////////////////// VALIDATION

    isGeoJSON: function ( x ) {
        // Validate a GeoJSON object.
        return (
            GeoJSON.isGeometry(x) ||
            GeoJSON.isFeature(x)  ||
            GeoJSON.isFeatureCollection(x)
        );
    },

    isGeometry: function ( x ) {
        // Validate a GeoJSON Geometry.
        return (
            GeoJSON.isPoint(x) ||
            GeoJSON.isMultiPoint(x) ||
            GeoJSON.isLineString(x) ||
            GeoJSON.isMultiLineString(x) ||
            GeoJSON.isPolygon(x) ||
            GeoJSON.isMultiPolygon(x) ||
            GeoJSON.isGeometryCollection(x)
        );
    },

    isPosition: function ( x ) {
        // Validate a GeoJSON Position.
        return (
            Array.isArray(x) &&
            x.length > 1 &&
            x.every(
                function ( element ) {
                    return (typeof element === 'number');
                }
            )
        );
    },

    isPointCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON Point.
        return GeoJSON.isPosition(x);
    },

    isMultiPointCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiPoint.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isPosition)
        );
    },

    isLineStringCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON LineString.
        return (
            Array.isArray(x) &&
            x.length > 1 &&
            GeoJSON.isMultiPointCoordinates(x)
        );
    },

    isLinearRingCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON LinearRing.
        return (
            Array.isArray(x) &&
            x.length > 3 &&
            GeoJSON.isLineStringCoordinates(x) &&
            GeoJSON.equalPositions(x[0],x[x.length-1])
        );
    },

    isMultiLineStringCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiLineString.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isLineStringCoordinates)
        );
    },

    isPolygonCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON Polygon.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isLinearRingCoordinates) &&
            x.every(
                function ( LinearRingPosition , i , PolygonPosition ) {
                    if (i == 0) return true;
                    else return GeoJSON.containedPolygon(
                        LinearRingPosition,
                        PolygonPosition[0]
                    );
                }
            )
        );
    },

    isMultiPolygonCoordinates: function ( x ) {
        // Validate the coordinates of a GeoJSON MultiPolygon.
        return (
            Array.isArray(x) &&
            x.every(GeoJSON.isPolygonCoordinates)
        );
    },

    isPoint: function ( x ) {
        // Validate a GeoJSON Point.
        return (
            x != null &&
            x.type === 'Point' &&
            GeoJSON.isPointCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiPoint: function ( x ) {
        // Validate a GeoJSON MultiPoint.
        return (
            x != null &&
            x.type === 'MultiPoint' &&
            GeoJSON.isMultiPointCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isLineString: function ( x ) {
        // Validate a GeoJSON LineString.
        return (
            x != null &&
            x.type === 'LineString' &&
            GeoJSON.isLineStringCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiLineString: function ( x ) {
        // Validate a GeoJSON MultiLineString.
        return (
            x != null &&
            x.type === 'MultiLineString' &&
            GeoJSON.isMultiLineStringCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isPolygon: function ( x ) {
        // Validate a GeoJSON Polygon.
        return (
            x != null &&
            x.type === 'Polygon' &&
            GeoJSON.isPolygonCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isMultiPolygon: function ( x ) {
        // Validate a GeoJSON MultiPolygon.
        return (
            x != null &&
            x.type === 'MultiPolygon' &&
            GeoJSON.isMultiPolygonCoordinates(x.coordinates) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isGeometryCollection: function ( x ) {
        // Validate a GeoJSON GeometryCollection.
        return (
            x != null &&
            x.type === 'GeometryCollection' &&
            Array.isArray(x.geometries) &&
            x.geometries.every(GeoJSON.isGeometry) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isFeature: function ( x ) {
        // Validate a GeoJSON Feature.
        return (
            x != null &&
            x.type === 'Feature' &&
            typeof x.properties === 'object' &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x) &&
            (
                x.geometry === null ||
                GeoJSON.isGeometry(x.geometry)
            )
        );
    },

    isFeatureCollection: function ( x ) {
        // Validate a GeoJSON FeatureCollection.
        return (
            x != null &&
            x.type === 'FeatureCollection' &&
            Array.isArray(x.features) &&
            x.features.every(GeoJSON.isFeature) &&
            GeoJSON.validCRS(x) &&
            GeoJSON.validBbox(x)
        );
    },

    isCRS: function ( x ) {
        // Validate a GeoJSON Coordinate Reference System.
        return (
            x != null &&
            (
                (
                    x.type === 'name' &&
                    x.properties != null &&
                    typeof x.properties.name === 'string' &&
                    x.properties.name.length > 0
                ) ||
                (
                    x.type === 'link' &&
                    GeoJSON.isLink(x.properties)
                )
            )
        );
    },

    validCRS: function ( x ) {
        // Validate the CRS property of a GeoJSON object.
        return (
            x != null &&
            (
                typeof x.crs === 'undefined' ||
                x.crs === null ||
                GeoJSON.isCRS(x.crs)
            )
        )
    },

    isBbox: function ( x ) {
        throw Error('Not Implemented')
    },

    validBbox: function ( x ) {
        // Validate the bbox property of a GeoJSON object.
        return (
            x != null &&
            (
                typeof x.bbox === 'undefined' ||
                (
                    Array.isArray(x.bbox) &&
                    x.bbox.length%2 === 0 &&
                    GeoJSON.isBbox()
                )
            )
        );
    },

    isLink: function ( x ) {
        // Validate a GeoJSON Link.
        try {
            return (
                x != null &&
                x.properties != null &&
                typeof x.properties.href === 'string' &&
                URI.parse(x.properties.href) &&
                (
                    typeof x.properties.type === 'undefined' ||
                    (
                        typeof x.properties.type === 'string' &&
                        x.properties.type.length > 0
                    )
                )
            );
        }
        catch (e) {
            return false;
        }
    },

//////////////////////////////////////////////////////////////////////// UTILITY

    equalPositions: function ( a , b ) {
        // Compare two GeoJSON Positions for equality.
        return (
            GeoJSON.isPosition(a) && GeoJSON.isPosition(b) &&
            a.length == b.length &&
            a.every(
                function ( element , index ) {
                    return (a[index] == b[index]);
                }
            )
        );
    },

    containedPolygon: function ( inner , outer ) {
        // Determine whether one GeoJSON LinearRing contains another.
        return inner.every(
            function ( Position ) {
                return inside(Position,outer);
            }
        );
    },

/////////////////////////////////////////////////////////////////////// TEMPLATE

    Point: function ( latitude , longitude , altitude ) {
        // Create a valid GeoJSON Point geometry.
        var Point = null;
        if (typeof longitude === 'number' && typeof latitude === 'number') {
            Point = {
                type: 'Point',
                coordinates: [longitude,latitude]
            };
            if (typeof altitude === 'number') Point.coordinates.push(altitude);
        }
        return Point;
    },

    Feature: function ( Geometry , properties ) {
        // Create a valid GeoJSON Feature.
        var Feature = {
            type: 'Feature',
            geometry: null,
            properties: (typeof properties === 'object') ? properties : {}
        };
        if (GeoJSON.isGeometry(Geometry)) Feature.geometry = Geometry;
        return Feature;
    },

    FeatureCollection: function ( Features ) {
        // Create a valid GeoJSON FeatureCollection.
        var FeatureCollection = {
            type: 'FeatureCollection',
            features: []
        };
        if (GeoJSON.isFeature(Features)) {
            FeatureCollection.features.push(Features);
        }
        else if (Array.isArray(Features)) Features.forEach(
            function ( Feature ) {
                if (GeoJSON.isFeature(Feature)) {
                    FeatureCollection.features.push(Feature);
                }
            }
        );
        return FeatureCollection;
    },

    GeometryCollection: function ( Geometries ) {
        // Create a valid GeoJSON GeometryCollection.
        var GeometryCollection = {
            type: 'GeometryCollection',
            geometries: []
        };
        if (GeoJSON.isGeometry(Geometries)) {
            GeometryCollection.geometries.push(Geometries);
        }
        else if (Array.isArray(Geometries)) Geometries.forEach(
            function ( Geometry ) {
                if (GeoJSON.isGeometry(Geometry)) {
                    GeometryCollection.geometries.push(Geometry);
                }
            }
        );
        return GeometryCollection;
    },

///////////////////////////////////////////////////////////////////// EXTRACTION

    positionsOf: function ( geojson ) {
        // Find all the Positions in a valid GeoJSON object.
        var positions = [];
        var extractLineStringPositions = function ( LineStringPosition ) {
            LineStringPosition.forEach(
                function ( Position ) {
                    positions.push(Position);
                }
            );
        };
        var extractPolygonPositions = function ( PolygonPosition ) {
            PolygonPosition.forEach(extractLineStringPositions);
        };
        switch (geojson.type) {
            case 'Point':
                positions.push(geojson.coordinates);
                break;
            case 'MultiPoint':
            case 'LineString':
                extractLineStringPositions(geojson.coordinates);
                break;
            case 'MultiLineString':
            case 'Polygon':
                extractPolygonPositions(geojson.coordinates);
                break;
            case 'MultiPolygon':
                geojson.coordinates.forEach(extractPolygonPositions);
                break;
            case 'GeometryCollection':
                extractLineStringPositions(
                    GeoJSON.positionsOf(geojson.geometries)
                );
                break;
            case 'Feature':
                extractLineStringPositions(
                    GeoJSON.positionsOf(geojson.geometry)
                );
                break;
            case 'FeatureCollection':
                geojson.features.forEach(
                    function ( Feature ) {
                        extractLineStringPositions(
                            GeoJSON.positionsOf(Feature.geometry)
                        );
                    }
                );
                break;
        }
        return positions;
    },

    featuresOf: function ( geojson ) {
        // Find all Features in a valid GeoJSON object.
        var features = [];
        switch (geojson.type) {
            case 'Feature':
                features.push(geojson);
                break;
            case 'FeatureCollection':
                geojson.features.forEach(
                    function ( Feature ) {
                        GeoJSON.featuresOf(Feature).forEach(
                            function ( Feature ) {
                                features.push(Feature);
                            }
                        );
                    }
                );
                break;
        }
        return features;
    },

    geometriesOf: function ( geojson ) {
        // Find all Geometries in a valid GeoJSON object.
        var geometries = [];
        var extractFeatureGeometries = function ( Feature ) {
            GeoJSON.geometriesOf(Feature.geometry).forEach(
                function ( Geometry ) {
                    geometries.push(Geometry);
                }
            );
        };
        switch (geojson.type) {
            case 'Point':
            case 'MultiPoint':
            case 'LineString':
            case 'MultiLineString':
            case 'Polygon':
            case 'MultiPolygon':
                geometries.push(geojson);
                break;
            case 'GeometryCollection':
                geojson.geometries.forEach(
                    function ( Geometry ) {
                        GeoJSON.geometriesOf(Geometry).forEach(
                            function ( Geometry ) {
                                geometries.push(Geometry);
                            }
                        );
                    }
                );
                break;
            case 'Feature':
                extractFeatureGeometries(geojson);
                break;
            case 'FeatureCollection':
                geojson.features.forEach(extractFeatureGeometries);
                break;
        }
        return geometries;
    }

};
<|endoftext|>


<commit_before>Helpers = initHelpers(window, document);

function initHelpers(w, d, undefined) {
  "use strict";
  var useCustomCss = false;
  var helperObj = {
    report: reportHTML,
    isObj: isPlainObject,
    useJQ: loadJQ,
    augment: extensions,
    useCSS: setCustomCss,
    log2Screen: log2Screen,
    initSO: SOInit
  };

  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = document.createElement('div');
          r.id = 'result';
          document.querySelector('body').appendChild(r);
          return r;
        }();
    var entry = document.createElement('p');
    entry.innerHTML = [].slice.call(arguments).join('');
    report.appendChild(entry);

    if (useCustomCss) {
      var to = function () { entry.className = 'fadeIn'; };
      var dummy = setTimeout(to, 200);
    }
  }

  function setCustomCss(yn) {
    useCustomCss = yn;
    if (useCustomCss) {
     loadCSS();
    } else {
     unloadCSS();
    }
  }

  function isPlainObject(item) {
    return (
        item &&
        typeof item === "object" &&
        Object.prototype.toString.call(item) === "object Object" &&
        !item.nodeType
    );
  }

  function loadJQ(cb) {
      if (w.jQuery) {
        return function () {return void( cb && cb());}
      }
      return function (cb) {
        var head  = d.querySelector('head')
           ,jq    = d.createElement('script');

        jq.src    = '//code.jquery.com/jquery-2.1.1.min.js';
        jq.id     = 'jqloaded';
        head.appendChild(jq);
        if (cb && cb instanceof Function)
          initcb();

        function initcb() {
          if (!w.jQuery) {
            console.log('still waiting');
            setTimeout(initcb, 10);
          } else {
            cb();
          }
         };
      };
  }

  function loadCSS() {
   if (document.querySelector('#HelperCSS')) {
    return true;
   }
   var css = document.createElement('link');
   css.href = "https://rawgit.com/KooiInc/Helpers/master/Helpers.css";
   css.type = "text/css";
   css.rel = "stylesheet";
   css.id = "HelperCSS";
   return document.querySelector('head').appendChild(css);
  }

  function unloadCSS() {
   var css = document.querySelector('#HelperCSS');
   void (css && document.querySelector('head').removeChild(css));
  }

   // a few usefull augments/polyfills
  function extensions() {
        // remove double values from an array
        function noDoubles(arr) {
          arr = arr || this;
          return arr.filter(function(val) {
           return !this[val] ? ((this[val] = true), true) : false;
          }, {});
        }

        function args2Array(args){
          var arr = [];
          for (var i=0;i<args.length;i+=1) {
            arr.push(args[i]);
          }
          return arr;
        }

        function stringformat() {
                var args = args2Array(arguments);
                return this.replace(/(\{\d+\})/g, function(a){
                    return args[+(a.substr(1,a.length-2))||0];
                });
        };

        // determine value frequencies in an array
        function frequencies(arr) {
          var mapped = {sum: 0};
          (arr || this).map(function (a){
              if (!(a in this)) { this[a] = 1; }
              else { this[a] += 1; }
              this.sum += 1;
              return a; }, mapped
          );
          return mapped;
        }

        String.Format = function(){
            var args = [].slice.call(arguments);
            return stringformat.apply(args[0],args.slice(1));
        };

        String.prototype.format = function () {
          return stringformat.apply(this,arguments);
        }

        String.prototype.repeat = function(n){
            var s = this, r = '';
            while(n--) {
                r += s;
            }
            return r;
        };

        // run functions sequentially
        Function.prototype.andThen = function () {
         var args = [].slice.call(arguments)
            ,next = args.slice(1);
         this();
         return args[0] && next.length
                 ? args[0].andThen.apply(args[0], next)
                 : args.length == 1  ? args[0]()
                 : true;
        };

        // is character @ [atpos] upperCase?
        boolean:String.prototype.charIsUpper = function (atpos){
          var chr = this.charAt(atpos);
          return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
        };

        String.prototype.firstUp = function () {
          return this.slice(0,1).toUpperCase()+this.slice(1).toLowerCase();
        }

        String.prototype.isValidEmail = function() {
          // should be sufficient
          return  /^[\w._-]{1,}[+]?[\w._-]{0,}@[\w.-]+\.[a-zA-Z]{2,6}$/.test(this);
        }

        Array.prototype.toRE = function (){
          try { return RegExp.apply(null, this); }
          catch(e) { return /.*/; }
        }

        Array.toRE = function(arr) {
          return ([].toRE.call(arr));
        }

        String.prototype.reCleanup = function(encodeHTML){
          var str = encodeHTML ? this.replace(/[\u0080-\u024F]/g, function(a) {return '&#'+a.charCodeAt(0)+';';}) : this;
          return str.replace(/[?*|.+$\/]|\\/g, function(c) {return c==='\\' ? '' : '\\\\'+c;});
        }

        String.concat = function(joinchar){
          joinchar = joinchar || '';
          return [].slice.call(arguments).join(joinchar);
        }

        // MDN Array filter polyfill
        if (!Array.prototype.filter) {
          Array.prototype.filter = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun != "function")
              throw new TypeError();

            var res = [];
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)  {
                var val = t[i];
                if (fun.call(thisArg, val, i, t))
                  res.push(val);
              }
            }

            return res;
          };
        }

        // MDN Array map polyfill
        if (!Array.prototype.map) {
          Array.prototype.map = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun !== "function")
              throw new TypeError();

            var res = new Array(len);
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)
                res[i] = fun.call(thisArg, t[i], i, t);
            }

            return res;
        };
       }
       Array.prototype.uniquify = noDoubles;
       Array.prototype.frequencies = Array.prototype.frequencies || frequencies;

       Array.prototype.each = Array.prototype.each || function (fn,rewrite) {
       for (var i = 0; i < this.length; i++) {
        if (rewrite){
          this[i] = fn(this[i]);
        } else {
         fn(this[i]);
        }
       }
       return this;
     };
  }

  // SO specials
  function SOInit() {
    setCustomCss(true);
    loadJQ( function () {
      $(document).on('mouseover', '.solink', setSOLink );
      $(document).on('click', '[data-link]', clicklink);
    });
  }

  function setSOLink(e) {
      console.log('are we loaded?');
      if ($(this).attr('data-link')) { return true; }

      $.ajax(
          {
              url: 'http://www.nicon.nl/node/stackx/questionx',
              data: {qid: $('.solink').first().attr('data-linkid')},
              method: 'post',
              success: SOcb
          }
      );

      function SOcb(data) {
          var resp = data.items && data.items[0] || data
          ,linkelement = $('.solink').first()
          ,linktip = linkelement.find('.linkhover').first()
          ;
          linktip.html(
              'Click logo to view the related question:

' + resp.title + '

' +
              'Asked by
'+ resp.owner.display_name + '
; '+
              'rep ' + resp.owner.reputation +'; question views: '+resp.view_count
          );
          linkelement.attr('data-link', resp.link);
      }

      return true;
  }

  // firefox needs a link added to the DOM, Chrome, IE don't
  function clicklink(e) {
      e.stopPropagation(); //just this link
      var linkurl = this.getAttribute('data-link')
         ,xlink = document.querySelector('a[href="'+linkurl+'"]') ||
                  function() {
                      var _link = document.createElement('a');
                      _link.href = linkurl;
                      _link.target = '_blank';
                      _link.style.display = 'none';
                      document.body.appendChild(_link);
                      return _link; }();
      xlink.click();
  }
  // alternative screen log
  function log2Screen(){
      var result = document.querySelector('#result') ||
                   function () { var r = document.createElement('div');
                       r.id = 'result';
                       document.body.appendChild(r);
                       return r; }()
                       ,args = [].slice.call(arguments)
                       ,lastarg = args.slice(-1)[0]
                       ,optkeys = /clear|clrscr|direct|opts|useopts|continuous/i
                       ,opts = lastarg instanceof Object
                               && Object.keys(lastarg).filter(function(v){return optkeys.test(v);}).length
                                ? lastarg.opts instanceof Object ? lastarg.opts : lastarg
                                : {empty: 1};
      void(!opts.empty && (args = args.slice(0,-1)));

      if (opts.clrscr) {
          return result.innerHTML = '';
      }

      if (opts.clear) {
          result.innerHTML = '';
      }

      if (opts.continuous) {
          return result.innerHTML += args.join('').replace(/\n/g,'
');
      }

      var p = document.createElement('p');
      p.innerHTML = args.join('').replace(/\n/g,'
');
      result.appendChild(p);
      return opts.direct ? (p.className = 'fadeIn')
                         : setTimeout(function () { p.className = 'fadeIn'; }, +opts.timed*1000 || 0);
  }

  return helperObj
}
<commit_msg>debug 5 (closure?)<commit_after>Helpers = initHelpers(window, document);

function initHelpers(w, d, undefined) {
  "use strict";
  var useCustomCss = false;
  var helperObj = {
    report: reportHTML,
    isObj: isPlainObject,
    useJQ: loadJQ,
    augment: extensions,
    useCSS: setCustomCss,
    log2Screen: log2Screen,
    initSO: SOInit
  };

  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = document.createElement('div');
          r.id = 'result';
          document.querySelector('body').appendChild(r);
          return r;
        }();
    var entry = document.createElement('p');
    entry.innerHTML = [].slice.call(arguments).join('');
    report.appendChild(entry);

    if (useCustomCss) {
      var to = function () { entry.className = 'fadeIn'; };
      var dummy = setTimeout(to, 200);
    }
  }

  function setCustomCss(yn) {
    useCustomCss = yn;
    if (useCustomCss) {
     loadCSS();
    } else {
     unloadCSS();
    }
  }

  function isPlainObject(item) {
    return (
        item &&
        typeof item === "object" &&
        Object.prototype.toString.call(item) === "object Object" &&
        !item.nodeType
    );
  }

  function loadJQ(cb) {
      if (w.jQuery) {
        return function () {return void( cb && cb());}
      }
      return function (cb) {
        var head  = d.querySelector('head')
           ,jq    = d.createElement('script');

        jq.src    = '//code.jquery.com/jquery-2.1.1.min.js';
        jq.id     = 'jqloaded';
        head.appendChild(jq);
        if (cb && cb instanceof Function)
          initcb();

        function initcb() {
          if (!w.jQuery) {
            console.log('still waiting');
            setTimeout(initcb, 10);
          } else {
            cb();
          }
         };
      };
  }

  function loadCSS() {
   if (document.querySelector('#HelperCSS')) {
    return true;
   }
   var css = document.createElement('link');
   css.href = "https://rawgit.com/KooiInc/Helpers/master/Helpers.css";
   css.type = "text/css";
   css.rel = "stylesheet";
   css.id = "HelperCSS";
   return document.querySelector('head').appendChild(css);
  }

  function unloadCSS() {
   var css = document.querySelector('#HelperCSS');
   void (css && document.querySelector('head').removeChild(css));
  }

   // a few usefull augments/polyfills
  function extensions() {
        // remove double values from an array
        function noDoubles(arr) {
          arr = arr || this;
          return arr.filter(function(val) {
           return !this[val] ? ((this[val] = true), true) : false;
          }, {});
        }

        function args2Array(args){
          var arr = [];
          for (var i=0;i<args.length;i+=1) {
            arr.push(args[i]);
          }
          return arr;
        }

        function stringformat() {
                var args = args2Array(arguments);
                return this.replace(/(\{\d+\})/g, function(a){
                    return args[+(a.substr(1,a.length-2))||0];
                });
        };

        // determine value frequencies in an array
        function frequencies(arr) {
          var mapped = {sum: 0};
          (arr || this).map(function (a){
              if (!(a in this)) { this[a] = 1; }
              else { this[a] += 1; }
              this.sum += 1;
              return a; }, mapped
          );
          return mapped;
        }

        String.Format = function(){
            var args = [].slice.call(arguments);
            return stringformat.apply(args[0],args.slice(1));
        };

        String.prototype.format = function () {
          return stringformat.apply(this,arguments);
        }

        String.prototype.repeat = function(n){
            var s = this, r = '';
            while(n--) {
                r += s;
            }
            return r;
        };

        // run functions sequentially
        Function.prototype.andThen = function () {
         var args = [].slice.call(arguments)
            ,next = args.slice(1);
         this();
         return args[0] && next.length
                 ? args[0].andThen.apply(args[0], next)
                 : args.length == 1  ? args[0]()
                 : true;
        };

        // is character @ [atpos] upperCase?
        boolean:String.prototype.charIsUpper = function (atpos){
          var chr = this.charAt(atpos);
          return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
        };

        String.prototype.firstUp = function () {
          return this.slice(0,1).toUpperCase()+this.slice(1).toLowerCase();
        }

        String.prototype.isValidEmail = function() {
          // should be sufficient
          return  /^[\w._-]{1,}[+]?[\w._-]{0,}@[\w.-]+\.[a-zA-Z]{2,6}$/.test(this);
        }

        Array.prototype.toRE = function (){
          try { return RegExp.apply(null, this); }
          catch(e) { return /.*/; }
        }

        Array.toRE = function(arr) {
          return ([].toRE.call(arr));
        }

        String.prototype.reCleanup = function(encodeHTML){
          var str = encodeHTML ? this.replace(/[\u0080-\u024F]/g, function(a) {return '&#'+a.charCodeAt(0)+';';}) : this;
          return str.replace(/[?*|.+$\/]|\\/g, function(c) {return c==='\\' ? '' : '\\\\'+c;});
        }

        String.concat = function(joinchar){
          joinchar = joinchar || '';
          return [].slice.call(arguments).join(joinchar);
        }

        // MDN Array filter polyfill
        if (!Array.prototype.filter) {
          Array.prototype.filter = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun != "function")
              throw new TypeError();

            var res = [];
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)  {
                var val = t[i];
                if (fun.call(thisArg, val, i, t))
                  res.push(val);
              }
            }

            return res;
          };
        }

        // MDN Array map polyfill
        if (!Array.prototype.map) {
          Array.prototype.map = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun !== "function")
              throw new TypeError();

            var res = new Array(len);
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)
                res[i] = fun.call(thisArg, t[i], i, t);
            }

            return res;
        };
       }
       Array.prototype.uniquify = noDoubles;
       Array.prototype.frequencies = Array.prototype.frequencies || frequencies;

       Array.prototype.each = Array.prototype.each || function (fn,rewrite) {
       for (var i = 0; i < this.length; i++) {
        if (rewrite){
          this[i] = fn(this[i]);
        } else {
         fn(this[i]);
        }
       }
       return this;
     };
  }

  // SO specials
  function SOInit() {
    setCustomCss(true);
    loadJQ( jqcallback );

    function jqcallback() {
      $(document).on('mouseover', '.solink', setSOLink );
      $(document).on('click', '[data-link]', clicklink);
    }
  }

  function setSOLink(e) {
      console.log('are we loaded?');
      if ($(this).attr('data-link')) { return true; }

      $.ajax(
          {
              url: 'http://www.nicon.nl/node/stackx/questionx',
              data: {qid: $('.solink').first().attr('data-linkid')},
              method: 'post',
              success: SOcb
          }
      );

      function SOcb(data) {
          var resp = data.items && data.items[0] || data
          ,linkelement = $('.solink').first()
          ,linktip = linkelement.find('.linkhover').first()
          ;
          linktip.html(
              'Click logo to view the related question:

' + resp.title + '

' +
              'Asked by
'+ resp.owner.display_name + '
; '+
              'rep ' + resp.owner.reputation +'; question views: '+resp.view_count
          );
          linkelement.attr('data-link', resp.link);
      }

      return true;
  }

  // firefox needs a link added to the DOM, Chrome, IE don't
  function clicklink(e) {
      e.stopPropagation(); //just this link
      var linkurl = this.getAttribute('data-link')
         ,xlink = document.querySelector('a[href="'+linkurl+'"]') ||
                  function() {
                      var _link = document.createElement('a');
                      _link.href = linkurl;
                      _link.target = '_blank';
                      _link.style.display = 'none';
                      document.body.appendChild(_link);
                      return _link; }();
      xlink.click();
  }
  // alternative screen log
  function log2Screen(){
      var result = document.querySelector('#result') ||
                   function () { var r = document.createElement('div');
                       r.id = 'result';
                       document.body.appendChild(r);
                       return r; }()
                       ,args = [].slice.call(arguments)
                       ,lastarg = args.slice(-1)[0]
                       ,optkeys = /clear|clrscr|direct|opts|useopts|continuous/i
                       ,opts = lastarg instanceof Object
                               && Object.keys(lastarg).filter(function(v){return optkeys.test(v);}).length
                                ? lastarg.opts instanceof Object ? lastarg.opts : lastarg
                                : {empty: 1};
      void(!opts.empty && (args = args.slice(0,-1)));

      if (opts.clrscr) {
          return result.innerHTML = '';
      }

      if (opts.clear) {
          result.innerHTML = '';
      }

      if (opts.continuous) {
          return result.innerHTML += args.join('').replace(/\n/g,'
');
      }

      var p = document.createElement('p');
      p.innerHTML = args.join('').replace(/\n/g,'
');
      result.appendChild(p);
      return opts.direct ? (p.className = 'fadeIn')
                         : setTimeout(function () { p.className = 'fadeIn'; }, +opts.timed*1000 || 0);
  }

  return helperObj
}
<|endoftext|>


<commit_before>'use strict';

var log = log4javascript.getLogger("credentialController-logger");

angular.module('uluwatuControllers').controller('credentialController', ['$scope', '$rootScope', '$base64', 'UserCredential', 'GlobalCredential', 'GlobalCredentialCertificate',
    function ($scope, $rootScope, $base64, UserCredential, GlobalCredential, GlobalCredentialCertificate) {
        $rootScope.credentials = UserCredential.query();
        $rootScope.credentialInCreation = false;
        $scope.credentialAws = {};
        $scope.credentialAzure = {};
        $scope.credentialGcc = {};
        $scope.azureCredential = false;
        $scope.awsCredential = true;
        $scope.gccCredential = false;
        $scope.awsCredentialForm = {};
        $scope.gccCredentialForm = {};
        $scope.azureCredentialForm = {};
        $scope.gcc = {};
        $scope.gcc.p12 = "";

        $scope.createAwsCredentialRequest = function() {
            $scope.azureCredential = false;
            $scope.awsCredential = true;
            $scope.gccCredential = false;
        }

        $scope.createAzureCredentialRequest = function() {
            $scope.azureCredential = true;
            $scope.awsCredential = false;
            $scope.gccCredential = false;
        }

        $scope.createGccCredentialRequest = function() {
            $scope.azureCredential = false;
            $scope.awsCredential = false;
            $scope.gccCredential = true;
        }

        $scope.createAwsCredential = function() {
            $scope.credentialAws.cloudPlatform = "AWS";
            $rootScope.credentialInCreation = true;
            UserCredential.save($scope.credentialAws, function(result) {
                $scope.credentialAws.id = result.id;
                $rootScope.credentials.push($scope.credentialAws);
                $scope.credentialAws = {};
                $scope.modifyStatusMessage($rootScope.error_msg.aws_credential_success1 + result.id + $rootScope.error_msg.aws_credential_success2);
                $scope.modifyStatusClass("has-success");
                $scope.awsCredentialForm.$setPristine();
                collapseCreateCredentialFormPanel();
                $rootScope.credentialInCreation = false;
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.aws_credential_failed + error.data.message);
                $scope.modifyStatusClass("has-error");
                $rootScope.credentialInCreation = false;
                // $scope.isFailedCreation = true;
            });
        }

        $scope.createAzureCredential = function() {
            $scope.credentialAzure.cloudPlatform = "AZURE";

            UserCredential.save($scope.credentialAzure, function(result){
                $scope.credentialAzure.id = result.id;
                $rootScope.credentials.push($scope.credentialAzure);
                $scope.credentialAzure = {};
                $scope.modifyStatusMessage($rootScope.error_msg.azure_credential_success1 + result.id + $rootScope.error_msg.azure_credential_success2);
                $scope.modifyStatusClass("has-success");
                window.location.href = "credentials/certificate/" + result.id
                $scope.azureCredentialForm.$setPristine();
                collapseCreateCredentialFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.azure_credential_failed + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createGccCredential = function() {
            $scope.credentialGcc.cloudPlatform = "GCC";
            $rootScope.credentialInCreation = true

            var p12File = $scope.gcc.p12
            var reader = new FileReader();

            reader.onloadend = function(evt) {
                if (evt.target.readyState == FileReader.DONE) {
                  $scope.credentialGcc.parameters.serviceAccountPrivateKey = $base64.encode(evt.target.result);
                  UserCredential.save($scope.credentialGcc, function(result){
                      $scope.credentialGcc.id = result.id;
                      $rootScope.credentials.push($scope.credentialGcc);
                      $scope.credentialGcc = {};
                      $scope.modifyStatusMessage($rootScope.error_msg.gcc_credential_success1 + result.id + $rootScope.error_msg.gcc_credential_success2);
                      $scope.modifyStatusClass("has-success");
                      $rootScope.credentialInCreation = false;
                      $scope.gccCredentialForm.$setPristine();
                      collapseCreateCredentialFormPanel();
                  }, function (error) {
                      $scope.modifyStatusMessage($rootScope.error_msg.gcc_credential_failed + error.data.message);
                      $scope.modifyStatusClass("has-error");
                      $rootScope.credentialInCreation = false;
                  });
                }
            };

            var blob = p12File.slice(0, p12File.size);
            reader.readAsBinaryString(blob);

        }

        $scope.deleteCredential = function(credential) {
            GlobalCredential.delete({ id: credential.id }, function(success){
                $rootScope.credentials.splice($rootScope.credentials.indexOf(credential), 1 );
                $scope.modifyStatusMessage($rootScope.error_msg.credential_delete_success1 + credential.id + $rootScope.error_msg.credential_delete_success2);
                $scope.modifyStatusClass("has-success");
            }, function(error){
                $scope.modifyStatusMessage(error.data.message);
                $scope.modifyStatusClass("has-error");
            });

        }

        function collapseCreateCredentialFormPanel() {
          angular.element(document.querySelector('#panel-create-credentials-collapse-btn')).click();
        }
    }]
);
<commit_msg>CLOUD-364 encode azure public key<commit_after>'use strict';

var log = log4javascript.getLogger("credentialController-logger");

angular.module('uluwatuControllers').controller('credentialController', ['$scope', '$rootScope', '$base64', 'UserCredential', 'GlobalCredential', 'GlobalCredentialCertificate',
    function ($scope, $rootScope, $base64, UserCredential, GlobalCredential, GlobalCredentialCertificate) {
        $rootScope.credentials = UserCredential.query();
        $rootScope.credentialInCreation = false;
        $scope.credentialAws = {};
        $scope.credentialAzure = {};
        $scope.credentialGcc = {};
        $scope.azureCredential = false;
        $scope.awsCredential = true;
        $scope.gccCredential = false;
        $scope.awsCredentialForm = {};
        $scope.gccCredentialForm = {};
        $scope.azureCredentialForm = {};
        $scope.gcc = {};
        $scope.gcc.p12 = "";

        $scope.createAwsCredentialRequest = function() {
            $scope.azureCredential = false;
            $scope.awsCredential = true;
            $scope.gccCredential = false;
        }

        $scope.createAzureCredentialRequest = function() {
            $scope.azureCredential = true;
            $scope.awsCredential = false;
            $scope.gccCredential = false;
        }

        $scope.createGccCredentialRequest = function() {
            $scope.azureCredential = false;
            $scope.awsCredential = false;
            $scope.gccCredential = true;
        }

        $scope.createAwsCredential = function() {
            $scope.credentialAws.cloudPlatform = "AWS";
            $rootScope.credentialInCreation = true;
            UserCredential.save($scope.credentialAws, function(result) {
                $scope.credentialAws.id = result.id;
                $rootScope.credentials.push($scope.credentialAws);
                $scope.credentialAws = {};
                $scope.modifyStatusMessage($rootScope.error_msg.aws_credential_success1 + result.id + $rootScope.error_msg.aws_credential_success2);
                $scope.modifyStatusClass("has-success");
                $scope.awsCredentialForm.$setPristine();
                collapseCreateCredentialFormPanel();
                $rootScope.credentialInCreation = false;
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.aws_credential_failed + error.data.message);
                $scope.modifyStatusClass("has-error");
                $rootScope.credentialInCreation = false;
                // $scope.isFailedCreation = true;
            });
        }

        $scope.createAzureCredential = function() {
            $scope.credentialAzure.cloudPlatform = "AZURE";
            $scope.credentialAzure.publicKey = $base64.encode($scope.credentialAzure.publicKey)

            UserCredential.save($scope.credentialAzure, function(result){
                $scope.credentialAzure.id = result.id;
                $rootScope.credentials.push($scope.credentialAzure);
                $scope.credentialAzure = {};
                $scope.modifyStatusMessage($rootScope.error_msg.azure_credential_success1 + result.id + $rootScope.error_msg.azure_credential_success2);
                $scope.modifyStatusClass("has-success");
                window.location.href = "credentials/certificate/" + result.id
                $scope.azureCredentialForm.$setPristine();
                collapseCreateCredentialFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.azure_credential_failed + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createGccCredential = function() {
            $scope.credentialGcc.cloudPlatform = "GCC";
            $rootScope.credentialInCreation = true

            var p12File = $scope.gcc.p12
            var reader = new FileReader();

            reader.onloadend = function(evt) {
                if (evt.target.readyState == FileReader.DONE) {
                  $scope.credentialGcc.parameters.serviceAccountPrivateKey = $base64.encode(evt.target.result);
                  UserCredential.save($scope.credentialGcc, function(result){
                      $scope.credentialGcc.id = result.id;
                      $rootScope.credentials.push($scope.credentialGcc);
                      $scope.credentialGcc = {};
                      $scope.modifyStatusMessage($rootScope.error_msg.gcc_credential_success1 + result.id + $rootScope.error_msg.gcc_credential_success2);
                      $scope.modifyStatusClass("has-success");
                      $rootScope.credentialInCreation = false;
                      $scope.gccCredentialForm.$setPristine();
                      collapseCreateCredentialFormPanel();
                  }, function (error) {
                      $scope.modifyStatusMessage($rootScope.error_msg.gcc_credential_failed + error.data.message);
                      $scope.modifyStatusClass("has-error");
                      $rootScope.credentialInCreation = false;
                  });
                }
            };

            var blob = p12File.slice(0, p12File.size);
            reader.readAsBinaryString(blob);

        }

        $scope.deleteCredential = function(credential) {
            GlobalCredential.delete({ id: credential.id }, function(success){
                $rootScope.credentials.splice($rootScope.credentials.indexOf(credential), 1 );
                $scope.modifyStatusMessage($rootScope.error_msg.credential_delete_success1 + credential.id + $rootScope.error_msg.credential_delete_success2);
                $scope.modifyStatusClass("has-success");
            }, function(error){
                $scope.modifyStatusMessage(error.data.message);
                $scope.modifyStatusClass("has-error");
            });

        }

        function collapseCreateCredentialFormPanel() {
          angular.element(document.querySelector('#panel-create-credentials-collapse-btn')).click();
        }
    }]
);
<|endoftext|>


<commit_before>var args = arguments[0] || {};
if(args !== {})
	init(args);
function init(o){
	//dynamic exprs in tss files no longer accepted
	if(OS_IOS){
		$.imgMain.top = 7;//0
		$.table.top = 0;//-15
	}
	$.title.text = o.title || "";
	$.main.text = o.main || "";
	$.licence.text = o.licence || "";
	if(o.thanksTo || $.thanksTo.text != ""){
		$.thanksTitle.text = o.thanksTitle || ($.thanksTitle.text == ""? "Thanks to:" : $.thanksTitle.text);
	}else{
		$.mainView.remove($.thanksTo);
	}
	if(o.imgTitle == false){
		$.head.remove($.thanksTo);
	}else{
		$.imgTitle.image = o.imgTitle || $.imgTitle.image;
	}
	if(o.imgMain == false){
		$.mainView.remove($.imgMain);
	}else{
		$.imgMain.image = o.imgMain || $.imgMain.image;
	}
	if(o.imgWin == false){
		$.win.backgroundImage = null;
	}else{
		$.win.backgroundImage = o.imgWin || (OS_ANDROID?$.win.backgroundImage.toLowerCase():$.win.backgroundImage);
	}
	if(o.thanksTo){
		var data = [];
		_.each(o.thanksTo.split(','), function(pair) {
			var row = Alloy.createWidget('es.kabomi.about', 'rows', {
				name: pair.split('|')[0],
				contrib: pair.split('|')[1]
			}).getView();
			data.push(row);
		});
		$.table.setData(data);
		$.thanksTo.hide();
	}

	if(OS_ANDROID){
		$.win.addEventListener('android:back', function(){
			$.win.close();
		});
	}
};
exports.init = init;
exports.show = function(){
	if(Alloy.CFG.navgroup){
		Alloy.CFG.navgroup.open($.win);
	}else{
		$.win.open();
	}
};
exports.hide = function(){
	$.win.close();
};
exports.setPath = function(o, path){
	switch(o){
		case "main":
			$.imgMain.image = WPATH(path);
			break;
		case "logo":
			$.imgTitle.image = WPATH(path);
			break;
		case "win":
			$.win.backgroundImage = WPATH(path);
			break;
	}
};
<commit_msg>Clean up<commit_after>var args = arguments[0] || {};
if(args !== {})
	init(args);
function init(o){
	//dynamic exprs in tss files no longer accepted
	if(OS_IOS){
		$.imgMain.top = 7;//0
		$.table.top = 0;//-15
	}
	$.title.text = o.title || "";
	$.main.text = o.main || "";
	$.licence.text = o.licence || "";
	if(o.thanksTo || $.thanksTo.text != ""){
		$.thanksTitle.text = o.thanksTitle || ($.thanksTitle.text == ""? "Thanks to:" : $.thanksTitle.text);
	}else{
		$.mainView.remove($.thanksTo);
	}
	if(!o.imgTitle){
		$.head.remove($.thanksTo);
	}else{
		$.imgTitle.image = o.imgTitle || $.imgTitle.image;
	}
	if(!o.imgMain){
		$.mainView.remove($.imgMain);
	}else{
		$.imgMain.image = o.imgMain || $.imgMain.image;
	}
	if(!o.imgWin){
		$.win.backgroundImage = null;
	}else{
		$.win.backgroundImage = o.imgWin || (OS_ANDROID?$.win.backgroundImage.toLowerCase():$.win.backgroundImage);
	}
	if(o.thanksTo){
		var data = [];
		_.each(o.thanksTo.split(','), function(pair) {
			var row = Alloy.createWidget('es.kabomi.about', 'rows', {
				name: pair.split('|')[0],
				contrib: pair.split('|')[1]
			}).getView();
			data.push(row);
		});
		$.table.setData(data);
		$.thanksTo.hide();
	}

	if(OS_ANDROID){
		$.win.addEventListener('android:back', function(){
			$.win.close();
		});
	}
};
exports.init = init;
exports.show = function(){
	if(Alloy.CFG.navgroup){
		Alloy.CFG.navgroup.open($.win);
	}else{
		$.win.open();
	}
};
exports.hide = function(){
	$.win.close();
};
exports.setPath = function(o, path){
	switch(o){
		case "main":
			$.imgMain.image = WPATH(path);
			break;
		case "logo":
			$.imgTitle.image = WPATH(path);
			break;
		case "win":
			$.win.backgroundImage = WPATH(path);
			break;
	}
};
<|endoftext|>


<commit_before>/*
 * This script reloads the graph image when one of its display options is changed.
 */

jQuery(document).ready(function($) {

  // save the base url of the image for use when updating the source url inside the change event
  $("#graph").data("src", $("#graph").attr("src"));
  $(".graph_option").change(function() {
    var params = new Array();

    // add time as a parameter so the browser doesn't cache out of date images
    params.push("time=" + new Date().getUTCMilliseconds());

    if ($("#ops").attr("checked"))
      params.push($("#ops").attr("value") + "=1");
    if ($("#perms").attr("checked"))
      params.push($("#perms").attr("value") + "=1");
    $("#graph").attr("src", $("#graph").data("src") + "?" + params.join("&"));
  }).change();
});
<commit_msg>Only reload the graph image once on page load to reduce the number of broken pipes occurring.<commit_after>/*
 * This script reloads the graph image when one of its display options is changed.
 */

(function($){
  window.reloadGraph = function(elm) {
    var params = new Array();

    // add time as a parameter so the browser doesn't cache out of date images
    params.push("time=" + new Date().getTime());

    if ($("#ops").attr("checked"))
      params.push($("#ops").attr("value") + "=1");
    if ($("#perms").attr("checked"))
      params.push($("#perms").attr("value") + "=1");
    $("#graph").attr("src", $("#graph").data("src") + "?" + params.join("&"));
  }
})(jQuery);

jQuery(document).ready(function($) {

  // save the base url of the image for use when updating the source url inside the change event
  $("#graph").data("src", $("#graph").attr("src"));

  // add the change events and call the reload function once on page load, to make
  // sure the options are in sync with the image
  $(".graph_option").change(function() { reloadGraph(this) });
  window.reloadGraph();
});
<|endoftext|>