<commit_before>$(document).ready(function() {

	$('.scroll-link').on('click', function(event){
		event.preventDefault();
		var sectionID = $(this).attr("data-id");
		scrollToID('#' + sectionID, 750);
	});

	if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
		$(".timeline-text-container").on("click", function () {
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		});
	} else {
		$(".timeline-text-container").hover(function(){
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		//$(this).find(".hover").fadeIn(300);
		});
		/*$(".timeline-text-container").on("mouseenter", function () {
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		});

		$(".timeline-text-container").on("mouseleave", function () {
			$(this).children(".timeline-class-desc").slideToggle();
		});*/
	}

	navSetter('main');
	navSetter('timeline');
	navSetter('portfolio');

});
// scroll function
function scrollToID(id, speed){
	var targetOffset = $(id).offset().top -40;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function navSetter(id) {

	var target = $("#"+id).offset().top -50,
	    timeout = null;

	$(window).scroll(function () {
	    if (!timeout) {
	        timeout = setTimeout(function () {
	            clearTimeout(timeout);
	            timeout = null;
	            if ($(window).scrollTop() >= target) {
	            	$(".nav").children().removeClass('active');
	                $("#nav-"+id).addClass('active');
	            }
	        }, 250);
	    }
	});

}
<commit_msg>Update script.js<commit_after>$(document).ready(function() {

	$('.scroll-link').on('click', function(event){
		event.preventDefault();
		var sectionID = $(this).attr("data-id");
		scrollToID('#' + sectionID, 750);
	});

	if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
		$(".timeline-text-container").on("click", function () {
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").stop(true,true).slideToggle();
		});
	} else {
		$(".timeline-text-container").hover(function(){
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		//$(this).find(".hover").fadeIn(300);
		});
		/*$(".timeline-text-container").on("mouseenter", function () {
			$(this).children(".timeline-hover-notice").hide();
			$(this).children(".timeline-class-desc").slideToggle();
		});

		$(".timeline-text-container").on("mouseleave", function () {
			$(this).children(".timeline-class-desc").slideToggle();
		});*/
	}

	navSetter('main');
	navSetter('timeline');
	navSetter('portfolio');

});
// scroll function
function scrollToID(id, speed){
	var targetOffset = $(id).offset().top -40;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function navSetter(id) {

	var target = $("#"+id).offset().top -50,
	    timeout = null;

	$(window).scroll(function () {
	    if (!timeout) {
	        timeout = setTimeout(function () {
	            clearTimeout(timeout);
	            timeout = null;
	            if ($(window).scrollTop() >= target) {
	            	$(".nav").children().removeClass('active');
	                $("#nav-"+id).addClass('active');
	            }
	        }, 250);
	    }
	});

}
<|endoftext|>


<commit_before>/**
 * safe-regex-cli © 2016 Adrien Valcke
 * The command line tool for safe-regex module to detect potentially catastrophic exponential-time regular expressions by limiting the star height to 1..
 *
 * Main entry for lib. Synchronous and asynchronous functions.
 *
 */
const defaults = require('../lib/defaults');

const DirectoryToSafe = require('./models/DirectoryToSafe.class');
const FileToSafe = require('./models/FileToSafe.class');
const utils = require('./utils');

const safe = require('safe-regex');

/** MAIN ENTRY POINT : can be require in a module. const safeReport = require('safe-regex-cli');
 * safeReport Asynchronous function to get a report on unsafe regex files
 * @param  {String}     dirorfile     path to a directory or a file
 * @param  {Object}     options       recursive: false, limit: 25, watch: false
 * @param  {Function}   callback      callback
 */
const safeReport = function safeReport(dirorfile, options, callback) {
  let recursive = defaults.recursive,
      limit = defaults.limit,
      watch = defaults.watch,
      cb = callback;

  // if no options then options is the callback
  if (utils.is(options, Function)) {
    cb = options;
  } else {
    // check options like this because options can be a missing parameter and we need to filter options
    // otherwise we could do const {recursive = false, limit = FileToSafe.LIMIT, watch = false} in parameter replacing options
    if (options.recursive) recursive = utils.toBoolean(options.recursive);
    if (options.limit) {
      limit = utils.getInt(options.limit, 1); // get limit if Number or 1 at least (min)
      FileToSafe.prototype.limit = limit; // all future fileToSafe objects will be set with this limit or default constant LIMIT of class, so they will have this.limit access
    }
    if (options.watch) watch = utils.toBoolean(options.watch);
  }

  let directory = new DirectoryToSafe(dirorfile, recursive);
  directory.getUnsafeRegexInFiles(() => {
    if (watch) {
      directory.report();
      directory.watchUnsafeRegexInFiles();
    }
    else cb(directory);
  });
};

/** ENTRY POINT for cli
 * safeReport Synchronous function to get a report on unsafe regex files
 * @param  {String}  dirorfile     path to a directory or a file
 * @param  {Boolean} recursive     indicates whether all subdirectories should be tested or watched, or only the current directory (false by default)
 * @param  {Number}  [limit=25]    number of allowed repetitions in the entire regular expressions found (default 25)
 * @param  {Boolean} [watch=false] watch or not files when changing
 */
const safeReportSync = function safeReportSync({dirorfile = '', recursive = defaults.recursive, limit = defaults.limit, watch = defaults.watch}) {

  // filter options limit, recursive and watch if different from defaults (= set by caller) only to avoid useless filter processing on data
  if (recursive !== defaults.recursive) recursive = utils.toBoolean(recursive);
  if (limit !== defaults.limit) {
    limit = utils.getInt(limit, 1); // get limit if Number or 1 at least (min)
    FileToSafe.prototype.limit = limit; // all future fileToSafe objects will be set with this limit or default constant LIMIT of class, so they will have this.limit access
  }
  if (watch !== defaults.watch) watch = utils.toBoolean(watch);

  let directory = new DirectoryToSafe(dirorfile, recursive);
  directory.getUnsafeRegexInFilesSync();
  directory.report();

  if (watch) { directory.watchUnsafeRegexInFiles(); return watch; }
  else if (directory.isUnsafe()) return false;
  else return true;
};

module.exports = safeReport;
module.exports.safeReportSync = safeReportSync;
module.exports.safe = safe;
<commit_msg>add ES6 features, removed prototype and add documentation<commit_after>/**
 * safe-regex-cli © 2016 Adrien Valcke
 *
 * The command line tool for the safe-regex module to ensure your regular expressions
 * are not susceptible of regular expression denial of service (ReDOS) attacks.
 * Get a report on a file or a directory of files,
 * watch a file or a directory of files for unsafe regex live
 * or test a regex in cli.
 *
 * lib index, synchronous and asynchronous reports.
 */
const utils = require('./utils');
const defaults = require('./defaults');
const DirectoryToSafe = require('./models/DirectoryToSafe.class');
const FileToSafe = require('./models/FileToSafe.class');

const safe = require('safe-regex');

/** ENTRY POINT FOR CLI
 * safeReport Synchronous function to get a report on unsafe regex found in files
 * @param  {Object}  with these properties :
 *   {String}  dirorfile     path to a directory or a file
 *   {Boolean} recursive     indicates whether all subdirectories should be tested or watched, or only the current directory (false by default)
 *   {Number}  limit         number of allowed repetitions in the entire regular expressions found (default 25)
 *   {Boolean} watch         watch or not files when changing
 */
const safeReportSync = function safeReportSync({dirorfile = '', recursive = defaults.recursive, limit = defaults.limit, watch = defaults.watch}) {

  // filter option 'watch' only, 'limit' and 'recursive' are filtered in DirectoryToSafe constructor
  // only if different from defaults (= set by caller) to avoid useless filter processing on data
  if (watch !== defaults.watch) watch = utils.toBoolean(watch);

  const directory = new DirectoryToSafe(dirorfile, recursive, limit);
  directory.getUnsafeRegexInFilesSync();
  directory.report();

  if (watch) { directory.watchUnsafeRegexInFiles(); return watch; }
  else if (directory.isUnsafe()) return false;
  else return true;
};

/** MAIN ENTRY POINT FOR API : const safeReport = require('safe-regex-cli');
 * safeReport Asynchronous function to get a report on unsafe regex files
 * @param  {String}     dirorfile     path to a directory or a file
 * @param  {Object}     options       recursive, limit, watch
 * @param  {Function}   callback      callback
 */
const safeReport = function safeReport(dirorfile, options, callback) {
  let recursive,
      limit,
      watch,
      cb = callback;

  // if no options then options is the callback
  if (utils.is(options, Function)) {
    cb = options;
  } else {
    // check options like this because options can be a missing parameter and we need to filter option watch (recursive and limit will be filtered in DirectoryToSafe constructor)
    // otherwise we could do const {recursive = defaults.recursive, limit = defaults.limit, watch = defaults.watch} in parameter replacing options
    recursive = options.recursive || defaults.recursive;
    limit = options.limit || defaults.limit;
    watch = options.watch || defaults.watch;
    if (watch !== defaults.watch) watch = utils.toBoolean(watch);
  }

  const directory = new DirectoryToSafe(dirorfile, recursive, limit);
  directory.getUnsafeRegexInFiles(() => {
    if (watch) {
      directory.report();
      directory.watchUnsafeRegexInFiles();
    }
    else cb(directory);
  });
};

module.exports = safeReport;
module.exports.safeReportSync = safeReportSync;
module.exports.safe = safe;
<|endoftext|>


<commit_before>var express = require('express');

var env = process.env.NODE_ENV || 'development';
console.log('process.env.NODE_ENV : ' + process.env.NODE_ENV)
console.log('process.env.PORT : ' + process.env.PORT)

var app = express();
var config = require('./server/config/config')[env];

require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
require('./server/config/passport')();
require('./server/config/routes')(app);

var server = app.listen(config.port);
require('./server/config/socket').init(server);
console.log("NODE_ENV = " + env);
console.log("Server running on port: " + config.port);

module.exports = {
    app: app,
    port: config.port,
    host: 'http://localhost'
};<commit_msg>edit server.js env<commit_after>var express = require('express');

var env = process.env.NODE_ENV || 'development';
console.log('process.env.NODE_ENV : ' + process.env.NODE_ENV)

var app = express();
var config = require('./server/config/config')[env];

require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
require('./server/config/passport')();
require('./server/config/routes')(app);

var server = app.listen(config.port);
require('./server/config/socket').init(server);
console.log("NODE_ENV = " + env);
console.log("Server running on port: " + config.port);

module.exports = {
    app: app,
    port: config.port,
    host: 'http://localhost'
};<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding change<commit_msg>What do you mean you can't pack up the commit?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes<|endoftext|>


<commit_before>myApp.factory('survey', [function() {
  //var mydb = new Pouch('http://db.wiflo.org:5984/survey-cus_sat');
  //Pouch.replicate('wiflo_current-users', 'http://db.wiflo.org:5984/wiflo_current-users', {continuous: true});
  //Pouch.replicate('http://db.wiflo.org:5984/wiflo_current-users', 'wiflo_current-users', {continuous: true});
  return mydb;
}]);

myApp.factory('surveyListener', ['$rootScope', 'survey', function($rootScope, survey) {

  survey.changes({
    continuous: true,
    onChange: function(change) {
    	//console.log(change.changes);
      if (!change.deleted) {
        $rootScope.$apply(function() {
          survey.get(change.id, function(err, doc) {
            $rootScope.$apply(function() {
              if (err) console.log(err);
              $rootScope.$broadcast('add_surveyItem', doc);
            })
          });
        })
      } else (change.deleted)
        $rootScope.$apply(function() {
          $rootScope.$broadcast('rem_surveyItem', change.id);
        });
    }
  })
}]);

myApp.directive('fileDrag', function () {
  return {
    restrict: 'A',
    link: function (scope, elem) {
      elem.bind('drop', function(e){
        e.preventDefault();
        e..stopPropagation();
        var file = e.dataTransfer.files[0], reader = new FileReader();
          reader.onload = function (event) {
          console.log(event.target);
          elem.style.background = 'url(' + event.target.result + ') no-repeat center';
        };
        console.log(file);
        reader.readAsDataURL(file);

        return false;
      });
    }
  };
});

myApp.controller('surveyCtrl', ['$scope', 'surveyListener', '$window', '$timeout', function($scope, surveyListener, $window, $timeout) {

  //Dyanmic style function
  $scope.color = function (user) {
    if (user.status == "active") {
      return { backgroundColor: "#75FF75" }
    } else {
      return { backgroundColor: "#FF3333" }
    }
  };

  //Holds all the survey items
  $scope.surveyItems = [];

  // Holds the questions and their sums
  $scope.questions = [];

  //Holds comments
  $scope.comments = [];

  //Holds the current comment to view
  $scope.activeComment = "";

  //Holds all the survey IDs and their associated satisfaction indexes
  $scope.surveyIDs = {};

  //Filter to make sure questions are only kpu related questions
  $scope.type = "kpi";

	//Holds the metrics
  $scope.mean = "...";
  $scope.variance = "...";
  $scope.stdDev = "...";
  $scope.lowerBound = "...";
  $scope.upperBound = "...";

  //Holds the outlying data points
  $scope.outliers = [];

  //Listeners to broadcasts
  $scope.$on('add_surveyItem', function(event, surveyItemDoc) {
	var surveyItem = {
		_id: surveyItemDoc._id,
		type: surveyItemDoc.type,
		questionName: surveyItemDoc.questionName,
		questionId: surveyItemDoc.questionId,
		data: surveyItemDoc.data
	};
  //console.log(surveyItem);
	if(surveyItem.type == "kpi"){
  	$scope.surveyItems.push(surveyItem);
  	if(!(surveyItem.questionId in $scope.questions)){
			var question = {
        type: "kpi",
				questionId: surveyItemDoc.questionId,
				questionName: surveyItemDoc.questionName,
        questionHTMLName: surveyItemDoc.questionName.replace(/\s/g, ''),
				ratings: [0, 0, 0, 0, 0],
        percentages: [0, 0, 0 ,0, 0],
        total: 0
			}
			$scope.questions[surveyItem.questionId] = question;
			$scope.questions[surveyItem.questionId].ratings[surveyItem.data - 1] ++;
      $scope.questions[surveyItem.questionId].total ++;
      //Recalculate percentages
      for (var i=0;i<$scope.questions[surveyItem.questionId].percentages.length;i++) {
        $scope.questions[surveyItem.questionId].percentages[i] = (($scope.questions[surveyItem.questionId].ratings[i] / $scope.questions[surveyItem.questionId].total) * 100).toFixed(0);
      }
		} else {
			$scope.questions[surveyItem.questionId].ratings[surveyItem.data - 1] ++;
      $scope.questions[surveyItem.questionId].total ++;
      for (var i=0;i<$scope.questions[surveyItem.questionId].percentages.length;i++) {
        $scope.questions[surveyItem.questionId].percentages[i] = (($scope.questions[surveyItem.questionId].ratings[i] / $scope.questions[surveyItem.questionId].total) * 100).toFixed(0);
      }
		}
    //Add to the object that holds the satisfaction indexes
    if(surveyItemDoc.surveyId in $scope.surveyIDs){
      $scope.surveyIDs[surveyItemDoc.surveyId] =  $scope.surveyIDs[surveyItemDoc.surveyId] + surveyItem.data;
    } else {
      $scope.surveyIDs[surveyItemDoc.surveyId] =  surveyItem.data;
    }
	} else if(surveyItem.type == "comment" && surveyItem.questionName != "submit"){
    var comment = {
      type: "comment",
      surveyId: surveyItemDoc.surveyId,
      questionName: surveyItem.questionName,
      data: surveyItem.data
    }
    $scope.comments.push(comment);
  }
  });

  $scope.genMetrics = function()
  {
    //Calculate the mean
    var indexTotal = 0;
    var numIndexes = 0;
    var mean = 0;
    for(var key in $scope.surveyIDs) {
      if($scope.surveyIDs.hasOwnProperty(key)) {
        indexTotal = indexTotal + $scope.surveyIDs[key];
        numIndexes ++;
      }
    }
    mean = (indexTotal / numIndexes);
    //Calculate the variance
    var varianceSum = 0;
    var variance = 0;
    for(var key in $scope.surveyIDs) {
      if($scope.surveyIDs.hasOwnProperty(key)) {
        varianceSum = varianceSum + Math.pow(Math.abs($scope.surveyIDs[key] - mean), 2);
      }
    }
    //Get the outlying data points
    variance = (varianceSum / numIndexes);
    //Calculate standard deviation
    var stdDev = 0;
    stdDev = (Math.sqrt(variance));
    //Assign the variables
    $scope.mean = mean.toFixed(2);
    $scope.variance = variance.toFixed(2);
    $scope.stdDev = stdDev.toFixed(2);
    var lowerBound = (mean - stdDev).toFixed(2);
    var upperBound = (mean + stdDev).toFixed(2);
    $scope.lowerBound = lowerBound;
    $scope.upperBound = upperBound;
    //Collect the outlying data points
    $scope.outliers = [];
    for(var key in $scope.surveyIDs) {
      if($scope.surveyIDs.hasOwnProperty(key)) {
        if($scope.surveyIDs[key] < lowerBound){
          var outlier = {
            surveyId: key,
            satIndex: $scope.surveyIDs[key]
          }
          $scope.outliers.push(outlier);
        }
      }
    }
  };

  $scope.showComment = function(surveyId){
    console.log("HEyYYYYY");
    console.log($scope.comments);
    for(var i=0;i<$scope.comments.length;i++) {
      if($scope.comments[i].surveyId == surveyId){
        $scope.activeComment = "Comment: " + $scope.comments[i].data;
      }
    }
  }

}]);

<commit_msg>Delete survey.js<commit_after><|endoftext|>


<commit_before>function getStats(txt) {
	let words = txt.split(/[\W_]/g).filter(function (word) {
			return word.length > 0;
		});

	for (let i in words)
		words[i] = words[i].toLowerCase();

	words.sort(); // alphabetize

	let lines = txt.split(/[\r\n]/);
	let nonEmptyLines = lines.filter(function (line) {
			return line.length > 0;
		});

	return {
		nChars: txt.length,
		nWords: words.length,
		nLines: lines.length,
		nNonEmptyLines: nonEmptyLines.length,
		averageWordLength: getAverageLength(words),
		maxLineLength: getMaxLength(lines),
		palindromes: "[ " + findPalindromes(words).join(", ") + " ]",
		longestWords: "[ " + findLongest(words).join(", ") + " ]",
		mostFrequentWords: "[ " + findMostFrequent(words).join(", ") + " ]"
	};
}

function findMostFrequent(words) {
	let map = new Map();
	for (let word of words) {
		map.has(word) ? map.set(word, map.get(word) + 1) : map.set(word, 1);
	}

	freqArray = [];
	for (let[key, value]of map) {
		freqArray.push([key, value]);
	}

	freqArray.sort(function (first, second) {
		return second[1] - first[1];
	});

	stringArray = [];
	for (let elem of freqArray.slice(0, 10))
		stringArray.push( elem[0] + "(" + elem[1] + ")");

	return stringArray;
}

function findPalindromes(words) {
	let palindromes = [];
	for (let word of words) {
		if (isPalindrome(word))
			palindromes.push(word);
	}

	return palindromes;
}

function isPalindrome(word) {
	let chars = word.split("");
	if (chars.length <= 2) {
		return false
	} else {
		let left = 0;
		let right = chars.length - 1;
		while (left < right) {
			if (chars[left] != chars[right]) {
				return false;
			}

			left++;
			right--;
		}

		return true;
	}

	return false;
}

function findLongest(words) {
	return words.sort(
		function (first, second) {
		return second.length - first.length;
	}).slice(0, 10);
}

function getAverageLength(words) {
	let numChars = 0;
	for (let word of words) {
		numChars += word.length;
	}

	return numChars / words.length;
}

function getMaxLength(words) {
	let currentMax = "";
	for (let word of words) {
		if ( word.length > currentMax.length)
			currentMax = word;
	}

	return currentMax.length;
}
<commit_msg>Fixed regexp to not break up words on apostrophes<commit_after>function getStats(txt) {
	let words = txt.split(/[^a-zA-Z0-9']/g).filter(function (word) {
			return word.length > 0;
		});

	for (let i in words)
		words[i] = words[i].toLowerCase();

	words.sort(); // alphabetize

	let lines = txt.split(/[\r\n]/);
	let nonEmptyLines = lines.filter(function (line) {
			return line.length > 0;
		});

	return {
		nChars: txt.length,
		nWords: words.length,
		nLines: lines.length,
		nNonEmptyLines: nonEmptyLines.length,
		averageWordLength: getAverageLength(words),
		maxLineLength: getMaxLength(lines),
		palindromes: "[ " + findPalindromes(words).join(", ") + " ]",
		longestWords: "[ " + findLongest(words).join(", ") + " ]",
		mostFrequentWords: "[ " + findMostFrequent(words).join(", ") + " ]"
	};
}

function findMostFrequent(words) {
	let map = new Map();
	for (let word of words) {
		map.has(word) ? map.set(word, map.get(word) + 1) : map.set(word, 1);
	}

	freqArray = [];
	for (let[key, value]of map) {
		freqArray.push([key, value]);
	}

	freqArray.sort(function (first, second) {
		return second[1] - first[1];
	});

	stringArray = [];
	for (let elem of freqArray.slice(0, 10))
		stringArray.push(elem[0] + "(" + elem[1] + ")");

	return stringArray;
}

function findPalindromes(words) {
	let palindromes = [];
	for (let word of words) {
		if (isPalindrome(word))
			palindromes.push(word);
	}

	return palindromes;
}

function isPalindrome(word) {
	let chars = word.split("");
	if (chars.length <= 2) {
		return false
	} else {
		let left = 0;
		let right = chars.length - 1;
		while (left < right) {
			if (chars[left] != chars[right]) {
				return false;
			}

			left++;
			right--;
		}

		return true;
	}

	return false;
}

function findLongest(words) {
	return words.sort(
		function (first, second) {
		return second.length - first.length;
	}).slice(0, 10);
}

function getAverageLength(words) {
	let numChars = 0;
	for (let word of words) {
		numChars += word.length;
	}

	return numChars / words.length;
}

function getMaxLength(words) {
	let currentMax = "";
	for (let word of words) {
		if (word.length > currentMax.length)
			currentMax = word;
	}

	return currentMax.length;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var os = require("adapter/os"),
        log = require("adapter/log");

    module.exports = {
        acquireFocus: function () {
            os.acquireKeyboardFocus().catch(function (err) {
                log.error("Failed to acquire keyboard focus", err);
            });
        },
        componentDidMount: function () {
            this.getDOMNode().addEventListener("mousedown", this.acquireFocus);
        },
        componentWillUnmount: function () {
            this.getDOMNode().removeEventListener("mousedown", this.acquireFocus);
        }
    };
});
<commit_msg>Fix reference to the log module<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports, module) {
    "use strict";

    var os = require("adapter/os"),
        log = require("js/util/log");

    module.exports = {
        acquireFocus: function () {
            os.acquireKeyboardFocus().catch(function (err) {
                log.error("Failed to acquire keyboard focus", err);
            });
        },
        componentDidMount: function () {
            this.getDOMNode().addEventListener("mousedown", this.acquireFocus);
        },
        componentWillUnmount: function () {
            this.getDOMNode().removeEventListener("mousedown", this.acquireFocus);
        }
    };
});
<|endoftext|>


