<commit_before>var args = arguments[0] || {};
var urlCollection = Alloy.Collections.info_urlModel;

//-----------------------------------------------------------
// Args skickade från listvy
//-----------------------------------------------------------
try {
	$.lblInfoTitle.text = args.name || "Title";
	$.infoImg.image = "/pics/" + args.img;
	$.lblInfoText.text = args.infoTxt;
	var id = args.id;

} catch(e) {
	newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - load data into labels");
}

setRowData();

//-----------------------------------------------------------
// Visar info för valt item i listvyn
//-----------------------------------------------------------
function showinfoDetails(info) {
	try {
		var selectedInfo = info.row;
		var args = {
			id : selectedInfo.id,
			name : selectedInfo.name,
			infoTxt : selectedInfo.infoTxt,
			link : selectedInfo.link,
			img : selectedInfo.image,
			desc : selectedInfo.desc
		};

		var infoDetail = Alloy.createController("infoDetail", args).getView();
		infoDetail.open();
	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - showInfoDetail");
	}
}

//-----------------------------------------------------------
// sätter alla items i listan
//-----------------------------------------------------------
function setRowData() {
	try {
		var tableViewData = [];
		urlCollection.fetch({
			query : 'SELECT * from info_urlModel WHERE info_id ="' + id + '"'
		});

		var urlJson = urlCollection.toJSON();

		for (var i = 0; i < urlJson.length; i++) {
			var row = Ti.UI.createTableViewRow({
				id : urlJson[i].id,
				layout : 'horizontal',
				height : '60dp',
				top : '0dp'
			});

			// var txt = Ti.UI.createLabel({
				// left : '15dp',
				// right : '15dp',
				// width : Ti.UI.FILL,
				// font : {
					// fontSize : '12dp'
				// },
				// text : urlJson[i].url_text,
			// });

			var linkName = Ti.UI.createLabel({
				width : Ti.UI.FILL,
				left : '15dp',
				right : '15dp',
				font : {
					fontSize : '12dp',
				},
				color : 'blue',
				text : urlJson[i].linkname
			});

			// row.add(txt);
			row.add(linkName);

			tableViewData.push(row);
		}
		$.tableView.data = tableViewData;

	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoList - setRowData");
	}
}

//-----------------------------------------------------------
// Hämtar all info som ska läsas in i listan
//-----------------------------------------------------------
function getLink(e) {

		var rowId = e.rowData.id;
		urlCollection.fetch({
			query : 'SELECT url FROM info_urlModel WHERE id = "' + rowId + '"'
		});

		var jsonObj = urlCollection.toJSON();
		var web =  jsonObj[0].url;

	openLink(web);
}

//-----------------------------------------------------------
// Öppnar url'en i en webView.
//-----------------------------------------------------------
function openLink(link) {
	try {
		var webview = Titanium.UI.createWebView({
			url : link
		});
		var window = Titanium.UI.createWindow();
		window.backButtonTitle = "Tillbaka";

		window.add(webview);
		Alloy.CFG.tabs.activeTab.open(window);

	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - openLink");
	}
}<commit_msg>mer fix<commit_after>var args = arguments[0] || {};
var urlCollection = Alloy.Collections.info_urlModel;

//-----------------------------------------------------------
// Args skickade från listvy
//-----------------------------------------------------------
try {
	$.lblInfoTitle.text = args.name || "Title";
	$.infoImg.image = "/pics/" + args.img;
	$.lblInfoText.text = args.infoTxt;
	var id = args.id;

} catch(e) {
	newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - load data into labels");
}

setRowData();

//-----------------------------------------------------------
// Visar info för valt item i listvyn
//-----------------------------------------------------------
function showinfoDetails(info) {
	try {
		var selectedInfo = info.row;
		var args = {
			id : selectedInfo.id,
			name : selectedInfo.name,
			infoTxt : selectedInfo.infoTxt,
			link : selectedInfo.link,
			img : selectedInfo.image,
			desc : selectedInfo.desc
		};

		var infoDetail = Alloy.createController("infoDetail", args).getView();
		infoDetail.open();
	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - showInfoDetail");
	}
}

//-----------------------------------------------------------
// sätter alla items i listan
//-----------------------------------------------------------
function setRowData() {
	try {
		var tableViewData = [];
		urlCollection.fetch({
			query : 'SELECT * from info_urlModel WHERE info_id ="' + id + '"'
		});

		var urlJson = urlCollection.toJSON();

		for (var i = 0; i < urlJson.length; i++) {
			var row = Ti.UI.createTableViewRow({
				id : urlJson[i].id,
				height : '60dp',
				top : '0dp',
				hasChild : true
			});

			// var txt = Ti.UI.createLabel({
				// left : '15dp',
				// right : '15dp',
				// width : Ti.UI.FILL,
				// font : {
					// fontSize : '12dp'
				// },
				// text : urlJson[i].url_text,
			// });

			var linkName = Ti.UI.createLabel({
				width : Ti.UI.FILL,
				left : '15dp',
				right : '15dp',
				font : {
					fontSize : '12dp',
				},
				color : 'blue',
				text : urlJson[i].linkname
			});

			// row.add(txt);
			row.add(linkName);

			tableViewData.push(row);
		}
		$.tableView.data = tableViewData;

	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoList - setRowData");
	}
}

//-----------------------------------------------------------
// Hämtar all info som ska läsas in i listan
//-----------------------------------------------------------
function getLink(e) {

		var rowId = e.rowData.id;
		urlCollection.fetch({
			query : 'SELECT url FROM info_urlModel WHERE id = "' + rowId + '"'
		});

		var jsonObj = urlCollection.toJSON();
		var web =  jsonObj[0].url;

	openLink(web);
}

//-----------------------------------------------------------
// Öppnar url'en i en webView.
//-----------------------------------------------------------
function openLink(link) {
	try {
		var webview = Titanium.UI.createWebView({
			url : link
		});
		var window = Titanium.UI.createWindow();
		window.backButtonTitle = "Tillbaka";

		window.add(webview);
		Alloy.CFG.tabs.activeTab.open(window);

	} catch(e) {
		newError("Något gick fel när sidan skulle laddas, prova igen!", "infoDetail - openLink");
	}
}<|endoftext|>


<commit_before>/**
 * This file contains the function for running simulation of infection steps
 *
 * @file default.js
 * @author Yibo G (https://github.com/nilyibo)
 */

/**
 * Initial configuration
 */

var params = {	// Default parameter
	n: 4,
	r: 1,
	p: 0.5,
	rows: 10,
	columns: 10,
	rounds: 1000
};

function initPage() {
	var nSelect = document.getElementById('nSelect');
	var rSelect = document.getElementById('rSelect');
	var n = parseInt(nSelect.options[nSelect.selectedIndex].value);
	for(var i = 0; i < n; ++i)
	{
		var option = document.createElement("option");
		option.text = i + 1;
		rSelect.options.add(option);
	}
}

/**
 * UI event handler
 */

function runButton_click() {
	var errorCode = inputParams();
	if (errorCode == -1)
		return;

	var status = document.getElementById('status');
	status.style.color = '#00ff33';
	status.innerHTML = 'Simulation started.';

	var steps = simulation();

	status.style.color = '#000000';
	status.innerHTML = 'Simulation ended.';
	alert('average steps: ' + steps);
}

function nSelect_changed() {
	var nSelect = document.getElementById('nSelect');
	params.n = parseInt(nSelect.options[nSelect.selectedIndex].value);

	var rSelect = document.getElementById('rSelect');
	var selectedIndex = rSelect.selectedIndex;
	for(var i = rSelect.options.length - 1; i >= 0; --i)
	{
		rSelect.remove(i);
	}

	for(var i = 0; i < params.n; ++i)
	{
		var option = document.createElement("option");
		option.text = i + 1;
		rSelect.options.add(option);
	}

	if (selectedIndex < params.n)
		rSelect.selectedIndex = selectedIndex;
	else
	{
		rSelect.selectedIndex = params.n - 1;
		params.r = params.n;	// Choose the largest possible one
	}
}

function rSelect_changed() {
	var rSelect = document.getElementById('rSelect');
	params.r = parseInt(rSelect.options[rSelect.selectedIndex].value);
}

function inputKeyDown(event) {
	if (event.keyCode == 13)	// 'Enter' key
		document.getElementById('runButton').click();
}

/**
 * Simulation function
 */

function simulation() {
	return 0;
}

/**
 * Data Transfer helper function
 */

