<commit_before>// === Debug Variable ===
var debugMode = false;

// === Import Necessary Functionality ===
var fileSystem = require('fs');
var parser = require('./parser.js');

// === Creat Necessary Variables ===
var games = {};

// ----------------------------\
// === Main Function ==================================================================================================
// ----------------------------/
exports.input = function(input, gameID){
	var command = parser.parse(input);
	var game = games[gameID];
	if(game){
		var gameActions = game.gameActions;
		game = game.gameData;
		++game.commandCounter;
		var returnString;
		console.log(gameID + ': ' + game.commandCounter);
		try {
			try {
				debug('---Attempting to run cartridge command "'+command.action+'"');
				returnString = eval('gameActions.'+command.action+'(game,command,consoleInterface)');
			} catch(cartridgeCommandError) {
				debug('-----'+cartridgeCommandError);
				debug('---Attempting to run cartridge command "'+command.action+'"');
				returnString = eval('actions.'+command.action+'(game,command)').message;
			}
		} catch(consoleCommandError){
			try {
				debug('-----'+consoleCommandError);
				debug('---Attempting to perform '+command.action+' interaction');
				returnString = interact(game, command.action, command.subject);
			} catch (interactionError) {
				debug('-----'+interactionError);
			}
		}
		if(returnString === undefined){
			returnString = "I don't know how to do that.";
		} else {
			try {
				var updateLocationString = getCurrentLocation(game).updateLocation(command);
			} catch(updateLocationError){
				debug('---Failed to Perform updateLocation()');
				debug('-----'+updateLocationError);
			}
		}
		if(updateLocationString !== undefined){
			returnString = updateLocationString;
		}
		return checkForGameEnd(game, returnString);
	} else {
		console.log(gameID + ': no game');
		if(command.action === 'load'){
			return loadCartridge(gameID, command.subject);
		} else {
			return listCartridges();
		}
	}
};

// ----------------------------\
// === Game Setup Functions ===========================================================================================
// ----------------------------/
function listCartridges(){
	var cartridges = fileSystem.readdirSync('./cartridges/').filter(function(file){
		return file && file[0] != '.';
	});
	if (cartridges.length === 0){
		return 'No game cartridges found.'
	}
	var cartridgesFormated = 'Available Games: \n';
	for(var i = 0; i < cartridges.length; i++){
		cartridgesFormated = cartridgesFormated.concat(cartridges[i].substr(0,cartridges[i].lastIndexOf('.')));
		if(i < cartridges.length-1){
			cartridgesFormated = cartridgesFormated.concat('\n');
		}
	}
	return cartridgesFormated;
}

function loadCartridge(gameID, gameName){
	if (!gameName){
		return "Specify game cartridge to load.";
	}
	try {
		delete require.cache[require.resolve('../cartridges/'+gameName+'.js')];
		var file = require('../cartridges/'+gameName+'.js');
		games[gameID] = {gameData: file.gameData, gameActions: file.gameActions};
		games[gameID].gameData.gameID = gameID;
		return games[gameID].gameData.introText + '\n' + getLocationDescription(games[gameID].gameData);
	} catch(error){
		return "Could not load " + gameName;
	}
}

// ----------------------------\
// === Console Actions =================================================================================================
// ----------------------------/
var actions = {

	die : function(game, command){
		delete games[game.gameID];
		return {message:'You are dead', sucess: true};
	},

	drop : function(game, command){
		if(!command.subject){
			return 'What do you want to drop?';
		}
		try{
			return interact(game, 'drop', command.subject);
		} catch(error) {
			try {
				var currentLocation = getCurrentLocation(game);
				moveItem(command.subject, game.player.inventory, currentLocation.items);
				var item = getItem(currentLocation.items, command.subject);
				item.hidden = false;
				return command.subject + ' dropped';
			} catch(error2){
				return 'You do not have a ' + command.subject + ' to drop.';
			}
		}
	},

	go : function(game, command){
		if(!command.subject){
			return {message: 'Where do you want to go?', sucess: false};
		}
		var exits = getCurrentLocation(game).exits;
		var playerDestination = null
		try {
			playerDestination = exits[command.subject].destination;
		} catch (error) {
			for(var exit in exits){
				var exitObject = exits[exit];
				if(exitObject.displayName.toLowerCase() === command.subject){
					playerDestination = exitObject.destination;
				}
			}
		}
		if(playerDestination === null){
			return {message: 'You can\'t go there.', sucess: false};
		}
		getCurrentLocation(game).firstVisit = false;
		if (getCurrentLocation(game).teardown !== undefined){
			getCurrentLocation(game).teardown();
		}
		if (game.map[playerDestination].setup !== undefined){
			game.map[playerDestination].setup();
		}
		game.player.currentLocation = playerDestination;
		return {message: getLocationDescription(game), sucess: true};
	},

	inventory : function(game, command){
		var inventoryList = 'Your inventory contains:';
		for (var item in game.player.inventory){
			var itemObject = game.player.inventory[item];
			var itemName = itemObject.displayName;
			if(itemObject.quantity > 1){
				itemName = itemName.concat(' x'+itemObject.quantity);
			}
			inventoryList = inventoryList.concat('\n'+itemName);
		}
		if (inventoryList === 'Your inventory contains:'){
			return {message: 'Your inventory is empty.', sucess: true};
		} else {
			return {message: inventoryList, sucess: true};
		}
	},

	look : function(game, command){
		if(!command.subject){
			return {message: getLocationDescription(game, true), sucess: true};
		}
		try {
			try {
				return {message: getItem(game.player.inventory, command.subject).description, sucess: true};
			} catch (itemNotInInventoryError){
				return {message: getItem(getCurrentLocation(game).items, command.subject).description, sucess: true};
			}
		} catch(isNotAnItemError) {
			try {
				return {message: interact(game, 'look', command.subject), sucess: true};
			} catch(subjectNotFound
				) {
				return {message: 'There is nothing important about the '+command.subject+'.', sucess: false};
			}
		}
	},

	take : function(game, command){
		if(!command.subject){
			return 'What do you want to take?';
		}
		try{
			return interact(game, 'take', command.subject);
		} catch(error) {
			try {
				moveItem(command.subject, getCurrentLocation(game).items, game.player.inventory);
				return command.subject + ' taken';
			} catch(error2){
				return 'Best just to leave the ' + command.subject + ' as it is.';
			}
		}
	},

	use : function(game, command){
		if(!command.subject){
			return 'What would you like to use?';
		}
		try {
			return getItem(game.player.inventory, command.subject).use();;
		} catch (itemNotInInventoryError) {
			return 'Can\'t do that.'
		}
	}
};

// ----------------------------\
// === Helper Functions ===============================================================================================
// ----------------------------/
function checkForGameEnd(game, returnString){
	if(game.gameOver){
	returnString = returnString + '\n' + game.outroText;
		actions.die(game,{action:'die'});
	}
	return returnString;
}

function clone(obj) {
    if(obj == null || typeof(obj) != 'object'){
        return obj;
    }
    var temp = obj.constructor();
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            temp[key] = clone(obj[key]);
        }
    }
    return temp;
}

function consoleInterface(game, command){
	return eval('actions.'+command.action+'(game,command);')
}

function debug(debugText){
	if(debugMode){
		console.log(debugText);
	}
}

function exitsToString(exitsObject){
	var numOfExits = Object.keys(exitsObject).length;
	if(numOfExits === 0){
		return '';
	}
	var visibleExits = [];
	for(var exit in exitsObject){
		var exitObject = exitsObject[exit];
		if(!exitObject.hidden){
			visibleExits.push(exitObject.displayName);
		}
	}
	switch(visibleExits.length){
		case 0:
			return '';
		case 	1:
			var returnString = ' Exit is ';
			break;
		default :
			var returnString = ' Exits are ';
	}
	for(i=0; i<visibleExits.length; ++i){
		returnString = returnString.concat(visibleExits[i]);
		if(i === visibleExits.length-2){
			returnString = returnString.concat(' and ');
		} else if (i === visibleExits.length-1){
			returnString = returnString.concat('.');
		} else {
			returnString = returnString.concat(', ');
		}
	}
	return returnString;
}

function getCurrentLocation(game){
	return game.map[game.player.currentLocation];
}

function getLocationDescription(game, forcedLongDescription){
	var currentLocation = getCurrentLocation(game);
	var description;
	if(currentLocation.firstVisit || forcedLongDescription){
		description = currentLocation.description;
		if(currentLocation.items){
			description = description.concat(itemsToString(currentLocation.items));
		}
		if(currentLocation.exits){
			description = description.concat(exitsToString(currentLocation.exits));
		}
	} else {
		description = currentLocation.displayName;
	}
	return description;
}

function getItem(itemLocation, itemName){
	return itemLocation[getItemName(itemLocation, itemName)];
}

function getItemName(itemLocation, itemName){
	if(itemLocation[itemName] !== undefined) {
		return itemName;
	} else {
		for(var item in itemLocation){
			if(itemLocation[item].displayName.toLowerCase() === itemName){
				return item;
			}
		}
	}
}