<commit_before>// Uses some ideas from https://gist.github.com/kevinSuttle/c8b198aaa30349088c35

var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./common/common');

var del           = require('del'),
    sass          = require('gulp-sass'),
    sourcemaps    = require('gulp-sourcemaps'),
    autoprefixer  = require('gulp-autoprefixer'),
    browserSync   = require('browser-sync'),
    reload        = browserSync.reload,
    tap           = require('gulp-tap'),
    runSequence   = require('run-sequence').use(gulp),
    exec          = require('child_process').exec,
    nodemon       = require('gulp-nodemon');

// Auto load all gulp plugins
var plug = require('gulp-load-plugins')();

// Paths
var paths = {
  source : {
    root : './client',
    css : [
        './client/css/**/*.css',
        '!./client/css/**/*.min.css'
    ],
    sass : [
        './client/scss',
        './client/lib/github/zurb/bower-foundation@5.5.2/scss'
    ],
    sassMain : './client/scss/app.scss',
    js : './client/**/*.js',
    jsMain : './client/app.js'
  },
  dest : {
    css : './client/css',
    cssMain : 'app.min.css',
    jsMain : './client/app.min.js'
  }
};

// Load common utils
var _ = plug.loadUtils(['colors', 'env', 'log', 'date']);

// Create comments for minified files
var commentHeader = common.createComments(_);