function inputParams() {
	var pInput = document.getElementById('pInput');
	var rowInput = document.getElementById('rowInput');
	var columnInput = document.getElementById('columnInput');
	var roundInput = document.getElementById('roundInput');

	var p = parseFloat(pInput.value);
	if (isNaN(p) || p < 0 || p > 1)
	{
		inputWarning('pInput');
		return -1;
	}
	else
		params.p = p;

	var rows = parseInt(rowInput.value);
	if (isNaN(rows) || rows <= 0)
	{
		inputWarning('rowInput');
		return -1;
	}
	else
		params.rows = rows;

	var columns = parseInt(columnInput.value);
	if (isNaN(columns) || columns <= 0)
	{
		inputWarning('columnInput');
		return -1;
	}
	else
		params.columns = columns;

	var rounds = parseInt(roundInput.value);
	if (isNaN(rounds) || rounds <= 0)
	{
		inputWarning('roundInput');
		return -1;
	}
	else
		params.rounds = rounds;

	return 0;	// No error in parameters
}

/**
 * General helper function
 */
function inputWarning(id) {
	var status = document.getElementById('status');
	status.innerHTML = 'Invalid parameter.';
	status.style.color = '#ff0000';

	var input = document.getElementById(id);
	input.select();
}<commit_msg>Added simulation skeleton. Need to add oneRound().<commit_after>/**
 * This file contains the function for running simulation of infection steps
 *
 * @file default.js
 * @author Yibo G (https://github.com/nilyibo)
 */

/**
 * Initial configuration
 */

var params = {	// Default parameter
	n: 4,
	r: 1,
	p: 0.5,
	rows: 10,
	columns: 10,
	simulations: 1000
};

function initPage() {
	var nSelect = document.getElementById('nSelect');
	var rSelect = document.getElementById('rSelect');
	var n = parseInt(nSelect.options[nSelect.selectedIndex].value);
	for(var i = 0; i < n; ++i)
	{
		var option = document.createElement("option");
		option.text = i + 1;
		rSelect.options.add(option);
	}
}

/**
 * UI event handler
 */

function runButton_click() {
	var errorCode = inputParams();
	if (errorCode == -1)
		return;

	// TODO: Disable parameter change

	var status = document.getElementById('status');
	status.style.color = '#00ff33';
	status.innerHTML = 'Simulation started.';

	var steps = simulation();

	// TODO: Enable parameter change

	status.style.color = '#000000';
	status.innerHTML = 'Simulation ended.';
	alert('average steps: ' + steps);
}

function nSelect_changed() {
	var nSelect = document.getElementById('nSelect');
	params.n = parseInt(nSelect.options[nSelect.selectedIndex].value);

	var rSelect = document.getElementById('rSelect');
	var selectedIndex = rSelect.selectedIndex;
	for(var i = rSelect.options.length - 1; i >= 0; --i)
	{
		rSelect.remove(i);
	}

	for(var i = 0; i < params.n; ++i)
	{
		var option = document.createElement("option");
		option.text = i + 1;
		rSelect.options.add(option);
	}

	if (selectedIndex < params.n)
		rSelect.selectedIndex = selectedIndex;
	else
	{
		rSelect.selectedIndex = params.n - 1;
		params.r = params.n;	// Choose the largest possible one
	}
}

function rSelect_changed() {
	var rSelect = document.getElementById('rSelect');
	params.r = parseInt(rSelect.options[rSelect.selectedIndex].value);
}

function inputKeyDown(event) {
	if (event.keyCode == 13)	// 'Enter' key
		document.getElementById('runButton').click();
}

/**
 * Simulation function
 */

// Run the whole simulation
function simulation() {
	var progress = document.getElementById('progressbar').children[0];
	var sum = 0;
	for (var i = 0; i < params.simulations; ++i)
	{
		sum += oneSimulation();
		progress.style.width = Math.ceil(i * 100 / params.simulations) + '%';
		var status = document.getElementById('status');
		status.innerHTML = 'Simulations completed: ' + i;
	}
	return sum / params.simulations;
}

// Random initial seed
function buildGrid() {
	var grid = [];
	for (var i = 0; i < params.rows; ++i)
	{
		grid.push([]);
		for (var j = 0; j < params.columns; ++j)
			if (Math.random() < params.p)
				grid[i].push(true);
			else
				grid[i].push(false);
	}
	return grid;
}

// Run one simulation
function oneSimulation() {
	var grid = buildGrid();
	var oldGrid = [];
	var rounds = 0;

	while (true)
	{
		oldGrid = grid;
		oneRound();
		if (compareGrid(grid, oldGrid))
			break;
		++counter;
	}
	return 0;
}

// One round of infection spread, updates grid
function oneRound() {
	;
}

function copyGrid(grid) {
	var result = [];
	for (var i = 0; i < grid.length; ++i)
	{
		result.push([]);
		for (var j = 0; j < grid[i].length; ++j)
			result[i].push(grid[i][j]);
	}
	return result;
}

// Check whether two grids have the same infection status
function compareGrid(grid1, grid2) {
	if (grid1.length != grid2.length)
		return false;

	for (var i = 0; i < grid1.length; ++i)
	{
		if (grid1[i].length != grid2[i].length)
			return false;
		for (var j = 0; j < grid1[i].length; ++j)
			if (grid1[i][j] != grid2[i][j])
				return false;
	}

	return true;
}

/**
 * Data Transfer helper function
 */

function inputParams() {
	var pInput = document.getElementById('pInput');
	var rowInput = document.getElementById('rowInput');
	var columnInput = document.getElementById('columnInput');
	var simulationInput = document.getElementById('simulationInput');

	var p = parseFloat(pInput.value);
	if (isNaN(p) || p < 0 || p > 1)
	{
		inputWarning('pInput');
		return -1;
	}
	else
		params.p = p;

	var rows = parseInt(rowInput.value);
	if (isNaN(rows) || rows <= 0)
	{
		inputWarning('rowInput');
		return -1;
	}
	else
		params.rows = rows;

	var columns = parseInt(columnInput.value);
	if (isNaN(columns) || columns <= 0)
	{
		inputWarning('columnInput');
		return -1;
	}
	else
		params.columns = columns;

	var simulations = parseInt(simulationInput.value);
	if (isNaN(simulations) || simulations <= 0)
	{
		inputWarning('simulationInput');
		return -1;
	}
	else
		params.simulations = simulations;

	return 0;	// No error in parameters
}

/**
 * General helper function
 */
function inputWarning(id) {
	var status = document.getElementById('status');
	status.innerHTML = 'Invalid parameter.';
	status.style.color = '#ff0000';

	var input = document.getElementById(id);
	input.select();
}<|endoftext|>


<commit_before>var helper = {};