function itemsToString(itemsObject){
	var numOfItems = Object.keys(itemsObject).length;
	if(numOfItems === 0){
		return '';
	}
	var visibleItems = [];
	for(var item in itemsObject){
		var itemObject = itemsObject[item];
		if(!itemObject.hidden){
			visibleItems.push({name:itemObject.displayName, quantity:itemObject.quantity});
		}
	}
	if(visibleItems.length === 0){
		return '';
	}
	if(visibleItems[0].quantity === 1){
		var returnString = ' There is ';
	} else {
		var returnString = ' There are ';
	}
	for(i=0; i<visibleItems.length; ++i){
		if(visibleItems[i].quantity > 1){
			returnString = returnString.concat(visibleItems[i].quantity+' '+visibleItems[i].name+'s');
		} else {
			returnString = returnString.concat('a '+visibleItems[i].name);
		}
		if(i === visibleItems.length-2){
			returnString = returnString.concat(' and ');
		} else if (i === visibleItems.length-1){
			returnString = returnString.concat(' here.');
		} else {
			returnString = returnString.concat(', ');
		}
	}
	return returnString;
}

function interact(game, interaction, subject){
	//TODO search items in inventory
	return getCurrentLocation(game).interactables[subject][interaction];
}

function moveItem(itemName, startLocation, endLocation){
	var itemName = getItemName(startLocation, itemName);
	var itemAtOrigin = getItem(startLocation, itemName);
	if(itemAtOrigin === undefined){
		throw 'itemDoesNotExist';
	}
	var itemAtDestination = getItem(endLocation, itemName);
	if(itemAtDestination === undefined) {
		endLocation[itemName] = clone(itemAtOrigin);
		endLocation[itemName].quantity = 1;
	} else {
		++endLocation[itemName].quantity;
	}
	if (itemAtOrigin.hasOwnProperty('quantity')){
		--itemAtOrigin.quantity;
		if(itemAtOrigin.quantity === 0){
			delete startLocation[itemName];
		}
	}
}<commit_msg>Take() Command Returns Two-Tuple<commit_after>// === Debug Variable ===
var debugMode = false;

// === Import Necessary Functionality ===
var fileSystem = require('fs');
var parser = require('./parser.js');

// === Creat Necessary Variables ===
var games = {};

// ----------------------------\
// === Main Function ==================================================================================================
// ----------------------------/
exports.input = function(input, gameID){
	var command = parser.parse(input);
	var game = games[gameID];
	if(game){
		var gameActions = game.gameActions;
		game = game.gameData;
		++game.commandCounter;
		var returnString;
		console.log(gameID + ': ' + game.commandCounter);
		try {
			try {
				debug('---Attempting to run cartridge command "'+command.action+'"');
				returnString = eval('gameActions.'+command.action+'(game,command,consoleInterface)');
			} catch(cartridgeCommandError) {
				debug('-----'+cartridgeCommandError);
				debug('---Attempting to run cartridge command "'+command.action+'"');
				returnString = eval('actions.'+command.action+'(game,command)').message;
			}
		} catch(consoleCommandError){
			try {
				debug('-----'+consoleCommandError);
				debug('---Attempting to perform '+command.action+' interaction');
				returnString = interact(game, command.action, command.subject);
			} catch (interactionError) {
				debug('-----'+interactionError);
			}
		}
		if(returnString === undefined){
			returnString = "I don't know how to do that.";
		} else {
			try {
				var updateLocationString = getCurrentLocation(game).updateLocation(command);
			} catch(updateLocationError){
				debug('---Failed to Perform updateLocation()');
				debug('-----'+updateLocationError);
			}
		}
		if(updateLocationString !== undefined){
			returnString = updateLocationString;
		}
		return checkForGameEnd(game, returnString);
	} else {
		console.log(gameID + ': no game');
		if(command.action === 'load'){
			return loadCartridge(gameID, command.subject);
		} else {
			return listCartridges();
		}
	}
};

// ----------------------------\
// === Game Setup Functions ===========================================================================================
// ----------------------------/
function listCartridges(){
	var cartridges = fileSystem.readdirSync('./cartridges/').filter(function(file){
		return file && file[0] != '.';
	});
	if (cartridges.length === 0){
		return 'No game cartridges found.'
	}
	var cartridgesFormated = 'Available Games: \n';
	for(var i = 0; i < cartridges.length; i++){
		cartridgesFormated = cartridgesFormated.concat(cartridges[i].substr(0,cartridges[i].lastIndexOf('.')));
		if(i < cartridges.length-1){
			cartridgesFormated = cartridgesFormated.concat('\n');
		}
	}
	return cartridgesFormated;
}

function loadCartridge(gameID, gameName){
	if (!gameName){
		return "Specify game cartridge to load.";
	}
	try {
		delete require.cache[require.resolve('../cartridges/'+gameName+'.js')];
		var file = require('../cartridges/'+gameName+'.js');
		games[gameID] = {gameData: file.gameData, gameActions: file.gameActions};
		games[gameID].gameData.gameID = gameID;
		return games[gameID].gameData.introText + '\n' + getLocationDescription(games[gameID].gameData);
	} catch(error){
		return "Could not load " + gameName;
	}
}

// ----------------------------\
// === Console Actions =================================================================================================
// ----------------------------/
var actions = {

	die : function(game, command){
		delete games[game.gameID];
		return {message:'You are dead', success: true};
	},

	drop : function(game, command){
		if(!command.subject){
			return 'What do you want to drop?';
		}
		try{
			return interact(game, 'drop', command.subject);
		} catch(error) {
			try {
				var currentLocation = getCurrentLocation(game);
				moveItem(command.subject, game.player.inventory, currentLocation.items);
				var item = getItem(currentLocation.items, command.subject);
				item.hidden = false;
				return command.subject + ' dropped';
			} catch(error2){
				return 'You do not have a ' + command.subject + ' to drop.';
			}
		}
	},

	go : function(game, command){
		if(!command.subject){
			return {message: 'Where do you want to go?', success: false};
		}
		var exits = getCurrentLocation(game).exits;
		var playerDestination = null
		try {
			playerDestination = exits[command.subject].destination;
		} catch (error) {
			for(var exit in exits){
				var exitObject = exits[exit];
				if(exitObject.displayName.toLowerCase() === command.subject){
					playerDestination = exitObject.destination;
				}
			}
		}
		if(playerDestination === null){
			return {message: 'You can\'t go there.', success: false};
		}
		getCurrentLocation(game).firstVisit = false;
		if (getCurrentLocation(game).teardown !== undefined){
			getCurrentLocation(game).teardown();
		}
		if (game.map[playerDestination].setup !== undefined){
			game.map[playerDestination].setup();
		}
		game.player.currentLocation = playerDestination;
		return {message: getLocationDescription(game), success: true};
	},

	inventory : function(game, command){
		var inventoryList = 'Your inventory contains:';
		for (var item in game.player.inventory){
			var itemObject = game.player.inventory[item];
			var itemName = itemObject.displayName;
			if(itemObject.quantity > 1){
				itemName = itemName.concat(' x'+itemObject.quantity);
			}
			inventoryList = inventoryList.concat('\n'+itemName);
		}
		if (inventoryList === 'Your inventory contains:'){
			return {message: 'Your inventory is empty.', success: true};
		} else {
			return {message: inventoryList, success: true};
		}
	},

	look : function(game, command){
		if(!command.subject){
			return {message: getLocationDescription(game, true), success: true};
		}
		try {
			try {
				return {message: getItem(game.player.inventory, command.subject).description, success: true};
			} catch (itemNotInInventoryError){
				return {message: getItem(getCurrentLocation(game).items, command.subject).description, success: true};
			}
		} catch(isNotAnItemError) {
			try {
				return {message: interact(game, 'look', command.subject), success: true};
			} catch(subjectNotFound
				) {
				return {message: 'There is nothing important about the '+command.subject+'.', success: false};
			}
		}
	},

	take : function(game, command){
		if(!command.subject){
			return {message: 'What do you want to take?', success: false};
		}
		try{
			return {message: interact(game, 'take', command.subject), success: true};
		} catch(error) {
			try {
				moveItem(command.subject, getCurrentLocation(game).items, game.player.inventory);
				return {message: command.subject + ' taken', success: true};
			} catch(error2){
				return {message: 'Best just to leave the ' + command.subject + ' as it is.', success: false};
			}
		}
	},

	use : function(game, command){
		if(!command.subject){
			return 'What would you like to use?';
		}
		try {
			return getItem(game.player.inventory, command.subject).use();;
		} catch (itemNotInInventoryError) {
			return 'Can\'t do that.'
		}
	}
};

// ----------------------------\
// === Helper Functions ===============================================================================================
// ----------------------------/
function checkForGameEnd(game, returnString){
	if(game.gameOver){
	returnString = returnString + '\n' + game.outroText;
		actions.die(game,{action:'die'});
	}
	return returnString;
}

function clone(obj) {
    if(obj == null || typeof(obj) != 'object'){
        return obj;
    }
    var temp = obj.constructor();
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            temp[key] = clone(obj[key]);
        }
    }
    return temp;
}

function consoleInterface(game, command){
	return eval('actions.'+command.action+'(game,command);')
}

function debug(debugText){
	if(debugMode){
		console.log(debugText);
	}
}

