<commit_before>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        clearTestingFields();
        clearIssueFields();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #INotes, change #IPriority': function (event) {
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },
    // When some fields are clicked, increase the text box size
    'click #IURIs, click #IEvidence, click #INotes, click #PrjNotes': function (event) {
        //console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(400);
    },
    // When some fields are unselected, decrease the text box size to a default height
    'blur #IURIs, blur #IEvidence, blur #INotes, blur #PrjNotes': function (event) {
        //console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(40);
    },
    // When Evidence and Notes fields are double-clicked, prefill them with template text.
    'dblclick #IEvidence, dblclick #INotes': function () {
        addIssueTemplateTextToUI();
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<commit_msg>Minor update.<commit_after>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        clearTestingFields();
        clearIssueFields();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #INotes, change #IPriority': function (event) {
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },
    // When some fields are clicked, increase the text box size
    'click #IURIs, click #IEvidence, click #INotes, click #PrjNotes': function (event) {
        //console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(400);
    },
    // When some fields are unselected, decrease the text box size to a default height
    'blur #IURIs, blur #IEvidence, blur #INotes, blur #PrjNotes': function (event) {
        //console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(40);
    },
    // When Evidence and Notes fields are double-clicked, prefill them with template text.
    'dblclick #IEvidence, dblclick #INotes': function () {
        addIssueTemplateTextToUI();
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dijit/_WidgetBase", "dojo/on",
	"dojo/dom-class", "dijit/_Templated", "dojo/text!./templates/FeatureOverview.html",
	"dojo/request", "dojo/_base/lang", "dojox/charting/Chart2D", "dojox/charting/themes/ThreeD", "dojox/charting/action2d/MoveSlice",
	"dojox/charting/action2d/Tooltip", "dojo/dom-construct"

], function(declare, WidgetBase, on,
			domClass, Templated, Template,
			xhr, lang, Chart2D, Theme, MoveSlice,
			ChartTooltip, domConstruct){
	return declare([WidgetBase, Templated], {
		baseClass: "FeatureOverview",
		disabled: false,
		templateString: Template,
		apiServiceUrl: window.App.dataAPI,
		feature: null,
		state: null,

		_setStateAttr: function(state){
			this._set("state", state);
			if(state.feature){
				this.set("feature", state.feature);
			}else{
				//
			}
		},

		_setFeatureAttr: function(feature){
			this.feature = feature;
			console.log("Set Feature", feature);

			this.createSummary(feature);
			this.getSummaryData();
			this.set("functionalProperties", feature);
		},
		_setRelatedFeatureListAttr: function(summary){

			domConstruct.empty(this.relatedFeatureNode);
			var table = domConstruct.create("table", {"class": "basic stripe far2x"}, this.relatedFeatureNode);
			var thead = domConstruct.create("thead", {}, table);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, thead);
			domConstruct.create("th", {innerHTML: "Annotation"}, htr);
			domConstruct.create("th", {innerHTML: "Locus Tag"}, htr);
			domConstruct.create("th", {innerHTML: "Start"}, htr);
			domConstruct.create("th", {innerHTML: "End"}, htr);
			domConstruct.create("th", {innerHTML: "NT Length"}, htr);
			domConstruct.create("th", {innerHTML: "AA Length"}, htr);
			domConstruct.create("th", {innerHTML: "Product"}, htr);

			summary.forEach(function(row){
				var tr = domConstruct.create('tr', {}, tbody);
				domConstruct.create("td", {innerHTML: row.annotation}, tr);
				domConstruct.create("td", {innerHTML: row.alt_locus_tag}, tr);
				domConstruct.create("td", {innerHTML: row.start}, tr);
				domConstruct.create("td", {innerHTML: row.end}, tr);
				domConstruct.create("td", {innerHTML: row.na_length}, tr);
				domConstruct.create("td", {innerHTML: row.aa_length || '-'}, tr);
				domConstruct.create("td", {innerHTML: row.product || '(feature type: ' + row.feature_type + ')'}, tr);
			});
		},
		_setFunctionalPropertiesAttr: function(feature){

			domConstruct.empty(this.functionalPropertiesNode);
			var table = domConstruct.create("table", {"class": "basic stripe far2x"}, this.functionalPropertiesNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "GO Assignments", scope: "row", style: "width:20%"}, htr);
			domConstruct.create("td", {innerHTML: feature.go || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "EC Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.ec || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "PATRIC Local Family Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.plfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "PATRIC Global Family Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.pgfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "FIGfam Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.figfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "Pathway Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.pathway || '-'}, htr);

			// TODO: implement structure
			// TODO: implement protein interaction
		},
		getSummaryData: function(){
			// getting uniprot mapping
			if(this.feature.gi != null){
				xhr.get(this.apiServiceUrl + "/id_ref/?eq(id_type,GI)&eq(id_value," + this.feature.gi + ")&limit(0)&http_accept=application/solr+json", {
					handleAs: "json",
					headers: {"accept": "application/solr+json"}
				}).then(lang.hitch(this, function(data){
					//console.log("Uniprot Accessions: ", data);

					// TODO: process uniprot mapping
				}));
			}

			// get related feature list
			if(this.feature.pos_group != null){
				//xhr.get(this.apiServiceUrl + "/genome_feature/?eq(pos_group," + encodeURIComponent('"' + this.feature.pos_group + '"') + ")&limit(0)&http_accept=application/solr+json", {
				xhr.get(this.apiServiceUrl + "/genome_feature/?and(eq(sequence_id," + this.feature.sequence_id + "),eq(end," + this.feature.end + "),eq(strand,\\" + this.feature.strand + "))&limit(0)&http_accept=application/solr+json", {
					handleAs: "json",
					headers: {"accept": "application/solr+json"}
				}).then(lang.hitch(this, function(data){
					var relatedFeatures = data.response.docs;
					this.set("relatedFeatureList", relatedFeatures);
				}));
			}
		},
		createSummary: function(feature){
			if(feature && feature.feature_id){
				this.geneIdList.innerHTML = 'PATRIC ID: ' + feature.patric_id + '';
				if(feature.refseq_locus_tag != null){
					this.geneIdList.innerHTML += '  RefSeq: ' + feature.refseq_locus_tag + '';
				}
				if(feature.alt_locus_tag != null){
					this.geneIdList.innerHTML += '  Alt Locus Tag: ' + feature.alt_locus_tag + '';
				}

				this.proteinIdList.innerHTML = '';
				if(feature.protein_id != null){
					this.proteinIdList.innerHTML += 'RefSeq: ' + feature.protein_id + '';
				}

				// feature box
				this.featureBoxNode.innerHTML = '
' + feature.gene || '' + '
';
				if(feature.strand == '+'){
					this.featureBoxNode.innerHTML += '';
				}else{
					this.featureBoxNode.innerHTML += '';
				}
				this.featureBoxNode.innerHTML += '
' + this.feature.feature_type + '
';

			}else{
				console.log("Invalid Feature: ", feature);
			}
		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
		}
	});
});
<commit_msg>handle when gene symbol is not defined<commit_after>define([
	"dojo/_base/declare", "dijit/_WidgetBase", "dojo/on",
	"dojo/dom-class", "dijit/_Templated", "dojo/text!./templates/FeatureOverview.html",
	"dojo/request", "dojo/_base/lang", "dojox/charting/Chart2D", "dojox/charting/themes/ThreeD", "dojox/charting/action2d/MoveSlice",
	"dojox/charting/action2d/Tooltip", "dojo/dom-construct"

], function(declare, WidgetBase, on,
			domClass, Templated, Template,
			xhr, lang, Chart2D, Theme, MoveSlice,
			ChartTooltip, domConstruct){
	return declare([WidgetBase, Templated], {
		baseClass: "FeatureOverview",
		disabled: false,
		templateString: Template,
		apiServiceUrl: window.App.dataAPI,
		feature: null,
		state: null,

		_setStateAttr: function(state){
			this._set("state", state);
			if(state.feature){
				this.set("feature", state.feature);
			}else{
				//
			}
		},

		_setFeatureAttr: function(feature){
			this.feature = feature;
			console.log("Set Feature", feature);

			this.createSummary(feature);
			this.getSummaryData();
			this.set("functionalProperties", feature);
		},
		_setRelatedFeatureListAttr: function(summary){

			domConstruct.empty(this.relatedFeatureNode);
			var table = domConstruct.create("table", {"class": "basic stripe far2x"}, this.relatedFeatureNode);
			var thead = domConstruct.create("thead", {}, table);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, thead);
			domConstruct.create("th", {innerHTML: "Annotation"}, htr);
			domConstruct.create("th", {innerHTML: "Locus Tag"}, htr);
			domConstruct.create("th", {innerHTML: "Start"}, htr);
			domConstruct.create("th", {innerHTML: "End"}, htr);
			domConstruct.create("th", {innerHTML: "NT Length"}, htr);
			domConstruct.create("th", {innerHTML: "AA Length"}, htr);
			domConstruct.create("th", {innerHTML: "Product"}, htr);

			summary.forEach(function(row){
				var tr = domConstruct.create('tr', {}, tbody);
				domConstruct.create("td", {innerHTML: row.annotation}, tr);
				domConstruct.create("td", {innerHTML: row.alt_locus_tag}, tr);
				domConstruct.create("td", {innerHTML: row.start}, tr);
				domConstruct.create("td", {innerHTML: row.end}, tr);
				domConstruct.create("td", {innerHTML: row.na_length}, tr);
				domConstruct.create("td", {innerHTML: row.aa_length || '-'}, tr);
				domConstruct.create("td", {innerHTML: row.product || '(feature type: ' + row.feature_type + ')'}, tr);
			});
		},
		_setFunctionalPropertiesAttr: function(feature){

			domConstruct.empty(this.functionalPropertiesNode);
			var table = domConstruct.create("table", {"class": "basic stripe far2x"}, this.functionalPropertiesNode);
			var tbody = domConstruct.create("tbody", {}, table);

			var htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "GO Assignments", scope: "row", style: "width:20%"}, htr);
			domConstruct.create("td", {innerHTML: feature.go || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "EC Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.ec || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "PATRIC Local Family Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.plfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "PATRIC Global Family Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.pgfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "FIGfam Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.figfam_id || '-'}, htr);

			htr = domConstruct.create("tr", {}, tbody);
			domConstruct.create("th", {innerHTML: "Pathway Assignments", scope: "row"}, htr);
			domConstruct.create("td", {innerHTML: feature.pathway || '-'}, htr);

			// TODO: implement structure
			// TODO: implement protein interaction
		},
		getSummaryData: function(){
			// getting uniprot mapping
			if(this.feature.gi != null){
				xhr.get(this.apiServiceUrl + "/id_ref/?eq(id_type,GI)&eq(id_value," + this.feature.gi + ")&limit(0)&http_accept=application/solr+json", {
					handleAs: "json",
					headers: {"accept": "application/solr+json"}
				}).then(lang.hitch(this, function(data){
					//console.log("Uniprot Accessions: ", data);

					// TODO: process uniprot mapping
				}));
			}

			// get related feature list
			if(this.feature.pos_group != null){
				//xhr.get(this.apiServiceUrl + "/genome_feature/?eq(pos_group," + encodeURIComponent('"' + this.feature.pos_group + '"') + ")&limit(0)&http_accept=application/solr+json", {
				xhr.get(this.apiServiceUrl + "/genome_feature/?and(eq(sequence_id," + this.feature.sequence_id + "),eq(end," + this.feature.end + "),eq(strand,\\" + this.feature.strand + "))&limit(0)&http_accept=application/solr+json", {
					handleAs: "json",
					headers: {"accept": "application/solr+json"}
				}).then(lang.hitch(this, function(data){
					var relatedFeatures = data.response.docs;
					this.set("relatedFeatureList", relatedFeatures);
				}));
			}
		},
		createSummary: function(feature){
			if(feature && feature.feature_id){
				this.geneIdList.innerHTML = 'PATRIC ID: ' + feature.patric_id + '';
				if(feature.refseq_locus_tag != null){
					this.geneIdList.innerHTML += '  RefSeq: ' + feature.refseq_locus_tag + '';
				}
				if(feature.alt_locus_tag != null){
					this.geneIdList.innerHTML += '  Alt Locus Tag: ' + feature.alt_locus_tag + '';
				}

				this.proteinIdList.innerHTML = '';
				if(feature.protein_id != null){
					this.proteinIdList.innerHTML += 'RefSeq: ' + feature.protein_id + '';
				}

				// feature box
				this.featureBoxNode.innerHTML = '
' + (feature.gene || ' ') + '
';
				if(feature.strand == '+'){
					this.featureBoxNode.innerHTML += '';
				}else{
					this.featureBoxNode.innerHTML += '';
				}
				this.featureBoxNode.innerHTML += '
' + this.feature.feature_type + '
';

			}else{
				console.log("Invalid Feature: ", feature);
			}
		},
		startup: function(){
			if(this._started){
				return;
			}
			this.inherited(arguments);
		}
	});
});
<|endoftext|>