// TASKS
// ----------------------------

// Js linter -- currently not used!
gulp.task('jshint', function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.jshint('.jshintrc'))
             .pipe(plug.jshint.reporter('jshint-stylish'));
});

// uses jspm to create a self-executing bundle at /client/app.js
gulp.task('jspmBundle', function(cb) {
  exec('jspm bundle-sfx app/main ' + paths.source.jsMain, function(err) {
    if (err) return cb(err);
    cb();
  });
});

// js minify & header injection
gulp.task('js', ['jspmBundle'], function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.size({ showFiles : true }))
             .pipe(plug.uglify())
             .pipe(plug.header(commentHeader))
               .pipe(tap(function(file,t) {
                 file.path = file.path.replace(/\.js$/, '.min.js');  // using gulp-tap to create a .min.js file with same name in same folder
               }))
               .pipe(gulp.dest(paths.source.root))
               .pipe(plug.size({ showFiles : true }));
});

// converting sass to css
gulp.task('sass', function() {
  return gulp.src(paths.source.sassMain)
               .pipe(sass({
                 includePaths : paths.source.sass,
                 outputStyle : 'nested'
               }, { errLogToConsole : true }))
               .pipe(autoprefixer())
               .pipe(gulp.dest(paths.dest.css));
});

// css minify & bundling
gulp.task('css', ['sass'], function() {
  return gulp.src(paths.source.css)
             .pipe(plug.size({ showFiles : true }))
             .pipe(sourcemaps.init())
             .pipe(plug.minifyCss({}))
             .pipe(plug.concat(paths.dest.cssMain))
             .pipe(plug.header(commentHeader))
             .pipe(sourcemaps.write('.'))
             .pipe(gulp.dest(paths.dest.css))
             .pipe(plug.size({ showFiles : true }));
});

gulp.task('clean', function(cb) {
  del([paths.dest.css, paths.source.root + '/app*'], function(err, paths) {
    var msg = 'Deleted files/folders:\n' + paths.join('\n');
    _.log(_.colors.yellow(msg));

    cb();
  });
});

gulp.task('build', function(cb) {
  runSequence('clean',
              ['css', 'js'],
              cb);
});

gulp.task('nodemon', function(cb) {
  var called = false;
  return nodemon({ script : pkg.main, ext : 'js vash ejs jade', ignore : ['./client/**', './logs/**'] }).on('start', function() {
    if (!called) {
      _.log(_.colors.green('Starting nodemon..'));
      called = true;
      cb();
    }
  });
});

gulp.task('browser-sync', ['nodemon'], function() {
  browserSync({
    proxy : 'http://localhost:5000'
  });
});

function reportChange(event) {
  _.log('File ' + _.colors.green(event.path) + ' was ' + _.colors.yellow(event.type) + ', running tasks...');
}

gulp.task('watch', ['browser-sync'], function() {
  gulp.watch(paths.source.sassMain, ['sass', reload({ stream : true })]).on('change', reportChange);
  gulp.watch(paths.source.js, ['', reload]).on('change', reportChange);
});

gulp.task('default', function(cb) {
  runSequence('build', 'watch', cb);
});

gulp.task('serveprod', function() {
  connect.server({
    root: paths.source.root,
    port: process.env.PORT || 5000, // localhost:5000
    livereload: false
  });
});