function exitsToString(exitsObject){
	var numOfExits = Object.keys(exitsObject).length;
	if(numOfExits === 0){
		return '';
	}
	var visibleExits = [];
	for(var exit in exitsObject){
		var exitObject = exitsObject[exit];
		if(!exitObject.hidden){
			visibleExits.push(exitObject.displayName);
		}
	}
	switch(visibleExits.length){
		case 0:
			return '';
		case 	1:
			var returnString = ' Exit is ';
			break;
		default :
			var returnString = ' Exits are ';
	}
	for(i=0; i<visibleExits.length; ++i){
		returnString = returnString.concat(visibleExits[i]);
		if(i === visibleExits.length-2){
			returnString = returnString.concat(' and ');
		} else if (i === visibleExits.length-1){
			returnString = returnString.concat('.');
		} else {
			returnString = returnString.concat(', ');
		}
	}
	return returnString;
}

function getCurrentLocation(game){
	return game.map[game.player.currentLocation];
}

function getLocationDescription(game, forcedLongDescription){
	var currentLocation = getCurrentLocation(game);
	var description;
	if(currentLocation.firstVisit || forcedLongDescription){
		description = currentLocation.description;
		if(currentLocation.items){
			description = description.concat(itemsToString(currentLocation.items));
		}
		if(currentLocation.exits){
			description = description.concat(exitsToString(currentLocation.exits));
		}
	} else {
		description = currentLocation.displayName;
	}
	return description;
}

function getItem(itemLocation, itemName){
	return itemLocation[getItemName(itemLocation, itemName)];
}

function getItemName(itemLocation, itemName){
	if(itemLocation[itemName] !== undefined) {
		return itemName;
	} else {
		for(var item in itemLocation){
			if(itemLocation[item].displayName.toLowerCase() === itemName){
				return item;
			}
		}
	}
}

function itemsToString(itemsObject){
	var numOfItems = Object.keys(itemsObject).length;
	if(numOfItems === 0){
		return '';
	}
	var visibleItems = [];
	for(var item in itemsObject){
		var itemObject = itemsObject[item];
		if(!itemObject.hidden){
			visibleItems.push({name:itemObject.displayName, quantity:itemObject.quantity});
		}
	}
	if(visibleItems.length === 0){
		return '';
	}
	if(visibleItems[0].quantity === 1){
		var returnString = ' There is ';
	} else {
		var returnString = ' There are ';
	}
	for(i=0; i<visibleItems.length; ++i){
		if(visibleItems[i].quantity > 1){
			returnString = returnString.concat(visibleItems[i].quantity+' '+visibleItems[i].name+'s');
		} else {
			returnString = returnString.concat('a '+visibleItems[i].name);
		}
		if(i === visibleItems.length-2){
			returnString = returnString.concat(' and ');
		} else if (i === visibleItems.length-1){
			returnString = returnString.concat(' here.');
		} else {
			returnString = returnString.concat(', ');
		}
	}
	return returnString;
}

function interact(game, interaction, subject){
	//TODO search items in inventory
	return getCurrentLocation(game).interactables[subject][interaction];
}

function moveItem(itemName, startLocation, endLocation){
	var itemName = getItemName(startLocation, itemName);
	var itemAtOrigin = getItem(startLocation, itemName);
	if(itemAtOrigin === undefined){
		throw 'itemDoesNotExist';
	}
	var itemAtDestination = getItem(endLocation, itemName);
	if(itemAtDestination === undefined) {
		endLocation[itemName] = clone(itemAtOrigin);
		endLocation[itemName].quantity = 1;
	} else {
		++endLocation[itemName].quantity;
	}
	if (itemAtOrigin.hasOwnProperty('quantity')){
		--itemAtOrigin.quantity;
		if(itemAtOrigin.quantity === 0){
			delete startLocation[itemName];
		}
	}
}<|endoftext|>


<commit_before>/*global availity, beforeEach, expect, module, describe, it, inject */
describe('analytic service provider', function() {
  'use strict';

  var avAnalyticsServices;
  var serviceName;

  beforeEach(function() {

    var AnalyticsTestServiceFactory = function() {
      var TestAnalyticService = function() {};
      var proto = TestAnalyticService.prototype;
      proto.trackEvent = function() {};
      proto.trackPageView  = function() {};
      return new TestAnalyticService();
    };
    availity.core.factory('TestAnalyticService', AnalyticsTestServiceFactory);
    module('availity', function(avAnalyticsServicesProvider) {
      avAnalyticsServices = avAnalyticsServicesProvider;
    });
  });

  describe('by default', function() {
    it('should register two services', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(2);
    }));

  });

  describe('registerPlugins', function() {
    beforeEach(function() {
      avAnalyticsServices.registerPlugins(['TestAnalyticService']);
    });

    it('should add a new analytic', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(3);
    }));
  });

  describe('deregisterPlugins', function() {
    beforeEach(function() {
      avAnalyticsServices.deregisterPlugins(['TestAnalyticService']);
    });

    it('should remove a services from being registered', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(2);
    }));
  });

  describe('getServiceName', function() {
    beforeEach(function() {
      serviceName = avAnalyticsServices.getServiceName('TestAnalyticService');
    });

    it('should add return only the first word of the service in all uppercase ', function() {
      expect(serviceName).toEqual('TEST');
    });
  });

  describe('virtualPageTracking', function() {
    beforeEach(function() {
      avAnalyticsServices.virtualPageTracking(false);
    });

    it('should set AV_ANALYTIC.VIRTUALPAGETRACKING to the value you pass in', inject(function(AV_ANALYTIC) {
      expect(AV_ANALYTIC.VIRTUALPAGETRACKING).toEqual(false);
    }));
  });

});
<commit_msg>Polyfill for XP Object.keys<commit_after>/*global availity, beforeEach, expect, module, describe, it, inject */
describe('analytic service provider', function() {
  'use strict';

  var avAnalyticsServices;
  var serviceName;

  beforeEach(function() {
    // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
    if(!Object.keys) {
      Object.keys = (function() {
        'use strict';
        var hasOwnProperty = Object.prototype.hasOwnProperty;
        var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
        var dontEnums = [
              'toString',
              'toLocaleString',
              'valueOf',
              'hasOwnProperty',
              'isPrototypeOf',
              'propertyIsEnumerable',
              'constructor'
            ];

        var dontEnumsLength = dontEnums.length;

        return function(obj) {
          if(typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
            throw new TypeError('Object.keys called on non-object');
          }

          var result = [];
          var prop;
          var i;

          for(prop in obj) {
            if(hasOwnProperty.call(obj, prop)) {
              result.push(prop);
            }
          }

          if(hasDontEnumBug) {
            for(i = 0; i < dontEnumsLength; i++) {
              if(hasOwnProperty.call(obj, dontEnums[i])) {
                result.push(dontEnums[i]);
              }
            }
          }
          return result;
        };
      }());
    }

    var AnalyticsTestServiceFactory = function() {
      var TestAnalyticService = function() {};
      var proto = TestAnalyticService.prototype;
      proto.trackEvent = function() {};
      proto.trackPageView  = function() {};
      return new TestAnalyticService();
    };
    availity.core.factory('TestAnalyticService', AnalyticsTestServiceFactory);
    module('availity', function(avAnalyticsServicesProvider) {
      avAnalyticsServices = avAnalyticsServicesProvider;
    });
  });

  describe('by default', function() {
    it('should register two services', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(2);
    }));

  });

  describe('registerPlugins', function() {
    beforeEach(function() {
      avAnalyticsServices.registerPlugins(['TestAnalyticService']);
    });

    it('should add a new analytic', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(3);
    }));
  });

  describe('deregisterPlugins', function() {
    beforeEach(function() {
      avAnalyticsServices.deregisterPlugins(['TestAnalyticService']);
    });

    it('should remove a services from being registered', inject(function(avAnalyticsServices) {
      var services = Object.keys(avAnalyticsServices.services).length;
      expect(services).toEqual(2);
    }));
  });

  describe('getServiceName', function() {
    beforeEach(function() {
      serviceName = avAnalyticsServices.getServiceName('TestAnalyticService');
    });

    it('should add return only the first word of the service in all uppercase ', function() {
      expect(serviceName).toEqual('TEST');
    });
  });

  describe('virtualPageTracking', function() {
    beforeEach(function() {
      avAnalyticsServices.virtualPageTracking(false);
    });

    it('should set AV_ANALYTIC.VIRTUALPAGETRACKING to the value you pass in', inject(function(AV_ANALYTIC) {
      expect(AV_ANALYTIC.VIRTUALPAGETRACKING).toEqual(false);
    }));
  });

});
<|endoftext|>