(function(){
  var $iframeContainer, $iframe, jsLibraries = {};

  helper.init = function(cb){
    $iframeContainer = $("#iframe-container");

    $.get('/static/js/jquery.js').done(function(code){
      // make sure we don't override existing jquery
      jsLibraries["jquery"] = "if(typeof $ === 'undefined') {\n" + code + "\n}";

      $.get('/tests/frontend/lib/sendkeys.js').done(function(code){
        jsLibraries["sendkeys"] = code;

        cb();
      });
    });
  }

  helper.randomString = function randomString(len)
  {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i = 0; i < len; i++)
    {
      var rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
  }

  var getFrameJQuery = function($iframe){
    /*
      I tried over 9000 ways to inject javascript into iframes.
      This is the only way I found that worked in IE 7+8+9, FF and Chrome
    */

    var win = $iframe[0].contentWindow;
    var doc = win.document;

    //IE 8+9 Hack to make eval appear
    //http://stackoverflow.com/questions/2720444/why-does-this-window-object-not-have-the-eval-function
    win.execScript && win.execScript("null");

    win.eval(jsLibraries["jquery"]);
    win.eval(jsLibraries["sendkeys"]);

    win.$.window = win;
    win.$.document = doc;

    return win.$;
  }

  helper.clearCookies = function(){
    window.document.cookie = "";
  }

  helper.newPad = function(cb, padName){
    //build opts object
    var opts = {clearCookies: true}
    if(typeof cb === 'function'){
      opts.cb = cb
    } else {
      opts = _.defaults(cb, opts);
    }

    //clear cookies
    if(opts.clearCookies){
      helper.clearCookies();
    }

    if(!padName)
      padName = "FRONTEND_TEST_" + helper.randomString(20);
    $iframe = $("");

    //clean up inner iframe references
    helper.padChrome$ = helper.padOuter$ = helper.padInner$ = null;

    //clean up iframes properly to prevent IE from memoryleaking
    $iframeContainer.find("iframe").purgeFrame().done(function(){
      $iframeContainer.append($iframe);
      $iframe.one('load', function(){
        helper.waitFor(function(){
          return !$iframe.contents().find("#editorloadingbox").is(":visible");
        }, 50000).done(function(){
          helper.padChrome$ = getFrameJQuery(                $('#iframe-container iframe'));
          helper.padOuter$  = getFrameJQuery(helper.padChrome$('iframe.[name="ace_outer"]'));
          helper.padInner$  = getFrameJQuery( helper.padOuter$('iframe.[name="ace_inner"]'));

          //disable all animations, this makes tests faster and easier
          helper.padChrome$.fx.off = true;
          helper.padOuter$.fx.off = true;
          helper.padInner$.fx.off = true;

          opts.cb();
        }).fail(function(){
          throw new Error("Pad never loaded");
        });
      });
    });

    return padName;
  }

  helper.waitFor = function(conditionFunc, _timeoutTime, _intervalTime){
    var timeoutTime = _timeoutTime || 1000;
    var intervalTime = _intervalTime || 10;

    var deferred = $.Deferred();

    var _fail = deferred.fail;
    var listenForFail = false;
    deferred.fail = function(){
      listenForFail = true;
      _fail.apply(this, arguments);
    }

    var intervalCheck = setInterval(function(){
      var passed = false;

      passed = conditionFunc();

      if(passed){
        clearInterval(intervalCheck);
        clearTimeout(timeout);

        deferred.resolve();
      }
    }, intervalTime);

    var timeout = setTimeout(function(){
      clearInterval(intervalCheck);
      var error = new Error("wait for condition never became true " + conditionFunc.toString());
      deferred.reject(error);

      if(!listenForFail){
        throw error;
      }
    }, timeoutTime);

    return deferred;
  }

  /* Ensure console.log doesn't blow up in IE, ugly but ok for a test framework imho*/
  window.console = window.console || {};
  window.console.log = window.console.log || function(){}

  //force usage of callbacks in it
  var _it = it;
  it = function(name, func){
    if(func && func.length !== 1){
      func = function(){
        throw new Error("Please use always a callback with it() - " + func.toString());
      }
    }

    _it(name, func);
  }
})()<commit_msg>Make iframe selectors work with jquery 1.9<commit_after>var helper = {};

(function(){
  var $iframeContainer, $iframe, jsLibraries = {};

  helper.init = function(cb){
    $iframeContainer = $("#iframe-container");

    $.get('/static/js/jquery.js').done(function(code){
      // make sure we don't override existing jquery
      jsLibraries["jquery"] = "if(typeof $ === 'undefined') {\n" + code + "\n}";

      $.get('/tests/frontend/lib/sendkeys.js').done(function(code){
        jsLibraries["sendkeys"] = code;

        cb();
      });
    });
  }

  helper.randomString = function randomString(len)
  {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i = 0; i < len; i++)
    {
      var rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
  }

  var getFrameJQuery = function($iframe){
    /*
      I tried over 9000 ways to inject javascript into iframes.
      This is the only way I found that worked in IE 7+8+9, FF and Chrome
    */

    var win = $iframe[0].contentWindow;
    var doc = win.document;

    //IE 8+9 Hack to make eval appear
    //http://stackoverflow.com/questions/2720444/why-does-this-window-object-not-have-the-eval-function
    win.execScript && win.execScript("null");

    win.eval(jsLibraries["jquery"]);
    win.eval(jsLibraries["sendkeys"]);

    win.$.window = win;
    win.$.document = doc;

    return win.$;
  }

  helper.clearCookies = function(){
    window.document.cookie = "";
  }

  helper.newPad = function(cb, padName){
    //build opts object
    var opts = {clearCookies: true}
    if(typeof cb === 'function'){
      opts.cb = cb
    } else {
      opts = _.defaults(cb, opts);
    }

    //clear cookies
    if(opts.clearCookies){
      helper.clearCookies();
    }

    if(!padName)
      padName = "FRONTEND_TEST_" + helper.randomString(20);
    $iframe = $("");

    //clean up inner iframe references
    helper.padChrome$ = helper.padOuter$ = helper.padInner$ = null;

    //clean up iframes properly to prevent IE from memoryleaking
    $iframeContainer.find("iframe").purgeFrame().done(function(){
      $iframeContainer.append($iframe);
      $iframe.one('load', function(){
        helper.waitFor(function(){
          return !$iframe.contents().find("#editorloadingbox").is(":visible");
        }, 50000).done(function(){
          helper.padChrome$ = getFrameJQuery(                $('#iframe-container iframe'));
          helper.padOuter$  = getFrameJQuery(helper.padChrome$('iframe[name="ace_outer"]'));
          helper.padInner$  = getFrameJQuery( helper.padOuter$('iframe[name="ace_inner"]'));

          //disable all animations, this makes tests faster and easier
          helper.padChrome$.fx.off = true;
          helper.padOuter$.fx.off = true;
          helper.padInner$.fx.off = true;

          opts.cb();
        }).fail(function(){
          throw new Error("Pad never loaded");
        });
      });
    });

    return padName;
  }

  helper.waitFor = function(conditionFunc, _timeoutTime, _intervalTime){
    var timeoutTime = _timeoutTime || 1000;
    var intervalTime = _intervalTime || 10;

    var deferred = $.Deferred();

    var _fail = deferred.fail;
    var listenForFail = false;
    deferred.fail = function(){
      listenForFail = true;
      _fail.apply(this, arguments);
    }

    var intervalCheck = setInterval(function(){
      var passed = false;

      passed = conditionFunc();

      if(passed){
        clearInterval(intervalCheck);
        clearTimeout(timeout);

        deferred.resolve();
      }
    }, intervalTime);

    var timeout = setTimeout(function(){
      clearInterval(intervalCheck);
      var error = new Error("wait for condition never became true " + conditionFunc.toString());
      deferred.reject(error);

      if(!listenForFail){
        throw error;
      }
    }, timeoutTime);

    return deferred;
  }

  /* Ensure console.log doesn't blow up in IE, ugly but ok for a test framework imho*/
  window.console = window.console || {};
  window.console.log = window.console.log || function(){}

  //force usage of callbacks in it
  var _it = it;
  it = function(name, func){
    if(func && func.length !== 1){
      func = function(){
        throw new Error("Please use always a callback with it() - " + func.toString());
      }
    }

    _it(name, func);
  }
})()<|endoftext|>


<commit_before>function setup() {

}

function draw() {

}<commit_msg>pages<commit_after><|endoftext|>


<commit_before>/* global Diff2HtmlUI */
import createDebug from 'debug';

import { route } from './util';

const debug = createDebug('ms:code_status');

route('/status/code', () => {
  $('#show-all-gem-versions').click(e => {
    e.preventDefault();
    $('table#gems-versions-table .minor').toggleClass('hide');
    $(this).toggleClass('shown');
  });
  $('#toggle-compare-diff').click(e => {
    e.preventDefault();
    $(this).toggleClass('shown')
           .parents('details')
           .find('.compare-diff')
           .toggleClass('hide');
  });
  $('#toggle-commit-diff').click(e => {
    e.preventDefault();
    $(this).toggleClass('shown')
           .parents('details')
           .find('.commit-diff')
           .toggleClass('hide');
  });
  $.get('/status/code.json', ({ repo, compare, compare_diff, commit, commit_diff }) => {
    const { default_branch: defaultBranch } = repo;
    $('.fill-branch')
      .text(defaultBranch)
      .attr('href', `https://github.com/Charcoal-SE/metasmoke/tree/${defaultBranch}`);

    const status = [];
    if (compare.ahead_by > 0) {
      status.push(`${compare.ahead_by} commit${compare.ahead_by === 1 ? '' : 's'} behind`);
    }
    if (compare.behind_by > 0) {
      status.push(`${compare.behind_by} commit${compare.behind_by === 1 ? '' : 's'} ahead of`);
    }
    if (status.length === 0) {
      status.push('even with');
    }
    $('.fill-status').text(status.join(', '));

    renderDiff('compare', compare_diff);
    renderDiff('commit', commit_diff);

    const [message, ...other] = commit.commit.message.split('\n\n');
    $('.commit summary').text(escapeAndLinkify(message));
    $('.commit pre').text(escapeAndLinkify(other.join('\n\n').trim()) || 'No details');
  }).fail(debug);
});