<commit_before>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        clearUI();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #INotes, change #IPriority': function (event) {
        addIssueTemplateTextToUI();
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'click #IEvidence, click #INotes, click #PrjNotes': function (event) {
        console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(400);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'blur #IEvidence, blur #INotes, blur #PrjNotes': function (event) {
        console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(50);
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<commit_msg>Minor update.<commit_after>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        clearUI();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #INotes, change #IPriority': function (event) {
        addIssueTemplateTextToUI();
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'click #IURIs, click #IEvidence, click #INotes, click #PrjNotes': function (event) {
        console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(400);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'blur #IURIs, blur #IEvidence, blur #INotes, blur #PrjNotes': function (event) {
        console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(40);
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<|endoftext|>


<commit_before>/*
 * This scripts shows how we can work with socket.io
 * notifications sendby Hunt framework.
 */
var socket = io.connect('', {
  'connect timeout': 1000
});

var model = {
  'clock': ko.observable(),
  'recentVisits': ko.observableArray(),
  'pingerUrl': ko.observable(),
  'pingerAnswer': ko.observable('Enter URL'),
  'sioMessage': ko.observable(),
  'sendSioMessage':function(){
    socket.send(this.sioMessage());
  },
  'flash':{
    'error':ko.observableArray(),
    'info':ko.observableArray(),
    'success':ko.observableArray(),
  }
}

model.pingerUrl.subscribe(function(newUrl){
  if(newUrl){
    socket.emit('pingerUrl', newUrl);
  } else {
    model.pingerAnswer('Enter URL...');
  }
});

ko.applyBindings(model);

//socket.io event for pinger
socket.on('pingerAnswer', model.pingerAnswer);

//socket.io events, delivered to all users online
socket.on('broadcast', function (data) {
//  console.log(data);
  if (data.time) {
    model.clock(data.time);
  }

  if(data.httpSuccess){
    model.recentVisits.push(data.httpSuccess);
  }

  if(data.notification){
    console.log(data);
  }
});
<commit_msg>fixes in frontend of example<commit_after>/*
 * This scripts shows how we can work with socket.io
 * notifications sendby Hunt framework.
 */
var socket = io.connect('', {
  'connect timeout': 1000
});

var model = {
  'clock': ko.observable(),
  'recentVisits': ko.observableArray(),
  'pingerUrl': ko.observable(),
  'pingerAnswer': ko.observable('Enter URL'),
  'sioMessage': ko.observable(),
  'sendSioMessage':function(){
    var that = this;
    socket.send(that.sioMessage(), function(error){
      if(error){
        throw error;
      }
      that.sioMessage('');
    });
  },
  'flash':{
    'error':ko.observableArray(),
    'info':ko.observableArray(),
    'success':ko.observableArray(),
  }
}

model.pingerUrl.subscribe(function(newUrl){
  if(newUrl){
    socket.emit('pingerUrl', newUrl);
  } else {
    model.pingerAnswer('Enter URL...');
  }
});

ko.applyBindings(model);

//socket.io event for pinger
socket.on('pingerAnswer', model.pingerAnswer);

//socket.io events, delivered to all users online
socket.on('broadcast', function (data) {
//  console.log(data);
  if (data.time) {
    model.clock(data.time);
  }

  if(data.httpSuccess){
    model.recentVisits.push(data.httpSuccess);
  }

  if(data.notification){
    console.log(data);
  }
});
<|endoftext|>


<commit_before>
if (!library) {
    var library = {};
}

library.json = {
   replacer: function(match, pIndent, pKey, pVal, pEnd) {
        var key = '';
        var val = '';
        var str = '';
        var r = pIndent || '';
        if (pKey) {
            r = r + key + pKey.replace(/[": ]/g, '') + ': ';
        }
        if (pVal) {
            r = r + (pVal[0] == '"' ? str : val) + pVal + '';
        }
        return r + (pEnd || '');
    },
    prettyPrint: function(obj) {
        var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
        return JSON.stringify(obj, null, 3)
            .replace(/&/g, '&').replace(/\\"/g, '"')
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(jsonLine, library.json.replacer);
    }
};
<commit_msg>[BUG] Fixed issue where init preview wasn't quoting the keynames<commit_after>
if (!library) {
    var library = {};
}

library.json = {
   replacer: function(match, pIndent, pKey, pVal, pEnd) {
        var key = '';
        var val = '';
        var str = '';
        var r = pIndent || '';
        if (pKey) {
            r = r + key + pKey.replace(/[: ]/g, '') + ': ';
        }
        if (pVal) {
            r = r + (pVal[0] == '"' ? str : val) + pVal + '';
        }
        return r + (pEnd || '');
    },
    prettyPrint: function(obj) {
        var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
        return JSON.stringify(obj, null, 3)
            .replace(/&/g, '&').replace(/\\"/g, '"')
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(jsonLine, library.json.replacer);
    }
};
<|endoftext|>


<commit_before>var ajaxPrefix = 'http://localhost:9090/'; // For development
// var ajaxPrefix = '/'; // For deployment

var stage;
var actorLayer;

var record;
var schema;

function onLoad()
{
	populateNavBar();
	populateButtons();
	updateSchema();
	initStage();
	initUi();
}

function populateNavBar()
{
	$("#navbar").empty();
	$('
Records
').appendTo("#navbar");
	$.getJSON(ajaxPrefix + 'records/', function(data) {
		for (record in data)
		{
			var recordItem = $("
"+data[record].name+"
").
				click(function() {loadRecord($(this).attr("data-id"));}).
				appendTo('#navbar');
		}
	});
}

function populateButtons()
{
	$("#save").click(onSave);
	$("#export").click(onExport);
}

function updateSchema()
{
	$.getJSON(ajaxPrefix + 'schema/', function(data) {
		schema = data;

		var structs = schema.structs;

		for (item in structs)
		{
			if (structs[item].type == "entity")
			{
				$("
"+structs[item].description+"
").click(function() {createEntity($(this).attr("data-id"));}).appendTo('#entityTypes');
			}
			if (structs[item].type == "record")
			{
				$("
"+structs[item].description+"
").click(function() {
					$('#createRecordModal').attr("data-id", $(this).attr("data-id"));
					$('#createRecordModal').modal();
				}).appendTo('#recordTypes');
			}
		}

		$('.dropdown-toggle').dropdown();
	});
}

function initStage()
{
	$('#canvas').empty();
	stage = new Kinetic.Stage({container: 'canvas',
		width:600,
		height:600});

	actorLayer = new Kinetic.Layer();
	stage.add(actorLayer);
}

function initUi()
{
	$('#createRecordModal').submit(function() {
		$('#createRecordModal').modal('hide');

		$.ajax({
			type: 'POST',
			url: ajaxPrefix+'records?type='+$(this).attr("data-id")+'&name='+$('#createRecordName').attr("value"),
			complete : function() {
				populateNavBar();
			}
		});

		return false;
	});
}

function loadRecord(record)
{
	initStage();

	this.record = record;

	$.getJSON(ajaxPrefix + 'record/' + record + '/entities', function(data) {
		for (entity in data)
		{
			var shape = new Kinetic.RegularPolygon({
				x: toPixels(data[entity].data.Transform.tx),
				y: toPixels(data[entity].data.Transform.ty),
				sides: 10,
				radius: 2*32,
				fill: 'red',
				stroke: 'black',
				strokeWidth: 4,
				draggable: true
			});

			shape.entityId = data[entity].data.Uid;

			shape.on("dragend", function(evt) {
				var url = ajaxPrefix+'record/'+record+'/entity/'+evt.shape.entityId+'/transform?tx='+getX(evt.shape)+'&ty='+getY(evt.shape);
				$.ajax({
							type: 'PUT',
							url: url,
							complete : function() {
							}
						});

				actorLayer.draw();
			});

			actorLayer.add(shape);
		}

		actorLayer.draw();
	});
}

function createRecord(recordType)
{
	$.ajax({
		type: 'POST',
		url: ajaxPrefix+'records?type='+recordType,
		complete : function() {
			populateNavBar();
		}
	});
}

function createEntity(entityType)
{
	$.ajax({
		type: 'POST',
		url: ajaxPrefix+'record/'+record+'/entities?type='+entityType,
		complete : function() {
			loadRecord(record);
		}
	});
}

function onSave()
{
	$.ajax({
		type: 'PUT',
		url: ajaxPrefix+'save',
		complete : function() {
		}
	});
}

function onExport()
{
	$.ajax({
		type: 'PUT',
		url: ajaxPrefix+'export',
		complete : function() {
		}
	});
}

function toPixels(unit)
{
	return unit*32;
}

function fromPixels(pixels)
{
	return pixels/32;
}

function getX(shape)
{
	return fromPixels(shape.getPosition().x);
}

function getY(shape)
{
	return fromPixels(shape.getPosition().y);
}
<commit_msg>Load schema in a nicer way, and use circles instead of polygons<commit_after>var ajaxPrefix = 'http://localhost:9090/'; // For development
// var ajaxPrefix = '/'; // For deployment

var stage;
var actorLayer;

var record;
var schema;

function onLoad()
{
	populateNavBar();
	populateButtons();
	updateSchema();
	initStage();
	initUi();
}

function populateNavBar()
{
	$("#navbar").empty();
	$('
Records
').appendTo("#navbar");
	$.getJSON(ajaxPrefix + 'records/', function(data) {
		for (record in data)
		{
			var recordItem = $("
"+data[record].name+"
").
				click(function() {loadRecord($(this).attr("data-id"));}).
				appendTo('#navbar');
		}
	});
}

function populateButtons()
{
	$("#save").click(onSave);
	$("#export").click(onExport);
}

function updateSchema()
{
	$.getJSON(ajaxPrefix + 'schema/', function(data) {
		schema = new Object();
		for (struct in data.structs)
		{
			schema[data.structs[struct].name] = data.structs[struct];
		}

		for (item in schema)
		{
			if (schema[item].type == "entity")
			{
				$("
"+schema[item].description+"
").click(function() {createEntity($(this).attr("data-id"));}).appendTo('#entityTypes');
			}
			if (schema[item].type == "record")
			{
				$("
"+schema[item].description+"
").click(function() {
					$('#createRecordModal').attr("data-id", $(this).attr("data-id"));
					$('#createRecordModal').modal();
				}).appendTo('#recordTypes');
			}
		}

		$('.dropdown-toggle').dropdown();
	});
}

function initStage()
{
	$('#canvas').empty();
	stage = new Kinetic.Stage({container: 'canvas',
		width:600,
		height:600});

	actorLayer = new Kinetic.Layer();
	stage.add(actorLayer);
}

function initUi()
{
	$('#createRecordModal').submit(function() {
		$('#createRecordModal').modal('hide');

		$.ajax({
			type: 'POST',
			url: ajaxPrefix+'records?type='+$(this).attr("data-id")+'&name='+$('#createRecordName').attr("value"),
			complete : function() {
				populateNavBar();
			}
		});

		return false;
	});
}

function loadRecord(record)
{
	initStage();

	this.record = record;

	$.getJSON(ajaxPrefix + 'record/' + record + '/entities', function(data) {
		for (entity in data)
		{
			initialiseEntity(data[entity]);
		}

		actorLayer.draw();
	});
}

function createRecord(recordType)
{
	$.ajax({
		type: 'POST',
		url: ajaxPrefix+'records?type='+recordType,
		complete : function() {
			populateNavBar();
		}
	});
}

function createEntity(entityType)
{
	$.ajax({
		type: 'POST',
		url: ajaxPrefix+'record/'+record+'/entities?type='+entityType,
		complete : function() {
			loadRecord(record);
		}
	});
}

function initialiseEntity(entity)
{
	var schemaStruct = schema[entity.data.Type];
	var shape;

	if (!schemaStruct)
	{
		shape = new Kinetic.Circle({
			x: toPixels(entity.data.Transform.tx),
			y: toPixels(entity.data.Transform.ty),
			radius: 32,
			fill: 'grey',
			stroke: 'black',
			strokeWidth: 1.5,
			draggable: true
		});
	} else {
		shape = new Kinetic.Circle({
			x: toPixels(entity.data.Transform.tx),
			y: toPixels(entity.data.Transform.ty),
			radius: 32,
			fill: 'red',
			stroke: 'black',
			strokeWidth: 1.5,
			draggable: true
		});
	}

	shape.entityId = entity.data.Uid;

	shape.on("dragend", function(evt) {
		var url = ajaxPrefix+'record/'+record+'/entity/'+evt.shape.entityId+'/transform?tx='+getX(evt.shape)+'&ty='+getY(evt.shape);
		$.ajax({
			type: 'PUT',
			url: url,
			complete : function() {
			}
		});
	});

	actorLayer.add(shape);
}

function onSave()
{
	$.ajax({
		type: 'PUT',
		url: ajaxPrefix+'save',
		complete : function() {
		}
	});
}

function onExport()
{
	$.ajax({
		type: 'PUT',
		url: ajaxPrefix+'export',
		complete : function() {
		}
	});
}

function toPixels(unit)
{
	return unit*32;
}

function fromPixels(pixels)
{
	return pixels/32;
}

function getX(shape)
{
	return fromPixels(shape.getPosition().x);
}

function getY(shape)
{
	return fromPixels(shape.getPosition().y);
}
<|endoftext|>


<commit_before>"use strict";

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

import SignIn from "../components/Windows/SignIn.vue";
import Connect from "../components/Windows/Connect.vue";
import Settings from "../components/Windows/Settings.vue";
import Help from "../components/Windows/Help.vue";
import Changelog from "../components/Windows/Changelog.vue";
import NetworkEdit from "../components/Windows/NetworkEdit.vue";
import RoutedChat from "../components/RoutedChat.vue";
import constants from "./constants";
import store from "./store";

const router = new VueRouter({
	routes: [
		{
			name: "SignIn",
			path: "/sign-in",
			component: SignIn,
			beforeEnter(to, from, next) {
				// Prevent navigating to sign-in when already signed in
				if (store.state.appLoaded) {
					next(false);
					return;
				}

				next();
			},
		},
	],
});

router.beforeEach((to, from, next) => {
	// Disallow navigating to non-existing routes
	if (store.state.appLoaded && !to.matched.length) {
		next(false);
		return;
	}

	// Disallow navigating to invalid channels
	if (to.name === "RoutedChat" && !store.getters.findChannel(Number(to.params.id))) {
		next(false);
		return;
	}

	// Handle closing image viewer with the browser back button
	if (!router.app.$refs.app) {
		next();
		return;
	}

	const imageViewer = router.app.$root.$refs.app.$refs.imageViewer;

	if (imageViewer && imageViewer.link) {
		imageViewer.closeViewer();
		next(false);
		return;
	}

	next();
});

router.afterEach(() => {
	if (store.state.appLoaded) {
		if (window.innerWidth <= constants.mobileViewportPixels) {
			store.commit("sidebarOpen", false);
		}
	}

	if (store.state.activeChannel) {
		const channel = store.state.activeChannel.channel;
		store.commit("activeChannel", null);

		// When switching out of a channel, mark everything as read
		if (channel.messages.length > 0) {
			channel.firstUnread = channel.messages[channel.messages.length - 1].id;
		}

		if (channel.messages.length > 100) {
			channel.messages.splice(0, channel.messages.length - 100);
			channel.moreHistoryAvailable = true;
		}
	}
});

function initialize() {
	router.addRoutes([
		{
			name: "Connect",
			path: "/connect",
			component: Connect,
			props: (route) => ({queryParams: route.query}),
		},
		{
			name: "Settings",
			path: "/settings",
			component: Settings,
		},
		{
			name: "Help",
			path: "/help",
			component: Help,
		},
		{
			name: "Changelog",
			path: "/changelog",
			component: Changelog,
		},
		{
			name: "NetworkEdit",
			path: "/edit-network/:uuid",
			component: NetworkEdit,
		},
		{
			name: "RoutedChat",
			path: "/chan-:id",
			component: RoutedChat,
		},
	]);
}

function navigate(routeName, params = {}) {
	router.push({name: routeName, params}).catch(() => {});
}

function switchToChannel(channel) {
	return navigate("RoutedChat", {id: channel.id});
}

export {initialize, router, navigate, switchToChannel};
<commit_msg>Fix Vue error when navigating to channels via InlineChannel.<commit_after>"use strict";

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

import SignIn from "../components/Windows/SignIn.vue";
import Connect from "../components/Windows/Connect.vue";
import Settings from "../components/Windows/Settings.vue";
import Help from "../components/Windows/Help.vue";
import Changelog from "../components/Windows/Changelog.vue";
import NetworkEdit from "../components/Windows/NetworkEdit.vue";
import RoutedChat from "../components/RoutedChat.vue";
import constants from "./constants";
import store from "./store";

const router = new VueRouter({
	routes: [
		{
			name: "SignIn",
			path: "/sign-in",
			component: SignIn,
			beforeEnter(to, from, next) {
				// Prevent navigating to sign-in when already signed in
				if (store.state.appLoaded) {
					next(false);
					return;
				}

				next();
			},
		},
	],
});

router.beforeEach((to, from, next) => {
	// Disallow navigating to non-existing routes
	if (store.state.appLoaded && !to.matched.length) {
		next(false);
		return;
	}

	// Disallow navigating to invalid channels
	if (to.name === "RoutedChat" && !store.getters.findChannel(Number(to.params.id))) {
		next(false);
		return;
	}

	// Handle closing image viewer with the browser back button
	if (!router.app.$refs.app) {
		next();
		return;
	}

	const imageViewer = router.app.$root.$refs.app.$refs.imageViewer;

	if (imageViewer && imageViewer.link) {
		imageViewer.closeViewer();
		next(false);
		return;
	}

	next();
});

router.afterEach((to) => {
	if (store.state.appLoaded) {
		if (window.innerWidth <= constants.mobileViewportPixels) {
			store.commit("sidebarOpen", false);
		}
	}

	if (store.state.activeChannel) {
		const channel = store.state.activeChannel.channel;

		if (to.name !== "RoutedChat") {
			store.commit("activeChannel", null);
		}

		// When switching out of a channel, mark everything as read
		if (channel.messages.length > 0) {
			channel.firstUnread = channel.messages[channel.messages.length - 1].id;
		}

		if (channel.messages.length > 100) {
			channel.messages.splice(0, channel.messages.length - 100);
			channel.moreHistoryAvailable = true;
		}
	}
});

function initialize() {
	router.addRoutes([
		{
			name: "Connect",
			path: "/connect",
			component: Connect,
			props: (route) => ({queryParams: route.query}),
		},
		{
			name: "Settings",
			path: "/settings",
			component: Settings,
		},
		{
			name: "Help",
			path: "/help",
			component: Help,
		},
		{
			name: "Changelog",
			path: "/changelog",
			component: Changelog,
		},
		{
			name: "NetworkEdit",
			path: "/edit-network/:uuid",
			component: NetworkEdit,
		},
		{
			name: "RoutedChat",
			path: "/chan-:id",
			component: RoutedChat,
		},
	]);
}

function navigate(routeName, params = {}) {
	router.push({name: routeName, params}).catch(() => {});
}

function switchToChannel(channel) {
	return navigate("RoutedChat", {id: channel.id});
}

export {initialize, router, navigate, switchToChannel};
<|endoftext|>


<commit_before>'use strict';

var config = rootRequire('config/config');

var crypto = require("crypto");
var fs = require("fs");
var gcloud = require('gcloud')({
    keyFilename: config.GOOGLE_DEVELOPER_KEY_PATH,
    projectId: config.GOOGLE_PROJECT_NAME
});

var credentials = require(config.GOOGLE_DEVELOPER_KEY_PATH);
var bucket = gcloud.storage().bucket(config.BUCKET_NAME);
var googlePrivateKey = credentials.private_key;
var googleAccessEmail = credentials.client_email;

/**
 * Returns the https url of the bucket
 **/
function getBucketUrl() {
    return "https://" + config.BUCKET_NAME + ".storage.googleapis.com";
}

exports.getBucketUrl = getBucketUrl;

/**
 * Returns the https url of the bucket
 **/
function getGoogleAccessEmail() {
    return googleAccessEmail;
}

exports.getGoogleAccessEmail = getGoogleAccessEmail;

/**
 * Function to create signed urls to google cloud storage
 * key: key of the object that we want to read (GET), write (PUT) or delete (DELETE)
 * method: HTTP method supported by the signed url (GET, PUT, DELETE)
 * timeToLive: is the time the signed url will last after being generated (in seconds)
 * callback: error first callback to handle the signed url
 */
function createSignedUrl(key, method, timeToLive, callback) {
    if (!key) {
        var err = new Error
        err.status = 404
        err.message = "File not found"
        callback(err);
        return;
    }
    var options = {};
    switch (method) {
        case 'GET':
            options.action = 'read';
            break;
        case 'PUT':
            options.action = 'write';
            options.contentType = 'application/json;charset=utf-8';
            break;
        case 'DELETE':
            options.action = 'delete';
            break;
        default:
            action = 'read';
            break;
    }
    var file = bucket.file(key);
    options.expires = Math.round(Date.now() / 1000) + timeToLive;
    file.getSignedUrl(options, callback);
}

exports.createSignedUrl = createSignedUrl;

/**
 * Creates a policy and its signature
 * TODO handle contentType
 **/
function createSignedPolicy(key, expiration, maxByteSize, contentType) {
    var policy = {
        expiration: expiration.toISOString(),
        conditions: [
            ["eq", "$key", key],
            ["content-length-range", 0, maxByteSize], {
                "bucket": config.BUCKET_NAME
            }
        ]
    };

    var policyString = JSON.stringify(policy);
    console.log(policyString);
    var policyBase64 = new Buffer(policyString).toString('base64');
    console.log(policyBase64);
    var sign = crypto.createSign('RSA-SHA256');
    sign.update(policyBase64);
    var signature = sign.sign(googlePrivateKey, 'base64');
    console.log(signature);

    return {
        policy: policyBase64,
        signature: signature
    };
}

exports.createSignedPolicy = createSignedPolicy;

/**
 * Uploads a file to Cloud Storage0
 */
function upload(filename, filepath, callback) {
    /*
      // Long way to upload a file
      var file = bucket.file(filename);
      var error = false;
      var readStream = fs.createReadStream(filepath);
      readStream.on('open', function() {
          var writeStream = file.createWriteStream();
          writeStream.on('error', function(err) {
              error = true;
          });
          writeStream.on('close', function() {
            console.log("Closing write stream");
            if (!error) callback(null, filename);
            else callback("Error uploading file", filename);
          });

        });
      readStream.on('error', function(err) {
          callback("Error reading file", filename);
      });
    */
    // Short way to upload a file
    bucket.upload(filepath, {
        destination: filename
    }, function(err) {
        callback(err, filename);
    });
}

exports.upload = upload;

/**
 * Removes a file from cloud storage
 */
function move(filename, newFilename, callback) {
    if (filename) {
        bucket.file(filename).copy(newFilename, function(err, newFile) {
            if (err) {
                callback(err)
            } else {
                file.delete(callback);
            }
        });
    } else {
        callback(new Error("Filename not specified"))
    }
}

exports.remove = remove;

/**
 * Removes a file from cloud storage
 */
function remove(filename, callback) {
    if (filename)
        bucket.file(filename).delete(callback);
    else
        callback(new Error("Filename not specified"))
}

exports.remove = remove;

/**
 * Create a read stream for a file corresponding to filename
 **/
function createReadStream(filename) {
    var file = bucket.file(filename);
    return file.createReadStream();
}

exports.createReadStream = createReadStream;

/**
 * Create a read stream for a file corresponding to filename
 **/
function createReadStream(filename) {
    var file = bucket.file(filename);
    return file.createReadStream();
}

exports.createReadStream = createReadStream;
<commit_msg>Added APIs to copy and move a file<commit_after>'use strict';

var config = rootRequire('config/config');

var crypto = require("crypto");
var fs = require("fs");
var gcloud = require('gcloud')({
    keyFilename: config.GOOGLE_DEVELOPER_KEY_PATH,
    projectId: config.GOOGLE_PROJECT_NAME
});

var credentials = require(config.GOOGLE_DEVELOPER_KEY_PATH);
var bucket = gcloud.storage().bucket(config.BUCKET_NAME);
var googlePrivateKey = credentials.private_key;
var googleAccessEmail = credentials.client_email;

/**
 * Returns the https url of the bucket
 **/
function getBucketUrl() {
    return "https://" + config.BUCKET_NAME + ".storage.googleapis.com";
}

exports.getBucketUrl = getBucketUrl;

/**
 * Returns the https url of the bucket
 **/
function getGoogleAccessEmail() {
    return googleAccessEmail;
}

exports.getGoogleAccessEmail = getGoogleAccessEmail;

/**
 * Function to create signed urls to google cloud storage
 * key: key of the object that we want to read (GET), write (PUT) or delete (DELETE)
 * method: HTTP method supported by the signed url (GET, PUT, DELETE)
 * timeToLive: is the time the signed url will last after being generated (in seconds)
 * callback: error first callback to handle the signed url
 */
function createSignedUrl(key, method, timeToLive, callback) {
    if (!key) {
        var err = new Error
        err.status = 404
        err.message = "File not found"
        callback(err);
        return;
    }
    var options = {};
    switch (method) {
        case 'GET':
            options.action = 'read';
            break;
        case 'PUT':
            options.action = 'write';
            options.contentType = 'application/json;charset=utf-8';
            break;
        case 'DELETE':
            options.action = 'delete';
            break;
        default:
            action = 'read';
            break;
    }
    var file = bucket.file(key);
    options.expires = Math.round(Date.now() / 1000) + timeToLive;
    file.getSignedUrl(options, callback);
}

exports.createSignedUrl = createSignedUrl;

/**
 * Creates a policy and its signature
 * TODO handle contentType
 **/
function createSignedPolicy(key, expiration, maxByteSize, contentType) {
    var policy = {
        expiration: expiration.toISOString(),
        conditions: [
            ["eq", "$key", key],
            ["content-length-range", 0, maxByteSize], {
                "bucket": config.BUCKET_NAME
            }
        ]
    };

    var policyString = JSON.stringify(policy);
    console.log(policyString);
    var policyBase64 = new Buffer(policyString).toString('base64');
    console.log(policyBase64);
    var sign = crypto.createSign('RSA-SHA256');
    sign.update(policyBase64);
    var signature = sign.sign(googlePrivateKey, 'base64');
    console.log(signature);

    return {
        policy: policyBase64,
        signature: signature
    };
}

exports.createSignedPolicy = createSignedPolicy;

/**
 * Uploads a file to Cloud Storage0
 */
function upload(filename, filepath, callback) {
    /*
      // Long way to upload a file
      var file = bucket.file(filename);
      var error = false;
      var readStream = fs.createReadStream(filepath);
      readStream.on('open', function() {
          var writeStream = file.createWriteStream();
          writeStream.on('error', function(err) {
              error = true;
          });
          writeStream.on('close', function() {
            console.log("Closing write stream");
            if (!error) callback(null, filename);
            else callback("Error uploading file", filename);
          });

        });
      readStream.on('error', function(err) {
          callback("Error reading file", filename);
      });
    */
    // Short way to upload a file
    bucket.upload(filepath, {
        destination: filename
    }, function(err) {
        callback(err, filename);
    });
}

exports.upload = upload;

/**
 * Removes a file from cloud storage
 */
function move(filename, newFilename, callback) {
    if (filename) {
        var file = bucket.file(filename);
        file.copy(newFilename, function(err, newFile) {
            if (err) {
                callback(err)
            } else {
                file.delete(callback);
            }
        });
    } else {
        callback(new Error("Filename not specified"))
    }
}

exports.move = move;

/**
 * Copies a file from cloud storage
 */
function copy(filename, newFilename, callback) {
    if (filename) {
        bucket.file(filename).copy(newFilename, function(err, newFile) {
            callback(err)
        });
    } else {
        callback(new Error("Filename not specified"))
    }
}

exports.copy = copy;

/**
 * Removes a file from cloud storage
 */
function remove(filename, callback) {
    if (filename)
        bucket.file(filename).delete(callback);
    else
        callback(new Error("Filename not specified"))
}

exports.remove = remove;

/**
 * Create a read stream for a file corresponding to filename
 **/
function createReadStream(filename) {
    var file = bucket.file(filename);
    return file.createReadStream();
}

exports.createReadStream = createReadStream;

/**
 * Create a read stream for a file corresponding to filename
 **/
function createReadStream(filename) {
    var file = bucket.file(filename);
    return file.createReadStream();
}

exports.createReadStream = createReadStream;
<|endoftext|>