<commit_before>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load the pre- and post-processors */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile'));

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /** Load the UglifyJS compressor */
  var uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function called when minifying is complete.
   */
  function compile(source, callback) {
    var stderr = '',
        stdout = '';

    var compiler = spawn('java', [
      // load the Closure Compiler and set the compression options
      '-jar', path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar'),
      '--compilation_level=ADVANCED_OPTIMIZATIONS',
      '--language_in=ECMASCRIPT5_STRICT',
      '--warning_level=QUIET'
    ]);

    // explicitly set the encoding of the output and error streams
    compiler.stdout.setEncoding('utf8');
    compiler.stderr.setEncoding('utf8');

    compiler.stdout.on('data', function(data) {
      stdout += data;
    });

    compiler.stderr.on('data', function(data) {
      stderr += data;
    });

    compiler.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to Closure Compiler
    compiler.stdin.end(source);
  }

  /**
   * Compresses a `source` string using the Unix `gzip` commands. Yields the
   * result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to gzip.
   * @param {Function} callback The function called when gzipping is complete.
   */
  function gzip(source, callback) {
    var compressor = spawn('gzip', ['-9f', '-c']),
        stderr = '',
        stdout = '';

    compressor.stdout.setEncoding('binary');
    compressor.stderr.setEncoding('utf8');

    compressor.stdout.on('data', function(data) {
      stdout += data;
    });

    compressor.stderr.on('data', function(data) {
      stderr += data;
    });

    compressor.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to the `gzip` executable
    compressor.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }

  // compress and `gzip` Lo-Dash using the Closure Compiler
  compile(source, function(exception, compiledSource) {
    if (exception) {
      throw exception;
    }

    // post-process the compiled source
    compiledSource = postprocess(compiledSource);

    // save the final compiled version
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiledSource);

    // `gzip` the compiled version
    gzip(compiledSource, function gzipCompiled(exception, result) {
      if (exception) {
        throw exception;
      }

      // record the size of the compiled version
      var compiledSize = result.length;

      // explicit `binary` encoding is necessary to ensure that the stream is written correctly
      fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), result, 'binary');

      // compress Lo-Dash using UglifyJS
      var ugly = uglifyJS.uglify,
          uglifiedSource = ugly.gen_code(
            // enable unsafe transformations
            ugly.ast_squeeze_more(
              ugly.ast_squeeze(
                // munge variable and function names, excluding the special `define`
                // function exposed by AMD loaders
                ugly.ast_mangle(uglifyJS.parser.parse(source), {
                  'except': ['define']
                }
              ))), {
                'ascii_only': true
          });

      // post-process the uglified source and split lines at 500 characters for
      // consistency with Closure Compiler
      uglifiedSource = postprocess(ugly.split_lines(uglifiedSource, 500));

      // save the uglified version
      fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglifiedSource);

      // `gzip` the uglified version
      gzip(uglifiedSource, function gzipUglified(exception, result) {
        if (exception) {
          throw exception;
        }
        var uglifiedSize = result.length;
        fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), result, 'binary');

        // select the smallest minified distribution and use it as the official
        // minified release
        fs.writeFileSync(path.join(__dirname, "lodash.min.js"), compiledSize < uglifiedSize ? compiledSource : uglifiedSource);
      });
    });
  });
}());
<commit_msg>`build.js`: Print compression status messages to the console.<commit_after>#!/usr/bin/env node
;(function() {
  'use strict';

  /** The Node filesystem, path, and child process modules */
  var fs = require('fs'),
      path = require('path'),
      spawn = require('child_process').spawn;

  /** The build directory containing the build scripts */
  var buildPath = path.join(__dirname, 'build');

  /** The distribution directory */
  var distPath = path.join(__dirname, 'dist');

  /** Load the pre- and post-processors */
  var preprocess = require(path.join(buildPath, 'pre-compile')),
      postprocess = require(path.join(buildPath, 'post-compile'));

  /** The pre-processed Lo-Dash source */
  var source = preprocess(fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'));

  /** Load the UglifyJS compressor */
  var uglifyJS = require(path.join(__dirname, 'vendor', 'uglifyjs', 'uglify-js'));

  /*--------------------------------------------------------------------------*/

  /**
   * Compresses a `source` string using the Closure Compiler. Yields the
   * minified result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to minify.
   * @param {Function} callback The function called when minifying is complete.
   */
  function compile(source, callback) {
    var stderr = '',
        stdout = '';

    var compiler = spawn('java', [
      // load the Closure Compiler and set the compression options
      '-jar', path.join(__dirname, 'vendor', 'closure-compiler', 'compiler.jar'),
      '--compilation_level=ADVANCED_OPTIMIZATIONS',
      '--language_in=ECMASCRIPT5_STRICT',
      '--warning_level=QUIET'
    ]);

    // explicitly set the encoding of the output and error streams
    compiler.stdout.setEncoding('utf8');
    compiler.stderr.setEncoding('utf8');

    compiler.stdout.on('data', function(data) {
      stdout += data;
    });

    compiler.stderr.on('data', function(data) {
      stderr += data;
    });

    compiler.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to Closure Compiler
    compiler.stdin.end(source);
  }

  /**
   * Compresses a `source` string using the Unix `gzip` commands. Yields the
   * result, and any exceptions encountered, to a `callback` function.
   *
   * @private
   * @param {String} source The JavaScript source to gzip.
   * @param {Function} callback The function called when gzipping is complete.
   */
  function gzip(source, callback) {
    var compressor = spawn('gzip', ['-9f', '-c']),
        stderr = '',
        stdout = '';

    compressor.stdout.setEncoding('binary');
    compressor.stderr.setEncoding('utf8');

    compressor.stdout.on('data', function(data) {
      stdout += data;
    });

    compressor.stderr.on('data', function(data) {
      stderr += data;
    });

    compressor.on('exit', function(status) {
      var exception = null;
      if (status) {
        exception = new Error(stderr);
        exception.status = status;
      }
      callback(exception, stdout);
    });

    // proxy the source string to the `gzip` executable
    compressor.stdin.end(source);
  }

  /*--------------------------------------------------------------------------*/

  // create the destination directory if it doesn't exist
  if (!path.existsSync(distPath)) {
    fs.mkdirSync(distPath);
  }

  // compress and `gzip` Lo-Dash using the Closure Compiler
  compile(source, function(exception, compiledSource) {
    if (exception) {
      throw exception;
    }

    console.log("Compressing Lodash using the Closure Compiler...");

    // post-process the compiled source
    compiledSource = postprocess(compiledSource);

    // save the final compiled version
    fs.writeFileSync(path.join(distPath, 'lodash.compiler.js'), compiledSource);

    // `gzip` the compiled version
    gzip(compiledSource, function gzipCompiled(exception, result) {
      if (exception) {
        throw exception;
      }

      // record the size of the compiled version
      var compiledSize = result.length;

      // explicit `binary` encoding is necessary to ensure that the stream is written correctly
      fs.writeFileSync(path.join(distPath, 'lodash.compiler.js.gz'), result, 'binary');

      console.log("Done. Size: %d KB.", compiledSize);

      // compress Lo-Dash using UglifyJS
      var ugly = uglifyJS.uglify,
          uglifiedSource = ugly.gen_code(
            // enable unsafe transformations
            ugly.ast_squeeze_more(
              ugly.ast_squeeze(
                // munge variable and function names, excluding the special `define`
                // function exposed by AMD loaders
                ugly.ast_mangle(uglifyJS.parser.parse(source), {
                  'except': ['define']
                }
              ))), {
                'ascii_only': true
          });

      console.log("Compressing Lodash using UglifyJS...");

      // post-process the uglified source and split lines at 500 characters for
      // consistency with Closure Compiler
      uglifiedSource = postprocess(ugly.split_lines(uglifiedSource, 500));

      // save the uglified version
      fs.writeFileSync(path.join(distPath, 'lodash.uglify.js'), uglifiedSource);

      // `gzip` the uglified version
      gzip(uglifiedSource, function gzipUglified(exception, result) {
        if (exception) {
          throw exception;
        }
        var uglifiedSize = result.length;
        fs.writeFileSync(path.join(distPath, 'lodash.uglify.js.gz'), result, 'binary');

        console.log("Done. Size: %d KB.", uglifiedSize);

        // select the smallest minified distribution and use it as the official
        // minified release
        fs.writeFileSync(path.join(__dirname, "lodash.min.js"), compiledSize < uglifiedSize ? compiledSource : uglifiedSource);
      });
    });
  });
}());
<|endoftext|>


<commit_before>"use strict";
let bsCaps;
if (process.env.BROWSER_STACK_USERNAME) {
    bsCaps = require("browserstack-capabilities")(process.env.BROWSER_STACK_USERNAME, process.env.BROWSER_STACK_ACCESS_KEY);
}

module.exports = config => {
    let customLaunchers = {};
    config.set({
        frameworks: ["mocha"],
        reporters: ["coverage-istanbul", "progress", "BrowserStack"].slice(0, bsCaps ? 3: 2),
        files: ["test/test_index.js"],
        preprocessors: {
            "test/test_index.js": ["webpack", "sourcemap"]
        },
        webpack: require("./webpack.config"),
        beforeMiddleware: ["webpackBlocker"],
        concurrency: bsCaps ? 1: Infinity,
        browsers: bsCaps ? bsCaps.create({
            browser: "ie",
            browser_version: "latest"
        }).map(cap => {
            cap.base = "BrowserStack";
            var browser = ("device" in cap && cap.device) ? cap.device:
                (cap.browser + " " +
                cap.browser_version + " on " +
                cap.os + " " +
                cap.os_version + " resolution:" +
                cap.resolution);
            customLaunchers[browser] = cap;
            return browser;
        }).filter((_, i) => i % (process.env.CIRCLE_NODE_TOTAL || 1) == process.env.CIRCLE_NODE_INDEX): [],
        browserStack: {
            project: (process.env.CIRCLE_PROJECT_REPONAME || "frame") + "_" + (process.env.CIRCLE_BRANCH || require("child_process").execSync("git branch | grep \\* | cut -d \" \" -f2-"))
        },
        customLaunchers: customLaunchers
    });
};
<commit_msg>テスト対象をIE -> Chrome, FireFox に変更しました。(Temporary)<commit_after>"use strict";
let bsCaps;
if (process.env.BROWSER_STACK_USERNAME) {
    bsCaps = require("browserstack-capabilities")(process.env.BROWSER_STACK_USERNAME, process.env.BROWSER_STACK_ACCESS_KEY);
}

module.exports = (config) => {
    let customLaunchers = {};
    config.set({
        frameworks: ["mocha"],
        reporters: ["coverage-istanbul", "progress", "BrowserStack"].slice(0, bsCaps ? 3: 2),
        files: ["test/test_index.js"],
        preprocessors: {
            "test/test_index.js": ["webpack", "sourcemap"]
        },
        webpack: require("./webpack.config"),
        beforeMiddleware: ["webpackBlocker"],
        concurrency: bsCaps ? 1: Infinity,
        browsers: bsCaps ? bsCaps.create({
            browser: ["chrome", "firefox"],
            "browser_version": "latest"
        }).map((cap) => {
            cap.base = "BrowserStack";
            var browser = ("device" in cap && cap.device) ? cap.device:
                (cap.browser + " " +
                cap.browser_version + " on " +
                cap.os + " " +
                cap.os_version + " resolution:" +
                cap.resolution);
            customLaunchers[browser] = cap;
            return browser;
        }).filter((_, i) => i % (process.env.CIRCLE_NODE_TOTAL || 1) == process.env.CIRCLE_NODE_INDEX): [],
        browserStack: {
            project: (process.env.CIRCLE_PROJECT_REPONAME || "frame") + "_" + (process.env.CIRCLE_BRANCH || require("child_process").execSync("git branch | grep \\* | cut -d \" \" -f2-"))
        },
        customLaunchers: customLaunchers
    });
};
<|endoftext|>


<commit_before>({
  baseUrl: "apps",
  paths:{
    requireLib:"../components/requirejs/require",
    fabric: "../libs/fabric",
    jquery: "../components/jquery/jquery",
    hbs: "../components/require-handlebars-plugin/hbs",
    handlebars: "../components/require-handlebars-plugin/Handlebars",
    underscore: "../components/require-handlebars-plugin/hbs/underscore",
    json2: "../components/require-handlebars-plugin/hbs/json2",
    i18nprecompile: "../components/require-handlebars-plugin/hbs/i18nprecompile",
    bootstrap: "../components/bootstrap/js/bootstrap",
    spectrum: "../components/spectrum/spectrum"
  },
  shim:{
    fabric: {
      exports: "fabric"
    },
    jquery: {
      exports: "$"
    },
    "spectrum": ["jquery"],
    "../components/flight/lib/component": {
      deps: ["jquery"]
    },
    bootstrap: {
      deps: ["jquery"]
    }
  },
  hbs: {
    disableI18n: true
  },
  map: {
    "*": {
      'flight/component': '../components/flight/lib/component',
      'brushes': 'brushes'
    }
  },
  name: "../main",
  include: ["requireLib"],
  out: "main-built.js"
})<commit_msg>simplify build<commit_after>({
  baseUrl: "apps",
  paths: {
    requireLib: "../components/requirejs/require"
  },
  name: "../main",
  mainConfigFile: "main.js",
  include: ["requireLib"],
  out: "main-built.js"
})<|endoftext|>


<commit_before>var bleacon = require("bleacon");
var moment = require("moment");
var fs = require("fs");
var path = require("path");

var PORT = 8888;

/**
 * ファイルの存在チェック
 */
function exists(file){
	try{
		fs.accessSync(file, fs.R_OK);
		return true;
	} catch (e){
		return false;
	}
}

/**
 * ログ
 */
function log(message){
	console.log("[" + moment().format("YYYY/MM/DD HH:mm:ss") + "] " + message);
}

/**
 * 簡易HTTPサーバー
 */
var server = require("http").createServer(function(request, response) {
	//URLの整形
	var p = request.url;
	if(p.lastIndexOf("/") == p.length - 1){
		p += "index.html"
	}
	if(p.indexOf("/") == 0){
		p = p.substring(1);
	}
	//実パス変換
	var realPath = path.resolve(__dirname, p);
	if(exists(realPath) == false){
		//ファイルが存在しない
		log("404 Not Found: " + request.url + " => " + realPath);
		response.writeHead(404);
		response.end();
		return;
	}
	//返却
	log("200 OK: " + request.url + " => " + realPath);
	fs.readFile(realPath, "binary", function(err, data){
		response.writeHead(200, {"Content-Length": data.length});
		response.write(data, "binary");
		response.end();
	});
});
server.listen(PORT, "127.0.0.1", function() {
    log("Server is listening... Press Ctrl-C for quit server.");
});

/**
 * WebSocket
 */
var socket = require("socket.io")(server);
socket.on("connection", function(s){
	//接続した
	log("Connected.");
	s.on("event", function(data){
		//イベント発生
		log("Event raised.");
	});
	s.on("disconnect", function(){
		//切断した
		log("Disconnected.");
	});
});

/**
 * ビーコン検出時処理
 */
bleacon.on('discover', function(beacon) {
	//変換
	var temperature = (((beacon.major >> 4) & 0x03ff) * 100 - 30000) / 1000.0;
	var humidity = ((beacon.major << 3) & 0x0078) | ((beacon.minor >> 13) & 0x0007);
	var pressure = Math.floor(((beacon.minor & 0x1fff) * 0.1 + 300) * 10) / 10;

	//送信
	socket.sockets.emit("data", '{ "rssi": ' + beacon.rssi + ', "temperature": ' + temperature + ', "humidity": ' + humidity + ', "pressure": ' + pressure + ' }');
});
//ビーコン検索開始
bleacon.startScanning("c722db4c5d911801beb5001c4de7b3fd");

setInterval(function(){
	var beacon = {
		rssi: -1 * Math.floor(Math.random() * 100)
	};
	var temperature = 25 + Math.floor(Math.random() * 10) / 10;
	var humidity = 50 + Math.floor(Math.random() * 10 - 5) / 10;
	var pressure = 1013 + Math.floor(Math.random() * 10 - 5) / 10;
	socket.sockets.emit("data", '{ "rssi": ' + beacon.rssi + ', "temperature": ' + temperature + ', "humidity": ' + humidity + ', "pressure": ' + pressure + ' }');
}, 1000);
<commit_msg>テスト用コードを削除<commit_after>var bleacon = require("bleacon");
var moment = require("moment");
var fs = require("fs");
var path = require("path");

var PORT = 8888;

/**
 * ファイルの存在チェック
 */
function exists(file){
	try{
		fs.accessSync(file, fs.R_OK);
		return true;
	} catch (e){
		return false;
	}
}

/**
 * ログ
 */
function log(message){
	console.log("[" + moment().format("YYYY/MM/DD HH:mm:ss") + "] " + message);
}

/**
 * 簡易HTTPサーバー
 */
var server = require("http").createServer(function(request, response) {
	//URLの整形
	var p = request.url;
	if(p.lastIndexOf("/") == p.length - 1){
		p += "index.html"
	}
	if(p.indexOf("/") == 0){
		p = p.substring(1);
	}
	//実パス変換
	var realPath = path.resolve(__dirname, p);
	if(exists(realPath) == false){
		//ファイルが存在しない
		log("404 Not Found: " + request.url + " => " + realPath);
		response.writeHead(404);
		response.end();
		return;
	}
	//返却
	log("200 OK: " + request.url + " => " + realPath);
	fs.readFile(realPath, "binary", function(err, data){
		response.writeHead(200, {"Content-Length": data.length});
		response.write(data, "binary");
		response.end();
	});
});
server.listen(PORT, "127.0.0.1", function() {
    log("Server is listening... Press Ctrl-C for quit server.");
});

/**
 * WebSocket
 */
var socket = require("socket.io")(server);
socket.on("connection", function(s){
	//接続した
	log("Connected.");
	s.on("event", function(data){
		//イベント発生
		log("Event raised.");
	});
	s.on("disconnect", function(){
		//切断した
		log("Disconnected.");
	});
});

/**
 * ビーコン検出時処理
 */
bleacon.on('discover', function(beacon) {
	//変換
	var temperature = (((beacon.major >> 4) & 0x03ff) * 100 - 30000) / 1000.0;
	var humidity = ((beacon.major << 3) & 0x0078) | ((beacon.minor >> 13) & 0x0007);
	var pressure = Math.floor(((beacon.minor & 0x1fff) * 0.1 + 300) * 10) / 10;

	//送信
	socket.sockets.emit("data", '{ "rssi": ' + beacon.rssi + ', "temperature": ' + temperature + ', "humidity": ' + humidity + ', "pressure": ' + pressure + ' }');
});
//ビーコン検索開始
bleacon.startScanning("c722db4c5d911801beb5001c4de7b3fd");
<|endoftext|>


<commit_before>'use strict';

module.exports = function(config) {

  var configuration = {
    frameworks: ['jasmine'],
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-story-reporter'
    ],
    files: [
      'jq-plugin.js',
     	'tests/*.js'
    ],
    // browsers: [ 'Chrome', 'Firefox' ],
    browsers: [ 'Chrome' ],
    singleRun: true,
    reporters: ['story']
  };

  if(process.env.TRAVIS){
    configuration.browsers = [ 'Chrome', 'Firefox' ];
  }

  if( process.env.DRONE || process.env.WERCKER ){
    configuration.browsers = [ 'Chrome' ];
  }

  config.set(configuration);

};
<commit_msg>trying to run travis tests<commit_after>'use strict';