const $escaper = $('
');
function escapeAndLinkify(message) {
  return $escaper
    .text(message)
    .html()
    .replace(/(^|\W)@([a-z0-9][a-z0-9-]*)(?!\/)(?=\.+[ \t\W]|\.+$|[^0-9a-zA-Z_.]|$)/ig, '$1@$2')
    .replace(/#(\d+)/g, '#$1');
}

function renderDiff(type, diff) {
  if (!(diff && typeof diff === 'string')) {
    $(`#toggle-${type}-diff`).addClass('no-diff');
    return;
  }
  const diff2htmlUi = new Diff2HtmlUI({
    diff
  });
  diff2htmlUi.draw(`.${type}-diff`, {
    showFiles: true,
    matching: 'words'
  });
  diff2htmlUi.highlightCode(`.${type}-diff`);
  diff2htmlUi.fileListCloseable(`.${type}-diff`, false);
}
<commit_msg>Render escaped HTML<commit_after>/* global Diff2HtmlUI */
import createDebug from 'debug';

import { route } from './util';

const debug = createDebug('ms:code_status');

route('/status/code', () => {
  $('#show-all-gem-versions').click(e => {
    e.preventDefault();
    $('table#gems-versions-table .minor').toggleClass('hide');
    $(this).toggleClass('shown');
  });
  $('#toggle-compare-diff').click(e => {
    e.preventDefault();
    $(this).toggleClass('shown')
           .parents('details')
           .find('.compare-diff')
           .toggleClass('hide');
  });
  $('#toggle-commit-diff').click(e => {
    e.preventDefault();
    $(this).toggleClass('shown')
           .parents('details')
           .find('.commit-diff')
           .toggleClass('hide');
  });
  $.get('/status/code.json', ({ repo, compare, compare_diff, commit, commit_diff }) => {
    const { default_branch: defaultBranch } = repo;
    $('.fill-branch')
      .text(defaultBranch)
      .attr('href', `https://github.com/Charcoal-SE/metasmoke/tree/${defaultBranch}`);

    const status = [];
    if (compare.ahead_by > 0) {
      status.push(`${compare.ahead_by} commit${compare.ahead_by === 1 ? '' : 's'} behind`);
    }
    if (compare.behind_by > 0) {
      status.push(`${compare.behind_by} commit${compare.behind_by === 1 ? '' : 's'} ahead of`);
    }
    if (status.length === 0) {
      status.push('even with');
    }
    $('.fill-status').text(status.join(', '));

    renderDiff('compare', compare_diff);
    renderDiff('commit', commit_diff);

    const [message, ...other] = commit.commit.message.split('\n\n');
    $('.commit summary').html(escapeAndLinkify(message));
    $('.commit pre').html(escapeAndLinkify(other.join('\n\n').trim()) || 'No details');
  }).fail(debug);
});

const $escaper = $('
');
function escapeAndLinkify(message) {
  return $escaper
    .text(message)
    .html()
    .replace(/(^|\W)@([a-z0-9][a-z0-9-]*)(?!\/)(?=\.+[ \t\W]|\.+$|[^0-9a-zA-Z_.]|$)/ig, '$1@$2')
    .replace(/#(\d+)/g, '#$1');
}

function renderDiff(type, diff) {
  if (!(diff && typeof diff === 'string')) {
    $(`#toggle-${type}-diff`).addClass('no-diff');
    return;
  }
  const diff2htmlUi = new Diff2HtmlUI({
    diff
  });
  diff2htmlUi.draw(`.${type}-diff`, {
    showFiles: true,
    matching: 'words'
  });
  diff2htmlUi.highlightCode(`.${type}-diff`);
  diff2htmlUi.fileListCloseable(`.${type}-diff`, false);
}
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import {connect} from 'store'
import {msg} from 'translate'
import styles from './form.module.css'

export function form(inputs, mapStateToProps) {
    return (WrappedComponent) => {
        class Form extends React.Component {
            onDirtyListeners = []
            onCleanListeners = []

            constructor(props) {
                super(props)
                const state = {
                    initialValues: {...props.values} || {},
                    values: {...props.values} || {},
                    errors: {...props.errors} || {},
                    invalidValue: {},
                    dirty: false
                }
                Object.keys(inputs).forEach(name => {
                    state.initialValues[name] = name in state.initialValues ? state.initialValues[name] : ''
                    state.values[name] = name in state.values ? state.values[name] : ''
                    state.errors[name] = name in state.errors ? state.errors[name] : ''
                })
                this.state = state

                this.handleChange = this.handleChange.bind(this)
                this.value = this.value.bind(this)
                this.validate = this.validate.bind(this)
                this.hasInvalid = this.hasInvalid.bind(this)
            }

            subscribe(description, stream$, observer) {
                this.props.subscribe(description, stream$, observer)
            }

            componentWillReceiveProps(nextProps) {
                if ('errors' in nextProps)
                    this.setState((prevState) =>
                        ({...prevState, errors: nextProps.errors})
                    )
            }

            handleChange(e) {
                const target = e.target
                const name = target.name
                const value = target.type === 'checkbox'
                    ? target.checked
                    : target.value
                this.set(name, value)
                return this
            }

            set(name, value) {
                if (value != null && value !== this.state.values[name])
                    this.setState((prevState) => {
                        const state = Object.assign({}, prevState)
                        state.values[name] = value
                        state.errors[name] = ''
                        state.invalidValue[name] = ''
                        state.dirty = state.initialValues[name] !== value
                        state.gotDirty = state.dirty && !prevState.dirty
                        state.gotClean = !state.dirty && prevState.dirty
                        return state
                    }, () => this.notifyOnDirtyOrClean())
                return this
            }

            notifyOnDirtyOrClean() {
                if (this.state.gotDirty)
                    this.onDirty()
                else if (this.state.gotClean)
                    this.onClean()
            }

            value(name) {
                return this.state.values[name]
            }

            error(name) {
                let constraints = inputs[name]
                if (constraints == null)
                    constraints = new Constraints()
                return constraints.check(name, this.state.values)
            }

            validate(name) {
                this.setState((prevState) => {
                    const state = Object.assign({}, prevState)
                    if (!state.invalidValue[name])
                        state.errors[name] = this.error(name)
                    return state
                })
                return this
            }

            hasInvalid() {
                return !!Object.keys(this.state.values).find(name => this.error(name))
            }

            setInitialValues(values) {
                if (!values)
                    return
                this.setState((prevState) => {
                    const state = {...prevState, dirty: false}
                    Object.keys(inputs).forEach(name => {
                        state.initialValues[name] = name in values ? values[name] : ''
                        state.values[name] = name in values ? values[name] : ''
                        state.errors[name] = ''
                    })
                    if (prevState.dirty)
                        this.onClean()
                    return state
                })
            }

            reset() {
                this.setState((prevState) => {
                    const state = {...prevState, values: {...prevState.initialValues}, dirty: false}
                    Object.keys(inputs).forEach(name => {
                        state.errors[name] = ''
                    })
                    state.gotDirty = false
                    state.gotClean = prevState.dirty
                    return state
                }, () => this.notifyOnDirtyOrClean())
            }

            isValueDirty(name) {
                const state = this.state
                return state.values[name] !== state.initialValues[name]
            }

            isDirty() {
                return !!Object.keys(this.state.initialValues)
                    .find((name) => this.isValueDirty(name))
            }

            onDirty() {
                this.onDirtyListeners.forEach((listener) => listener())
            }

            onClean() {
                this.onCleanListeners.forEach((listener) => listener())
            }

            render() {
                const formInputs = {}
                Object.keys(inputs).forEach(name => {
                    formInputs[name] = {
                        name: name,
                        value: this.state.values[name],
                        error: this.state.errors[name],
                        errorClass: this.state.errors[name] ? styles.error : null,
                        invalid: (msg) => this.setState((prevState) => ({
                            ...prevState,
                            errors: {...prevState.errors, [name]: msg},
                            invalidValue: {...prevState.invalidValue, [name]: this.state.values[name]}
                        })),
                        set: (value) => this.set(name, value),
                        handleChange: (e) => this.handleChange(e),
                        isDirty: () => this.isValueDirty(name),
                        validate: () => this.validate(name)
                    }
                })
                return React.createElement(WrappedComponent, {
                    ...this.props,
                    form: {
                        errors: Object.values(this.state.errors)
                            .filter(error => error),
                        errorClass: styles.error,
                        hasInvalid: this.hasInvalid,
                        onDirty: (listener) => this.onDirtyListeners.push(listener),
                        onClean: (listener) => this.onCleanListeners.push(listener),
                        setInitialValues: (values) => this.setInitialValues(values),
                        reset: () => this.reset(),
                        isDirty: () => this.isDirty(),
                        values: () => this.state.values
                    },
                    inputs: formInputs
                })
            }
        }

        Form.displayName = `Form(${getDisplayName(WrappedComponent)})`
        Form = connect(mapStateToProps ? mapStateToProps : null)(Form)
        return Form
    }
}

function getDisplayName(Component) {
    return Component.displayName || Component.name || 'Component'
}

export class Constraints {
    static _EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ // eslint-disable-line no-useless-escape

    _constraints = []
    _skip = []

    skip(when) {
        this._skip.push(when)
        return this
    }

    predicate(constraint, messageId) {
        this._constraints.push([constraint, messageId])
        return this
    }

    match(regex, messageId) {
        return this.predicate(value => regex.test(value), messageId)
    }

    notBlank(messageId) {
        return this.predicate(value => !!value, messageId)
    }

    email(messageId) {
        return this.match(Constraints._EMAIL_REGEX, messageId)
    }

    check(name, values) {
        const skip = this._skip.find((when) => when(values[name], values))
        const failingConstraint = !skip &&
            this._constraints.find((constraint) =>
                constraint[0](values[name], values) ? null : constraint[1]
            )
        return failingConstraint ? msg(failingConstraint[1]) : ''
    }
}

export const ErrorMessage = ({input}) =>

        {input && input.error}

export class Input extends React.Component {
    render() {
        const {input, validate = 'onBlur', onChange, onBlur, ...props} = this.props
        return (
            <input
                {...props}
                name={input.name}
                value={input.value}
                onChange={(e) => {
                    input.handleChange(e)
                    if (onChange)
                        onChange(e)
                    if (validate === 'onChange')
                        input.validate()
                }}
                onBlur={(e) => {
                    if (onBlur)
                        onBlur(e)
                    if (validate === 'onBlur')
                        input.validate()
                }}
                className={input.errorClass}
            />
        )
    }
}

Input.propTypes = {
    input: PropTypes.object.isRequired,
    validate: PropTypes.oneOf(['onChange', 'onBlur']),
    onChange: PropTypes.func,
    onBlur: PropTypes.func,
    placeholder: PropTypes.string,
    tabIndex: PropTypes.number,
    autoComplete: PropTypes.string,
}
<commit_msg>Fixed bug with form dirt state.<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import {connect} from 'store'
import {msg} from 'translate'
import styles from './form.module.css'

export function form(inputs, mapStateToProps) {
    return (WrappedComponent) => {
        class Form extends React.Component {
            onDirtyListeners = []
            onCleanListeners = []

            constructor(props) {
                super(props)
                const state = {
                    initialValues: {...props.values} || {},
                    values: {...props.values} || {},
                    errors: {...props.errors} || {},
                    invalidValue: {},
                    dirty: false
                }
                Object.keys(inputs).forEach(name => {
                    state.initialValues[name] = name in state.initialValues ? state.initialValues[name] : ''
                    state.values[name] = name in state.values ? state.values[name] : ''
                    state.errors[name] = name in state.errors ? state.errors[name] : ''
                })
                this.state = state

                this.handleChange = this.handleChange.bind(this)
                this.value = this.value.bind(this)
                this.validate = this.validate.bind(this)
                this.hasInvalid = this.hasInvalid.bind(this)
            }

            subscribe(description, stream$, observer) {
                this.props.subscribe(description, stream$, observer)
            }

            componentWillReceiveProps(nextProps) {
                if ('errors' in nextProps)
                    this.setState((prevState) =>
                        ({...prevState, errors: nextProps.errors})
                    )
            }

            handleChange(e) {
                const target = e.target
                const name = target.name
                const value = target.type === 'checkbox'
                    ? target.checked
                    : target.value
                this.set(name, value)
                return this
            }

            set(name, value) {
                if (value != null && value !== this.state.values[name])
                    this.setState((prevState) => {
                        const state = Object.assign({}, prevState)
                        state.values[name] = value
                        state.errors[name] = ''
                        state.invalidValue[name] = ''
                        state.dirty = !!Object.keys(state.initialValues).find((name) =>
                            state.initialValues !== state.values[name]
                        )
                        state.gotDirty = state.dirty && !prevState.dirty
                        state.gotClean = !state.dirty && prevState.dirty
                        return state
                    }, () => this.notifyOnDirtyOrClean())
                return this
            }

            notifyOnDirtyOrClean() {
                if (this.state.gotDirty)
                    this.onDirty()
                else if (this.state.gotClean)
                    this.onClean()
            }

            value(name) {
                return this.state.values[name]
            }

            error(name) {
                let constraints = inputs[name]
                if (constraints == null)
                    constraints = new Constraints()
                return constraints.check(name, this.state.values)
            }

            validate(name) {
                this.setState((prevState) => {
                    const state = Object.assign({}, prevState)
                    if (!state.invalidValue[name])
                        state.errors[name] = this.error(name)
                    return state
                })
                return this
            }

            hasInvalid() {
                return !!Object.keys(this.state.values).find(name => this.error(name))
            }

            setInitialValues(values) {
                if (!values)
                    return
                this.setState((prevState) => {
                    const state = {...prevState, dirty: false}
                    Object.keys(inputs).forEach(name => {
                        state.initialValues[name] = name in values ? values[name] : ''
                        state.values[name] = name in values ? values[name] : ''
                        state.errors[name] = ''
                    })
                    if (prevState.dirty)
                        this.onClean()
                    return state
                })
            }

            reset() {
                this.setState((prevState) => {
                    const state = {...prevState, values: {...prevState.initialValues}, dirty: false}
                    Object.keys(inputs).forEach(name => {
                        state.errors[name] = ''
                    })
                    state.gotDirty = false
                    state.gotClean = prevState.dirty
                    return state
                }, () => this.notifyOnDirtyOrClean())
            }

            isValueDirty(name) {
                const state = this.state
                return state.values[name] !== state.initialValues[name]
            }

            isDirty() {
                return !!Object.keys(this.state.initialValues)
                    .find((name) => this.isValueDirty(name))
            }

            onDirty() {
                this.onDirtyListeners.forEach((listener) => listener())
            }

            onClean() {
                this.onCleanListeners.forEach((listener) => listener())
            }

            render() {
                const formInputs = {}
                Object.keys(inputs).forEach(name => {
                    formInputs[name] = {
                        name: name,
                        value: this.state.values[name],
                        error: this.state.errors[name],
                        errorClass: this.state.errors[name] ? styles.error : null,
                        invalid: (msg) => this.setState((prevState) => ({
                            ...prevState,
                            errors: {...prevState.errors, [name]: msg},
                            invalidValue: {...prevState.invalidValue, [name]: this.state.values[name]}
                        })),
                        set: (value) => this.set(name, value),
                        handleChange: (e) => this.handleChange(e),
                        isDirty: () => this.isValueDirty(name),
                        validate: () => this.validate(name)
                    }
                })
                return React.createElement(WrappedComponent, {
                    ...this.props,
                    form: {
                        errors: Object.values(this.state.errors)
                            .filter(error => error),
                        errorClass: styles.error,
                        hasInvalid: this.hasInvalid,
                        onDirty: (listener) => this.onDirtyListeners.push(listener),
                        onClean: (listener) => this.onCleanListeners.push(listener),
                        setInitialValues: (values) => this.setInitialValues(values),
                        reset: () => this.reset(),
                        isDirty: () => this.isDirty(),
                        values: () => this.state.values
                    },
                    inputs: formInputs
                })
            }
        }

        Form.displayName = `Form(${getDisplayName(WrappedComponent)})`
        Form = connect(mapStateToProps ? mapStateToProps : null)(Form)
        return Form
    }
}

function getDisplayName(Component) {
    return Component.displayName || Component.name || 'Component'
}

export class Constraints {
    static _EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ // eslint-disable-line no-useless-escape

    _constraints = []
    _skip = []

    skip(when) {
        this._skip.push(when)
        return this
    }

    predicate(constraint, messageId) {
        this._constraints.push([constraint, messageId])
        return this
    }

    match(regex, messageId) {
        return this.predicate(value => regex.test(value), messageId)
    }

    notBlank(messageId) {
        return this.predicate(value => !!value, messageId)
    }

    email(messageId) {
        return this.match(Constraints._EMAIL_REGEX, messageId)
    }

    check(name, values) {
        const skip = this._skip.find((when) => when(values[name], values))
        const failingConstraint = !skip &&
            this._constraints.find((constraint) =>
                constraint[0](values[name], values) ? null : constraint[1]
            )
        return failingConstraint ? msg(failingConstraint[1]) : ''
    }
}

export const ErrorMessage = ({input}) =>

        {input && input.error}

export class Input extends React.Component {
    render() {
        const {input, validate = 'onBlur', onChange, onBlur, ...props} = this.props
        return (
            <input
                {...props}
                name={input.name}
                value={input.value}
                onChange={(e) => {
                    input.handleChange(e)
                    if (onChange)
                        onChange(e)
                    if (validate === 'onChange')
                        input.validate()
                }}
                onBlur={(e) => {
                    if (onBlur)
                        onBlur(e)
                    if (validate === 'onBlur')
                        input.validate()
                }}
                className={input.errorClass}
            />
        )
    }
}

Input.propTypes = {
    input: PropTypes.object.isRequired,
    validate: PropTypes.oneOf(['onChange', 'onBlur']),
    onChange: PropTypes.func,
    onBlur: PropTypes.func,
    placeholder: PropTypes.string,
    tabIndex: PropTypes.number,
    autoComplete: PropTypes.string,
}
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var rdControllers = angular.module('rdControllers', []);

// ------------------------------
// ----- Temp Controller --------
// ------------------------------
rdControllers.controller('tempCtrl', ['$scope', '$sessionStorage', function($scope, $sessionStorage) {
    console.log("Temp Controller!");

    // Clear local Storage
    $sessionStorage.$reset();
}]);

// ------------------------------
// ------ Map Controller --------
// ------------------------------
rdControllers.controller('mapCtrl', ['$scope', '$sessionStorage', 'Map', 'Browser', function($scope, $sessionStorage, Map, Browser) {
    console.log("Map Controller!");

    // Covert Lat & Long coordinates into State
    function codeLatLng(coordinate) {
        // Declarations
        var geocoder = new google.maps.Geocoder();
        var state = '', address = '', code = '';
        var states = Map.getData();

        geocoder.geocode({'latLng': coordinate}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    state = results[5].formatted_address.split(",")[0];
                    address = results[0].formatted_address;
                    code = states[state];
                    window.location = '/#/form/'+state + '/' + code;

                    // End Loading animation and render the page
                    var body = angular.element(document.querySelector("body"));
                    body.addClass('loaded');
                } else {
                    alert('No results found');
                }
            } else {
                alert('Geocoder failed due to: ' + status);
            }
        });
    }

    // Get User's Latitude & Longitude
    function success(position) {
        console.log("Got Location!");
        var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        codeLatLng(latlng);
    }

    function error(msg) {
        console.log("Could not gain access to User Location: " + msg);

        // End Loading animation and render the page
        var body = angular.element(document.querySelector("body"));
        body.addClass('loaded');
    }

    // Initiate process of receiving user location
    if (Browser.isSafari()) {
        error('Safari problems');
    } else {
        // Ask for Location
        if (navigator.geolocation) {
            // Get user input (Allow || Do not allow)
            navigator.geolocation.getCurrentPosition(success, error);

            // FailSafe for IE Firefox
            setTimeout(function(){
                var body = angular.element(document.querySelector("body"));
                body.addClass('loaded');
            }, 4500);
        } else {
            error('Browser does not support geolocation');
        }
    }
}]);

// ------------------------------
// ----- Results Controller -----
// ------------------------------
rdControllers.controller('resultsCtrl', ['$scope', '$sessionStorage', 'MonthMap', function($scope, $sessionStorage, MonthMap) {
    console.log("Results Controller!");

    // Grab Search Parameters
    if ($sessionStorage.classification) $scope.classification = $sessionStorage.classification[0];
    if ($sessionStorage.recalling_firm) $scope.recalling_firm = $sessionStorage.recalling_firm.join(" and ");
    if ($sessionStorage.product_description) $scope.product_description = $sessionStorage.product_description.join(" and ");

    // Grab results
    $scope.totalRecalls = $sessionStorage.results;

    // Initialize number -> month
    var monthMap = MonthMap.getData();

    // Format Output
    function prettify(recalls) {
        // Make Date pretty
        for (var i =0; i<recalls.length; i++) {
            var date = recalls[i]['report_date'];
            date = monthMap[date.substring(4,6)] + " " + date.substring(6) + ", " + date.substring(0,4);
            recalls[i]['report_date']= date;
        }
    }

    // Sort by date
    $scope.totalRecalls.sort(function(a, b) {
        if (a.report_date > b.report_date) return -1;
        if (a.report_date < b.report_date) return 1;
        return 0;
    });

    // Convert UTC dates to User-Friendly one (IE doesn't support ForEach loops)
    //$scope.totalRecalls.forEach(prettify);
    prettify($scope.totalRecalls);

    // Bind Results to front-end HTML elements
    $scope.state = $sessionStorage.state;
    $scope.quantity = $sessionStorage.quantity;
    $scope.orderProp = 'report_date';

    // Infinite Scroll
    var index = 10;
    var appendedItems = []
    $scope.recalls = $scope.totalRecalls.slice(0,10);
    $scope.loadMore = function() {
        appendedItems = $scope.totalRecalls.slice(index, index+10);
        $scope.recalls = $scope.recalls.concat(appendedItems);
        index+=10;
    }
}]);

// ------------------------------
// ----- Form Controller --------
// ------------------------------
rdControllers.controller('formCtrl', ['$scope', '$sessionStorage', '$routeParams', '$http', 'ClassMap', 'Validation', function($scope, $sessionStorage, $routeParams, $http, ClassMap, Validation) {
    $scope.recalls = "";
    $scope.state = $routeParams.state;
    $scope.stateCode = $routeParams.stateCode;
    var previousParams = $sessionStorage.params;
    var dataMap = {0: 'food', 1: 'brand', 2: 'all', 3: 'anything'};
    var reference = {
        "food": "product_description",
        "brand": "recalling_firm",
        "all": "classification",
        "anything": "reason_for_recall"
    };

    if (!Validation.isEmpty(previousParams)) {
        $scope.food = (previousParams['product_description'] ? previousParams['product_description'].join(' and ') : 'food');
        $scope.brand = (previousParams['recalling_firm'] ? previousParams['recalling_firm'].join(' and ') : 'brand');
    }

    // Initialize text -> classifications
    var classMap = ClassMap.getData();

    // Helpful Tooltip displays only if not already seen
    if (!$sessionStorage.seen) {
        var button = angular.element(document.querySelector("#hint"));
        setTimeout(function() {
            button.popover({
                "placement":'bottom',
                html: true
            }).popover('show');
        }, 250);
        setTimeout(function() {
            button.popover('hide');
        }, 5000);
    }

    // PAGE READY

    // process the form
    $scope.processForm = function() {
        // User has figured it out
        $sessionStorage.seen = true;

        /*
        function joinPlus(element, index, array) {
            console.log(element);
            console.log(element.split(" ").join("+"));
            return element.split(" ").join("+")
        }*/

        // Find the Form elements
        var parms = {};
        var e = angular.element(document.querySelectorAll(".nl-field-toggle"));
        var inputs = [e[0].text, e[1].text, e[2].text, e[3].text];

        console.log(e);
        console.log(inputs);
        console.log("Building Parameter object");
        for (var i = 0; i<inputs.length; i++) {
            console.log("For Loop: ");
            if (!(inputs[i] in reference)) {
                console.log(inputs[i]);
                parms[reference[dataMap[i]]] = (reference[dataMap[i]] == 'classification') ? classMap[inputs[i]].split(" and ") : inputs[i].split(" and ");
            }
        }

        // FOR EACH
            // SPLIT ON SPACE
                // JOIN WITH +

        // Store Parameters
        console.log(parms);
        $sessionStorage.params = parms;

        $http.post('/foodQuery', {
            params: parms,
            'distribution_pattern': $scope.stateCode,
            'status': "Ongoing"
        })
        .success(function(results) {
            var data = JSON.parse(results);

            // No Results
            if ('error' in data) {
                console.log("ERROR");

                // PopOver
                var button = angular.element(document.querySelector(".Bam"));
                button.popover({
                    "placement":'top',
                    html: true
                }).popover('show');
                setTimeout(function() {
                    button.popover('hide');
                }, 3000);

            } else {

                // Search Criteria
                $sessionStorage.state = $scope.state;
                if ('classification' in parms) $sessionStorage.classification = parms['classification'];
                if ('product_description' in parms) $sessionStorage.product_description = parms['product_description'];
                if ('recalling_firm' in parms) $sessionStorage.recalling_firm = parms['recalling_firm'];

                // Results
                $sessionStorage.results = data['results'];
                $sessionStorage.quantity = data['meta']['results']['total'];
                window.location = '/#/recalls/';
            }
        })
        .error(function(data){
            console.log("Error making request: " + data);
        });
    };
}]);<commit_msg>IE debug code<commit_after>'use strict';

/* Controllers */

var rdControllers = angular.module('rdControllers', []);

// ------------------------------
// ----- Temp Controller --------
// ------------------------------
rdControllers.controller('tempCtrl', ['$scope', '$sessionStorage', function($scope, $sessionStorage) {
    console.log("Temp Controller!");

    // Clear local Storage
    $sessionStorage.$reset();
}]);

// ------------------------------
// ------ Map Controller --------
// ------------------------------
rdControllers.controller('mapCtrl', ['$scope', '$sessionStorage', 'Map', 'Browser', function($scope, $sessionStorage, Map, Browser) {
    console.log("Map Controller!");

    // Covert Lat & Long coordinates into State
    function codeLatLng(coordinate) {
        // Declarations
        var geocoder = new google.maps.Geocoder();
        var state = '', address = '', code = '';
        var states = Map.getData();

        geocoder.geocode({'latLng': coordinate}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    state = results[5].formatted_address.split(",")[0];
                    address = results[0].formatted_address;
                    code = states[state];
                    window.location = '/#/form/'+state + '/' + code;

                    // End Loading animation and render the page
                    var body = angular.element(document.querySelector("body"));
                    body.addClass('loaded');
                } else {
                    alert('No results found');
                }
            } else {
                alert('Geocoder failed due to: ' + status);
            }
        });
    }

    // Get User's Latitude & Longitude
    function success(position) {
        console.log("Got Location!");
        var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        codeLatLng(latlng);
    }

    function error(msg) {
        console.log("Could not gain access to User Location: " + msg);

        // End Loading animation and render the page
        var body = angular.element(document.querySelector("body"));
        body.addClass('loaded');
    }

    // Initiate process of receiving user location
    if (Browser.isSafari()) {
        error('Safari problems');
    } else {
        // Ask for Location
        if (navigator.geolocation) {
            // Get user input (Allow || Do not allow)
            navigator.geolocation.getCurrentPosition(success, error);

            // FailSafe for IE Firefox
            setTimeout(function(){
                var body = angular.element(document.querySelector("body"));
                body.addClass('loaded');
            }, 4500);
        } else {
            error('Browser does not support geolocation');
        }
    }
}]);