gulp.task('heroku:production', function(){
  runSequence('clean', 'js')
})<commit_msg>Updated gulpfile<commit_after>// Uses some ideas from https://gist.github.com/kevinSuttle/c8b198aaa30349088c35

var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./common/common');

var del           = require('del'),
    sass          = require('gulp-sass'),
    sourcemaps    = require('gulp-sourcemaps'),
    autoprefixer  = require('gulp-autoprefixer'),
    browserSync   = require('browser-sync'),
    reload        = browserSync.reload,
    tap           = require('gulp-tap'),
    runSequence   = require('run-sequence').use(gulp),
    exec          = require('child_process').exec,
    nodemon       = require('gulp-nodemon');

// Auto load all gulp plugins
var plug = require('gulp-load-plugins')();

// Paths
var paths = {
  source : {
    root : './client',
    css : [
        './client/css/**/*.css',
        '!./client/css/**/*.min.css'
    ],
    sass : [
        './client/scss',
        './client/lib/github/zurb/bower-foundation@5.5.2/scss'
    ],
    sassMain : './client/scss/app.scss',
    js : './client/**/*.js',
    jsMain : './client/app.js'
  },
  dest : {
    css : './client/css',
    cssMain : 'app.min.css',
    jsMain : './client/app.min.js'
  }
};

// Load common utils
var _ = plug.loadUtils(['colors', 'env', 'log', 'date']);

// Create comments for minified files
var commentHeader = common.createComments(_);

// TASKS
// ----------------------------

// Js linter -- currently not used!
gulp.task('jshint', function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.jshint('.jshintrc'))
             .pipe(plug.jshint.reporter('jshint-stylish'));
});

// uses jspm to create a self-executing bundle at /client/app.js
gulp.task('jspmBundle', function(cb) {
  exec('jspm bundle-sfx app/main ' + paths.source.jsMain, function(err) {
    if (err) return cb(err);
    cb();
  });
});

// js minify & header injection
gulp.task('js', ['jspmBundle'], function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.size({ showFiles : true }))
             .pipe(plug.uglify())
             .pipe(plug.header(commentHeader))
               .pipe(tap(function(file,t) {
                 file.path = file.path.replace(/\.js$/, '.min.js');  // using gulp-tap to create a .min.js file with same name in same folder
               }))
               .pipe(gulp.dest(paths.source.root))
               .pipe(plug.size({ showFiles : true }));
});

// converting sass to css
gulp.task('sass', function() {
  return gulp.src(paths.source.sassMain)
               .pipe(sass({
                 includePaths : paths.source.sass,
                 outputStyle : 'nested'
               }, { errLogToConsole : true }))
               .pipe(autoprefixer())
               .pipe(gulp.dest(paths.dest.css));
});

// css minify & bundling
gulp.task('css', ['sass'], function() {
  return gulp.src(paths.source.css)
             .pipe(plug.size({ showFiles : true }))
             .pipe(sourcemaps.init())
             .pipe(plug.minifyCss({}))
             .pipe(plug.concat(paths.dest.cssMain))
             .pipe(plug.header(commentHeader))
             .pipe(sourcemaps.write('.'))
             .pipe(gulp.dest(paths.dest.css))
             .pipe(plug.size({ showFiles : true }));
});

gulp.task('clean', function(cb) {
  del([paths.dest.css, paths.source.root + '/app*'], function(err, paths) {
    var msg = 'Deleted files/folders:\n' + paths.join('\n');
    _.log(_.colors.yellow(msg));

    cb();
  });
});

gulp.task('build', function(cb) {
  runSequence('clean',
              ['css', 'js'],
              cb);
});

gulp.task('nodemon', function(cb) {
  var called = false;
  return nodemon({ script : pkg.main, ext : 'js vash ejs jade', ignore : ['./client/**', './logs/**'] }).on('start', function() {
    if (!called) {
      _.log(_.colors.green('Starting nodemon..'));
      called = true;
      cb();
    }
  });
});

gulp.task('browser-sync', ['nodemon'], function() {
  browserSync({
    proxy : 'http://localhost:5000'
  });
});

function reportChange(event) {
  _.log('File ' + _.colors.green(event.path) + ' was ' + _.colors.yellow(event.type) + ', running tasks...');
}

gulp.task('watch', ['browser-sync'], function() {
  gulp.watch(paths.source.sassMain, ['sass', reload({ stream : true })]).on('change', reportChange);
  gulp.watch(paths.source.js, ['', reload]).on('change', reportChange);
});

gulp.task('default', function(cb) {
  runSequence('build', 'watch', cb);
});

gulp.task('serveprod', function() {
  connect.server({
    root: paths.source.root,
    port: process.env.PORT || 5000, // localhost:5000
    livereload: false
  });
});

gulp.task('heroku:production', function(){
  // runSequence('clean')
  connect.server({
    root: paths.source.root,
    port: process.env.PORT || 5000, // localhost:5000
    livereload: false
  });
})<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing fr<commit_msg>Grammar fix<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing fro<|endoftext|>


<commit_before>const Command = require("../base/Command");

class Need extends Command {
    constructor(client) {
        super(client, {
            name: "need",
            category: "SWGoH",
            enabled: true,
            permissions: ["EMBED_LINKS"]
        });
    }

