<commit_before>;(function($){
/**
 * jqGrid Serbian Translation
 * Александар Миловац(Aleksandar Milovac) aleksandar.milovac@gmail.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = $.jgrid || {};
$.extend($.jgrid,{
	defaults : {
		recordtext: "Преглед {0} - {1} од {2}",
		emptyrecords: "Не постоји ниједан запис",
		loadtext: "Учитавање...",
		pgtext : "Страна {0} од {1}"
	},
	search : {
		caption: "Тражење...",
		Find: "Тражи",
		Reset: "Ресетуј",
		odata: [{ oper:'eq', text:"једнако"},{ oper:'ne', text:"није једнако"},{ oper:'lt', text:"мање"},{ oper:'le', text:"мање или једнако"},{ oper:'gt', text:"веће"},{ oper:'ge', text:"веће или једнако"},{ oper:'bw', text:"почиње са"},{ oper:'bn', text:"не почиње са"},{ oper:'in', text:"је у"},{ oper:'ni', text:"није у"},{ oper:'ew', text:"завршава са"},{ oper:'en', text:"не завршава са"},{ oper:'cn', text:"садржи"},{ oper:'nc', text:"не садржи"},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}],
		groupOps: [	{ op: "И", text: "сви" },	{ op: "ИЛИ",  text: "сваки" }	],
		operandTitle : "Click to select search operation.",
		resetTitle : "Reset Search Value"
	},
	edit : {
		addCaption: "Додај запис",
		editCaption: "Измени запис",
		bSubmit: "Пошаљи",
		bCancel: "Одустани",
		bClose: "Затвори",
		saveData: "Податак је измењен! Сачувај измене?",
		bYes : "Да",
		bNo : "Не",
		bExit : "Одустани",
		msg: {
			required:"Поље је обавезно",
			number:"Молим, унесите исправан број",
			minValue:"вредност мора бити већа од или једнака са ",
			maxValue:"вредност мора бити мања од или једнака са",
			email: "није исправна имејл адреса",
			integer: "Молим, унесите исправну целобројну вредност ",
			date: "Молим, унесите исправан датум",
			url: "није исправан УРЛ. Потребан је префикс ('http://' or 'https://')",
			nodefined : " није дефинисан!",
			novalue : " захтевана је повратна вредност!",
			customarray : "Custom function should return array!",
			customfcheck : "Custom function should be present in case of custom checking!"

		}
	},
	view : {
		caption: "Погледај запис",
		bClose: "Затвори"
	},
	del : {
		caption: "Избриши",
		msg: "Избриши изабран(е) запис(е)?",
		bSubmit: "Ибриши",
		bCancel: "Одбаци"
	},
	nav : {
		edittext: "",
		edittitle: "Измени изабрани ред",
		addtext:"",
		addtitle: "Додај нови ред",
		deltext: "",
		deltitle: "Избриши изабран ред",
		searchtext: "",
		searchtitle: "Нађи записе",
		refreshtext: "",
		refreshtitle: "Поново учитај податке",
		alertcap: "Упозорење",
		alerttext: "Молим, изаберите ред",
		viewtext: "",
		viewtitle: "Погледај изабрани ред"
	},
	col : {
		caption: "Изабери колоне",
		bSubmit: "ОК",
		bCancel: "Одбаци"
	},
	errors : {
		errcap : "Грешка",
		nourl : "Није постављен URL",
		norecords: "Нема записа за обраду",
		model : "Дужина модела colNames <> colModel!"
	},
	formatter : {
		integer : {thousandsSeparator: " ", defaultValue: '0'},
		number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
		currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
		date : {
			dayNames:   [
				"Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб",
				"Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"
			],
			monthNames: [
				"Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец",
				"Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"
			],
			AmPm : ["am","pm","AM","PM"],
			S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'},
			srcformat: 'Y-m-d',
			newformat: 'd/m/Y',
			parseRe : /[#%\\\/:_;.,\t\s-]/,
			masks : {
				ISO8601Long:"Y-m-d H:i:s",
				ISO8601Short:"Y-m-d",
				ShortDate: "n/j/Y",
				LongDate: "l, F d, Y",
				FullDateTime: "l, F d, Y g:i:s A",
				MonthDay: "F d",
				ShortTime: "g:i A",
				LongTime: "g:i:s A",
				SortableDateTime: "Y-m-d\\TH:i:s",
				UniversalSortableDateTime: "Y-m-d H:i:sO",
				YearMonth: "F, Y"
			},
			reformatAfterEdit : false
		},
		baseLinkUrl: '',
		showAction: '',
		target: '',
		checkbox : {disabled:true},
		idName : 'id'
	}
});
})(jQuery);
<commit_msg>-- fix<commit_after>unction($){
/**
 * jqGrid Serbian Translation
 * Александар Миловац(Aleksandar Milovac) aleksandar.milovac@gmail.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = $.jgrid || {};
$.extend($.jgrid,{
	defaults : {
		recordtext: "Преглед {0} - {1} од {2}",
		emptyrecords: "Не постоји ниједан запис",
		loadtext: "Учитавање...",
		pgtext : "Страна {0} од {1}"
	},
	search : {
		caption: "Тражење...",
		Find: "Тражи",
		Reset: "Ресетуј",
		odata: [{ oper:'eq', text:"једнако"},{ oper:'ne', text:"није једнако"},{ oper:'lt', text:"мање"},{ oper:'le', text:"мање или једнако"},{ oper:'gt', text:"веће"},{ oper:'ge', text:"веће или једнако"},{ oper:'bw', text:"почиње са"},{ oper:'bn', text:"не почиње са"},{ oper:'in', text:"је у"},{ oper:'ni', text:"није у"},{ oper:'ew', text:"завршава са"},{ oper:'en', text:"не завршава са"},{ oper:'cn', text:"садржи"},{ oper:'nc', text:"не садржи"},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}],
		groupOps: [	{ op: "И", text: "сви" },	{ op: "ИЛИ",  text: "сваки" }	],
		operandTitle : "Click to select search operation.",
		resetTitle : "Reset Search Value"
	},
	edit : {
		addCaption: "Додај запис",
		editCaption: "Измени запис",
		bSubmit: "Пошаљи",
		bCancel: "Одустани",
		bClose: "Затвори",
		saveData: "Податак је измењен! Сачувај измене?",
		bYes : "Да",
		bNo : "Не",
		bExit : "Одустани",
		msg: {
			required:"Поље је обавезно",
			number:"Молим, унесите исправан број",
			minValue:"вредност мора бити већа од или једнака са ",
			maxValue:"вредност мора бити мања од или једнака са",
			email: "није исправна имејл адреса",
			integer: "Молим, унесите исправну целобројну вредност ",
			date: "Молим, унесите исправан датум",
			url: "није исправан УРЛ. Потребан је префикс ('http://' or 'https://')",
			nodefined : " није дефинисан!",
			novalue : " захтевана је повратна вредност!",
			customarray : "Custom function should return array!",
			customfcheck : "Custom function should be present in case of custom checking!"

		}
	},
	view : {
		caption: "Погледај запис",
		bClose: "Затвори"
	},
	del : {
		caption: "Избриши",
		msg: "Избриши изабран(е) запис(е)?",
		bSubmit: "Ибриши",
		bCancel: "Одбаци"
	},
	nav : {
		edittext: "",
		edittitle: "Измени изабрани ред",
		addtext:"",
		addtitle: "Додај нови ред",
		deltext: "",
		deltitle: "Избриши изабран ред",
		searchtext: "",
		searchtitle: "Нађи записе",
		refreshtext: "",
		refreshtitle: "Поново учитај податке",
		alertcap: "Упозорење",
		alerttext: "Молим, изаберите ред",
		viewtext: "",
		viewtitle: "Погледај изабрани ред"
	},
	col : {
		caption: "Изабери колоне",
		bSubmit: "ОК",
		bCancel: "Одбаци"
	},
	errors : {
		errcap : "Грешка",
		nourl : "Није постављен URL",
		norecords: "Нема записа за обраду",
		model : "Дужина модела colNames <> colModel!"
	},
	formatter : {
		integer : {thousandsSeparator: " ", defaultValue: '0'},
		number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
		currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
		date : {
			dayNames:   [
				"Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб",
				"Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"
			],
			monthNames: [
				"Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец",
				"Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"
			],
			AmPm : ["am","pm","AM","PM"],
			S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'},
			srcformat: 'Y-m-d',
			newformat: 'd/m/Y',
			parseRe : /[#%\\\/:_;.,\t\s-]/,
			masks : {
				ISO8601Long:"Y-m-d H:i:s",
				ISO8601Short:"Y-m-d",
				ShortDate: "n/j/Y",
				LongDate: "l, F d, Y",
				FullDateTime: "l, F d, Y g:i:s A",
				MonthDay: "F d",
				ShortTime: "g:i A",
				LongTime: "g:i:s A",
				SortableDateTime: "Y-m-d\\TH:i:s",
				UniversalSortableDateTime: "Y-m-d H:i:sO",
				YearMonth: "F, Y"
			},
			reformatAfterEdit : false
		},
		baseLinkUrl: '',
		showAction: '',
		target: '',
		checkbox : {disabled:true},
		idName : 'id'
	}
});
})(jQuery);
<|endoftext|>


<commit_before>/**
 *  Every object can be serialized to json
 **/
!function (exports) {
    'use strict;'

    var toString = Object.prototype.toString,
        slice = Array.prototype.slice,
        objType = function (obj) {
            return toString.call(obj).match(/\[object ([a-zA-Z]+)\]/)[1];
        };

    function textOmit (text) {
        var len = text.length;
        if (len > 70) {
            text = text.substr(0, 30) + ' ... ' + text.substr(len - 30, len - 1);
        }
        return text;
    }

    function jsonify (obj) {
        var jsonObj,
            type = objType(obj);

        try {
            if (type == 'Undefined') {
                jsonObj = 'undefined';
            } else if (obj !== obj) {
                jsonObj = 'NaN';
            } else {
                jsonObj = JSON.parse(JSON.stringify(obj));
            }

        } catch (e) {
            if (type.match('Element')) {
                jsonObj = obj.outerHTML.replace(obj.innerHTML, '');
            } else if (type == 'Text') {
                jsonObj = textOmit(obj.textContent);
            } else if (type == 'Array' || type == 'NodeList') {
                var array = [];
                obj = slice.call(obj);

                obj.forEach(function (item) {
                    array.push(jsonify(item));
                });
                jsonObj = array;
            } else if (type == 'Object') {
                var keys = Object.keys(obj),
                    object = {};
                keys.forEach(function (key) {
                    object[key] = jsonify(obj[key]);
                });
                jsonObj = object;
            } else if (type == 'Function') {
                jsonObj = textOmit(obj.toString());
            } else if (type == 'global' || type == 'HTMLDocument') {
                var keys = Object.keys(obj),
                    object = {};
                keys.forEach(function (key) {
                    object[key] = objType(obj[key]);
                });
                jsonObj = object;
            } else {
                jsonObj = toString.call(obj);
            }
        }

        return jsonObj;
    }

    exports.jsonify = jsonify;
}(this);<commit_msg>console.log support view whose are not json object with secound levels<commit_after>/**
 *  Every object can be serialized to json
 **/
!function (exports) {
    'use strict;'

    var toString = Object.prototype.toString,
        slice = Array.prototype.slice,
        objType = function (obj) {
            return toString.call(obj).match(/\[object ([a-zA-Z]+)\]/)[1];
        };

    function textOmit (text) {
        var len = text.length;
        if (len > 70) {
            text = text.substr(0, 30) + ' ... ' + text.substr(len - 30, len - 1);
        }
        return text;
    }

    function jsonify (obj, _time) {
        var jsonObj,
            type = objType(obj);

        !_time && (_time = 0);
        try {
            if (type == 'Undefined') {
                jsonObj = undefined;
            } else if (obj !== obj) {
                jsonObj = 'NaN';
            } else if (type == 'String') {
                jsonObj = textOmit(obj);
            } else if (type == 'Null' || type == 'Number' || type == 'Boolean') {
                jsonObj = obj;
            } else {
                jsonObj = JSON.parse(JSON.stringify(obj));
            }

        } catch (e) {
            if (type.match('Element')) {
                jsonObj = obj.outerHTML.replace(obj.innerHTML, '');
            } else if (type == 'Text') {
                jsonObj = textOmit(obj.textContent);
            } else if (type == 'Array' || type == 'NodeList') {
                var array = [];
                obj = slice.call(obj);

                obj.forEach(function (item) {
                    if (_time >= 2 ) {
                        array.push(objType(item))
                    } else {
                        array.push(jsonify(item, _time + 1));
                    }
                });
                jsonObj = array;
            } else if (type == 'Object' || type == 'global' || type == 'HTMLDocument') {
                var keys = Object.keys(obj),
                    object = {};
                keys.forEach(function (key) {
                    if (!obj.hasOwnProperty(key)) return
                    if (_time >= 2 ) {
                        object[key] = (objType(obj[key]))
                    } else {
                        object[key] = jsonify(obj[key], _time + 1);
                    }
                });
                jsonObj = object;
            } else if (type == 'Function') {
                jsonObj = textOmit(obj.toString());
            } else {
                jsonObj = toString.call(obj);
            }
        }
        return jsonObj;
    }

    exports.jsonify = jsonify;
}(this);<|endoftext|>


<commit_before>// Copyright ScenPro, Inc 2007

// $Header: /cvsshare/content/cvsroot/cdecurate/WebRoot/js/VDPVS.js,v 1.5 2008-12-18 16:56:22 chickerura Exp $
// $Name: not supported by cvs2svn $

 var altWindow = "";

 function SearchCDValue()
 {
 	var contObj = document.getElementById('selContext');
 	var contText = "";
 	if (contObj != null)
    	contText = contObj[contObj.selectedIndex].text;
 //   var vAction = document.getElementById('VDAction').value;
 //   if (contObj[selIdx].text == "" && vAction != "BlockEdit")
 //     alert("Please select a context first");
 //   else
 //   {
      document.SearchActionForm.searchComp.value = "ConceptualDomain";
      document.SearchActionForm.SelContext.value = "";  //contText contObj.options[contObj.selectedIndex].text;   //get the context
      document.SearchActionForm.isValidSearch.value = "false";

      if (searchWindow && !searchWindow.closed)
        searchWindow.close()
      searchWindow = window.open("jsp/OpenSearchWindow.jsp", "searchWindow", "width=775,height=700,top=0,left=0,resizable=yes,scrollbars=yes")
 //   }
 }

 function DisableButtons()
 {
	//make the status message visible
	window.status = "Validating data, it may take a minute, please wait.....";
	var msgObj = document.getElementById("Message");
	if (msgObj != null)
	   msgObj.style.visibility="visible";

    //disable the buttons
 	var valObj = document.getElementById('btnValidate');
 	if (valObj != null)
    	valObj.disabled = true;

 	var clrObj = document.getElementById('btnClear');
 	if (clrObj != null)
    	clrObj.disabled = true;

 	var bkObj = document.getElementById('btnBack');
 	if (bkObj != null)
    	bkObj.disabled = true;

 	var dtlObj = document.getElementById('btnDetails');
 	if (dtlObj != null)
    	dtlObj.disabled = true;

 	var altObj = document.getElementById('btnAltName');
 	if (altObj != null)
    	altObj.disabled = true;

 	var refObj = document.getElementById('btnRefDoc');
 	if (refObj != null)
    	refObj.disabled = true;
 }

  function openBEDisplayWindow()
  {
    var evsWindow = "";
    if (evsWindow && !evsWindow.closed)
      evsWindow.focus();
    else
    {
      evsWindow = window.open("jsp/OpenBlockEditWindow.jsp", "BEWindow", "width=750,height=350,top=0,left=0,resizable=yes,scrollbars=yes");
    }
  }

  //open alternate names reference document window
  function openDesignateWindowVM(sType, vmID)
  {
    if (altWindow && !altWindow.closed)
      altWindow.close();
    document.SearchActionForm.isValidSearch.value = "false";
    document.SearchActionForm.itemType.value = sType
 // alert(" depage " + sType);
    //var windowW = screen.width - 410;
    if (sType == "Alternate Names")
        altWindow = window.open("../../cdecurate/NCICurationServlet?reqType=AltNamesDefs&searchEVS=ValueMeaning" + "&vmID=" + vmID, "designate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
    else
        altWindow = window.open("jsp/EditDesignateDE.jsp", "designate", "width=700,height=650,top=0,left=0,resizable=yes,scrollbars=yes");
  }

  //open alternate names reference document window
  function openDesignateWindow(sType)
  {
    if (altWindow && !altWindow.closed)
      altWindow.close();
    document.SearchActionForm.isValidSearch.value = "false";
    document.SearchActionForm.itemType.value = sType
 // alert(" depage " + sType);
    //var windowW = screen.width - 410;
    if (sType == "Alternate Names")
        altWindow = window.open("../../cdecurate/NCICurationServlet?reqType=AltNamesDefs&searchEVS=" + document.SearchActionForm.searchEVS.value, "designate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
    else
        altWindow = window.open("jsp/EditDesignateDE.jsp", "designate", "width=700,height=650,top=0,left=0,resizable=yes,scrollbars=yes");
  }

//open viewonly refe doc
function openRefDocViewWindow()
{
	var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=getRefDocument&acID="+document.SearchActionForm.acID.value, "ReferenceDocuments", "width=700,height=300,top=0,left=0,resizable=yes,scrollbars=yes");
}

//open viewonly alt name with something to tell view
function openAltNameViewWindow()
{
	var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=getAltNames&acID="+document.SearchActionForm.acID.value, "AlternateNames", "width=700,height=300,top=0,left=0,resizable=yes,scrollbars=yes");
	//var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=viewAltNamesDefs&searchEVS=" + document.SearchActionForm.searchEVS.value, "viewDesignate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
}

 //change the tabs
 function changeTab(tab)
 {
    document.createVDForm.action = "../../cdecurate/NCICurationServlet?reqType=viewVDPVSTab&vdpvstab=" +tab;
    document.createVDForm.submit();
 }<commit_msg>view VD page<commit_after>// Copyright ScenPro, Inc 2007

// $Header: /cvsshare/content/cvsroot/cdecurate/WebRoot/js/VDPVS.js,v 1.6 2009-01-06 21:04:06 veerlah Exp $
// $Name: not supported by cvs2svn $

 var altWindow = "";

 function SearchCDValue()
 {
 	var contObj = document.getElementById('selContext');
 	var contText = "";
 	if (contObj != null)
    	contText = contObj[contObj.selectedIndex].text;
 //   var vAction = document.getElementById('VDAction').value;
 //   if (contObj[selIdx].text == "" && vAction != "BlockEdit")
 //     alert("Please select a context first");
 //   else
 //   {
      document.SearchActionForm.searchComp.value = "ConceptualDomain";
      document.SearchActionForm.SelContext.value = "";  //contText contObj.options[contObj.selectedIndex].text;   //get the context
      document.SearchActionForm.isValidSearch.value = "false";

      if (searchWindow && !searchWindow.closed)
        searchWindow.close()
      searchWindow = window.open("jsp/OpenSearchWindow.jsp", "searchWindow", "width=775,height=700,top=0,left=0,resizable=yes,scrollbars=yes")
 //   }
 }

 function DisableButtons()
 {
	//make the status message visible
	window.status = "Validating data, it may take a minute, please wait.....";
	var msgObj = document.getElementById("Message");
	if (msgObj != null)
	   msgObj.style.visibility="visible";

    //disable the buttons
 	var valObj = document.getElementById('btnValidate');
 	if (valObj != null)
    	valObj.disabled = true;

 	var clrObj = document.getElementById('btnClear');
 	if (clrObj != null)
    	clrObj.disabled = true;

 	var bkObj = document.getElementById('btnBack');
 	if (bkObj != null)
    	bkObj.disabled = true;

 	var dtlObj = document.getElementById('btnDetails');
 	if (dtlObj != null)
    	dtlObj.disabled = true;

 	var altObj = document.getElementById('btnAltName');
 	if (altObj != null)
    	altObj.disabled = true;

 	var refObj = document.getElementById('btnRefDoc');
 	if (refObj != null)
    	refObj.disabled = true;
 }

  function openBEDisplayWindow()
  {
    var evsWindow = "";
    if (evsWindow && !evsWindow.closed)
      evsWindow.focus();
    else
    {
      evsWindow = window.open("jsp/OpenBlockEditWindow.jsp", "BEWindow", "width=750,height=350,top=0,left=0,resizable=yes,scrollbars=yes");
    }
  }

  //open alternate names reference document window
  function openDesignateWindowVM(sType, vmID)
  {
    if (altWindow && !altWindow.closed)
      altWindow.close();
    document.SearchActionForm.isValidSearch.value = "false";
    document.SearchActionForm.itemType.value = sType
 // alert(" depage " + sType);
    //var windowW = screen.width - 410;
    if (sType == "Alternate Names")
        altWindow = window.open("../../cdecurate/NCICurationServlet?reqType=AltNamesDefs&searchEVS=ValueMeaning" + "&vmID=" + vmID, "designate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
    else
        altWindow = window.open("jsp/EditDesignateDE.jsp", "designate", "width=700,height=650,top=0,left=0,resizable=yes,scrollbars=yes");
  }

  //open alternate names reference document window
  function openDesignateWindow(sType)
  {
    if (altWindow && !altWindow.closed)
      altWindow.close();
    document.SearchActionForm.isValidSearch.value = "false";
    document.SearchActionForm.itemType.value = sType
 // alert(" depage " + sType);
    //var windowW = screen.width - 410;
    if (sType == "Alternate Names")
        altWindow = window.open("../../cdecurate/NCICurationServlet?reqType=AltNamesDefs&searchEVS=" + document.SearchActionForm.searchEVS.value, "designate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
    else
        altWindow = window.open("jsp/EditDesignateDE.jsp", "designate", "width=700,height=650,top=0,left=0,resizable=yes,scrollbars=yes");
  }

//open viewonly refe doc
function openRefDocViewWindow()
{
	var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=getRefDocument&acID="+document.SearchActionForm.acID.value, "ReferenceDocuments", "width=700,height=300,top=0,left=0,resizable=yes,scrollbars=yes");
}

//open viewonly alt name with something to tell view
function openAltNameViewWindow()
{
	var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=getAltNames&acID="+document.SearchActionForm.acID.value, "AlternateNames", "width=700,height=300,top=0,left=0,resizable=yes,scrollbars=yes");
	//var refWindow = window.open("../../cdecurate/NCICurationServlet?reqType=viewAltNamesDefs&searchEVS=" + document.SearchActionForm.searchEVS.value, "viewDesignate", "width=900,height=600,top=0,left=0,resizable=yes,scrollbars=yes");
}

 //change the tabs
 function changeTab(tab)
 {
   if(tab == "PV"){
      document.createVDForm.action = "../../cdecurate/NCICurationServlet?reqType=viewVDPVSTab&vdpvstab=" +tab;
      document.createVDForm.submit();
   }else if (tab == "VD"){
      document.PVForm.action = "../../cdecurate/NCICurationServlet?reqType=viewVDPVSTab&vdpvstab=" +tab;
      document.PVForm.submit();
   }

 }<|endoftext|>


<commit_before>/* jshint esversion: 6 */
var robot = require('../..');
var targetpractice = require('targetpractice/index.js');
var elements, target;

describe('Integration/Screen', () => {
	beforeEach(done => {
		target = targetpractice.start();
		target.once('elements', message => {
			elements = message;
			done();
		});
	});

	afterEach(() => {
		targetpractice.stop();
		target = null;
	});

	it('reads a pixel color', () => {
		var color_1 = elements.color_1;
		const color = robot.getPixelColor(color_1.x, color_1.y);
		expect(color).toEqual('c0ff33');
	});
});
<commit_msg>hardened-screen-test<commit_after>/* jshint esversion: 6 */
var robot = require('../..');
var targetpractice = require('targetpractice/index.js');
var elements, target;

describe('Integration/Screen', () => {
	beforeEach(done => {
		target = targetpractice.start();
		target.once('elements', message => {
			elements = message;
			done();
		});
	});

	afterEach(() => {
		targetpractice.stop();
		target = null;
	});

	it('reads a pixel color', (done) => {
		const maxDelay = 1000
		jasmine.DEFAULT_TIMEOUT_INTERVAL = maxDelay + 1000
		const expected = 'c0ff33'
		const color_1 = elements.color_1;
		const sleepTime = robot.getPixelColor(color_1.x, color_1.y) === expected ? 0
			: maxDelay

		setTimeout(() => {
			const color = robot.getPixelColor(color_1.x, color_1.y);
			expect(color).toEqual(expected);
			done()
		}, sleepTime)
	});
});
<|endoftext|>


<commit_before>
/**
 * mod_{{ visualization_name }} was scaffolded using matta
 * Variables that start with an underscore (_) are passed as arguments in Python.
 * Variables that start with _data are data parameters of the visualization, and expected to be given as datum.
 *
 * For instance, d3.select('#figure').datum({'graph': a_json_graph, 'dataframe': a_json_dataframe}).call(visualization)
 * will fill the variables _data_graph and _data_dataframe.
 */

var matta_{{ visualization_name }} = function() {
    var __fill_data__ = function(__data__) {
        {% for var_name in __data_variables__ %}
            func_{{ visualization_name }}.{{ var_name }}(__data__.{{ var_name }});
        {% endfor %}
    };

    var func_{{ visualization_name }} = function (selection) {
        console.log('selection', selection);

        var _vis_width = _width - _padding.left - _padding.right;
        var _vis_height = _height - _padding.top - _padding.bottom;

        selection.each(function(__data__) {
            __fill_data__(__data__);

            var container = null;

            if (d3.select(this).select("{{ container_type }}.{{ visualization_name }}-container").empty()) {
                {% if container_type == 'svg' %}
                    var svg = d3.select(this).append("svg")
                        .attr("width", _width)
                        .attr("height", _height)
                        .attr('class', '{{ visualization_name }}-container');

                    {% if options.background_color %}
                        svg.append('rect')
                            .attr('width', _width)
                            .attr('height', _height)
                            .attr('fill', '{{ options.background_color }}');
                    {% endif %}

                    container = svg.append("g")
                        .classed('{{ visualization_name }}-container', true)
                        .attr('transform', 'translate(' + _padding.left + ',' + _padding.top + ')');

                {% elif container_type == 'div' %}
                    var div = d3.select(this).append("div")
                        .style({
                            'width': _width + 'px',
                            'height': _height + 'px',
                            'position': 'relative',
                            'display': 'block'
                        })
                        .classed('{{ visualization_name }}-container', true);

                    {% if options.background_color %}
                        div.style("background", '{{ options.background_color }}');
                    {% endif %}

                    container = div;

                {% else %}
                    console.log('unsupported container type!');
                    return;
                {% endif %}
            } else {
                container = d3.select(this).select("{{ container_type }}.{{ visualization_name }}-container");
            }

            console.log('container', container.node());

            {% if visualization_js %}
                {{ visualization_js }}
            {% endif %}

        });
    };

    {% for var_name in __data_variables__ %}
        var _data_{{ var_name }} = null;
        func_{{ visualization_name }}.{{ var_name }} = function(__) {
            if (arguments.length) {
                _data_{{ var_name }} = __;
                console.log('DATA {{ var_name }}', _data_{{ var_name }});
                return func_{{ visualization_name }};
            }
            return _data_{{ var_name }};
        };
    {% endfor %}

    {% if variables %}
    {% for var_name, var_value in variables.items() %}
        var _{{ var_name }} = {{ var_value }};
        func_{{ visualization_name }}.{{ var_name }} = function(__) {
            if (arguments.length) {
                _{{ var_name }} = __;
                console.log('setted {{ var_name }}', _{{ var_name }});
                return func_{{ visualization_name }};
            }
            return _{{ var_name }};
        };
    {% endfor %}
    {% endif %}

    {% if read_only %}
    {% for var_name in read_only %}
        var _{{ var_name }} = null;
        func_{{ visualization_name }}.{{ var_name }} = function() {
            return _{{ var_name }};
        };
    {% endfor %}
    {% endif %}
    return func_{{ visualization_name }};
};<commit_msg>adding options.events to base template<commit_after>
/**
 * mod_{{ visualization_name }} was scaffolded using matta - https://github.com/carnby/matta
 * Variables that start with an underscore (_) are passed as arguments in Python.
 * Variables that start with _data are data parameters of the visualization, and expected to be given as datum.
 *
 * For instance, d3.select('#figure').datum({'graph': a_json_graph, 'dataframe': a_json_dataframe}).call(visualization)
 * will fill the variables _data_graph and _data_dataframe.
 */

var matta_{{ visualization_name }} = function() {
    var __fill_data__ = function(__data__) {
        {% for var_name in __data_variables__ %}
            func_{{ visualization_name }}.{{ var_name }}(__data__.{{ var_name }});
        {% endfor %}
    };

    {% if options.events %}
        var _dispatcher = d3.dispatch('{{ options.events|join('\', \'') }}');
    {% endif %}

    var func_{{ visualization_name }} = function (selection) {
        console.log('selection', selection);

        var _vis_width = _width - _padding.left - _padding.right;
        var _vis_height = _height - _padding.top - _padding.bottom;

        selection.each(function(__data__) {
            __fill_data__(__data__);

            var container = null;
            var figure_dom_element = this;

            if (d3.select(this).select('{{ container_type }}.{{ visualization_name }}-container').empty()) {
                {% if container_type == 'svg' %}
                    var svg = d3.select(this).append('svg')
                        .attr('width', _width)
                        .attr('height', _height)
                        .attr('class', '{{ visualization_name }}-container');

                    {% if options.background_color %}
                        svg.append('rect')
                            .attr('width', _width)
                            .attr('height', _height)
                            .attr('fill', '{{ options.background_color }}');
                    {% endif %}

                    container = svg.append('g')
                        .classed('{{ visualization_name }}-container', true)
                        .attr('transform', 'translate(' + _padding.left + ',' + _padding.top + ')');

                {% elif container_type == 'div' %}
                    var div = d3.select(this).append('div')
                        .style({
                            'width': _width + 'px',
                            'height': _height + 'px',
                            'position': 'relative',
                            'display': 'block'
                        })
                        .classed('{{ visualization_name }}-container', true);

                    {% if options.background_color %}
                        div.style('background', '{{ options.background_color }}');
                    {% endif %}

                    container = div;

                {% else %}
                    console.log('unsupported container type!');
                    return;
                {% endif %}
            } else {
                container = d3.select(this).select('{{ container_type }}.{{ visualization_name }}-container');
            }

            console.log('container', container.node());

            {% if visualization_js %}
                {{ visualization_js }}
            {% endif %}

        });
    };

    {% for var_name in __data_variables__ %}
        var _data_{{ var_name }} = null;
        func_{{ visualization_name }}.{{ var_name }} = function(__) {
            if (arguments.length) {
                _data_{{ var_name }} = __;
                console.log('DATA {{ var_name }}', _data_{{ var_name }});
                return func_{{ visualization_name }};
            }
            return _data_{{ var_name }};
        };
    {% endfor %}

    {% if variables %}
    {% for var_name, var_value in variables.items() %}
        var _{{ var_name }} = {{ var_value }};
        func_{{ visualization_name }}.{{ var_name }} = function(__) {
            if (arguments.length) {
                _{{ var_name }} = __;
                console.log('set {{ var_name }}', _{{ var_name }});
                return func_{{ visualization_name }};
            }
            return _{{ var_name }};
        };
    {% endfor %}
    {% endif %}

    {% if read_only %}
    {% for var_name in read_only %}
        var _{{ var_name }} = null;
        func_{{ visualization_name }}.{{ var_name }} = function() {
            return _{{ var_name }};
        };
    {% endfor %}
    {% endif %}

    {% if options.events %}
        return d3.rebind(func_{{ visualization_name }}, _dispatcher, 'on');
    {% else %}
        return func_{{ visualization_name }};
    {% endif %}
};<|endoftext|>


<commit_before>import { define } from '../lib/obj-define.js';
import { reduceObjectProperty } from '../lib/reduce.js';
import { isString, isFunction } from '../lib/typeof.js';
import { matches } from '../lib/matches.js';
import { dispatch } from '../lib/dispatch.js';

/**
 * Check if an event has a selector in mathc in target list.
 * @private
 *
 * @param {Event} event The event to check.
 * @param {HTMLElement} node The root node.
 * @param {String} selector The CSS selector to match.
 * @return {HTMLElement} The element in target list which matches the selector.
 */
function checkDelegate(event, node, selector) {
    if (!selector) {
        return node;
    }
    let target = event.target;
    while (target && target !== node) {
        if (matches(target, selector)) {
            return target;
        }
        target = target.parentNode;
    }
    return null;
}
/**
 * Generate a delegate listener for an event.
 * @private
 *
 * @param {String} selector The CSS selector to match.
 * @param {Function} callback The original callback for the event.
 * @return {Function} Wrapped callback with a delegation check.
 */
function delegateCallback(selector, callback) {
    return (ev) => {
        let target = checkDelegate(ev, this.node, selector);
        if (target) {
            callback.call(this, ev, target);
        }
    };
}

/**
 * Simple Custom Component with events delegation,
 * It also implement a `dispatchEvent` wrapper named `trigger`.
 * @mixin EventsMixin
 * @memberof DNA.MIXINS.
 * @static
 *
 * @example
 * ```js
 * // my-component.js
 * import { BaseComponent } from '@dnajs/core';
 * export class MyComponent extends BaseComponent {
 *   get events() {
 *     return {
 *       'click button': 'onButtonClick'
 *     }
 *   }
 *   onButtonClick() {
 *     console.log('button clicked');
 *   }
 * }
 * ```
 * ```js
 * // app.js
 * import { define } from '@dnajs/core';
 * import { MyComponent } from './my-component.js';
 * define('my-component', MyComponent);
 * var element = new MyComponent();
 * var button = document.createElement('button');
 * button.innerText = 'Click me';
 * element.appendChild(button);
 * button.click(); // logs "button clicked"
 * ```
 */
export const EventsMixin = (SuperClass) => class extends SuperClass {
    /**
     * Iterate `events` properties.
     * @method constructor
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    constructor(node) {
        super(node);
        let events = reduceObjectProperty(this, 'events');
        for (let k in events) {
            let callback = isString(events[k]) ?
                this[events[k]] :
                events[k];
            if (isFunction(callback)) {
                let ev = k.trim().split(' ');
                let name = ev.shift();
                let selector = ev.join(' ');
                events[k] = {
                    name,
                    selector,
                    callback: delegateCallback.call(this, selector, callback),
                };
            } else {
                throw new TypeError('Invalid callback for event.');
            }
        }
        define(this, 'events', { value: events });
    }
    /**
     * Attach and delegate events to the component.
     * @method connectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    connectedCallback() {
        super.connectedCallback();
        // bind events
        let events = this.events;
        for (let k in events) {
            this.addEventListener(events[k].name, events[k].callback);
        }
    }
    /**
     * Detach and undelegate events from the component.
     * @method disconnectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    disconnectedCallback() {
        let events = this.events;
        for (let k in events) {
            let evName = k.split(' ').shift();
            this.removeEventListener(evName, events[k]);
        }
        super.disconnectedCallback();
    }
    /**
     * Delegate events to the component descendents.
     * @method delegate
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to delegate.
     * @param {String} selector A CSS selector for descendents.
     * @param {Function} callback The callback to fire.
     */
    delegate(evName, selector, callback) {
        let wrapCallback = delegateCallback.call(this, selector, callback);
        return this.addEventListener(evName, wrapCallback);
    }
    /**
     * `Node.prototype.dispatchEvent` wrapper.
     * @method trigger
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to fire.
     * @param {Object} data A set of custom data to pass to the event.
     * @param {Boolean} bubbles Should the event bubble throw the DOM tree.
     * @param {Boolean} cancelable Can be the event cancel by a callback.
     * @return {Boolean} True if event propagation has not be stopped.
     */
    trigger(evName, data, bubbles = true, cancelable = true) {
        return dispatch(this, evName, data, bubbles, cancelable);
    }
};
<commit_msg>fix: events undelegation<commit_after>import { define } from '../lib/obj-define.js';
import { reduceObjectProperty } from '../lib/reduce.js';
import { isString, isFunction } from '../lib/typeof.js';
import { matches } from '../lib/matches.js';
import { dispatch } from '../lib/dispatch.js';

/**
 * Check if an event has a selector in mathc in target list.
 * @private
 *
 * @param {Event} event The event to check.
 * @param {HTMLElement} node The root node.
 * @param {String} selector The CSS selector to match.
 * @return {HTMLElement} The element in target list which matches the selector.
 */
function checkDelegate(event, node, selector) {
    if (!selector) {
        return node;
    }
    let target = event.target;
    while (target && target !== node) {
        if (matches(target, selector)) {
            return target;
        }
        target = target.parentNode;
    }
    return null;
}
/**
 * Generate a delegate listener for an event.
 * @private
 *
 * @param {String} selector The CSS selector to match.
 * @param {Function} callback The original callback for the event.
 * @return {Function} Wrapped callback with a delegation check.
 */
function delegateCallback(selector, callback) {
    return (ev) => {
        let target = checkDelegate(ev, this.node, selector);
        if (target) {
            callback.call(this, ev, target);
        }
    };
}

/**
 * Simple Custom Component with events delegation,
 * It also implement a `dispatchEvent` wrapper named `trigger`.
 * @mixin EventsMixin
 * @memberof DNA.MIXINS.
 * @static
 *
 * @example
 * ```js
 * // my-component.js
 * import { BaseComponent } from '@dnajs/core';
 * export class MyComponent extends BaseComponent {
 *   get events() {
 *     return {
 *       'click button': 'onButtonClick'
 *     }
 *   }
 *   onButtonClick() {
 *     console.log('button clicked');
 *   }
 * }
 * ```
 * ```js
 * // app.js
 * import { define } from '@dnajs/core';
 * import { MyComponent } from './my-component.js';
 * define('my-component', MyComponent);
 * var element = new MyComponent();
 * var button = document.createElement('button');
 * button.innerText = 'Click me';
 * element.appendChild(button);
 * button.click(); // logs "button clicked"
 * ```
 */
export const EventsMixin = (SuperClass) => class extends SuperClass {
    /**
     * Iterate `events` properties.
     * @method constructor
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    constructor(node) {
        super(node);
        let events = reduceObjectProperty(this, 'events');
        for (let k in events) {
            let callback = isString(events[k]) ?
                this[events[k]] :
                events[k];
            if (isFunction(callback)) {
                let ev = k.trim().split(' ');
                let name = ev.shift();
                let selector = ev.join(' ');
                events[k] = {
                    name,
                    selector,
                    callback: delegateCallback.call(this, selector, callback),
                };
            } else {
                throw new TypeError('Invalid callback for event.');
            }
        }
        define(this, 'events', { value: events });
    }
    /**
     * Attach and delegate events to the component.
     * @method connectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    connectedCallback() {
        super.connectedCallback();
        // bind events
        let events = this.events;
        for (let k in events) {
            this.addEventListener(events[k].name, events[k].callback);
        }
    }
    /**
     * Detach and undelegate events from the component.
     * @method disconnectedCallback
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     */
    disconnectedCallback() {
        let events = this.events;
        for (let k in events) {
            this.removeEventListener(events[k].name, events[k].callback);
        }
        super.disconnectedCallback();
    }
    /**
     * Delegate events to the component descendents.
     * @method delegate
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to delegate.
     * @param {String} selector A CSS selector for descendents.
     * @param {Function} callback The callback to fire.
     */
    delegate(evName, selector, callback) {
        let wrapCallback = delegateCallback.call(this, selector, callback);
        return this.addEventListener(evName, wrapCallback);
    }
    /**
     * `Node.prototype.dispatchEvent` wrapper.
     * @method trigger
     * @memberof DNA.MIXINS.EventsMixin
     * @instance
     *
     * @param {String} evName The name of the event to fire.
     * @param {Object} data A set of custom data to pass to the event.
     * @param {Boolean} bubbles Should the event bubble throw the DOM tree.
     * @param {Boolean} cancelable Can be the event cancel by a callback.
     * @return {Boolean} True if event propagation has not be stopped.
     */
    trigger(evName, data, bubbles = true, cancelable = true) {
        return dispatch(this, evName, data, bubbles, cancelable);
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2012-2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

function parseLines(lines, callback) {
    var re = /^\/tmp\/[^:]+:([0-9]+)(:([0-9]+))?:\s+(.*)/;
    $.each(lines.split('\n'), function (_, line) {
        line = line.trim();
        if (line !== "") {
            var match = line.match(re);
            if (match) {
                callback(parseInt(match[1]), match[4].trim());
            } else {
                callback(null, line);
            }
        }
    });
}

function clearBackground(cm) {
    for (var i = 0; i < cm.lineCount(); ++i) {
        cm.removeLineClass(i, "background", null);
    }
}

const NumRainbowColours = 12;

function Compiler(domRoot, origFilters, windowLocalPrefix, onChangeCallback, lang) {
    var compilersById = {};
    var compilersByAlias = {};
    var pendingTimeout = null;
    var asmCodeMirror = null;
    var cppEditor = null;
    var lastRequest = null;
    var currentAssembly = null;
    var filters_ = $.extend({}, origFilters);
    var ignoreChanges = true; // Horrible hack to avoid onChange doing anything on first starting, ie before we've set anything up.

    function setCompilerById(id) {
        var compilerNode = domRoot.find('.compiler');
        compilerNode.text(compilersById[id].name);
        compilerNode.attr('data', id);
    }

    function currentCompilerId() {
        return domRoot.find('.compiler').attr('data');
    }

    function currentCompiler() {
        return compilersById[currentCompilerId()];
    }

    $('.autocompile').click(function () {
        $('.autocompile').toggleClass('active');
        onChange();
        setSetting('autocompile', $('.autocompile').hasClass('active'));
    });
    $('.autocompile').toggleClass('active', getSetting("autocompile") !== "false");

    function patchUpFilters(filters) {
        filters = $.extend({}, filters);
        var compiler = currentCompiler();
        var compilerSupportsBinary = compiler ? compiler.supportsBinary : true;
        if (filters.binary && !(OPTIONS.supportsBinary && compilerSupportsBinary)) {
            filters.binary = false;
        }
        return filters;
    }

    var cmMode;
    switch (lang.toLowerCase()) {
        default:
            cmMode = "text/x-c++src";
            break;
        case "c":
            cmMode = "text/x-c";
            break;
        case "rust":
            cmMode = "text/x-rustsrc";
            break;
        case "d":
            cmMode = "text/x-d";
            break;
        case "go":
            cmMode = "text/x-go";
            break;
    }

    cppEditor = CodeMirror.fromTextArea(domRoot.find(".editor textarea")[0], {
        lineNumbers: true,
        matchBrackets: true,
        useCPP: true,
        mode: cmMode
    });
    cppEditor.on("change", function () {
        if ($('.autocompile').hasClass('active')) {
            onChange();
        }
    });
    asmCodeMirror = CodeMirror.fromTextArea(domRoot.find(".asm textarea")[0], {
        lineNumbers: true,
        mode: "text/x-asm",
        readOnly: true,
        gutters: ['CodeMirror-linenumbers']
    });

    function getSetting(name) {
        return window.localStorage[windowLocalPrefix + "." + name];
    }

    function setSetting(name, value) {
        window.localStorage[windowLocalPrefix + "." + name] = value;
    }

    var codeText = getSetting('code');
    if (!codeText) codeText = $(".template.lang." + lang.replace(/[^a-zA-Z]/g, '').toLowerCase()).text();
    if (codeText) cppEditor.setValue(codeText);
    domRoot.find('.compiler_options').change(onChange).keyup(onChange);
    ignoreChanges = false;

    if (getSetting('compilerOptions')) {
        domRoot.find('.compiler_options').val(getSetting('compilerOptions'));
    }

    function makeErrNode(text) {
        var clazz = "error";
        if (text.match(/^warning/)) clazz = "warning";
        if (text.match(/^note/)) clazz = "note";
        var node = $('
!!
');
        node.find(".msg").text(text);
        return node[0];
    }

    var errorWidgets = [];

    function onCompileResponse(request, data) {
        var stdout = data.stdout || "";
        var stderr = data.stderr || "";
        if (data.code === 0) {
            stdout += "\nCompiled ok";
        } else {
            stderr += "\nCompilation failed";
        }
        if (_gaq) {
            _gaq.push(['_trackEvent', 'Compile', request.compiler, request.options, data.code]);
            _gaq.push(['_trackTiming', 'Compile', 'Timing', new Date() - request.timestamp]);
        }
        $('.result .output :visible').remove();
        for (var i = 0; i < errorWidgets.length; ++i)
            cppEditor.removeLineWidget(errorWidgets[i]);
        errorWidgets.length = 0;
        var numLines = 0;
        parseLines(stderr + stdout, function (lineNum, msg) {
            if (numLines > 50) return;
            if (numLines === 50) {
                lineNum = null;
                msg = "Too many output lines...truncated";
            }
            numLines++;
            var elem = $('.result .output .template').clone().appendTo('.result .output').removeClass('template');
            if (lineNum) {
                errorWidgets.push(cppEditor.addLineWidget(lineNum - 1, makeErrNode(msg), {
                    coverGutter: false, noHScroll: true
                }));
                elem.html($('').text(lineNum + " : " + msg)).click(function () {
                    cppEditor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0});
                    return false;
                });
            } else {
                elem.text(msg);
            }
        });
        currentAssembly = data.asm || fakeAsm("[no output]");
        updateAsm();
    }

    function numberUsedLines(asm) {
        var sourceLines = {};
        $.each(asm, function (_, x) {
            if (x.source) sourceLines[x.source - 1] = true;
        });
        var ordinal = 0;
        $.each(sourceLines, function (k, _) {
            sourceLines[k] = ordinal++;
        });
        var asmLines = {};
        $.each(asm, function (index, x) {
            if (x.source) asmLines[index] = sourceLines[x.source - 1];
        });
        return {source: sourceLines, asm: asmLines};
    }

    var lastUpdatedAsm = null;

    function updateAsm(forceUpdate) {
        if (!currentAssembly) return;
        var hashedUpdate = JSON.stringify(currentAssembly);
        if (!forceUpdate && lastUpdatedAsm == hashedUpdate) {
            return;
        }
        lastUpdatedAsm = hashedUpdate;

        var asmText = $.map(currentAssembly, function (x) {
            return x.text;
        }).join("\n");
        var numberedLines = numberUsedLines(currentAssembly);

        cppEditor.operation(function () {
            clearBackground(cppEditor);
        });
        var filters = currentFilters();
        asmCodeMirror.operation(function () {
            asmCodeMirror.setValue(asmText);
            clearBackground(asmCodeMirror);
            var addrToAddrDiv = {};
            $.each(currentAssembly, function (line, obj) {
                var address = obj.address ? obj.address.toString(16) : "";
                var div = $("
" + address + "
");
                addrToAddrDiv[address] = {div: div, line: line};
                asmCodeMirror.setGutterMarker(line, 'address', div[0]);
            });
            $.each(currentAssembly, function (line, obj) {
                var opcodes = $("

");
                if (obj.opcodes) {
                    var title = [];
                    $.each(obj.opcodes, function (_, op) {
                        var opcodeNum = "00" + op.toString(16);
                        opcodeNum = opcodeNum.substr(opcodeNum.length - 2);
                        title.push(opcodeNum);
                        var opcode = $("" + opcodeNum + "");
                        opcodes.append(opcode);
                    });
                    opcodes.attr('title', title.join(" "));
                }
                asmCodeMirror.setGutterMarker(line, 'opcodes', opcodes[0]);
                if (obj.links) {
                    $.each(obj.links, function (_, link) {
                        var from = {line: line, ch: link.offset};
                        var to = {line: line, ch: link.offset + link.length};
                        var address = link.to.toString(16);
                        var thing = $("" + address + "");
                        asmCodeMirror.markText(
                            from, to, {replacedWith: thing[0], handleMouseEvents: false});
                        var dest = addrToAddrDiv[address];
                        if (dest) {
                            thing.on('hover', function (e) {
                                var entered = e.type == "mouseenter";
                                dest.div.toggleClass("highlighted", entered);
                                thing.toggleClass("highlighted", entered);
                            });
                            thing.on('click', function (e) {
                                asmCodeMirror.scrollIntoView({line: dest.line, ch: 0}, 30);
                                dest.div.toggleClass("highlighted", false);
                                thing.toggleClass("highlighted", false);
                            });
                        }
                    });
                }
            });
            if (filters.binary) {
                asmCodeMirror.setOption('lineNumbers', false);
                asmCodeMirror.setOption('gutters', ['address', 'opcodes']);
            } else {
                asmCodeMirror.setOption('lineNumbers', true);
                asmCodeMirror.setOption('gutters', ['CodeMirror-linenumbers']);
            }
        });
        if (filters.colouriseAsm) {
            cppEditor.operation(function () {
                $.each(numberedLines.source, function (line, ordinal) {
                    cppEditor.addLineClass(parseInt(line),
                        "background", "rainbow-" + (ordinal % NumRainbowColours));
                });
            });
            asmCodeMirror.operation(function () {
                $.each(numberedLines.asm, function (line, ordinal) {
                    asmCodeMirror.addLineClass(parseInt(line),
                        "background", "rainbow-" + (ordinal % NumRainbowColours));
                });
            });
        }
    }

    function fakeAsm(text) {
        return [{text: text, source: null}];
    }

    function onChange() {
        if (ignoreChanges) return;  // Ugly hack during startup.
        if (pendingTimeout) clearTimeout(pendingTimeout);
        pendingTimeout = setTimeout(function () {
            var data = {
                source: cppEditor.getValue(),
                compiler: currentCompilerId(),
                options: $('.compiler_options').val(),
                filters: currentFilters()
            };
            setSetting('compiler', data.compiler);
            setSetting('compilerOptions', data.options);
            var stringifiedReq = JSON.stringify(data);
            if (stringifiedReq == lastRequest) return;
            lastRequest = stringifiedReq;
            data.timestamp = new Date();
            $.ajax({
                type: 'POST',
                url: '/compile',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (result) {
                    onCompileResponse(data, result);
                }
            });
            currentAssembly = fakeAsm("[Processing...]");
            updateAsm();
        }, 750);
        setSetting('code', cppEditor.getValue());
        updateAsm();
        onChangeCallback();
    }

    function setSource(code) {
        cppEditor.setValue(code);
    }

    function getSource() {
        return cppEditor.getValue();
    }

    function serialiseState(compress) {
        var state = {
            compiler: currentCompilerId(),
            options: domRoot.find('.compiler_options').val()
        };
        if (compress) {
            state.sourcez = LZString.compressToBase64(cppEditor.getValue());
        } else {
            state.source = cppEditor.getValue();
        }
        return state;
    }

    function deserialiseState(state) {
        if (state.hasOwnProperty('sourcez')) {
            cppEditor.setValue(LZString.decompressFromBase64(state.sourcez));
        } else {
            cppEditor.setValue(state.source);
        }
        state.compiler = mapCompiler(state.compiler);
        setCompilerById(state.compiler);
        domRoot.find('.compiler_options').val(state.options);
        // Somewhat hackily persist compiler into local storage else when the ajax response comes in
        // with the list of compilers it can splat over the deserialized version.
        // The whole serialize/hash/localStorage code is a mess! TODO(mg): fix
        setSetting('compiler', state.compiler);
        updateAsm(true);  // Force the update to reset colours after calling cppEditor.setValue
        return true;
    }

    function updateCompilerAndButtons() {
        var compiler = currentCompiler();
        $(".compilerVersion").text(compiler.name + " (" + compiler.version + ")");
        var filters = currentFilters();
        var supportsIntel = compiler.intelAsm || filters.binary;
        domRoot.find('.filter button.btn[value="intel"]').toggleClass("disabled", !supportsIntel);
        domRoot.find('.filter button.btn[value="binary"]').toggleClass("disabled", !compiler.supportsBinary).toggle(OPTIONS.supportsBinary);
        domRoot.find('.filter .nonbinary').toggleClass("disabled", !!filters.binary);
    }

    function onCompilerChange() {
        onChange();
        updateCompilerAndButtons();
    }

    function mapCompiler(compiler) {
        if (!compilersById[compiler]) {
            // Handle old settings and try the alias table.
            compiler = compilersByAlias[compiler];
            if (compiler) compiler = compiler.id;
        }
        return compiler;
    }

    function setCompilers(compilers, defaultCompiler) {
        domRoot.find('.compilers li').remove();
        compilersById = {};
        compilersByAlias = {};
        $.each(compilers, function (index, arg) {
            compilersById[arg.id] = arg;
            if (arg.alias) compilersByAlias[arg.alias] = arg;
            var elem = $('
' + arg.name + '
');
            domRoot.find('.compilers').append(elem);
            (function () {
                elem.click(function () {
                    setCompilerById(arg.id);
                    onCompilerChange();
                });
            })(elem.find("a"), arg.id);
        });
        var compiler = getSetting('compiler');
        if (!compiler) compiler = defaultCompiler;
        compiler = mapCompiler(compiler);
        if (compiler) {
            setCompilerById(compiler);
        }
        onCompilerChange();
    }

    function currentFilters() {
        return patchUpFilters(filters_);
    }

    function setFilters(f) {
        filters_ = $.extend({}, f);
        onChange();
        updateCompilerAndButtons();
    }

    function setEditorHeight(height) {
        const MinHeight = 100;
        if (height < MinHeight) height = MinHeight;
        cppEditor.setSize(null, height);
        asmCodeMirror.setSize(null, height);
    }

    return {
        serialiseState: serialiseState,
        deserialiseState: deserialiseState,
        setCompilers: setCompilers,
        getSource: getSource,
        setSource: setSource,
        setFilters: setFilters,
        setEditorHeight: setEditorHeight
    };
}
<commit_msg>fix typing '#' in triggering emacs keybind<commit_after>// Copyright (c) 2012-2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

function parseLines(lines, callback) {
    var re = /^\/tmp\/[^:]+:([0-9]+)(:([0-9]+))?:\s+(.*)/;
    $.each(lines.split('\n'), function (_, line) {
        line = line.trim();
        if (line !== "") {
            var match = line.match(re);
            if (match) {
                callback(parseInt(match[1]), match[4].trim());
            } else {
                callback(null, line);
            }
        }
    });
}

function clearBackground(cm) {
    for (var i = 0; i < cm.lineCount(); ++i) {
        cm.removeLineClass(i, "background", null);
    }
}

const NumRainbowColours = 12;

function Compiler(domRoot, origFilters, windowLocalPrefix, onChangeCallback, lang) {
    var compilersById = {};
    var compilersByAlias = {};
    var pendingTimeout = null;
    var asmCodeMirror = null;
    var cppEditor = null;
    var lastRequest = null;
    var currentAssembly = null;
    var filters_ = $.extend({}, origFilters);
    var ignoreChanges = true; // Horrible hack to avoid onChange doing anything on first starting, ie before we've set anything up.

    function setCompilerById(id) {
        var compilerNode = domRoot.find('.compiler');
        compilerNode.text(compilersById[id].name);
        compilerNode.attr('data', id);
    }

    function currentCompilerId() {
        return domRoot.find('.compiler').attr('data');
    }

    function currentCompiler() {
        return compilersById[currentCompilerId()];
    }

    $('.autocompile').click(function () {
        $('.autocompile').toggleClass('active');
        onChange();
        setSetting('autocompile', $('.autocompile').hasClass('active'));
    });
    $('.autocompile').toggleClass('active', getSetting("autocompile") !== "false");

    function patchUpFilters(filters) {
        filters = $.extend({}, filters);
        var compiler = currentCompiler();
        var compilerSupportsBinary = compiler ? compiler.supportsBinary : true;
        if (filters.binary && !(OPTIONS.supportsBinary && compilerSupportsBinary)) {
            filters.binary = false;
        }
        return filters;
    }

    var cmMode;
    switch (lang.toLowerCase()) {
        default:
            cmMode = "text/x-c++src";
            break;
        case "c":
            cmMode = "text/x-c";
            break;
        case "rust":
            cmMode = "text/x-rustsrc";
            break;
        case "d":
            cmMode = "text/x-d";
            break;
        case "go":
            cmMode = "text/x-go";
            break;
    }

    cppEditor = CodeMirror.fromTextArea(domRoot.find(".editor textarea")[0], {
        lineNumbers: true,
        matchBrackets: true,
        useCPP: true,
        mode: cmMode
    });
    cppEditor.setOption("extraKeys", {
      "Alt-F": false
    });
    cppEditor.on("change", function () {
        if ($('.autocompile').hasClass('active')) {
            onChange();
        }
    });
    asmCodeMirror = CodeMirror.fromTextArea(domRoot.find(".asm textarea")[0], {
        lineNumbers: true,
        mode: "text/x-asm",
        readOnly: true,
        gutters: ['CodeMirror-linenumbers']
    });

    function getSetting(name) {
        return window.localStorage[windowLocalPrefix + "." + name];
    }

    function setSetting(name, value) {
        window.localStorage[windowLocalPrefix + "." + name] = value;
    }

    var codeText = getSetting('code');
    if (!codeText) codeText = $(".template.lang." + lang.replace(/[^a-zA-Z]/g, '').toLowerCase()).text();
    if (codeText) cppEditor.setValue(codeText);
    domRoot.find('.compiler_options').change(onChange).keyup(onChange);
    ignoreChanges = false;

    if (getSetting('compilerOptions')) {
        domRoot.find('.compiler_options').val(getSetting('compilerOptions'));
    }

    function makeErrNode(text) {
        var clazz = "error";
        if (text.match(/^warning/)) clazz = "warning";
        if (text.match(/^note/)) clazz = "note";
        var node = $('
!!
');
        node.find(".msg").text(text);
        return node[0];
    }

    var errorWidgets = [];

    function onCompileResponse(request, data) {
        var stdout = data.stdout || "";
        var stderr = data.stderr || "";
        if (data.code === 0) {
            stdout += "\nCompiled ok";
        } else {
            stderr += "\nCompilation failed";
        }
        if (_gaq) {
            _gaq.push(['_trackEvent', 'Compile', request.compiler, request.options, data.code]);
            _gaq.push(['_trackTiming', 'Compile', 'Timing', new Date() - request.timestamp]);
        }
        $('.result .output :visible').remove();
        for (var i = 0; i < errorWidgets.length; ++i)
            cppEditor.removeLineWidget(errorWidgets[i]);
        errorWidgets.length = 0;
        var numLines = 0;
        parseLines(stderr + stdout, function (lineNum, msg) {
            if (numLines > 50) return;
            if (numLines === 50) {
                lineNum = null;
                msg = "Too many output lines...truncated";
            }
            numLines++;
            var elem = $('.result .output .template').clone().appendTo('.result .output').removeClass('template');
            if (lineNum) {
                errorWidgets.push(cppEditor.addLineWidget(lineNum - 1, makeErrNode(msg), {
                    coverGutter: false, noHScroll: true
                }));
                elem.html($('').text(lineNum + " : " + msg)).click(function () {
                    cppEditor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0});
                    return false;
                });
            } else {
                elem.text(msg);
            }
        });
        currentAssembly = data.asm || fakeAsm("[no output]");
        updateAsm();
    }

    function numberUsedLines(asm) {
        var sourceLines = {};
        $.each(asm, function (_, x) {
            if (x.source) sourceLines[x.source - 1] = true;
        });
        var ordinal = 0;
        $.each(sourceLines, function (k, _) {
            sourceLines[k] = ordinal++;
        });
        var asmLines = {};
        $.each(asm, function (index, x) {
            if (x.source) asmLines[index] = sourceLines[x.source - 1];
        });
        return {source: sourceLines, asm: asmLines};
    }

    var lastUpdatedAsm = null;

    function updateAsm(forceUpdate) {
        if (!currentAssembly) return;
        var hashedUpdate = JSON.stringify(currentAssembly);
        if (!forceUpdate && lastUpdatedAsm == hashedUpdate) {
            return;
        }
        lastUpdatedAsm = hashedUpdate;

        var asmText = $.map(currentAssembly, function (x) {
            return x.text;
        }).join("\n");
        var numberedLines = numberUsedLines(currentAssembly);

        cppEditor.operation(function () {
            clearBackground(cppEditor);
        });
        var filters = currentFilters();
        asmCodeMirror.operation(function () {
            asmCodeMirror.setValue(asmText);
            clearBackground(asmCodeMirror);
            var addrToAddrDiv = {};
            $.each(currentAssembly, function (line, obj) {
                var address = obj.address ? obj.address.toString(16) : "";
                var div = $("
" + address + "
");
                addrToAddrDiv[address] = {div: div, line: line};
                asmCodeMirror.setGutterMarker(line, 'address', div[0]);
            });
            $.each(currentAssembly, function (line, obj) {
                var opcodes = $("

");
                if (obj.opcodes) {
                    var title = [];
                    $.each(obj.opcodes, function (_, op) {
                        var opcodeNum = "00" + op.toString(16);
                        opcodeNum = opcodeNum.substr(opcodeNum.length - 2);
                        title.push(opcodeNum);
                        var opcode = $("" + opcodeNum + "");
                        opcodes.append(opcode);
                    });
                    opcodes.attr('title', title.join(" "));
                }
                asmCodeMirror.setGutterMarker(line, 'opcodes', opcodes[0]);
                if (obj.links) {
                    $.each(obj.links, function (_, link) {
                        var from = {line: line, ch: link.offset};
                        var to = {line: line, ch: link.offset + link.length};
                        var address = link.to.toString(16);
                        var thing = $("" + address + "");
                        asmCodeMirror.markText(
                            from, to, {replacedWith: thing[0], handleMouseEvents: false});
                        var dest = addrToAddrDiv[address];
                        if (dest) {
                            thing.on('hover', function (e) {
                                var entered = e.type == "mouseenter";
                                dest.div.toggleClass("highlighted", entered);
                                thing.toggleClass("highlighted", entered);
                            });
                            thing.on('click', function (e) {
                                asmCodeMirror.scrollIntoView({line: dest.line, ch: 0}, 30);
                                dest.div.toggleClass("highlighted", false);
                                thing.toggleClass("highlighted", false);
                            });
                        }
                    });
                }
            });
            if (filters.binary) {
                asmCodeMirror.setOption('lineNumbers', false);
                asmCodeMirror.setOption('gutters', ['address', 'opcodes']);
            } else {
                asmCodeMirror.setOption('lineNumbers', true);
                asmCodeMirror.setOption('gutters', ['CodeMirror-linenumbers']);
            }
        });
        if (filters.colouriseAsm) {
            cppEditor.operation(function () {
                $.each(numberedLines.source, function (line, ordinal) {
                    cppEditor.addLineClass(parseInt(line),
                        "background", "rainbow-" + (ordinal % NumRainbowColours));
                });
            });
            asmCodeMirror.operation(function () {
                $.each(numberedLines.asm, function (line, ordinal) {
                    asmCodeMirror.addLineClass(parseInt(line),
                        "background", "rainbow-" + (ordinal % NumRainbowColours));
                });
            });
        }
    }

    function fakeAsm(text) {
        return [{text: text, source: null}];
    }

    function onChange() {
        if (ignoreChanges) return;  // Ugly hack during startup.
        if (pendingTimeout) clearTimeout(pendingTimeout);
        pendingTimeout = setTimeout(function () {
            var data = {
                source: cppEditor.getValue(),
                compiler: currentCompilerId(),
                options: $('.compiler_options').val(),
                filters: currentFilters()
            };
            setSetting('compiler', data.compiler);
            setSetting('compilerOptions', data.options);
            var stringifiedReq = JSON.stringify(data);
            if (stringifiedReq == lastRequest) return;
            lastRequest = stringifiedReq;
            data.timestamp = new Date();
            $.ajax({
                type: 'POST',
                url: '/compile',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (result) {
                    onCompileResponse(data, result);
                }
            });
            currentAssembly = fakeAsm("[Processing...]");
            updateAsm();
        }, 750);
        setSetting('code', cppEditor.getValue());
        updateAsm();
        onChangeCallback();
    }

    function setSource(code) {
        cppEditor.setValue(code);
    }

    function getSource() {
        return cppEditor.getValue();
    }

    function serialiseState(compress) {
        var state = {
            compiler: currentCompilerId(),
            options: domRoot.find('.compiler_options').val()
        };
        if (compress) {
            state.sourcez = LZString.compressToBase64(cppEditor.getValue());
        } else {
            state.source = cppEditor.getValue();
        }
        return state;
    }

    function deserialiseState(state) {
        if (state.hasOwnProperty('sourcez')) {
            cppEditor.setValue(LZString.decompressFromBase64(state.sourcez));
        } else {
            cppEditor.setValue(state.source);
        }
        state.compiler = mapCompiler(state.compiler);
        setCompilerById(state.compiler);
        domRoot.find('.compiler_options').val(state.options);
        // Somewhat hackily persist compiler into local storage else when the ajax response comes in
        // with the list of compilers it can splat over the deserialized version.
        // The whole serialize/hash/localStorage code is a mess! TODO(mg): fix
        setSetting('compiler', state.compiler);
        updateAsm(true);  // Force the update to reset colours after calling cppEditor.setValue
        return true;
    }

    function updateCompilerAndButtons() {
        var compiler = currentCompiler();
        $(".compilerVersion").text(compiler.name + " (" + compiler.version + ")");
        var filters = currentFilters();
        var supportsIntel = compiler.intelAsm || filters.binary;
        domRoot.find('.filter button.btn[value="intel"]').toggleClass("disabled", !supportsIntel);
        domRoot.find('.filter button.btn[value="binary"]').toggleClass("disabled", !compiler.supportsBinary).toggle(OPTIONS.supportsBinary);
        domRoot.find('.filter .nonbinary').toggleClass("disabled", !!filters.binary);
    }

    function onCompilerChange() {
        onChange();
        updateCompilerAndButtons();
    }

    function mapCompiler(compiler) {
        if (!compilersById[compiler]) {
            // Handle old settings and try the alias table.
            compiler = compilersByAlias[compiler];
            if (compiler) compiler = compiler.id;
        }
        return compiler;
    }

    function setCompilers(compilers, defaultCompiler) {
        domRoot.find('.compilers li').remove();
        compilersById = {};
        compilersByAlias = {};
        $.each(compilers, function (index, arg) {
            compilersById[arg.id] = arg;
            if (arg.alias) compilersByAlias[arg.alias] = arg;
            var elem = $('
' + arg.name + '
');
            domRoot.find('.compilers').append(elem);
            (function () {
                elem.click(function () {
                    setCompilerById(arg.id);
                    onCompilerChange();
                });
            })(elem.find("a"), arg.id);
        });
        var compiler = getSetting('compiler');
        if (!compiler) compiler = defaultCompiler;
        compiler = mapCompiler(compiler);
        if (compiler) {
            setCompilerById(compiler);
        }
        onCompilerChange();
    }

    function currentFilters() {
        return patchUpFilters(filters_);
    }

    function setFilters(f) {
        filters_ = $.extend({}, f);
        onChange();
        updateCompilerAndButtons();
    }

    function setEditorHeight(height) {
        const MinHeight = 100;
        if (height < MinHeight) height = MinHeight;
        cppEditor.setSize(null, height);
        asmCodeMirror.setSize(null, height);
    }

    return {
        serialiseState: serialiseState,
        deserialiseState: deserialiseState,
        setCompilers: setCompilers,
        getSource: getSource,
        setSource: setSource,
        setFilters: setFilters,
        setEditorHeight: setEditorHeight
    };
}
<|endoftext|>


<commit_before>(function(){
  var $searchButton,
      $originInput,
      $destinationInput,
      $metricsContent,
      options = {
          modes: ['walking', 'biking', 'transit', 'driving'],
          metrics: ['cost', 'duration', 'calories', 'emissions']
      },
      metricsEjs = new EJS({url: 'views/metrics.ejs'}),
      geocoder = new google.maps.Geocoder(),
      curLatLng,
      log = function(toLog) {
        if (window.console && window.console.log) {
          window.console.log(toLog);
        }
      };

  var renderers = {
    'km': function(val) {
      return {
        value: (val * 0.62137).toFixed(1),
        label: 'miles'
      };
    },
    'sec': function(val) {
      return {
        value: (val / 60).toFixed(0),
        label: 'minutes'
      };
    },
    'kg_co2': function(val) {
      return {
        value: (val || 0).toFixed(2),
        label: 'kg of CO2'
      };
    },
    'usd': function(val) {
      return {
        value: '$' + (val || 0).toFixed(2),
        label: ' '
      };
    },
    'cal': function(val) {
      return {
        value: (val || 0).toFixed(),
        label: 'calories'
      };
    }
  };

  var locateMe = function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition( function(position) {
        curLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      },
      function(msg){
        alert('We couldn\'t locate your position.');
      },
      { enableHighAccuracy: true, maximumAge: 90000 });
    }
  };

  var formatResults = function(data) {
    var val, i, j, metric, mode, results = {};

    for(j=0; j<options.modes.length; j++) {
      mode = options.modes[j];

      if (data.results[mode]) {
        results[mode] = {};

        for (i=0; i<options.metrics.length; i++) {
          metric = options.metrics[i];

          if (metric) {
            results[mode][metric] = renderers[data.units[metric]](data.results[mode][metric]);
          }
        }
      }
    }

    return results;
  };

  var calculate = function(origin, destination) {
    $.mobile.pageLoading();

    $.ajax({
      url: 'info_for_route_bing',
      dataType: 'json',
      data: {
        origin: origin,
        destination: destination
      },
      success: function(data, textStatus, jqXHR) {
        var results = formatResults(data),
          html = metricsEjs.render({
            metrics: options.metrics,
            results: results
          });

        $metricsContent.html(html);

        $('#metrics-table tbody th, #metrics-table tbody td').bind('tap', function(evt) {
          $('#plan h1').text(this.parentNode.id);
          $.mobile.changePage('plan');
        });

        $.mobile.changePage('home', {
          transition: 'flip'
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {
        log(errorThrown);
        alert('Error calculating directions');
        $.mobile.pageLoading(true);
      },
      complete: function() {
        $.mobile.pageLoading(true);
      }
    });
  };

  var listAddresses = function(searchId) {
    var $list = $('#' + searchId + '-list'),
      $input = $('#' + searchId);

    return function (results, status) {
      $list.empty();

      $.each(results, function(i, val) {
        $list.append('
' + val.formatted_address + '
');
      });

      $list.listview('refresh');

      $('li', $list).tap(function() {
        $input.val(this.innerHTML);
        $list.empty();
      });
    };
  };

  var bindEvents = function() {
    var bounds;

    $originInput.keyup(function() {
      bounds = bounds || new google.maps.Circle({center:curLatLng, radius:8000}).getBounds();
      geocoder.geocode({'address': $originInput.val(), 'bounds':bounds }, listAddresses('origin'));
    });

    $destinationInput.keyup(  function() {
      bounds = bounds || new google.maps.Circle({center:curLatLng, radius:8000}).getBounds();
      geocoder.geocode({'address':$destinationInput.val(), 'bounds':bounds }, listAddresses('destination'));
    });

    $searchButton.tap(function() {
      calculate($originInput.val(), $destinationInput.val());
    });
  };

  $('#search').live('pagecreate',function(evt) {
    //Cache vars
    $searchButton = $('#search-button');
    $originInput = $('#origin');
    $destinationInput = $('#destination');
    $metricsContent = $('#metrics-content');

    locateMe();

    bindEvents();
  });

  $(document).bind("mobileinit", function() {
    //Disabling this b/c it could be bad for bookmarking
    $.mobile.hashListeningEnabled = false;
  });
})();<commit_msg>Delay execution of geocode autocomplete.<commit_after>(function(){
  var $searchButton,
      $originInput,
      $destinationInput,
      $metricsContent,
      options = {
          modes: ['walking', 'biking', 'transit', 'driving'],
          metrics: ['cost', 'duration', 'calories', 'emissions']
      },
      metricsEjs = new EJS({url: 'views/metrics.ejs'}),
      geocoder = new google.maps.Geocoder(),
      curLatLng,
      geocodeDelay = 2000, //ms
      log = function(toLog) {
        if (window.console && window.console.log) {
          window.console.log(toLog);
        }
      };

  var renderers = {
    'km': function(val) {
      return {
        value: (val * 0.62137).toFixed(1),
        label: 'miles'
      };
    },
    'sec': function(val) {
      return {
        value: (val / 60).toFixed(0),
        label: 'minutes'
      };
    },
    'kg_co2': function(val) {
      return {
        value: (val || 0).toFixed(2),
        label: 'kg of CO2'
      };
    },
    'usd': function(val) {
      return {
        value: '$' + (val || 0).toFixed(2),
        label: ' '
      };
    },
    'cal': function(val) {
      return {
        value: (val || 0).toFixed(),
        label: 'calories'
      };
    }
  };

  var locateMe = function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition( function(position) {
        curLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      },
      function(msg){
        alert('We couldn\'t locate your position.');
      },
      { enableHighAccuracy: true, maximumAge: 90000 });
    }
  };

  var formatResults = function(data) {
    var val, i, j, metric, mode, results = {};

    for(j=0; j<options.modes.length; j++) {
      mode = options.modes[j];

      if (data.results[mode]) {
        results[mode] = {};

        for (i=0; i<options.metrics.length; i++) {
          metric = options.metrics[i];

          if (metric) {
            results[mode][metric] = renderers[data.units[metric]](data.results[mode][metric]);
          }
        }
      }
    }

    return results;
  };

  var calculate = function(origin, destination) {
    $.mobile.pageLoading();

    $.ajax({
      url: 'info_for_route_bing',
      dataType: 'json',
      data: {
        origin: origin,
        destination: destination
      },
      success: function(data, textStatus, jqXHR) {
        var results = formatResults(data),
          html = metricsEjs.render({
            metrics: options.metrics,
            results: results
          });

        $metricsContent.html(html);

        $('#metrics-table tbody th, #metrics-table tbody td').bind('tap', function(evt) {
          $('#plan h1').text(this.parentNode.id);
          $.mobile.changePage('plan');
        });

        $.mobile.changePage('home', {
          transition: 'flip'
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {
        log(errorThrown);
        alert('Error calculating directions');
        $.mobile.pageLoading(true);
      },
      complete: function() {
        $.mobile.pageLoading(true);
      }
    });
  };

  var listAddresses = function(searchId) {
    var $list = $('#' + searchId + '-list'),
      $input = $('#' + searchId);

    return function (results, status) {
      $list.empty();

      $.each(results, function(i, val) {
        $list.append('
' + val.formatted_address + '
');
      });

      $list.listview('refresh');

      $('li', $list).tap(function() {
        $input.val(this.innerHTML);
        $list.empty();
      });
    };
  };

  var delay = function(func, timeout) {
    var timeoutId;
    return function() {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      timeoutId = setTimeout(func, timeout);
    };
  };

  var bindEvents = function() {
    var bounds;

    $originInput.keyup(function() {
      bounds = bounds || new google.maps.Circle({center:curLatLng, radius:8000}).getBounds();
      var geocode = delay(function() {
        geocoder.geocode({'address': $originInput.val(), 'bounds':bounds }, listAddresses('origin'));
      }, geocodeDelay);

      geocode();
    });

    $destinationInput.keyup(  function() {
      bounds = bounds || new google.maps.Circle({center:curLatLng, radius:8000}).getBounds();
      var geocode = delay(function() {
        geocoder.geocode({'address':$destinationInput.val(), 'bounds':bounds }, listAddresses('destination'));
      }, geocodeDelay);

      geocode();
    });

    $searchButton.tap(function() {
      calculate($originInput.val(), $destinationInput.val());
    });
  };

  $('#search').live('pagecreate',function(evt) {
    //Cache vars
    $searchButton = $('#search-button');
    $originInput = $('#origin');
    $destinationInput = $('#destination');
    $metricsContent = $('#metrics-content');

    locateMe();

    bindEvents();
  });

  $(document).bind("mobileinit", function() {
    //Disabling this b/c it could be bad for bookmarking
    $.mobile.hashListeningEnabled = false;
  });
})();<|endoftext|>


<commit_before>'use strict';

let Launcher = require('../lib/support/jar_launcher'),
  path = require('path'),
  log = require('intel');

describe('JarLauncher', function() {
  var launcher;

  beforeEach(() => {
    let jarPath = path.resolve(__dirname, '..', 'vendor', 'bmpwrapper-2.0.0-full.jar');
    launcher = new Launcher({
      'jarPath': jarPath,
      'stderrLogLevel': log.INFO,
      'startupCriteria': {
        'success': {
          'stdout': null,
          'stderr': 'Started SelectChannelConnector'
        },
        'failure': {
          'stdout': null,
          'stderr': 'Exception in thread'
        }
      }
    });
  });

  it('should launch bmp with args', function() {
    return launcher.start(['-port', 8080])
      .finally(function() {
        launcher.stop();
      });
  });

  it('should fail if bmp is launched with invalid args', function() {
    return launcher.start(['-port', 'foo'])
      .finally(function() {
        launcher.stop();
      })
      .should.be.rejected;
  });

});
<commit_msg>Forgot to return Promise from JarLauncher test.<commit_after>'use strict';

let Launcher = require('../lib/support/jar_launcher'),
  path = require('path'),
  log = require('intel');

describe('JarLauncher', function() {
  var launcher;

  beforeEach(() => {
    let jarPath = path.resolve(__dirname, '..', 'vendor', 'bmpwrapper-2.0.0-full.jar');
    launcher = new Launcher({
      'jarPath': jarPath,
      'stderrLogLevel': log.INFO,
      'startupCriteria': {
        'success': {
          'stdout': null,
          'stderr': 'Started SelectChannelConnector'
        },
        'failure': {
          'stdout': null,
          'stderr': 'Exception in thread'
        }
      }
    });
  });

  it('should launch bmp with args', function() {
    return launcher.start(['-port', 8080])
      .finally(function() {
        return launcher.stop();
      });
  });

  it('should fail if bmp is launched with invalid args', function() {
    return launcher.start(['-port', 'foo'])
      .finally(function() {
        launcher.stop();
      })
      .should.be.rejected;
  });

});
<|endoftext|>