// ------------------------------
// ----- Results Controller -----
// ------------------------------
rdControllers.controller('resultsCtrl', ['$scope', '$sessionStorage', 'MonthMap', function($scope, $sessionStorage, MonthMap) {
    console.log("Results Controller!");

    // Grab Search Parameters
    if ($sessionStorage.classification) $scope.classification = $sessionStorage.classification[0];
    if ($sessionStorage.recalling_firm) $scope.recalling_firm = $sessionStorage.recalling_firm.join(" and ");
    if ($sessionStorage.product_description) $scope.product_description = $sessionStorage.product_description.join(" and ");

    // Grab results
    $scope.totalRecalls = $sessionStorage.results;

    // Initialize number -> month
    var monthMap = MonthMap.getData();

    // Format Output
    function prettify(recalls) {
        // Make Date pretty
        for (var i =0; i<recalls.length; i++) {
            var date = recalls[i]['report_date'];
            date = monthMap[date.substring(4,6)] + " " + date.substring(6) + ", " + date.substring(0,4);
            recalls[i]['report_date']= date;
        }
    }

    // Sort by date
    $scope.totalRecalls.sort(function(a, b) {
        if (a.report_date > b.report_date) return -1;
        if (a.report_date < b.report_date) return 1;
        return 0;
    });

    // Convert UTC dates to User-Friendly one (IE doesn't support ForEach loops)
    //$scope.totalRecalls.forEach(prettify);
    prettify($scope.totalRecalls);

    // Bind Results to front-end HTML elements
    $scope.state = $sessionStorage.state;
    $scope.quantity = $sessionStorage.quantity;
    $scope.orderProp = 'report_date';

    // Infinite Scroll
    var index = 10;
    var appendedItems = []
    $scope.recalls = $scope.totalRecalls.slice(0,10);
    $scope.loadMore = function() {
        appendedItems = $scope.totalRecalls.slice(index, index+10);
        $scope.recalls = $scope.recalls.concat(appendedItems);
        index+=10;
    }
}]);