module.exports = function(config) {

  var configuration = {
    frameworks: ['jasmine'],
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-story-reporter'
    ],
    files: [
      'jq-plugin.js',
     	'tests/*.js'
    ],
    // browsers: [ 'Chrome', 'Firefox' ],
    browsers: [ 'Chrome' ],
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    singleRun: true,
    reporters: ['story']
  };

  if(process.env.TRAVIS){
    configuration.browsers = [ 'Chrome_travis_ci', 'Firefox' ];
  }

  if( process.env.DRONE || process.env.WERCKER ){
    configuration.browsers = [ 'Chrome' ];
  }

  config.set(configuration);

};
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.form.on("Website Theme", {
	onload_post_render(frm) {
		frm.events.make_app_theme_selector(frm);
	},

	refresh(frm) {
		frm.clear_custom_buttons();
		frm.toggle_display(["module", "custom"], !frappe.boot.developer_mode);

		frm.trigger("set_default_theme_button_and_indicator");
		frm.trigger("make_app_theme_selector");

		if (!frm.doc.custom && !frappe.boot.developer_mode) {
			frm.set_read_only();
			frm.disable_save();
		} else {
			frm.enable_save();
		}
	},

	set_default_theme_button_and_indicator(frm) {
		frappe.db
			.get_single_value("Website Settings", "website_theme")
			.then(value => {
				if (value === frm.doc.name) {
					frm.page.set_indicator(__("Default Theme"), "green");
				} else {
					frm.page.clear_indicator();
					// show set as default button
					if (!frm.is_new() && !frm.is_dirty()) {
						frm.add_custom_button(
							__("Set as Default Theme"),
							() => {
								frm.call("set_as_default").then(() =>
									frm.trigger("refresh")
								);
							}
						);
					}
				}
			});
	},

	make_app_theme_selector(frm) {
		if (frm.app_theme_selector) {
			frm.events.get_installed_apps(frm).then(apps => {
				let ignored_apps = frm.doc.ignored_apps.map(d => d.app);
				frm.app_theme_selector
					.get_field("apps")
					.select_options(
						apps
							.map(d => d.name)
							.filter(app => !ignored_apps.includes(app))
					);
			});
			return;
		}
		let $wrapper = frm.get_field("ignored_apps").$wrapper.hide();
		let $body = $("<div>").insertAfter($wrapper);
		let ignored_apps = frm.doc.ignored_apps.map(d => d.app);
		frm.events.get_installed_apps(frm).then(apps => {
			let form = new frappe.ui.FieldGroup({
				fields: [
					{
						label: __("Include Theme from Apps"),
						fieldname: "apps",
						fieldtype: "MultiCheck",
						columns: 4,
						on_change: () => {
							let value = form
								.get_field("apps")
								.get_unchecked_options()
								.map(app => ({ app: app }));
							frm.set_value("ignored_apps", value);
						},
						options: apps.map(app => ({
							label: app.title,
							value: app.name,
							checked: !ignored_apps.includes(app.name)
						}))
					}
				],
				body: $body
			});
			form.make();
			frm.app_theme_selector = form;
			$(form.wrapper)
				.find(".form-section")
				.css({
					padding: 0,
					marginLeft: "-15px",
					marginRight: "-15px"
				});
		});
	},

	get_installed_apps(frm) {
		return new Promise(resolve => {
			if (frm.installed_apps) {
				resolve(frm.installed_apps);
				return;
			}
			return frm.call("get_apps").then(r => {
				frm.installed_apps = r.message;
				resolve(r.message);
			});
		});
	}
});
<commit_msg>fix: empty array does not trigger form change<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.form.on("Website Theme", {
	onload_post_render(frm) {
		frm.events.make_app_theme_selector(frm);
	},

	refresh(frm) {
		frm.clear_custom_buttons();
		frm.toggle_display(["module", "custom"], !frappe.boot.developer_mode);

		frm.trigger("set_default_theme_button_and_indicator");
		frm.trigger("make_app_theme_selector");

		if (!frm.doc.custom && !frappe.boot.developer_mode) {
			frm.set_read_only();
			frm.disable_save();
		} else {
			frm.enable_save();
		}
	},

	set_default_theme_button_and_indicator(frm) {
		frappe.db
			.get_single_value("Website Settings", "website_theme")
			.then(value => {
				if (value === frm.doc.name) {
					frm.page.set_indicator(__("Default Theme"), "green");
				} else {
					frm.page.clear_indicator();
					// show set as default button
					if (!frm.is_new() && !frm.is_dirty()) {
						frm.add_custom_button(
							__("Set as Default Theme"),
							() => {
								frm.call("set_as_default").then(() =>
									frm.trigger("refresh")
								);
							}
						);
					}
				}
			});
	},

	make_app_theme_selector(frm) {
		if (frm.app_theme_selector) {
			frm.events.get_installed_apps(frm).then(apps => {
				let ignored_apps = frm.doc.ignored_apps.map(d => d.app);
				frm.app_theme_selector
					.get_field("apps")
					.select_options(
						apps
							.map(d => d.name)
							.filter(app => !ignored_apps.includes(app))
					);
			});
			return;
		}
		let $wrapper = frm.get_field("ignored_apps").$wrapper.hide();
		let $body = $("<div>").insertAfter($wrapper);
		let ignored_apps = frm.doc.ignored_apps.map(d => d.app);
		frm.events.get_installed_apps(frm).then(apps => {
			let form = new frappe.ui.FieldGroup({
				fields: [
					{
						label: __("Include Theme from Apps"),
						fieldname: "apps",
						fieldtype: "MultiCheck",
						columns: 4,
						on_change: () => {
							let value = form
								.get_field("apps")
								.get_unchecked_options()
								.map(app => ({ app: app }));
							frm.set_value("ignored_apps", value.length ? value : null);
						},
						options: apps.map(app => ({
							label: app.title,
							value: app.name,
							checked: !ignored_apps.includes(app.name)
						}))
					}
				],
				body: $body
			});
			form.make();
			frm.app_theme_selector = form;
			$(form.wrapper)
				.find(".form-section")
				.css({
					padding: 0,
					marginLeft: "-15px",
					marginRight: "-15px"
				});
		});
	},

	get_installed_apps(frm) {
		return new Promise(resolve => {
			if (frm.installed_apps) {
				resolve(frm.installed_apps);
				return;
			}
			return frm.call("get_apps").then(r => {
				frm.installed_apps = r.message;
				resolve(r.message);
			});
		});
	}
});
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    // basePath: 'app',
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    // files: [
    //   'bower_components/angular/angular.js',
    //   'bower_components/angular-mocks/angular-mocks.js',
    //   'bower_components/angular-resource/angular-resource.js',
    //   'bower_components/angular-cookies/angular-cookies.js',
    //   'bower_components/angular-sanitize/angular-sanitize.js',
    //   'bower_components/angular-route/angular-route.js',
    //   'scripts/*.js',
    //   'scripts/**/*.js',
    //   '../test/mock/**/*.js',
    //   '../test/spec/**/*.js'
    // ],
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Allow import and testing of templates
    // preprocessors: {
    //   'views/**/*.html': 'html2js'
    //   // ,'views/*.html': 'html2js'
    // },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>new module depencies added<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    // basePath: 'app',
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    // files: [
    //   'bower_components/angular/angular.js',
    //   'bower_components/angular-mocks/angular-mocks.js',
    //   'bower_components/angular-resource/angular-resource.js',
    //   'bower_components/angular-cookies/angular-cookies.js',
    //   'bower_components/angular-sanitize/angular-sanitize.js',
    //   'bower_components/angular-route/angular-route.js',
    //   'scripts/*.js',
    //   'scripts/**/*.js',
    //   '../test/mock/**/*.js',
    //   '../test/spec/**/*.js'
    // ],
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-local-storage/angular-local-storage.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Allow import and testing of templates
    preprocessors: {
      'views/**/*.html': 'html2js'
      // ,'views/*.html': 'html2js'
    },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Aug 15 2014 23:11:13 GMT-0500 (CDT)