    async run(client, message, args, options) { // eslint-disable-line no-unused-vars
        const shardsLeftAtStar = {
            0: 330,
            1: 320,
            2: 305,
            3: 280,
            4: 250,
            5: 185,
            6: 100
        };
        const {searchChar, allyCode, err} = await super.getUserAndChar(message, args, true);   // eslint-disable-line no-unused-vars
        if (err && !searchChar) {
            return super.error(message, "You need to specify a location or faction.", {usage: "need <faction|location>"});
        }
        if (!allyCode) {
            return super.error(message, message.language.get("COMMAND_NEED_MISSING_USER"));
        }

        const cooldown = client.getPlayerCooldown(message.author.id);
        const player = await client.swgohAPI.player(allyCode, null, cooldown);
        if (!player) {
            // Could not find the player, possible api issue?
            return super.error(message, "I couldn't find that player, please make sure you've got the corect ally code.");
        }

        let outChars = [];
        let outShips = [];

        let search;
        const staticMatches = {
            cantina: "Cantina Shipments",
            guild:   "Guild Shop",
            fleet:   "Fleet Shipments"
        };
        if (staticMatches[searchChar.toLowerCase()]) {
            search = staticMatches[searchChar.toLowerCase()];
        }

        let units = [];
        if (search) {
            units = client.charLocs.filter(c => c.locations.filter(l => l.type === search).length);
            units = units.concat(client.shipLocs.filter(s => s.locations.filter(l => l.type === search).length));
        } else {
            units = await getUnits(searchChar);
        }

        if (!units.length) {
            // Can't find a match, so let them know
            return super.error(message, message.language.get("COMMAND_NEED_MISSING_SEARCH", searchChar));
        }

        const totalShards = units.length * shardsLeftAtStar[0];
        let shardsLeft = 0;
        for (const unit of units) {
            // Go through the found characters and check them against the player's roster
            let u = player.roster.find(c => c.defId === unit.baseId);
            if (!u) continue;
            if (u.rarity === 7) continue;
            shardsLeft += shardsLeftAtStar[u.rarity];
            u = await client.swgohAPI.langChar(u, message.guildSettings.swgohLanguage);
            if (client.characters.find(c => c.uniqueName === unit.baseId)) {
                // It's a character
                outChars.push({
                    rarity: u.rarity,
                    name: u.nameKey
                });
            } else if (client.ships.find(s => s.uniqueName === unit.baseId)) {
                // It's a ship
                outShips.push({
                    rarity: u.rarity,
                    name: u.nameKey
                });
            } else {
                // It's neither and shouldn't be there
                continue;
            }
        }
        outChars = outChars.sort((a,b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);
        outShips = outShips.sort((a,b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);

        const fields = [];
        if (outChars.length) {
            outChars = outChars.map(c => `\`${c.rarity}*\` ${c.name}`);
            const msgArr = client.msgArray(outChars, "\n", 1000);
            msgArr.forEach((m, ix) => {
                let end = "";
                if (msgArr.length > 1) end = `(${ix+1})`;
                fields.push({
                    name: message.language.get("COMMAND_NEED_CHAR_HEADER") + end,
                    value: m
                });
            });
        }
        // else {
        //     fields.push({
        //         name: message.language.get("COMMAND_NEED_CHAR_HEADER"),
        //         value: message.language.get("COMMAND_NEED_ALL_CHAR")
        //     });
        // }
        if (outShips.length) {
            outShips = outShips.map(s => `\`${s.rarity}*\` ${s.name}`);
            const msgArr = client.msgArray(outShips, "\n", 1000);
            msgArr.forEach((m, ix) => {
                let end = "";
                if (msgArr.length > 1) end = `(${ix+1})`;
                fields.push({
                    name: message.language.get("COMMAND_NEED_SHIP_HEADER") + end,
                    value: m
                });
            });
        }
        // else {
        //     fields.push({
        //         name: message.language.get("COMMAND_NEED_SHIP_HEADER"),
        //         value: message.language.get("COMMAND_NEED_ALL_SHIP")
        //     });
        // }

        let desc = "";
        if (shardsLeft === 0) {
            desc = message.language.get("COMMAND_NEED_COMPLETE");
        } else {
            desc = message.language.get("COMMAND_NEED_PARTIAL", (((totalShards - shardsLeft)/ totalShards) * 100).toFixed(1));
        }

        fields.push({
            name: "-",
            value: "**Check out `" + message.guildSettings.prefix + "help need` for other searches**"
        });

        return message.channel.send({embed: {
            author: {
                name: message.language.get("COMMAND_NEED_HEADER", player.name, searchChar.toProperCase())
            },
            description: desc,
            fields: fields
        }});

        async function getUnits(searchName) {
            let search = searchName.replace(/[^\w\s]/g, "").replace(/s$/, "");  // Take out all alphanumeric characters and any s off the end
            if (search.toLowerCase() === "galactic republic") search = "affiliation_republic";
            if (search.toLowerCase() === "galactic war") search = "gw";
            if (search.includes("cantina") && search.includes("battle")) {
                search = search.replace(/(battles|battle)/gi, "");
            // } else if (search.includes("fleet") && (search.includes("store") || search.includes("shop"))) {
            //     search = search.replace(/(store|shop)/gi, "shipment");
            } else {
                search = search
                    .replace(/(store|shop|shipment)/g, "shop|store|shipment")
                    .replace(/(battles|battle)/gi, "hard")
                    .replace(/light/gi, "(l)")
                    .replace(/dark/gi, "(d)")
                    .replace("node", "mode");
            }

            const searchReg = search.split(" ").map(s => `(?=.*${s.replace(/(\(|\))/g, "\\$1")})`).join(".*");
            const query = new RegExp(`.*${searchReg}.*`, "gi");

            let units = client.charLocs.filter(c => c.locations.filter(l => l.type.match(query)).length);
            units = units.concat(client.shipLocs.filter(s => s.locations.filter(l => l.type.match(query)).length));

            for (const c of units) {
                // The char/ ship locations don't have the baseId so need to get those
                let char = client.characters.find(char => char.name.replace(/[^\w]/g, "").toLowerCase() === c.name.replace(/[^\w]/g, "").toLowerCase());
                if (!char) {
                    char = client.ships.find(char => char.name.replace(/[^\w]/g, "").toLowerCase() === c.name.replace(/[^\w]/g, "").toLowerCase());
                }
                if (!char) {
                    continue;
                }
                c.baseId = char.uniqueName;
            }

            if (!units.length) {
                // Must not be in a shop or node, try checking factions
                units = await client.cache.get("swapi", "units",
                    {categoryIdList: query, language: message.guildSettings.swgohLanguage.toLowerCase()},
                    {_id: 0, baseId: 1, nameKey: 1}
                );
            }
            return units;
        }
    }
}

module.exports = Need;
<commit_msg>Bit of cleanup<commit_after>const Command = require("../base/Command");

class Need extends Command {
    constructor(client) {
        super(client, {
            name: "need",
            category: "SWGoH",
            enabled: true,
            permissions: ["EMBED_LINKS"]
        });
    }

    async run(client, message, args, options) { // eslint-disable-line no-unused-vars
        const shardsLeftAtStar = {
            0: 330,
            1: 320,
            2: 305,
            3: 280,
            4: 250,
            5: 185,
            6: 100
        };
        const {searchChar, allyCode, err} = await super.getUserAndChar(message, args, true);   // eslint-disable-line no-unused-vars
        if (err && !searchChar) {
            return super.error(message, "You need to specify a location or faction.", {usage: "need <faction|location>"});
        }
        if (!allyCode) {
            return super.error(message, message.language.get("COMMAND_NEED_MISSING_USER"));
        }

        const cooldown = client.getPlayerCooldown(message.author.id);
        const player = await client.swgohAPI.player(allyCode, null, cooldown);
        if (!player) {
            // Could not find the player, possible api issue?
            return super.error(message, "I couldn't find that player, please make sure you've got the corect ally code.");
        }

        let outChars = [];
        let outShips = [];

        let search;
        const staticMatches = {
            cantina: "Cantina Shipments",
            guild:   "Guild Shop",
            fleet:   "Fleet Shipments"
        };
        if (staticMatches[searchChar.toLowerCase()]) {
            search = staticMatches[searchChar.toLowerCase()];
        }

        let units = [];
        if (search) {
            units = client.charLocs.filter(c => c.locations.filter(l => l.type === search).length);
            units = units.concat(client.shipLocs.filter(s => s.locations.filter(l => l.type === search).length));
        } else {
            units = await getUnits(searchChar);
        }

        if (!units.length) {
            // Can't find a match, so let them know
            return super.error(message, message.language.get("COMMAND_NEED_MISSING_SEARCH", searchChar));
        }

        const totalShards = units.length * shardsLeftAtStar[0];
        let shardsLeft = 0;
        for (const unit of units) {
            // Go through the found characters and check them against the player's roster
            let u = player.roster.find(c => c.defId === unit.baseId);
            if (!u) continue;
            if (u.rarity === 7) continue;
            shardsLeft += shardsLeftAtStar[u.rarity];
            u = await client.swgohAPI.langChar(u, message.guildSettings.swgohLanguage);
            if (client.characters.find(c => c.uniqueName === unit.baseId)) {
                // It's a character
                outChars.push({
                    rarity: u.rarity,
                    name: u.nameKey
                });
            } else if (client.ships.find(s => s.uniqueName === unit.baseId)) {
                // It's a ship
                outShips.push({
                    rarity: u.rarity,
                    name: u.nameKey
                });
            } else {
                // It's neither and shouldn't be there
                continue;
            }
        }
        outChars = outChars.sort((a,b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);
        outShips = outShips.sort((a,b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);

        const fields = [];
        if (outChars.length) {
            outChars = outChars.map(c => `\`${c.rarity}*\` ${c.name}`);
            const msgArr = client.msgArray(outChars, "\n", 1000);
            msgArr.forEach((m, ix) => {
                let end = "";
                if (msgArr.length > 1) end = `(${ix+1})`;
                fields.push({
                    name: message.language.get("COMMAND_NEED_CHAR_HEADER") + end,
                    value: m
                });
            });
        }
        if (outShips.length) {
            outShips = outShips.map(s => `\`${s.rarity}*\` ${s.name}`);
            const msgArr = client.msgArray(outShips, "\n", 1000);
            msgArr.forEach((m, ix) => {
                let end = "";
                if (msgArr.length > 1) end = `(${ix+1})`;
                fields.push({
                    name: message.language.get("COMMAND_NEED_SHIP_HEADER") + end,
                    value: m
                });
            });
        }

        let desc = "";
        if (shardsLeft === 0) {
            desc = message.language.get("COMMAND_NEED_COMPLETE");
        } else {
            desc = message.language.get("COMMAND_NEED_PARTIAL", (((totalShards - shardsLeft)/ totalShards) * 100).toFixed(1));
        }

        fields.push({
            name: "-",
            value: "**Check out `" + message.guildSettings.prefix + "help need` for other searches**"
        });

        return message.channel.send({embed: {
            author: {
                name: message.language.get("COMMAND_NEED_HEADER", player.name, searchChar.toProperCase())
            },
            description: desc,
            fields: fields
        }});

        async function getUnits(searchName) {
            let search = searchName.replace(/[^\w\s]/g, "").replace(/s$/, "");  // Take out all alphanumeric characters and any s off the end
            if (search.toLowerCase() === "galactic republic") search = "affiliation_republic";
            if (search.toLowerCase() === "galactic war") search = "gw";
            if (search.includes("cantina") && search.includes("battle")) {
                search = search.replace(/(battles|battle)/gi, "");
            // } else if (search.includes("fleet") && (search.includes("store") || search.includes("shop"))) {
            //     search = search.replace(/(store|shop)/gi, "shipment");
            } else {
                search = search
                    .replace(/(store|shop|shipment)/g, "shop|store|shipment")
                    .replace(/(battles|battle)/gi, "hard")
                    .replace(/light/gi, "(l)")
                    .replace(/dark/gi, "(d)")
                    .replace("node", "mode");
            }

            const searchReg = search.split(" ").map(s => `(?=.*${s.replace(/(\(|\))/g, "\\$1")})`).join(".*");
            const query = new RegExp(`.*${searchReg}.*`, "gi");

            let units = client.charLocs.filter(c => c.locations.filter(l => l.type.match(query)).length);
            units = units.concat(client.shipLocs.filter(s => s.locations.filter(l => l.type.match(query)).length));

            for (const c of units) {
                // The char/ ship locations don't have the baseId so need to get those
                let char = client.characters.find(char => char.name.replace(/[^\w]/g, "").toLowerCase() === c.name.replace(/[^\w]/g, "").toLowerCase());
                if (!char) {
                    char = client.ships.find(char => char.name.replace(/[^\w]/g, "").toLowerCase() === c.name.replace(/[^\w]/g, "").toLowerCase());
                }
                if (!char) {
                    continue;
                }
                c.baseId = char.uniqueName;
            }

            if (!units.length) {
                // Must not be in a shop or node, try checking factions
                units = await client.cache.get("swapi", "units",
                    {categoryIdList: query, language: message.guildSettings.swgohLanguage.toLowerCase()},
                    {_id: 0, baseId: 1, nameKey: 1}
                );
            }
            return units;
        }
    }
}

module.exports = Need;
<|endoftext|>


<commit_before>/**
 * Builds document-embedded map using c2corg maps API.
 */

Ext.namespace("c2corg");

c2corg.embeddedMap = (function() {

    if (!objectsToShow) return;

    var wkt_parser = new OpenLayers.Format.WKT();
    var features = [];
    for (var i = 0, len = objectsToShow.length; i < len; i++) {
        var obj = objectsToShow[i];
        // TODO: use simplified WKT?
        var f = wkt_parser.read(obj.wkt);
        f.fid = obj.id;
        f.attributes = {type: obj.type};
        if (obj.type == "routes" || obj.type == "outings" || obj.type == "areas" || obj.type == "maps") {
            f.style = {
                strokeColor: "yellow",
                strokeWidth: 1,
                fillColor: "yellow",
                fillOpacity: 0.1
            };
        } else {
            f.style = {
                pointRadius: 10,
                externalGraphic: '/static/images/modules/' + obj.type + '_mini.png'
                // FIXME: ${type} syntax seems not to work
            };
        }
        features.push(f);
    }

    var api = new c2corg.API({lang: mapLang}); // mapLang is defined in HTML document
    api.createMap();

    var drawingLayer = api.getDrawingLayer();
    drawingLayer.addFeatures(features);

    if (features.length == 1 && features[0].geometry instanceof OpenLayers.Geometry.Point) {
        var center = features[0].geometry;
        api.map.setCenter(new OpenLayers.LonLat(center.x, center.y), 12);
    } else {
        api.map.zoomToExtent(drawingLayer.getDataExtent());
        var extent = api.map.getExtent();
    }

    var initialCenter = api.map.getCenter();
    var initialZoom = api.map.getZoom();

    var bbar = api.createBbar();

    var addPermalinkButton = function() {
        var permalinkDiv = document.createElement("div");
        permalinkDiv.id = 'permalink' + api.apiId;
        Ext.getBody().appendChild(permalinkDiv);
        api.addPermalinkControl();
        bbar.add(new Ext.Action({
            text: OpenLayers.i18n('Permalink.openlink'),
            handler: function() {
                window.open(Ext.get('permalink' + api.apiId).dom.value);
            }
        }));
    };

    var addResetButton = function() {
        bbar.add(new Ext.Action({
            text: OpenLayers.i18n('Reset'),
            handler: function() {
                var center = initialCenter.clone();
                api.map.setCenter(center.transform(api.epsg900913, api.map.getProjectionObject()),
                                  initialZoom); // FIXME: zoom changes depending on base layer resolutions nb
            }
        }));
    };

    var mappanel = Ext.apply(api.createMapPanel(), {
        id: 'mappanel',
        margins: '0 0 0 0',
        region: 'center',
        border: false,
        bbar: bbar
    });

    var layertree = Ext.apply(api.createLayerTree(), {
        region: 'west',
        width: 250,
        border: false,
        collapsible: true,
        collapseMode: 'mini',
        split: true
    });

    return {
        init: function() {
            // hide loading message
            Ext.removeNode(Ext.getDom('mapLoading'));

            new Ext.Panel({
                applyTo: 'map',
                layout: 'border',
                border: false,
                cls: 'embeddedMap',
                items: [ mappanel, layertree ]
            });

            // FIXME: done here else the zoom level is incorrect (changed when creating panel?)
            if (extent) {
                api.map.zoomToExtent(extent);
                initialZoom = api.map.getZoom();
            }

            addResetButton();
            addPermalinkButton();
        }
    };
})();

Ext.onReady(c2corg.embeddedMap.init);
<commit_msg>updated label of "open map" link in embedded maps<commit_after>/**
 * Builds document-embedded map using c2corg maps API.
 */

Ext.namespace("c2corg");

c2corg.embeddedMap = (function() {

    if (!objectsToShow) return;

    var wkt_parser = new OpenLayers.Format.WKT();
    var features = [];
    for (var i = 0, len = objectsToShow.length; i < len; i++) {
        var obj = objectsToShow[i];
        // TODO: use simplified WKT?
        var f = wkt_parser.read(obj.wkt);
        f.fid = obj.id;
        f.attributes = {type: obj.type};
        if (obj.type == "routes" || obj.type == "outings" || obj.type == "areas" || obj.type == "maps") {
            f.style = {
                strokeColor: "yellow",
                strokeWidth: 1,
                fillColor: "yellow",
                fillOpacity: 0.1
            };
        } else {
            f.style = {
                pointRadius: 10,
                externalGraphic: '/static/images/modules/' + obj.type + '_mini.png'
                // FIXME: ${type} syntax seems not to work
            };
        }
        features.push(f);
    }

    var api = new c2corg.API({lang: mapLang}); // mapLang is defined in HTML document
    api.createMap();

    var drawingLayer = api.getDrawingLayer();
    drawingLayer.addFeatures(features);

    if (features.length == 1 && features[0].geometry instanceof OpenLayers.Geometry.Point) {
        var center = features[0].geometry;
        api.map.setCenter(new OpenLayers.LonLat(center.x, center.y), 12);
    } else {
        api.map.zoomToExtent(drawingLayer.getDataExtent());
        var extent = api.map.getExtent();
    }

    var initialCenter = api.map.getCenter();
    var initialZoom = api.map.getZoom();

    var bbar = api.createBbar();

    var addPermalinkButton = function() {
        var permalinkDiv = document.createElement("div");
        permalinkDiv.id = 'permalink' + api.apiId;
        Ext.getBody().appendChild(permalinkDiv);
        api.addPermalinkControl();
        bbar.add(new Ext.Action({
            text: OpenLayers.i18n('Expand map'),
            handler: function() {
                window.open(Ext.get('permalink' + api.apiId).dom.value);
            }
        }));
    };

    var addResetButton = function() {
        bbar.add(new Ext.Action({
            text: OpenLayers.i18n('Reset'),
            handler: function() {
                var center = initialCenter.clone();
                api.map.setCenter(center.transform(api.epsg900913, api.map.getProjectionObject()),
                                  initialZoom); // FIXME: zoom changes depending on base layer resolutions nb
            }
        }));
    };

    var mappanel = Ext.apply(api.createMapPanel(), {
        id: 'mappanel',
        margins: '0 0 0 0',
        region: 'center',
        border: false,
        bbar: bbar
    });

    var layertree = Ext.apply(api.createLayerTree(), {
        region: 'west',
        width: 250,
        border: false,
        collapsible: true,
        collapseMode: 'mini',
        split: true
    });

    return {
        init: function() {
            // hide loading message
            Ext.removeNode(Ext.getDom('mapLoading'));

            new Ext.Panel({
                applyTo: 'map',
                layout: 'border',
                border: false,
                cls: 'embeddedMap',
                items: [ mappanel, layertree ]
            });

            // FIXME: done here else the zoom level is incorrect (changed when creating panel?)
            if (extent) {
                api.map.zoomToExtent(extent);
                initialZoom = api.map.getZoom();
            }

            addResetButton();
            addPermalinkButton();
        }
    };
})();

Ext.onReady(c2corg.embeddedMap.init);
<|endoftext|>


<commit_before>// this is just a stub for a function you need to implement
//
function getStats(txt) {
    var numberChars = txt.length;
    var removePunc = txt.replace(/[^A-Za-z" "0-9\n]/g, " ");
    removePunc = removePunc.replace(/[\n\"]/g, " ");
    removePunc = removePunc.replace(/\s\s+/g, ' ');
    removePunc = removePunc.trim();
    var numberWords = 0;
    if (removePunc.split(" ")[0] === "")
      numberWords = 0;
    else {
      numberWords = removePunc.split(" ").length;
    }
    var numberLines = 0;
    if (txt.split("\n")[0] === "")
      numberLines = 0;
    else {
        numberLines = txt.split("\n").length;
    }

    var tempLines = txt.split("\n");
    var emptyLines = 0;
    var maxLine = 0;
    for (var i = 0; i < numberLines; i++) {
        if (tempLines[i].trim().length === 0) {
            emptyLines++;
        }
        if (tempLines[i].length > maxLine)
            maxLine = tempLines[i].length;
    }
    var tempWordList = removePunc.split(" ");
    var totalWordLength = 0;
    var listLongest = [];
    var longestWordSize = 0;
    var longestWords = {};
    /*
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "") {
            if (!(lowercaseWord in longestWords))
                longestWords[lowercaseWord] = lowercaseWord.length;
        }
    }
    */
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "" && !(listLongest.includes(lowercaseWord))) {
            listLongest.push(lowercaseWord);
        }
    }
    var sortLongestWords = [];
    listLongest.sort();
    for (var i = 0; i < (listLongest.length > 10 ? 10 : listLongest.length); i++) {
        var longestWord = "";
        for (var j = 0; j < listLongest.length; j++) {
            if (listLongest[j].length > longestWord.length && !(sortLongestWords.includes(listLongest[j])))
                longestWord = listLongest[j];

        }
        sortLongestWords.push(longestWord);
    }
    for (var i = 0; i < tempWordList.length; i++)
    {
      totalWordLength += tempWordList[i].length;
    }
    /*
    for (var word in longestWords)
        sortLongestWords.push([word, longestWords[word]]);
    sortLongestWords.sort(function(a, b) {
        return b[1] - a[1];
    });
    */

    /*
    var finalLongestWords = [];
    for (var i = 0; i < (sortLongestWords.length > 10 ? 10 : sortLongestWords.length); i++) {
        var formattingString = sortLongestWords[i][0];
        finalLongestWords[i] = formattingString;
    }
    */
    var removeDupes = Array.from(new Set(listLongest));
    listLongest.sort();
    var avWordLen = totalWordLength / numberWords;
    if (numberWords === 0)
      avWordLen = 0;
    var palindromeTestWords = removePunc.split(" ");
    var listOfPalindromes = [];

    for (var i = 0; i < palindromeTestWords.length; i++) {
        var isPalin = false;
        if (palindromeTestWords[i].length > 2)
            isPalin = isPalindrome(palindromeTestWords[i]);
        if (isPalin)
            listOfPalindromes.push(palindromeTestWords[i].toLowerCase());
    }

    var frequentWordsCalc = {};
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "") {
            if (lowercaseWord in frequentWordsCalc)
                frequentWordsCalc[lowercaseWord] += 1;
            else {
                frequentWordsCalc[lowercaseWord] = 1;
            }
        }

    }

    var sortFreqWords = [];
    for (var word in frequentWordsCalc)
        sortFreqWords.push([word, frequentWordsCalc[word]]);
    /*
    sortFreqWords.sort(function(a, b) {
        return b[0] - a[0];
    });
*/
    sortFreqWords.sort();
    var finalFreqWords = [];
    var alreadyUsedWords = [];
    for (var i = 0; i < (sortFreqWords.length > 10 ? 10 : sortFreqWords.length); i++) {
        maxLength = 0;
        var formattingString = "";
        var usedWord = "";
        for (var j = 0; j < sortFreqWords.length; j++) {
            if (sortFreqWords[j][1] > maxLength && !(alreadyUsedWords.includes(sortFreqWords[j][0]))) {
                formattingString = sortFreqWords[j][0] + "(" + sortFreqWords[j][1] + ")";
                maxLength = sortFreqWords[j][1];
                usedWord = sortFreqWords[j][0];
            }
        }
        alreadyUsedWords.push(usedWord);
        finalFreqWords.push(formattingString);
    }
    return {
        nChars: numberChars,
        nWords: numberWords,
        nLines: numberLines,
        averageWordLength: avWordLen,
        nNonEmptyLines: numberLines - emptyLines,
        maxLineLength: maxLine,
        palindromes: listOfPalindromes,
        longestWords: sortLongestWords,
        mostFrequentWords: finalFreqWords
    };
}

function isPalindrome(tstr) {
    tstr = tstr.toLowerCase();
    for (var i = 0, j = tstr.length - 1; i <= j; i++, j--) {
        if (tstr[i] != tstr[j])
            return false;
    }
    return true;
}
<commit_msg>changed js file<commit_after>// this is just a stub for a function you need to implement
//
function getStats(txt) {
    var numberChars = txt.length;
    var removePunc = txt.replace(/[^A-Za-z" "0-9\n]/g, " ");
    removePunc = removePunc.replace(/[\n\"]/g, " ");
    removePunc = removePunc.replace(/\s\s+/g, ' ');
    removePunc = removePunc.trim();
    var numberWords = 0;
    if (removePunc.split(" ")[0] === "")
      numberWords = 0;
    else {
      numberWords = removePunc.split(" ").length;
    }
    var numberLines = 0;
    if (txt.split("\n")[0] === "")
      numberLines = 0;
    else {
        numberLines = txt.split("\n").length;
    }

    var tempLines = txt.split("\n");
    var emptyLines = 0;
    var maxLine = 0;
    for (var i = 0; i < numberLines; i++) {
        if (tempLines[i].trim().length === 0) {
            emptyLines++;
        }
        if (tempLines[i].length > maxLine)
            maxLine = tempLines[i].length;
    }
    var tempWordList = removePunc.split(" ");
    var totalWordLength = 0;
    var listLongest = [];
    var longestWordSize = 0;
    var longestWords = {};
    /*
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "") {
            if (!(lowercaseWord in longestWords))
                longestWords[lowercaseWord] = lowercaseWord.length;
        }
    }
    */
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "" && !(listLongest.includes(lowercaseWord))) {
            listLongest.push(lowercaseWord);
        }
    }
    var sortLongestWords = [];
    listLongest.sort();
    for (var i = 0; i < (listLongest.length > 10 ? 10 : listLongest.length); i++) {
        var longestWord = "";
        for (var j = 0; j < listLongest.length; j++) {
            if (listLongest[j].length > longestWord.length && !(sortLongestWords.includes(listLongest[j])))
                longestWord = listLongest[j];

        }
        sortLongestWords.push(longestWord);
    }
    for (var i = 0; i < tempWordList.length; i++)
    {
      totalWordLength += tempWordList[i].length;
    }
    /*
    for (var word in longestWords)
        sortLongestWords.push([word, longestWords[word]]);
    sortLongestWords.sort(function(a, b) {
        return b[1] - a[1];
    });
    */

    /*
    var finalLongestWords = [];
    for (var i = 0; i < (sortLongestWords.length > 10 ? 10 : sortLongestWords.length); i++) {
        var formattingString = sortLongestWords[i][0];
        finalLongestWords[i] = formattingString;
    }
    */
    var removeDupes = Array.from(new Set(listLongest));
    listLongest.sort();
    var avWordLen = totalWordLength / numberWords;
    if (numberWords === 0)
      avWordLen = 0;
    var palindromeTestWords = removePunc.split(" ");
    var listOfPalindromes = [];

    for (var i = 0; i < palindromeTestWords.length; i++) {
        var isPalin = false;
        if (palindromeTestWords[i].length > 2)
            isPalin = isPalindrome(palindromeTestWords[i]);
        if (isPalin)
            listOfPalindromes.push(palindromeTestWords[i].toLowerCase());
    }

    var frequentWordsCalc = {};
    for (var i = 0; i < tempWordList.length; i++) {
        lowercaseWord = tempWordList[i].toLowerCase();
        lowercaseWord = lowercaseWord.trim();
        if (lowercaseWord != "") {
            if (lowercaseWord in frequentWordsCalc)
                frequentWordsCalc[lowercaseWord] += 1;
            else {
                frequentWordsCalc[lowercaseWord] = 1;
            }
        }

    }

    var sortFreqWords = [];
    for (var word in frequentWordsCalc)
        sortFreqWords.push([word, frequentWordsCalc[word]]);
    /*
    sortFreqWords.sort(function(a, b) {
        return b[0] - a[0];
    });
*/
    sortFreqWords.sort();
    var finalFreqWords = [];
    var alreadyUsedWords = [];
    for (var i = 0; i < (sortFreqWords.length > 10 ? 10 : sortFreqWords.length); i++) {
        maxLength = 0;
        var formattingString = "";
        var usedWord = "";
        for (var j = 0; j < sortFreqWords.length; j++) {
            if (sortFreqWords[j][1] > maxLength && !(alreadyUsedWords.includes(sortFreqWords[j][0]))) {
                formattingString = sortFreqWords[j][0] + "(" + sortFreqWords[j][1] + ")";
                maxLength = sortFreqWords[j][1];
                usedWord = sortFreqWords[j][0];
            }
        }
        alreadyUsedWords.push(usedWord);
        finalFreqWords.push(formattingString);
    }
    return {
        nChars: numberChars,
        nWords: numberWords,
        nLines: numberLines,
        nNonEmptyLines: numberLines - emptyLines,
        maxLineLength: maxLine,
        averageWordLength: avWordLen,
        palindromes: listOfPalindromes,
        longestWords: sortLongestWords,
        mostFrequentWords: finalFreqWords
    };
}

function isPalindrome(tstr) {
    tstr = tstr.toLowerCase();
    for (var i = 0, j = tstr.length - 1; i <= j; i++, j--) {
        if (tstr[i] != tstr[j])
            return false;
    }
    return true;
}
<|endoftext|>


<commit_before>'use strict';

describe('imagesCtrl', function() {
    var $rootScope, $controller, imagesCtrl, images, vm, $q, mockImageArray, $log, sampleJSON;

    sampleJSON = {contentType: "text/json",
        status: "success",

        photos: {
            photo: [
                {
                    farm: 6,
                    id: "23780914905",
                    isfamily: 0,
                    isfriend: 0,
                    ispublic: 1,
                    owner: "138698049@N03",
                    secret: "0eb2a77a55",
                    server: "5764",
                    title: ""
                },
                {
                    farm: 1,
                    id: "23698470321",
                    isfamily: 0,
                    isfriend: 0,
                    ispublic: 1,
                    owner: "138698049@N03",
                    secret: "1d4dc255d0",
                    server: "693",
                    title: ""
                }
            ]
        }

    };
    mockImageArray = ['https://farm6.staticflickr.com/5764/23780914905_0eb2a77a55_z.jpg', 'https://farm1.staticflickr.com/693/23698470321_1d4dc255d0_z.jpg'];

    beforeEach(module('flickrPOC'));

    describe('imagesCtrl', function(){

        describe('Sucessful call to api', function() {
            beforeEach(module(function ($provide) {
                $provide.service('images', function ($q) {
                    this.loadPics = sinon.stub().returns($q.resolve(sampleJSON));
                    this.createImagesArray = sinon.stub().returns($q.resolve(mockImageArray));
                });

            }));

            beforeEach(inject(function (_$rootScope_, _$controller_, _images_, _$q_, _$log_) {
                $rootScope = _$rootScope_.$new();
                $controller = _$controller_;
                images = _images_;
                $q = _$q_;
                $log = _$log_;
                vm = $controller('imagesCtrl');

                $rootScope.$apply();

            }));

            describe('return flickr images from object from http call', function(){
                var imageArray;

                beforeEach(function(){
                    imageArray = vm.images.$$state.value;
                });

               it('should return an array of images', function(){
                   expect(angular.isArray(imageArray)).to.equal(true);
               });

               it('Should have all strings', function(){
                   angular.forEach(imageArray, function(value){
                       expect(angular.isString(value)).to.equal(true);
                   });
               });

               it('Each strings must have an http address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value.substr(0, 8)).to.equal('https://');
                   });
               });

               it('Each strings must have an flickr address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value).to.contain('.staticflickr.com');
                   });
               });

               it('Each strings must have an flickr address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value.substr(-4, 4)).to.match(/^\.|\.jpg$|\.gif$|.png$/);
                   });
               });

            });

        });

        describe('Error from to api', function() {

            beforeEach(module(function($provide){
                $provide.service('images', function($q, $log){
                    this.loadPics = sinon.stub().returns($q.reject($log));
                });

            }));

            beforeEach(inject(function (_$rootScope_, _$controller_, _images_, _$q_, _$log_) {
                $rootScope = _$rootScope_.$new();
                $controller = _$controller_;
                images = _images_;
                $q = _$q_;
                $log = _$log_;
                vm = $controller('imagesCtrl');

                $rootScope.$apply();
            }));

            it('Should log error message ', function(){
                var errorMsg = 'Error loading images ';

                expect($log.error.logs[0]).to.include(errorMsg);
            });
        });
    });
});
<commit_msg>updating code for mock response from error call<commit_after>'use strict';