// ------------------------------
// ----- Form Controller --------
// ------------------------------
rdControllers.controller('formCtrl', ['$scope', '$sessionStorage', '$routeParams', '$http', 'ClassMap', 'Validation', function($scope, $sessionStorage, $routeParams, $http, ClassMap, Validation) {
    $scope.recalls = "";
    $scope.state = $routeParams.state;
    $scope.stateCode = $routeParams.stateCode;
    var previousParams = $sessionStorage.params;
    var dataMap = {0: 'food', 1: 'brand', 2: 'all', 3: 'anything'};
    var reference = {
        "food": "product_description",
        "brand": "recalling_firm",
        "all": "classification",
        "anything": "reason_for_recall"
    };

    if (!Validation.isEmpty(previousParams)) {
        $scope.food = (previousParams['product_description'] ? previousParams['product_description'].join(' and ') : 'food');
        $scope.brand = (previousParams['recalling_firm'] ? previousParams['recalling_firm'].join(' and ') : 'brand');
    }

    // Initialize text -> classifications
    var classMap = ClassMap.getData();

    // Helpful Tooltip displays only if not already seen
    if (!$sessionStorage.seen) {
        var button = angular.element(document.querySelector("#hint"));
        setTimeout(function() {
            button.popover({
                "placement":'bottom',
                html: true
            }).popover('show');
        }, 250);
        setTimeout(function() {
            button.popover('hide');
        }, 5000);
    }

    // PAGE READY

    // process the form
    $scope.processForm = function() {
        // User has figured it out
        $sessionStorage.seen = true;

        /*
        function joinPlus(element, index, array) {
            console.log(element);
            console.log(element.split(" ").join("+"));
            return element.split(" ").join("+")
        }*/

        // Find the Form elements
        var parms = {};
        var e = angular.element(document.querySelectorAll(".nl-field-toggle"));
        var inputs = [e[0].text, e[1].text, e[2].text, e[3].text];

        console.log(e);
        console.log(e[0].text);
        console.log(e[0].textContent);
        console.log(e[0].html);
        console.log(inputs);
        console.log("Building Parameter object");
        for (var i = 0; i<inputs.length; i++) {
            console.log("For Loop: ");
            if (!(inputs[i] in reference)) {
                console.log(inputs[i]);
                parms[reference[dataMap[i]]] = (reference[dataMap[i]] == 'classification') ? classMap[inputs[i]].split(" and ") : inputs[i].split(" and ");
            }
        }

        // FOR EACH
            // SPLIT ON SPACE
                // JOIN WITH +

        // Store Parameters
        console.log(parms);
        $sessionStorage.params = parms;

        $http.post('/foodQuery', {
            params: parms,
            'distribution_pattern': $scope.stateCode,
            'status': "Ongoing"
        })
        .success(function(results) {
            var data = JSON.parse(results);

            // No Results
            if ('error' in data) {
                console.log("ERROR");

                // PopOver
                var button = angular.element(document.querySelector(".Bam"));
                button.popover({
                    "placement":'top',
                    html: true
                }).popover('show');
                setTimeout(function() {
                    button.popover('hide');
                }, 3000);

            } else {

                // Search Criteria
                $sessionStorage.state = $scope.state;
                if ('classification' in parms) $sessionStorage.classification = parms['classification'];
                if ('product_description' in parms) $sessionStorage.product_description = parms['product_description'];
                if ('recalling_firm' in parms) $sessionStorage.recalling_firm = parms['recalling_firm'];

                // Results
                $sessionStorage.results = data['results'];
                $sessionStorage.quantity = data['meta']['results']['total'];
                window.location = '/#/recalls/';
            }
        })
        .error(function(data){
            console.log("Error making request: " + data);
        });
    };
}]);<|endoftext|>