var webpack = require('webpack');

function createCustomLauncher(browser, version, platform) {
  return {
    base: 'SauceLabs',
    browserName: browser,
    version: version,
    platform: platform
  };
}

module.exports = function(config) {
  var customLaunchers = {};
  var browsers = [];

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Running locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    browsers = ['Firefox', 'Chrome', 'Safari', 'Opera'];
  } else {
    customLaunchers = {};

    var runAll = true;
    var options = [
      'SAUCE_CHROME',
      'SAUCE_FIREFOX',
      'SAUCE_SAFARI',
      'SAUCE_OPERA',
      'SAUCE_IE',
      'SAUCE_EDGE',
      'SAUCE_IOS',
      'SAUCE_ANDROID'
    ];

    options.forEach(function (opt) {
      if (process.env[opt]) {
        runAll = false;
      }
    });

    // Chrome
    if (runAll || process.env.SAUCE_CHROME) {
      customLaunchers.SL_Chrome = createCustomLauncher('chrome');
      // customLaunchers.SL_ChromeDev = createCustomLauncher('chrome', 'dev');
      // customLaunchers.SL_ChromeBeta = createCustomLauncher('chrome', 'beta');
    }

    // Firefox
    if (runAll || process.env.SAUCE_FIREFOX) {
      customLaunchers.SL_Firefox = createCustomLauncher('firefox');
      // customLaunchers.SL_FirefoxDev = createCustomLauncher('firefox', 'dev');
      // customLaunchers.SL_FirefoxBeta = createCustomLauncher('firefox', 'beta');
    }

    // Safari
    if (runAll || process.env.SAUCE_SAFARI) {
      // customLaunchers.SL_Safari7 = createCustomLauncher('safari', 7);
      // customLaunchers.SL_Safari8 = createCustomLauncher('safari', 8);
      customLaunchers.SL_Safari9 = createCustomLauncher('safari', 9);
    }

    // Opera
    if (runAll || process.env.SAUCE_OPERA) {
      // TODO The available versions of Opera are too old and lack basic APIs
      // customLaunchers.SL_Opera11 = createCustomLauncher('opera', 11, 'Windows XP');
      // customLaunchers.SL_Opera12 = createCustomLauncher('opera', 12, 'Windows 7');
    }

    // IE
    if (runAll || process.env.SAUCE_IE) {
      // TODO These need to be fixed
      // customLaunchers.SL_IE8 = createCustomLauncher('internet explorer', 8, 'Windows 7');
      customLaunchers.SL_IE9 = createCustomLauncher('internet explorer', 9, 'Windows 2008');
      customLaunchers.SL_IE10 = createCustomLauncher('internet explorer', 10, 'Windows 2012');
      customLaunchers.SL_IE11 = createCustomLauncher('internet explorer', 11, 'Windows 8.1');
    }

    // Edge
    if (runAll || process.env.SAUCE_EDGE) {
      customLaunchers.SL_Edge = createCustomLauncher('microsoftedge', null, 'Windows 10');
    }

    // IOS
    if (runAll || process.env.SAUCE_IOS) {
      // TODO IOS7 capture always timesout
      // customLaunchers.SL_IOS7 = createCustomLauncher('iphone', '7.1', 'OS X 10.10');
      // TODO Mobile browsers are causing failures, possibly from too many concurrent VMs
      // customLaunchers.SL_IOS8 = createCustomLauncher('iphone', '8.4', 'OS X 10.10');
      // customLaunchers.SL_IOS9 = createCustomLauncher('iphone', '9.2', 'OS X 10.10');
    }

    // Android
    if (runAll || process.env.SAUCE_ANDROID) {
      // TODO Mobile browsers are causing failures, possibly from too many concurrent VMs
      // customLaunchers.SL_Android4 = createCustomLauncher('android', '4.4', 'Linux');
      // customLaunchers.SL_Android5 = createCustomLauncher('android', '5.1', 'Linux');
    }

    browsers = Object.keys(customLaunchers);
  }

  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine-ajax', 'jasmine', 'sinon'],

    // list of files / patterns to load in the browser
    files: [
      'test/specs/__helpers.js',
      'test/specs/**/*.spec.js',
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/specs/__helpers.js': ['webpack', 'sourcemap'],
      'test/specs/**/*.spec.js': ['webpack', 'sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'coverage', 'saucelabs'],

    // web server port
    port: 9876,

    // Increase timeout in case connection to CI is slow
    captureTimeout: 120000,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: browsers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Webpack config
    webpack: {
      cache: true,
      devtool: 'inline-source-map',
      module: {
        postLoaders: [
          {
            test: /\.js$/,
            exclude: /(node_modules|test)/,
            loader: 'istanbul-instrumenter'
          }
        ]
      },
      externals: [
        {
          './adapters/http': 'var undefined'
        }
      ],
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test')
        })
      ]
    },

    webpackServer: {
      stats: {
        colors: true
      }
    },

    // Coverage reporting
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/',
      subdir: '.'
    },

    // SauceLabs config
    sauceLabs: {
      recordScreenshots: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },

    customLaunchers: customLaunchers
  });
};
<commit_msg>Fixing issue with Travis<commit_after>// Karma configuration
// Generated on Fri Aug 15 2014 23:11:13 GMT-0500 (CDT)