describe('imagesCtrl', function() {
    var $rootScope, $controller, imagesCtrl, images, vm, $q, mockImageArray, $log, sampleJSON;

    sampleJSON = {contentType: "text/json",
        status: "success",

        photos: {
            photo: [
                {
                    farm: 6,
                    id: "23780914905",
                    isfamily: 0,
                    isfriend: 0,
                    ispublic: 1,
                    owner: "138698049@N03",
                    secret: "0eb2a77a55",
                    server: "5764",
                    title: ""
                },
                {
                    farm: 1,
                    id: "23698470321",
                    isfamily: 0,
                    isfriend: 0,
                    ispublic: 1,
                    owner: "138698049@N03",
                    secret: "1d4dc255d0",
                    server: "693",
                    title: ""
                }
            ]
        }

    };
    mockImageArray = ['https://farm6.staticflickr.com/5764/23780914905_0eb2a77a55_z.jpg', 'https://farm1.staticflickr.com/693/23698470321_1d4dc255d0_z.jpg'];

    beforeEach(module('flickrPOC'));

    describe('imagesCtrl', function(){

        describe('Sucessful call to api', function() {
            beforeEach(module(function ($provide) {
                $provide.service('images', function ($q) {
                    this.loadPics = sinon.stub().returns($q.resolve(sampleJSON));
                    this.createImagesArray = sinon.stub().returns($q.resolve(mockImageArray));
                });

            }));

            beforeEach(inject(function (_$rootScope_, _$controller_, _images_, _$q_, _$log_) {
                $rootScope = _$rootScope_.$new();
                $controller = _$controller_;
                images = _images_;
                $q = _$q_;
                $log = _$log_;
                vm = $controller('imagesCtrl');

                $rootScope.$apply();

            }));

            describe('return flickr images from object from http call', function(){
                var imageArray;

                beforeEach(function(){
                    imageArray = vm.images.$$state.value;
                });

               it('should return an array of images', function(){
                   expect(angular.isArray(imageArray)).to.equal(true);
               });

               it('Should have all strings', function(){
                   angular.forEach(imageArray, function(value){
                       expect(angular.isString(value)).to.equal(true);
                   });
               });

               it('Each strings must have an http address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value.substr(0, 8)).to.equal('https://');
                   });
               });

               it('Each strings must have an flickr address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value).to.contain('.staticflickr.com');
                   });
               });

               it('Each strings must have an flickr address', function(){
                   angular.forEach(imageArray, function(value){
                       expect(value.substr(-4, 4)).to.match(/^\.|\.jpg$|\.gif$|.png$/);
                   });
               });

            });

        });

        describe('Error from to api', function() {

            beforeEach(module(function($provide){
                $provide.service('images', function($q){
                    this.loadPics = sinon.stub().returns($q.reject({}));
                });

            }));

            beforeEach(inject(function (_$rootScope_, _$controller_, _images_, _$q_, _$log_) {
                $rootScope = _$rootScope_.$new();
                $controller = _$controller_;
                images = _images_;
                $q = _$q_;
                $log = _$log_;
                vm = $controller('imagesCtrl');

                $rootScope.$apply();
            }));

            it('Should log error message ', function(){
                var errorMsg = 'Error loading images ';

                expect($log.error.logs[0]).to.include(errorMsg);
            });
        });
    });
});
<|endoftext|>