<commit_before>/*********************************************
 *  Copyright (c) 2013 AnsibleWorks, Inc.
 *
 */

angular.module('AccessHelper', ['RestServices', 'Utilities', 'ngCookies'])
    .factory('CheckAccess', ['$rootScope', 'Alert', 'Rest', 'GetBasePath','ProcessErrors',
    function($rootScope, Alert, Rest, GetBasePath, ProcessErrors) {
    return function(params) {
       // set PermissionAddAllowed to true or false based on user access. admins and org admins are granted
       // accesss.
       var me = $rootScope.current_user;
       var scope = params.scope;

       if (me.is_superuser) {
          scope.PermissionAddAllowed = true;
       }
       else {
          if (me.related.admin_of_organizations) {
             Rest.setUrl(me.related.admin_of_organizations);
             Rest.get()
                 .success( function(data, status, headers, config) {
                     if (data.results.length > 0) {
                        scope.PermissionAddAllowed = true;
                     }
                     else {
                        scope.PermissionAddAllowed = false;
                     }
                 })
                 .error( function(data, status, headers, config) {
                     ProcessErrors(scope, data, status, null,
                         { hdr: 'Error!', msg: 'Call to ' + me.related.admin_of_organizations +
                         ' failed. DELETE returned status: ' + status });
                     });
          }
       }
       //if (!access) {
       //   Alert('Access Denied', 'You do not have access to this function. Please contact your system administrator.');
       //}
       //return access;
    }
    }])

    .factory('CheckLicense', ['$rootScope', '$cookieStore', 'Alert', '$location', 'Authorization',
    function($rootScope, $cookieStore, Alert, $location, Authorization) {
    return function() {
        // Check license status and alert the user, if needed
        var status = 'success';
        var hdr, msg;
        var license = $cookieStore.get('license');
        if (license && !Authorization.licenseTested()) {
           // This is our first time evaluating the license
           license['tested'] = true;
           $cookieStore.remove('license');
           $cookieStore.put('license', license);
           $rootScope.license_tested = true;
           if (license['valid_key'] !== undefined && license['valid_key'] == false) {
              // The license is invalid. Stop the user from logging in.
              status = 'alert-danger';
              hdr = 'License Error';
              msg = 'Something is wrong with your /etc/awx/license file on this server. ' +
                    'Please contact info@ansibleworks.com for assistance.';
              //action = function() { window.location = '#/logout'; };
              Alert(hdr, msg, status, null, false, true);
           }
           else if (license['demo'] !== undefined && license['demo'] == true) {
              // demo
              status = 'alert-info';
              hdr = 'AWX Demo';
              msg = 'Thank you for trying AnsibleWorks AWX. You can use this edition to manage up to 10 hosts free. ' +
                    'Should you wish to acquire a license for additional servers, please ' +
                    'visit the AnsibleWorks online store, or ' +
                    'contact info@ansibleworks.com for assistance.';
              Alert(hdr, msg, status);
           }
           if (license['date_warning'] !== undefined && license['date_warning'] == true) {
              status = 'alert-info';
              hdr = 'License Expired';
              msg = 'Your AnsibleWorks AWX License has expired and is no longer compliant. ' +
                    'You can continue, but you will be unable to add any additional hosts. Please ' +
                    'visit the AnsibleWorks online store ' +
                    'for license and renewal information, or contact info@ansibleworks.com ' +
                    'for assistance.';
              Alert(hdr, msg, status);
           }
           if (license['free_instances'] !== undefined && parseInt(license['free_instances']) <= 0) {
              status = 'alert-info';
              hdr = 'License Warning';
              msg = 'Your AnsibleWorks AWX License has reached capacity for the number of managed ' +
                    'hosts allowed. You will not be able to add any additional hosts. To extend your license, please ' +
                    'visit the AnsibleWorks online store, or ' +
                    'contact info@ansibleworks.com for more information.';
              Alert(hdr, msg, status, null, true);
           }
        }
    }
    }]);