var webpack = require('webpack');

function createCustomLauncher(browser, version, platform) {
  return {
    base: 'SauceLabs',
    browserName: browser,
    version: version,
    platform: platform
  };
}

module.exports = function(config) {
  var customLaunchers = {};
  var browsers = [];

  if (process.env.SAUCE_USERNAME || process.env.SAUCE_ACCESS_KEY) {
    customLaunchers = {};

    var runAll = true;
    var options = [
      'SAUCE_CHROME',
      'SAUCE_FIREFOX',
      'SAUCE_SAFARI',
      'SAUCE_OPERA',
      'SAUCE_IE',
      'SAUCE_EDGE',
      'SAUCE_IOS',
      'SAUCE_ANDROID'
    ];

    options.forEach(function (opt) {
      if (process.env[opt]) {
        runAll = false;
      }
    });

    // Chrome
    if (runAll || process.env.SAUCE_CHROME) {
      customLaunchers.SL_Chrome = createCustomLauncher('chrome');
      // customLaunchers.SL_ChromeDev = createCustomLauncher('chrome', 'dev');
      // customLaunchers.SL_ChromeBeta = createCustomLauncher('chrome', 'beta');
    }

    // Firefox
    if (runAll || process.env.SAUCE_FIREFOX) {
      customLaunchers.SL_Firefox = createCustomLauncher('firefox');
      // customLaunchers.SL_FirefoxDev = createCustomLauncher('firefox', 'dev');
      // customLaunchers.SL_FirefoxBeta = createCustomLauncher('firefox', 'beta');
    }

    // Safari
    if (runAll || process.env.SAUCE_SAFARI) {
      // customLaunchers.SL_Safari7 = createCustomLauncher('safari', 7);
      // customLaunchers.SL_Safari8 = createCustomLauncher('safari', 8);
      customLaunchers.SL_Safari9 = createCustomLauncher('safari', 9);
    }

    // Opera
    if (runAll || process.env.SAUCE_OPERA) {
      // TODO The available versions of Opera are too old and lack basic APIs
      // customLaunchers.SL_Opera11 = createCustomLauncher('opera', 11, 'Windows XP');
      // customLaunchers.SL_Opera12 = createCustomLauncher('opera', 12, 'Windows 7');
    }

    // IE
    if (runAll || process.env.SAUCE_IE) {
      // TODO These need to be fixed
      // customLaunchers.SL_IE8 = createCustomLauncher('internet explorer', 8, 'Windows 7');
      customLaunchers.SL_IE9 = createCustomLauncher('internet explorer', 9, 'Windows 2008');
      customLaunchers.SL_IE10 = createCustomLauncher('internet explorer', 10, 'Windows 2012');
      customLaunchers.SL_IE11 = createCustomLauncher('internet explorer', 11, 'Windows 8.1');
    }

    // Edge
    if (runAll || process.env.SAUCE_EDGE) {
      customLaunchers.SL_Edge = createCustomLauncher('microsoftedge', null, 'Windows 10');
    }

    // IOS
    if (runAll || process.env.SAUCE_IOS) {
      // TODO IOS7 capture always timesout
      // customLaunchers.SL_IOS7 = createCustomLauncher('iphone', '7.1', 'OS X 10.10');
      // TODO Mobile browsers are causing failures, possibly from too many concurrent VMs
      // customLaunchers.SL_IOS8 = createCustomLauncher('iphone', '8.4', 'OS X 10.10');
      // customLaunchers.SL_IOS9 = createCustomLauncher('iphone', '9.2', 'OS X 10.10');
    }

    // Android
    if (runAll || process.env.SAUCE_ANDROID) {
      // TODO Mobile browsers are causing failures, possibly from too many concurrent VMs
      // customLaunchers.SL_Android4 = createCustomLauncher('android', '4.4', 'Linux');
      // customLaunchers.SL_Android5 = createCustomLauncher('android', '5.1', 'Linux');
    }

    browsers = Object.keys(customLaunchers);
  } else if (process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST !== 'false') {
    console.log('Cannot run on Sauce Labs as encrypted environment variables are not available to PRs. Using PhantomJS.');
    browsers = ['PhantomJS'];
  } else {
    console.log('Running locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.');
    browsers = ['Firefox', 'Chrome', 'Safari', 'Opera'];
  }

  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine-ajax', 'jasmine', 'sinon'],

    // list of files / patterns to load in the browser
    files: [
      'test/specs/__helpers.js',
      'test/specs/**/*.spec.js',
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/specs/__helpers.js': ['webpack', 'sourcemap'],
      'test/specs/**/*.spec.js': ['webpack', 'sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'coverage', 'saucelabs'],

    // web server port
    port: 9876,

    // Increase timeout in case connection to CI is slow
    captureTimeout: 120000,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: browsers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Webpack config
    webpack: {
      cache: true,
      devtool: 'inline-source-map',
      module: {
        postLoaders: [
          {
            test: /\.js$/,
            exclude: /(node_modules|test)/,
            loader: 'istanbul-instrumenter'
          }
        ]
      },
      externals: [
        {
          './adapters/http': 'var undefined'
        }
      ],
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test')
        })
      ]
    },

    webpackServer: {
      stats: {
        colors: true
      }
    },

    // Coverage reporting
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/',
      subdir: '.'
    },

    // SauceLabs config
    sauceLabs: {
      recordScreenshots: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },

    customLaunchers: customLaunchers
  });
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Oct 15 2016 13:36:16 GMT+0100 (WAT)