<commit_before>var gulp = require("gulp");
// прописывает пути bower
var wiredep = require('wiredep').stream;
// сборка dist
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
// для удаления файлов
var clean = require('gulp-clean');
// создание локального сервера
var browserSync = require('browser-sync');
// позволяет удалять в автомате не используемые стили
var uncss = require('gulp-uncss');
// объединение стилей
var concatCss = require('gulp-concat-css');
// позволяет добавлять префиксы в css для поддержки в разных браузерах
var autoprefixer = require('gulp-autoprefixer');
// переименовывание
var rename = require("gulp-rename");
// уведомления
var notify = require("gulp-notify");
// Minify CSS
//var csso = require('gulp-csso');
//Shorthand - обединяет селекторы
var shorthand = require('gulp-shorthand');

// Сервер
gulp.task('server', function () {
    browserSync({
        port: 9000,
        server: {
            baseDir: 'app'
        }
    });
});

// Clean
gulp.task('clean', function () {
    return gulp.src('dist', {read: false})
        .pipe(clean())
});

// Build
gulp.task('build', ['clean'], function () {
    var assets = useref.assets();

    return gulp.src('app/*.html')
        .pipe(assets)
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.css', minifyCss()))
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(notify("Build end!"))
        .pipe(gulp.dest('dist'))
});