<commit_msg>AC-616 Fixed date warning vs. date expired message. The CheckLicense routine now looks for date_expired flag.<commit_after>/*********************************************
 *  Copyright (c) 2013 AnsibleWorks, Inc.
 *
 */

angular.module('AccessHelper', ['RestServices', 'Utilities', 'ngCookies'])
    .factory('CheckAccess', ['$rootScope', 'Alert', 'Rest', 'GetBasePath','ProcessErrors',
    function($rootScope, Alert, Rest, GetBasePath, ProcessErrors) {
    return function(params) {
       // set PermissionAddAllowed to true or false based on user access. admins and org admins are granted
       // accesss.
       var me = $rootScope.current_user;
       var scope = params.scope;

       if (me.is_superuser) {
          scope.PermissionAddAllowed = true;
       }
       else {
          if (me.related.admin_of_organizations) {
             Rest.setUrl(me.related.admin_of_organizations);
             Rest.get()
                 .success( function(data, status, headers, config) {
                     if (data.results.length > 0) {
                        scope.PermissionAddAllowed = true;
                     }
                     else {
                        scope.PermissionAddAllowed = false;
                     }
                 })
                 .error( function(data, status, headers, config) {
                     ProcessErrors(scope, data, status, null,
                         { hdr: 'Error!', msg: 'Call to ' + me.related.admin_of_organizations +
                         ' failed. DELETE returned status: ' + status });
                     });
          }
       }
       //if (!access) {
       //   Alert('Access Denied', 'You do not have access to this function. Please contact your system administrator.');
       //}
       //return access;
    }
    }])

    .factory('CheckLicense', ['$rootScope', '$cookieStore', 'Alert', '$location', 'Authorization',
    function($rootScope, $cookieStore, Alert, $location, Authorization) {
    return function() {
        // Check license status and alert the user, if needed
        var status = 'success';
        var hdr, msg;
        var license = $cookieStore.get('license');
        if (license && !Authorization.licenseTested()) {
           // This is our first time evaluating the license
           license['tested'] = true;
           $cookieStore.remove('license');
           $cookieStore.put('license', license);
           $rootScope.license_tested = true;
           if (license['valid_key'] !== undefined && license['valid_key'] == false) {
              // The license is invalid. Stop the user from logging in.
              status = 'alert-danger';
              hdr = 'License Error';
              msg = 'Something is wrong with your /etc/awx/license file on this server. ' +
                    'Please contact info@ansibleworks.com for assistance.';
              //action = function() { window.location = '#/logout'; };
              Alert(hdr, msg, status, null, false, true);
           }
           else if (license['demo'] !== undefined && license['demo'] == true) {
              // demo
              status = 'alert-info';
              hdr = 'AWX Demo';
              msg = 'Thank you for trying AnsibleWorks AWX. You can use this edition to manage up to 10 hosts free. ' +
                    'Should you wish to acquire a license for additional servers, please ' +
                    'visit the AnsibleWorks online store, or ' +
                    'contact info@ansibleworks.com for assistance.';
              Alert(hdr, msg, status);
           }
           if (license['date_expired'] !== undefined && license['date_expired'] == true) {
              // expired
              status = 'alert-info';
              hdr = 'AWX License Expired';
              msg = 'Your AnsibleWorks AWX License has expired and is no longer compliant. ' +
                    'You can continue, but you will be unable to add any additional hosts. Please ' +
                    'visit the AnsibleWorks online store ' +
                    'for license and renewal information, or contact info@ansibleworks.com ' +
                    'for assistance.';
              Alert(hdr, msg, status);
           }
           else if (license['date_warning'] !== undefined && license['date_warning'] == true) {
              status = 'alert-info';
              hdr = 'AWX License Warning';
              msg = 'Your AnsibleWorks AWX License is about to expire. To extend your license, please ' +
                    'visit the AnsibleWorks online store, or ' +
                    'contact info@ansibleworks.com for more information.';
              Alert(hdr, msg, status);
           }
           if (license['free_instances'] !== undefined && parseInt(license['free_instances']) <= 0) {
              status = 'alert-info';
              hdr = 'License Warning';
              msg = 'Your AnsibleWorks AWX License has reached capacity for the number of managed ' +
                    'hosts allowed. You will not be able to add any additional hosts. To extend your license, please ' +
                    'visit the AnsibleWorks online store, or ' +
                    'contact info@ansibleworks.com for more information.';
              Alert(hdr, msg, status, null, true);
           }
        }
    }
    }]);
<|endoftext|>


<commit_before>angular.module('myApp')
.directive('wtVideo', [ function() {
  return {
    replace: true,
    restrict: "E",
    templateUrl: "templates/directives/wt-video.html",
    scope: {
     src: "@",
     video: "@"
    },
    link: function(scope, element, attrs, controller){
      console.log(element);
      scope.$watch("video", function(value){
        ///console.log(value, element, scope);
        console.log(element["context"]["currentTime"]);
      });
    }

  };
}]);
<commit_msg>Clean up wtVideo directive.<commit_after>angular.module('myApp')
.directive('wtVideo', [ function() {
  return {
    replace: true,
    restrict: "E",
    templateUrl: "templates/directives/wt-video.html",
    scope: {
     src: "@",
     video: "@"
    },
    link: function(scope, element, attrs, controller){

    }

  };
}]);
<|endoftext|>