module.exports = function (config) {
  config.set({

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      './src/js/invertedIndex.js',
      './spec/invertedIndexSpec.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/js/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>fix: try chrome<commit_after>// Karma configuration
// Generated on Sat Oct 15 2016 13:36:16 GMT+0100 (WAT)

module.exports = function (config) {
  config.set({

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      './src/js/invertedIndex.js',
      './spec/invertedIndexSpec.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/js/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers:  ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++

/*!
 * JavaScript for Bootstrap's docs (https://getbootstrap.com)
 * Copyright 2011-2016 The Bootstrap Authors
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the Creative Commons Attribution 3.0 Unported License. For
 * details, see https://creativecommons.org/licenses/by/3.0/.
 */

/* global Clipboard, anchors */

!function ($) {
  'use strict';

  $(function () {

    // Tooltip and popover demos
    $('.tooltip-demo').tooltip({
      selector: '[data-toggle="tooltip"]',
      container: 'body'
    })

    $('[data-toggle="popover"]').popover()

    // Demos within modals
    $('.tooltip-test').tooltip()
    $('.popover-test').popover()

    // Indeterminate checkbox example
    $('.bd-example-indeterminate [type="checkbox"]').prop('indeterminate', true)

    // Disable empty links in docs examples
    $('.bd-example [href="#"]').click(function (e) {
      e.preventDefault()
    })

    // Modal relatedTarget demo
    $('#exampleModal').on('show.bs.modal', function (event) {
      var $button = $(event.relatedTarget)      // Button that triggered the modal
      var recipient = $button.data('whatever')  // Extract info from data-* attributes
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
      var $modal = $(this)
      $modal.find('.modal-title').text('New message to ' + recipient)
      $modal.find('.modal-body input').val(recipient)
    })

    // Insert copy to clipboard button before .highlight
    $('.highlight').each(function () {
      var btnHtml = '
Copy
'
      $(this).before(btnHtml)
      $('.btn-clipboard').tooltip()
    })

    var clipboard = new Clipboard('.btn-clipboard', {
      target: function (trigger) {
        return trigger.parentNode.nextElementSibling
      }
    })

    clipboard.on('success', function (e) {
      $(e.trigger)
        .attr('title', 'Copied!')
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')

      e.clearSelection()
    })

    clipboard.on('error', function (e) {
      var fallbackMsg = /Mac/i.test(navigator.userAgent) ? 'Press \u2318 to copy' : 'Press Ctrl-C to copy'

      $(e.trigger)
        .attr('title', fallbackMsg)
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')
    })

  })

}(jQuery)

;(function () {
  'use strict';

  anchors.options.placement = 'left';
  anchors.add('.bd-content > h1, .bd-content > h2, .bd-content > h3, .bd-content > h4, .bd-content > h5')
})();
<commit_msg>Replacement for #20602 (#21236)<commit_after>// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++

/*!
 * JavaScript for Bootstrap's docs (https://getbootstrap.com)
 * Copyright 2011-2016 The Bootstrap Authors
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the Creative Commons Attribution 3.0 Unported License. For
 * details, see https://creativecommons.org/licenses/by/3.0/.
 */

/* global Clipboard, anchors */

!function ($) {
  'use strict';

  $(function () {

    // Tooltip and popover demos
    $('.tooltip-demo').tooltip({
      selector: '[data-toggle="tooltip"]',
      container: 'body'
    })

    $('[data-toggle="popover"]').popover()

    // Demos within modals
    $('.tooltip-test').tooltip()
    $('.popover-test').popover()

    // Indeterminate checkbox example
    $('.bd-example-indeterminate [type="checkbox"]').prop('indeterminate', true)

    // Disable empty links in docs examples
    $('.bd-example [href="#"]').click(function (e) {
      e.preventDefault()
    })

    // Modal relatedTarget demo
    $('#exampleModal').on('show.bs.modal', function (event) {
      var $button = $(event.relatedTarget)      // Button that triggered the modal
      var recipient = $button.data('whatever')  // Extract info from data-* attributes
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
      var $modal = $(this)
      $modal.find('.modal-title').text('New message to ' + recipient)
      $modal.find('.modal-body input').val(recipient)
    })

    // Insert copy to clipboard button before .highlight
    $('.highlight').each(function () {
      var btnHtml = '
Copy
'
      $(this).before(btnHtml)
      $('.btn-clipboard').tooltip()
    })

    var clipboard = new Clipboard('.btn-clipboard', {
      target: function (trigger) {
        return trigger.parentNode.nextElementSibling
      }
    })

    clipboard.on('success', function (e) {
      $(e.trigger)
        .attr('title', 'Copied!')
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')

      e.clearSelection()
    })

    clipboard.on('error', function (e) {
      var modifierKey = /Mac/i.test(navigator.userAgent) ? '\u2318' : 'Ctrl-'
      var fallbackMsg = 'Press ' + modifierKey + 'C to copy'

      $(e.trigger)
        .attr('title', fallbackMsg)
        .tooltip('_fixTitle')
        .tooltip('show')
        .attr('title', 'Copy to clipboard')
        .tooltip('_fixTitle')
    })

  })

}(jQuery)

;(function () {
  'use strict';

  anchors.options.placement = 'left';
  anchors.add('.bd-content > h1, .bd-content > h2, .bd-content > h3, .bd-content > h4, .bd-content > h5')
})();
<|endoftext|>


<commit_before>import path from 'path';

function getStoryshotFile(fileName) {
  const { dir, name } = path.parse(fileName);
  return path.format({ dir: path.join(dir, '__snapshots__'), name, ext: '.storyshot' });
}

export function getPossibleStoriesFiles(storyshotFile) {
  const { dir, name } = path.parse(storyshotFile);

  return [
    path.format({ dir: path.dirname(dir), name, ext: '.js' }),
    path.format({ dir: path.dirname(dir), name, ext: '.jsx' }),
  ];
}

export function getSnapshotFileName(context) {
  const { fileName } = context;

  if (!fileName) {
    return null;
  }

  return getStoryshotFile(fileName);
}
<commit_msg>Add .ts exts to the getPossibleStoriesFiles<commit_after>import path from 'path';

function getStoryshotFile(fileName) {
  const { dir, name } = path.parse(fileName);
  return path.format({ dir: path.join(dir, '__snapshots__'), name, ext: '.storyshot' });
}

export function getPossibleStoriesFiles(storyshotFile) {
  const { dir, name } = path.parse(storyshotFile);

  return [
    path.format({ dir: path.dirname(dir), name, ext: '.js' }),
    path.format({ dir: path.dirname(dir), name, ext: '.jsx' }),
    path.format({ dir: path.dirname(dir), name, ext: '.ts' }),
    path.format({ dir: path.dirname(dir), name, ext: '.tsx' }),
  ];
}

export function getSnapshotFileName(context) {
  const { fileName } = context;

  if (!fileName) {
    return null;
  }

  return getStoryshotFile(fileName);
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Jul 30 2020 18:25:01 GMT-0400 (Eastern Daylight Time)

module.exports = function (config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '.',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      { pattern: 'src/*.js', type: 'module' },
      { pattern: 'test/*.js', type: 'module' },
      'test/*.html',
    ],

    // list of files / patterns to exclude
    exclude: [
      'src/text-fragments.js', // so that the polyfill doesn't run in test
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.html': ['html2js'],
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    html2JsPreprocessor: {
      // strip this from the file path
      stripPrefix: 'test/',
    },
  });
};
<commit_msg>Disabling sandbox in test (#30)<commit_after>// Karma configuration
// Generated on Thu Jul 30 2020 18:25:01 GMT-0400 (Eastern Daylight Time)

module.exports = function (config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '.',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      { pattern: 'src/*.js', type: 'module' },
      { pattern: 'test/*.js', type: 'module' },
      'test/*.html',
    ],

    // list of files / patterns to exclude
    exclude: [
      'src/text-fragments.js', // so that the polyfill doesn't run in test
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.html': ['html2js'],
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
          base: 'ChromeHeadless',
          flags: ['--no-sandbox']
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    html2JsPreprocessor: {
      // strip this from the file path
      stripPrefix: 'test/',
    },
  });
};
<|endoftext|>