// Bower
gulp.task('bower', function () {
    gulp.src('./app/index.html')
        .pipe(wiredep({
            directory : "app/bower"
        }))
        .pipe(gulp.dest('./app'))
});

// Uncss
gulp.task("uncss", function () {
    gulp.src('cssbuild/style.css')
        .pipe(uncss({
            html: ['app/index.html']
        }))
        .pipe(gulp.dest('app/css'))
});

// CSS
gulp.task("css", function () {
    gulp.src('cssbuild/*.css')
        .pipe(concatCss("main.css"))
        .pipe(shorthand())
        //.pipe(csso())
        .pipe(autoprefixer('last 15 versions'))
        .pipe(gulp.dest('app/css'))
});

// Слежка
gulp.task('watch', function () {
    gulp.watch('cssbuild/*.css', ['css']);
    gulp.watch([
        'app/*.html',
        'app/js/*.js',
        'app/css/*.css'
    ]).on('change', browserSync.reload);
});

// default
gulp.task('default', ['server', 'bower', 'css', 'watch']);<commit_msg>updeate task build<commit_after>var gulp = require("gulp");
// прописывает пути bower
var wiredep = require('wiredep').stream;
// сборка dist
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
// для удаления файлов
var clean = require('gulp-clean');
// создание локального сервера
var browserSync = require('browser-sync');
// позволяет удалять в автомате не используемые стили
var uncss = require('gulp-uncss');
// объединение стилей
var concatCss = require('gulp-concat-css');
// позволяет добавлять префиксы в css для поддержки в разных браузерах
var autoprefixer = require('gulp-autoprefixer');
// переименовывание
var rename = require("gulp-rename");
// уведомления
var notify = require("gulp-notify");
// Minify CSS
//var csso = require('gulp-csso');
//Shorthand - обединяет селекторы
var shorthand = require('gulp-shorthand');

// Сервер
gulp.task('server', function () {
    browserSync({
        port: 9000,
        server: {
            baseDir: 'app'
        }
    });
});

// Удаление папки dist
gulp.task('clean', function () {
    return gulp.src('dist', {read: false})
        .pipe(clean())
});

// Сборка production в папку dist
gulp.task('dist', function () {
    var assets = useref.assets();

    return gulp.src('app/*.html')
        .pipe(assets)
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.css', minifyCss()))
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(gulp.dest('dist'))
});

// Перенос картинак production в папку dist
gulp.task('img', function () {
    return gulp.src('app/img/**/*')
        .pipe(gulp.dest('dist/img'))
        .pipe(notify("Build end!"))
});

// Bower
gulp.task('bower', function () {
    gulp.src('./app/index.html')
        .pipe(wiredep({
            directory: "app/bower"
        }))
        .pipe(gulp.dest('./app'))
});

// Uncss
gulp.task("uncss", function () {
    gulp.src('cssbuild/style.css')
        .pipe(uncss({
            html: ['app/index.html']
        }))
        .pipe(gulp.dest('app/css'))
});

// CSS
gulp.task("css", function () {
    gulp.src('cssbuild/*.css')
        .pipe(concatCss("main.css"))
        .pipe(shorthand())
        //.pipe(csso())
        .pipe(autoprefixer('last 15 versions'))
        .pipe(gulp.dest('app/css'))
});

// Слежка
gulp.task('watch', function () {
    gulp.watch('cssbuild/*.css', ['css']);
    gulp.watch([
        'app/*.html',
        'app/js/*.js',
        'app/css/*.css'
    ]).on('change', browserSync.reload);
});

// default
gulp.task('default', ['server', 'bower', 'css', 'watch']);
// build
gulp.task('build', ['clean', 'dist', 'img']);<|endoftext|>