<commit_before>const app = new Vue({
    el: "#app",
    data: {
        characters: [],
        rarity: [],
        stats: {
            level: {
                value: 70,
                max: 70,
                min: 1,
                step: 1,
                color: "blue"
            },
            bs: {
                value: 40,
                max: 40,
                color: 'light-green'
            },
            spu: {
                value: 5,
                max: 5,
                color: 'deep-orange'
            },
            apu: {
                value: 0,
                max: 30,
                color: 'cyan'
            }
        },
        toggle: {
            lastEvo: true,
            special: false,
        },
        selected: {
            rarity: [],
            role: [],
            element: [],
            evolution: []
        },
        dataTable: {
            search: '',
            isLoading: true,
            pageRows: [15, 30, 50],
            headers: [{
                    text: 'Name',
                    align: 'left',
                    value: 'name'
                },
                {
                    text: 'Rarity',
                    align: 'right',
                    value: 'rarity'
                },
                {
                    text: 'Role',
                    align: 'right',
                    value: 'role'
                },
                {
                    text: 'Element',
                    align: 'right',
                    value: 'element'
                },
                {
                    text: 'Power',
                    align: 'right',
                    value: 'cur_pow'
                },
                {
                    text: 'Technique',
                    align: 'right',
                    value: 'cur_tec'
                },
                {
                    text: 'Vitality',
                    align: 'right',
                    value: 'cur_vit'
                },
                {
                    text: 'Speed',
                    align: 'right',
                    value: 'cur_spd'
                },
                {
                    text: 'Total Stats',
                    align: 'right',
                    value: 'cur_total'
                }
            ],
            customFilter: function (items, search, filter) {
                search = _.lowerCase(search);
                return items.filter(function (item) {
                    const selected = app.selected;
                    const toggle = app.toggle;
                    return filter(item.name, search) &&
                        app.filterToggle(item.isLastEvo, toggle.lastEvo) &&
                        app.filterToggle(item.isSpecial, toggle.special) &&
                        app.filterArray(item.rarity, selected.rarity) &&
                        app.filterArray(item.role, selected.role) &&
                        app.filterArray(item.evolution, selected.evolution) &&
                        app.filterArray(item.element, selected.element);
                });
            }
        },

    },
    created: function () {
        this.getCharData();
        this.deb_getFinalStats = _.debounce(this.getFinalStats, 500)
    },
    watch: {
        stats: {
            handler: function () {
                this.deb_getFinalStats();
            },
            deep: true
        }
    },
    methods: {
        filterToggle: function (val, toggle) {
            return (toggle && val) ||
                (toggle == false);
        },
        filterArray: function (obj, arr) {
            return (!arr.length >= 1) ||
                (arr.includes(obj.toString()));
        },
        isPlayer: function (character) {
            return (character === "Player") ? true : false;
        },
        getStat: function (minStat, maxStat, rarity) {
            let stLevel = this.stats.level.value / 10;
            let minStatRate = Math.pow(.176, (6 - (stLevel)) / 10);
            let stat = Math.round(minStat * minStatRate);
            let finalStat = Math.floor(stat + (maxStat - stat) * Math.pow((this.stats.level.value - 1) / (60 - 1), 1));
            let totalFinal = Math.floor(finalStat * this.getSpuBonus()) + this.getApuBonus(rarity) + this.stats.bs.value;
            return totalFinal;
        },
        getApuBonus: function (rarity) {
            return (rarity > 5) ?
                this.stats.apu.value :
                Math.floor(this.stats.apu.value * 1.2);
        },
        getSpuBonus: function () {
            return 1 + this.stats.spu.value * 0.1;
        },
        getFinalStats: function () {
            this.dataTable.isLoading = true;
            this.characters.forEach(char => {
                let cur_pow = this.getStat(char.min_pow, char.max_pow);
                let cur_tec = this.getStat(char.min_tec, char.max_tec);
                let cur_vit = this.getStat(char.min_vit, char.max_vit);
                let cur_spd = this.getStat(char.min_spd, char.max_spd);
                let cur_total = cur_pow + cur_tec + cur_vit + cur_spd;

                char.cur_pow = cur_pow;
                char.cur_tec = cur_tec;
                char.cur_vit = cur_vit;
                char.cur_spd = cur_spd;
                char.cur_total = cur_total;
            });
            this.dataTable.isLoading = false;
        },
        getCharData: function () {
            axios.get('/api/characters/').then(response => {
                this.loadCharData(response.data);
                this.getFinalStats();
                this.dataTable.isLoading = false;
            });
        },
        getEvoSuffix: function (id) {
            if (id == "3") {
                return " (EE)"
            } else if (id == "2") {
                return " (E)"
            }
            return "";
        },
        isLastEvo: function (id, ids) {
            let isLast;
            id = id.toString().substring(1);
            isLast = !(ids.indexOf(id) >= 0);
            if (isLast)
                ids.push(id);
            return isLast;
        },
        loadCharData: function (data) {
            let playerIds = [];
            this.characters = [];

            for (var x = data.length - 1; x >= 0; x--) {
                let player = data[x];

                if (this.isPlayer(player.category)) {
                    let evoLevel = player.id.toString().substring(0, 1);

                    this.characters.push({
                        name: player.name + this.getEvoSuffix(evoLevel),
                        rarity: player.rarity,
                        role: player.role,
                        element: player.element,
                        evolution: evoLevel,
                        isLastEvo: this.isLastEvo(player.id, playerIds),
                        isSpecial: player.is_special,
                        max_pow: player.max_pow,
                        max_tec: player.max_tec,
                        max_vit: player.max_vit,
                        max_spd: player.max_spd,
                        min_pow: player.min_pow,
                        min_tec: player.min_tec,
                        min_vit: player.min_vit,
                        min_spd: player.min_spd,
                        cur_pow: 0,
                        cur_tec: 0,
                        cur_vit: 0,
                        cur_spd: 0,
                        cur_total: 0
                    });
                }
            };
        }
    }
});<commit_msg>Update<commit_after>const app = new Vue({
    el: "#app",
    data: {
        characters: [],
        rarity: [],
        stats: {
            level: {
                value: 70,
                max: 70,
                min: 1,
                step: 1,
                color: "blue"
            },
            bs: {
                value: 40,
                max: 40,
                color: 'light-green'
            },
            spu: {
                value: 5,
                max: 5,
                color: 'deep-orange'
            },
            apu: {
                value: 0,
                max: 30,
                color: 'cyan'
            }
        },
        toggle: {
            lastEvo: true,
            special: false,
        },
        selected: {
            rarity: [],
            role: [],
            element: [],
            evolution: []
        },
        dataTable: {
            search: '',
            isLoading: true,
            pageRows: [15, 30, 50],
            headers: [{
                    text: 'Name',
                    align: 'left',
                    value: 'name'
                },
                {
                    text: 'Rarity',
                    align: 'right',
                    value: 'rarity'
                },
                {
                    text: 'Role',
                    align: 'right',
                    value: 'role'
                },
                {
                    text: 'Element',
                    align: 'right',
                    value: 'element'
                },
                {
                    text: 'Power',
                    align: 'right',
                    value: 'cur_pow'
                },
                {
                    text: 'Technique',
                    align: 'right',
                    value: 'cur_tec'
                },
                {
                    text: 'Vitality',
                    align: 'right',
                    value: 'cur_vit'
                },
                {
                    text: 'Speed',
                    align: 'right',
                    value: 'cur_spd'
                },
                {
                    text: 'Total Stats',
                    align: 'right',
                    value: 'cur_total'
                }
            ],
            customFilter: function (items, search, filter) {
                search = _.lowerCase(search);
                return items.filter(function (item) {
                    const selected = app.selected;
                    const toggle = app.toggle;
                    return filter(item.name, search) &&
                        app.filterToggle(item.isLastEvo, toggle.lastEvo) &&
                        app.filterToggle(item.isSpecial, toggle.special) &&
                        app.filterArray(item.rarity, selected.rarity) &&
                        app.filterArray(item.role, selected.role) &&
                        app.filterArray(item.evolution, selected.evolution) &&
                        app.filterArray(item.element, selected.element);
                });
            }
        },

    },
    created: function () {
        this.getCharData();
        this.deb_getFinalStats = _.debounce(this.getFinalStats, 500);
    },
    watch: {
        stats: {
            handler: function () {
                this.deb_getFinalStats();
            },
            deep: true
        }
    },
    methods: {
        filterToggle: function (val, toggle) {
            return (toggle && val) ||
                (toggle == false);
        },
        filterArray: function (obj, arr) {
            return (!arr.length >= 1) ||
                (arr.includes(obj.toString()));
        },
        isPlayer: function (character) {
            return (character === "Player") ? true : false;
        },
        getStat: function (minStat, maxStat, rarity) {
            let stLevel = this.stats.level.value / 10;
            let minStatRate = Math.pow(.176, (6 - (stLevel)) / 10);
            let stat = Math.round(minStat * minStatRate);
            let finalStat = Math.floor(stat + (maxStat - stat) * Math.pow((this.stats.level.value - 1) / (60 - 1), 1));
            let totalFinal = Math.floor(finalStat * this.getSpuBonus()) + this.getApuBonus(rarity) + this.stats.bs.value;
            return totalFinal;
        },
        getApuBonus: function (rarity) {
            return (rarity > 5) ?
                this.stats.apu.value :
                Math.floor(this.stats.apu.value * 1.2);
        },
        getSpuBonus: function () {
            return 1 + this.stats.spu.value * 0.1;
        },
        getFinalStats: function () {
            this.dataTable.isLoading = true;
            this.characters.forEach(char => {
                let cur_pow = this.getStat(char.min_pow, char.max_pow);
                let cur_tec = this.getStat(char.min_tec, char.max_tec);
                let cur_vit = this.getStat(char.min_vit, char.max_vit);
                let cur_spd = this.getStat(char.min_spd, char.max_spd);
                let cur_total = cur_pow + cur_tec + cur_vit + cur_spd;

                char.cur_pow = cur_pow;
                char.cur_tec = cur_tec;
                char.cur_vit = cur_vit;
                char.cur_spd = cur_spd;
                char.cur_total = cur_total;
            });
            this.dataTable.isLoading = false;
        },
        getCharData: function () {
            axios.get('/api/characters/').then(response => {
                this.loadCharData(response.data);
                this.getFinalStats();
                this.dataTable.isLoading = false;
            });
        },
        getEvoSuffix: function (id) {
            if (id == "3")
                return " (EE)";
            else if (id == "2")
                return " (E)";
            else
                return "";
        },
        isLastEvo: function (id, ids) {
            let isLast;
            id = id.toString().substring(1);
            isLast = !(ids.indexOf(id) >= 0);
            if (isLast)
                ids.push(id);
            return isLast;
        },
        loadCharData: function (data) {
            let playerIds = [];
            this.characters = [];

            for (var x = data.length - 1; x >= 0; x--) {
                let player = data[x];

                if (this.isPlayer(player.category)) {
                    let evoLevel = player.id.toString().substring(0, 1);

                    this.characters.push({
                        name: player.name + this.getEvoSuffix(evoLevel),
                        rarity: player.rarity,
                        role: player.role,
                        element: player.element,
                        evolution: evoLevel,
                        isLastEvo: this.isLastEvo(player.id, playerIds),
                        isSpecial: player.is_special,
                        max_pow: player.max_pow,
                        max_tec: player.max_tec,
                        max_vit: player.max_vit,
                        max_spd: player.max_spd,
                        min_pow: player.min_pow,
                        min_tec: player.min_tec,
                        min_vit: player.min_vit,
                        min_spd: player.min_spd,
                        cur_pow: 0,
                        cur_tec: 0,
                        cur_vit: 0,
                        cur_spd: 0,
                        cur_total: 0
                    });
                }
            };
        }
    }
});<|endoftext|>


<commit_before>

//expose the main layout panels for use later.
 var northPanel, southPanel, eastPanel, westPanel, centerPanel;

//The simple function will be called when the document is finished loading.  See event at bottem of file
Simple = function() {

   return {
       init : function() {
           var mainLayout = new Ext.BorderLayout("layout", {
               north: {
                   split: false, initialSize: 30
               },
               south: {
                   split: false, initialSize: 400
               },
               east: {
                   split: true, initialSize: 0
               },
               west: {
                   split: true, initialSize: 300
               },
               center: { split: true, initialSize: 80
               }
           });
           mainLayout.beginUpdate();
           mainLayout.add('north', northPanel = new Ext.ContentPanel('north-div', {
              fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('south', southPanel = new Ext.ContentPanel('south-div', {
               fitToFrame: true, closable: false
           }));
           mainLayout.add('east', eastPanel = new Ext.ContentPanel('east-div', {
               fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('west', westPanel = new Ext.ContentPanel('west-div', {
               fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('center', centerPanel = new Ext.ContentPanel('center-div', {
               fitToFrame: true , autoScroll: true
           }));
           mainLayout.endUpdate();
                       mainLayout.getRegion('east').hide();
                       mainLayout.getRegion('north').hide();
                       initBioMaterialGrid( );
                       initTree( );
               }
   };
}();

var showbms = function( id ) {
       var ids =  id.split(",");
       // note how we pass the new array in directly, without wraping it in an object first.
       ds.load({params:[ids]});
};

var ds;

var initBioMaterialGrid = function(div) {
       var     recordType = Ext.data.Record.create([
                       {name:"id", type:"int"},
                       {name:"name", type:"string"},
                       {name:"description", type:"string"}
               ]);

       ds = new Ext.data.Store(
               {
                       proxy:new Ext.data.DWRProxy(BioMaterialController.getBioMaterials),
                       reader:new Ext.data.ListRangeReader({id:"id"}, recordType),
                       remoteSort:false,
                       sortInfo:{field:'name'}
               });

       var cm = new Ext.grid.ColumnModel([
                       {header: "Name", width: 50, dataIndex:"name"},
                       {header: "Description",  width: 80, dataIndex:"description"}
                       ]);
       cm.defaultSortable = true;

       grid = new Ext.grid.Grid("south-div", {autoSizeColumns: true, ds:ds,cm:cm, loadMask: true });
       grid.render();

       var id = dwr.util.getValue("cslist");
       showbms(id);
};

var initTree = function(div){

   var tree = new Ext.tree.TreePanel("west-div", {
       animate:true,
       loader: new Ext.tree.DwrTreeLoader({dataUrl:MgedOntologyService.getBioMaterialTerms})
   });

   tree.on('click', function(node){
                   MgedOntologyService.getTerm(node.id,displayRestrictionsPanel);
          });

   // set the root node
   var root = new Ext.tree.AsyncTreeNode({
       text: 'Top of the tree',
       draggable:false,
       allowChildre:true,
       id:'root'
   });
   tree.setRootNode(root);

   // render the tree
   tree.render();
   root.expand();

};

//The call back method for the dwr call
var displayRestrictionsPanel = function(node){
	console.log(dwr.util.toDescriptiveString(node, 10));
	createRestrictionGui(node);
};

//Recursive function that walks the node given to it and creates a coresponding form to fill in
var createRestrictionGui = function(node, indent, parentDivId) {

		var dh = Ext.DomHelper;  //allows html output

		if (indent === undefined){
			dh.overwrite("center-div", {html : ""});
			indent = "";
		}
		if (parentDivId === undefined) {
			parentDivId = "center-div";
		}

		//dh.append(parentDivId, {html : indent + "Details for: " + node.uri });

        var res = node.restrictions;
        if ( (res !== undefined) && (res !== null) && (res.size() > 0) ) {

            for ( var i = 0, len = res.length; i < len; i++ ) {
            	var restrictedOn = res[i].restrictionOn;
            	var restrictedTo = res[i].restrictedTo;
            	//make a nested div for adding to.
            	var divId = (Math.random() * 100000).toFixed();
            	dh.append(parentDivId, {tag: 'div', id: divId});

            	if (restrictedOn.type !== undefined ) {	//Primitive Type
                    var primitiveRestrictedTo = restrictedOn.type
                    dh.append(parentDivId, {html : indent + " Primitive Type Slot to fill in: " + restrictedOn.label + " with a " + primitiveRestrictedTo.value });
            	} else if ( (restrictedTo !== undefined) && (restrictedTo !== null)) {	//is it a class restriction?

                    if (restrictedTo.restrictions === undefined || restrictedTo.restrictions === null || restrictedTo.restrictions.size() === 0){	// ie) we are at a leaf node so display gui
                        dh.append(divId, {html : indent + " Restricted To Slot to fill in: " + restrictedOn.label + " with a " + restrictedTo.term });

	                    var simple = createForm();

    	                if (restrictedTo.individuals !== undefined && restrictedTo.individuals !== null && restrictedTo.individuals.size() > 0){  //are there examples?
        		            	simple.add(createComboBox(restrictedTo.individuals));
                	    }

	                    simple.render(divId);
                    } else{        //Not a leaf node. recurse down another level
                        dh.append(divId, {html : indent + " The " + restrictedOn.label + " restriction has " + restrictedTo.restrictions.size()+ " slots to fill in"});
    	            	createRestrictionGui( restrictedTo, "    " + indent, divId );
                   }

                } else if ( res[i].cardinality !== undefined  ) { //Cardinality Type
                    // this will be rare.
                    var cardinality = res[i].cardinality;
                    var cardinalityType = res[i].cardinalityType;
                    dh.append(parentDivId,{ html: indent + " Cardinality Slot to fill in: " + restrictedOn.label + " with " + cardinalityType.term + " "
                            + cardinality + " things" });
                    // todo check range of the property (what 'things' should be) if specified.
                } else{
                	  dh.append(parentDivId,{ html: indent + " Error: This should not happen" });
                }
            }
        }
	    //dh.append(parentDivId, {html : indent + "End of details for " + node.uri}) ;
    };

var createComboBox = function(individuals){
	     	var recordType = Ext.data.Record.create([
							{name:"label", type : "string" },
							{name:"uri", type: "string" }
						]);

						//convert the arry of objects into an array of records
						var records = [];
						for(var i = 0, len = individuals.length; i < len; i++) {
							records.push(new recordType(individuals[i]));
						}

	                    var store = new Ext.data.Store({recordType : recordType} );
						store.add(records);

					    var combo = new Ext.form.ComboBox({
					    	fieldLabel: 'pick one',
					        store: store,
					        displayField:'label',
					        typeAhead: true,
					        mode: 'local',
					        triggerAction: 'all',
					        emptyText:'Select an individual',
					        selectOnFocus:true
					    });

					    return combo;

};

var createForm = function(){
	var simple = new Ext.form.Form({
					        labelWidth: 75, // label settings here cascade unless overridden
					        url:'save-form.php'
					    });
					    simple.add(
					        new Ext.form.TextField({
					            fieldLabel: 'Lookup',
					            name: 'lookup',
					            width:175,
					            allowBlank:true
					        }),

					        new Ext.form.TextField({
					            fieldLabel: 'custom',
					            name: 'custom',
					            width:175
					        })
					    );

					    //simple.addButton('Save');
					    //simple.addButton('Cancel');

					   return simple;
}

Ext.EventManager.onDocumentReady(Simple.init, Simple, true);

<commit_msg>fixed formating.<commit_after>

//expose the main layout panels for use later.
 var northPanel, southPanel, eastPanel, westPanel, centerPanel;

//The simple function will be called when the document is finished loading.  See event at bottem of file
Simple = function() {

   return {
       init : function() {
           var mainLayout = new Ext.BorderLayout("layout", {
               north: {
                   split: false, initialSize: 30
               },
               south: {
                   split: false, initialSize: 400
               },
               east: {
                   split: true, initialSize: 0
               },
               west: {
                   split: true, initialSize: 300
               },
               center: { split: true, initialSize: 80
               }
           });
           mainLayout.beginUpdate();
           mainLayout.add('north', northPanel = new Ext.ContentPanel('north-div', {
              fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('south', southPanel = new Ext.ContentPanel('south-div', {
               fitToFrame: true, closable: false
           }));
           mainLayout.add('east', eastPanel = new Ext.ContentPanel('east-div', {
               fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('west', westPanel = new Ext.ContentPanel('west-div', {
               fitToFrame: true, closable: false, autoScroll: true
           }));
           mainLayout.add('center', centerPanel = new Ext.ContentPanel('center-div', {
               fitToFrame: true , autoScroll: true
           }));
           mainLayout.endUpdate();
                       mainLayout.getRegion('east').hide();
                       mainLayout.getRegion('north').hide();
                       initBioMaterialGrid( );
                       initTree( );
               }
   };
}();

var showbms = function( id ) {
       var ids =  id.split(",");
       // note how we pass the new array in directly, without wraping it in an object first.
       ds.load({params:[ids]});
};

var ds;

var initBioMaterialGrid = function(div) {
       var     recordType = Ext.data.Record.create([
                       {name:"id", type:"int"},
                       {name:"name", type:"string"},
                       {name:"description", type:"string"}
               ]);

       ds = new Ext.data.Store(
               {
                       proxy:new Ext.data.DWRProxy(BioMaterialController.getBioMaterials),
                       reader:new Ext.data.ListRangeReader({id:"id"}, recordType),
                       remoteSort:false,
                       sortInfo:{field:'name'}
               });

       var cm = new Ext.grid.ColumnModel([
                       {header: "Name", width: 50, dataIndex:"name"},
                       {header: "Description",  width: 80, dataIndex:"description"}
                       ]);
       cm.defaultSortable = true;

       grid = new Ext.grid.Grid("south-div", {autoSizeColumns: true, ds:ds,cm:cm, loadMask: true });
       grid.render();

       var id = dwr.util.getValue("cslist");
       showbms(id);
};

var initTree = function(div){

   var tree = new Ext.tree.TreePanel("west-div", {
       animate:true,
       loader: new Ext.tree.DwrTreeLoader({dataUrl:MgedOntologyService.getBioMaterialTerms})
   });

   tree.on('click', function(node){
                   MgedOntologyService.getTerm(node.id,displayRestrictionsPanel);
          });

   // set the root node
   var root = new Ext.tree.AsyncTreeNode({
       text: 'Top of the tree',
       draggable:false,
       allowChildre:true,
       id:'root'
   });
   tree.setRootNode(root);

   // render the tree
   tree.render();
   root.expand();

};

//The call back method for the dwr call
var displayRestrictionsPanel = function(node){
	console.log(dwr.util.toDescriptiveString(node, 10));
	createRestrictionGui(node);
};

//Recursive function that walks the node given to it and creates a coresponding form to fill in
var createRestrictionGui = function(node, indent, parentDivId) {

		var dh = Ext.DomHelper;  //allows html output

		if (indent === undefined){
			dh.overwrite("center-div", {html : ""});
			indent = "";
		}
		if (parentDivId === undefined) {
			parentDivId = "center-div";
		}

		//dh.append(parentDivId, {html : indent + "Details for: " + node.uri });

        var res = node.restrictions;
        if ( (res !== undefined) && (res !== null) && (res.size() > 0) ) {

            for ( var i = 0, len = res.length; i < len; i++ ) {
            	var restrictedOn = res[i].restrictionOn;
            	var restrictedTo = res[i].restrictedTo;
            	//make a nested div for adding to.
            	var divId = (Math.random() * 100000).toFixed();
            	dh.append(parentDivId, {tag: 'div', id: divId});

            	if (restrictedOn.type !== undefined ) {	//Primitive Type... just fill in the value
                    var primitiveRestrictedTo = restrictedOn.type

                    	var simple = new Ext.form.Form({
					        labelWidth: 75, // label settings here cascade unless overridden
					        url:'save-form.php'
					    });
					    simple.add(
					        new Ext.form.TextField({
					            fieldLabel: restrictedOn.label ,
					            name: 'hasValue',
					            width:175,
					            allowBlank:false
					        })
					    );
                       dh.append(divId, {tag: 'h3', html : indent + 'Value:' });

					   simple.render(divId);

            	} else if ( (restrictedTo !== undefined) && (restrictedTo !== null)) {	//is it a class restriction?

                    if (restrictedTo.restrictions === undefined || restrictedTo.restrictions === null || restrictedTo.restrictions.size() === 0){	// ie) we are at a leaf node so display gui
                        dh.append(divId, {tag: 'h3', html : indent + restrictedTo.term });

	                    var simple = createForm();

    	                if (restrictedTo.individuals !== undefined && restrictedTo.individuals !== null && restrictedTo.individuals.size() > 0){  //are there examples?
        		            	simple.add(createComboBox(restrictedTo.individuals));
                	    }

	                    simple.render(divId);
                    } else{        //Not a leaf node. recurse down another level
                        dh.append(divId, {html : indent + " The " + restrictedOn.label + " restriction has " + restrictedTo.restrictions.size()+ " slots to fill in"});
    	            	createRestrictionGui( restrictedTo, "    " + indent, divId );
                   }

                } else if ( res[i].cardinality !== undefined  ) { //Cardinality Type
                    // this will be rare.
                    var cardinality = res[i].cardinality;
                    var cardinalityType = res[i].cardinalityType;
                    dh.append(parentDivId,{ html: indent + " Cardinality Slot to fill in: " + restrictedOn.label + " with " + cardinalityType.term + " "
                            + cardinality + " things" });
                    // todo check range of the property (what 'things' should be) if specified.
                } else{
                	  dh.append(parentDivId,{ html: indent + " Error: This should not happen" });
                }
            }
        }
        else if ((node.individuals !== undefined) && (node.individuals !== null) && (node.individuals.size() > 0)){
        	var simple = createForm();
   	    	simple.add(createComboBox(node.individuals));
           	var divId = (Math.random() * 100000).toFixed();
           	dh.append(parentDivId, {tag: 'div', id: divId});
        	simple.render(divId);
        }
        else{
	    	dh.append(parentDivId, {html : indent + "error: is this a nothing node? uri:" + node.uri}) ;
        }
    };

var createComboBox = function(individuals){
	     	var recordType = Ext.data.Record.create([
							{name:"label", type : "string" },
							{name:"uri", type: "string" }
						]);

						//convert the arry of objects into an array of records
						var records = [];
						for(var i = 0, len = individuals.length; i < len; i++) {
							records.push(new recordType(individuals[i]));
						}

	                    var store = new Ext.data.Store({recordType : recordType} );
						store.add(records);

					    var combo = new Ext.form.ComboBox({
					    	fieldLabel: 'pick one',
					        store: store,
					        displayField:'label',
					        typeAhead: true,
					        mode: 'local',
					        triggerAction: 'all',
					        emptyText:'Select an individual',
					        selectOnFocus:true
					    });

					    return combo;

};

var createForm = function(){
	var simple = new Ext.form.Form({
					        labelWidth: 75, // label settings here cascade unless overridden
					        url:'save-form.php'
					    });
					    simple.add(
					        new Ext.form.TextField({
					            fieldLabel: 'Lookup',
					            name: 'lookup',
					            width:175,
					            allowBlank:true
					        }),

					        new Ext.form.TextField({
					            fieldLabel: 'custom',
					            name: 'custom',
					            width:175
					        })
					    );

					    //simple.addButton('Save');
					    //simple.addButton('Cancel');

					   return simple;
}

Ext.EventManager.onDocumentReady(Simple.init, Simple, true);

<|endoftext|>


<commit_before>// TODO ** delete this file **
// 'use strict'
// require('babel-register')
// require('./microservices/products.test.js')
// require('./microservices/users.test.js')
<commit_msg>remote unwanted file<commit_after><|endoftext|>


<commit_before>import compileClient from "../compileClient"
import handleCompilationErrors from "../handleCompilationErrors";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";

const logger = require("react-server").logging.getLogger(__LOGGER__);

export default function compile(options){
	setupLogging(options);
	logProductionWarnings(options);

	const {compiler} = compileClient(options);

	logger.notice("Starting compilation of client JavaScript...");
	compiler.run((err, stats) => {
		const error = handleCompilationErrors(err, stats);
		if (!error) {
			logger.notice("Successfully compiled client JavaScript.");
		} else {
			logger.error(error);
		}
	});
}
<commit_msg>Fix a weird logger instantiation<commit_after>import compileClient from "../compileClient"
import handleCompilationErrors from "../handleCompilationErrors";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";
import {logging} from "../react-server";

const logger = logging.getLogger(__LOGGER__);

export default function compile(options){
	setupLogging(options);
	logProductionWarnings(options);

	const {compiler} = compileClient(options);

	logger.notice("Starting compilation of client JavaScript...");
	compiler.run((err, stats) => {
		const error = handleCompilationErrors(err, stats);
		if (!error) {
			logger.notice("Successfully compiled client JavaScript.");
		} else {
			logger.error(error);
		}
	});
}
<|endoftext|>


<commit_before>/*eslint-env mocha*/
"use strict";

describe("mPulse app - page groups", function() {
    var root = typeof window !== "undefined" ? window : {};
    var assert = (root.chai ? root.chai : require("chai")).assert;
    var mPulse = root.mPulse ? root.mPulse : require("../src/mpulse");

    /*eslint-disable camelcase*/
    var CONFIG_JSON_STRING = JSON.stringify({
        beacon_url: "http://127.0.0.1/beacon",
        PageParams: {
            customTimers: [
                {
                    name: "timer",
                    label: "timer"
                }
            ]
        }
    });
    /*eslint-enable camelcase*/

    var app = null;
    beforeEach(function() {
        app = mPulse.init("app_vg", {configUrl: ""});

        app.parseConfig(CONFIG_JSON_STRING);
    });

    afterEach(function() {
        mPulse.stop("app_vg");
        app = null;
    });

    describe("setPageGroup()", function() {
        it("Should not set a page group if not called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (number)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(1);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (boolean)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(true);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (null)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(null);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (undefined)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup();
            app.sendTimer("timer", 100);
        });

        it("Should set the page group for the next beacon if called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.equal(data["h.pg"], "group");
                done();
            });

            app.setPageGroup("group");
            app.sendTimer("timer", 100);
        });

        it("Should set the page group for all following beacons if called", function(done) {
            var beaconsFired = 0;
            app.subscribe("beacon", function(data) {
                beaconsFired++;

                assert.equal(data["h.pg"], "group");

                if (beaconsFired === 2) {
                    done();
                }
            });

            app.setPageGroup("group");
            app.sendTimer("timer", 100);
            app.sendTimer("timer", 100);
        });
    });

    describe("getPageGroup()", function() {
        it("Should return false if no page group is called", function() {
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (number)", function() {
            app.setPageGroup(1);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (boolean)", function() {
            app.setPageGroup(true);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (null)", function() {
            app.setPageGroup(null);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (undefined)", function() {
            app.setPageGroup();
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return the group if called with a string", function() {
            app.setPageGroup("group");
            assert.equal(app.getPageGroup(), "group");
        });
    });

    describe("resetPageGroup()", function() {
        it("Shouldn't cause any problems if called without calling setPageGroup() first", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                assert.equal(data["t_other"], "timer|100");
                done();
            });

            app.resetPageGroup();
            app.sendTimer("timer", 100);
        });

        it("Should remove the page group after being called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup("group");
            app.resetPageGroup();
            app.sendTimer("timer", 100);
        });
    });
});
<commit_msg>Small casing fix<commit_after>/*eslint-env mocha*/
"use strict";

describe("mPulse app - Page Groups", function() {
    var root = typeof window !== "undefined" ? window : {};
    var assert = (root.chai ? root.chai : require("chai")).assert;
    var mPulse = root.mPulse ? root.mPulse : require("../src/mpulse");

    /*eslint-disable camelcase*/
    var CONFIG_JSON_STRING = JSON.stringify({
        beacon_url: "http://127.0.0.1/beacon",
        PageParams: {
            customTimers: [
                {
                    name: "timer",
                    label: "timer"
                }
            ]
        }
    });
    /*eslint-enable camelcase*/

    var app = null;
    beforeEach(function() {
        app = mPulse.init("app_vg", {configUrl: ""});

        app.parseConfig(CONFIG_JSON_STRING);
    });

    afterEach(function() {
        mPulse.stop("app_vg");
        app = null;
    });

    describe("setPageGroup()", function() {
        it("Should not set a page group if not called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (number)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(1);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (boolean)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(true);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (null)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup(null);
            app.sendTimer("timer", 100);
        });

        it("Should not set a page group for non-string names (undefined)", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup();
            app.sendTimer("timer", 100);
        });

        it("Should set the page group for the next beacon if called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.equal(data["h.pg"], "group");
                done();
            });

            app.setPageGroup("group");
            app.sendTimer("timer", 100);
        });

        it("Should set the page group for all following beacons if called", function(done) {
            var beaconsFired = 0;
            app.subscribe("beacon", function(data) {
                beaconsFired++;

                assert.equal(data["h.pg"], "group");

                if (beaconsFired === 2) {
                    done();
                }
            });

            app.setPageGroup("group");
            app.sendTimer("timer", 100);
            app.sendTimer("timer", 100);
        });
    });

    describe("getPageGroup()", function() {
        it("Should return false if no page group is called", function() {
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (number)", function() {
            app.setPageGroup(1);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (boolean)", function() {
            app.setPageGroup(true);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (null)", function() {
            app.setPageGroup(null);
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return false for non-string names (undefined)", function() {
            app.setPageGroup();
            assert.equal(app.getPageGroup(), false);
        });

        it("Should return the group if called with a string", function() {
            app.setPageGroup("group");
            assert.equal(app.getPageGroup(), "group");
        });
    });

    describe("resetPageGroup()", function() {
        it("Shouldn't cause any problems if called without calling setPageGroup() first", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                assert.equal(data["t_other"], "timer|100");
                done();
            });

            app.resetPageGroup();
            app.sendTimer("timer", 100);
        });

        it("Should remove the page group after being called", function(done) {
            app.subscribe("beacon", function(data) {
                assert.isUndefined(data["h.pg"]);
                done();
            });

            app.setPageGroup("group");
            app.resetPageGroup();
            app.sendTimer("timer", 100);
        });
    });
});
<|endoftext|>


<commit_before>/*global d3*/

export class CallGraph {
    currentDirection = "down";// or "right"
    directionManager = {
        right: {
            nodeRenderer: function translateRight(d) {
                return "translate(" + d.y + "," + d.x + ")";
            },
            linkRenderer: function linkRenderer(d) {
              return "M" + d.y + "," + d.x
                  + "C" + (d.parent.y + 100) + "," + d.x
                  + " " + (d.parent.y + 100) + "," + d.parent.x
                  + " " + d.parent.y + "," + d.parent.x;
            }
        },
        down: {
            nodeRenderer: function translateRight(d) {
                return "translate(" + d.x + "," + d.y + ")";
            },
            linkRenderer: function linkRenderer(d) {
              return "M" + d.x + "," + d.y
                  + "C" + (d.parent.x + 100) + "," + d.y
                  + " " + (d.parent.x + 100) + "," + d.parent.y
                  + " " + d.parent.x + "," + d.parent.y;
            }
        }
    };
    controlFlowBlocks = [
        "IfStatement",
        "WhileStatement",
        "DoWhileStatement",
        "ForStatement",
        "ForInStatement",
        "SwitchStatement",
        "SwitchCase",
        "TryStatement",
        "CatchClause"
    ];

    programCalls = [
        "CallProgram",
        "CallExpression"
    ];

    programExecutors = [
        "Program",
        "FunctionDeclaration",
        "FunctionExpression",
        "FunctionData"
    ];
    constructor() {
        this.prepareFx();
        this.config = {
            type: 'CallGraph',
            styleClass: 'call-graph',
            title: 'Call Graph',
            trace: null,
            formatTraceFx: this.formatTraceFx,
            renderFx: this.renderFx,
            errorMessage: null
        };
    }

    collectTraceDecorationData(traceDecorationData, entry){
        if(!traceDecorationData){
           traceDecorationData = [];
        }

        if(!(entry && entry.type)){
            return traceDecorationData;
        }

        if(this.programCalls.indexOf(entry.type) > -1){
            traceDecorationData.push({type: entry.type, name: entry.id, range: entry.range, isReady: false});
            return traceDecorationData;
        }

        if(this.controlFlowBlocks.indexOf(entry.type) > -1){
            traceDecorationData.push( {type: entry.type, name: entry.type.replace("Statement", "").replace("Clause", ""), range: entry.range});
             return traceDecorationData;
        }

        if(entry.type === "SwitchCase"){
            traceDecorationData.push( {type: entry.type, name: "Switch", range: entry.range});
            return traceDecorationData;
        }

        return traceDecorationData;
    }

    decorateTree(root, validEntryData){

    }

    isRangeInRange(isRange, inRange){
        return (
                (isRange.start.row >= inRange.start.row && isRange.start.column >= inRange.start.column)
    			 &&
    			(isRange.end.row <= inRange.end.row && isRange.end.column <= inRange.end.column)
    			);
    }

    addEntryToTree(root, entry, validEntryData) {
        let currentNode = root;

        if(!entry){
            return;
        }

        if(!(entry.type === "BlockStatement" && entry.range)){
            return;
        }

        let newChild = { type: entry.type, name: "entryName" , range: entry.range, children : null} ;

        let nextNode = currentNode; // root is default

        do{
            currentNode = nextNode;
            nextNode = null;
            for(let childIndex in currentNode.children){
                let child = currentNode.children[childIndex];
                if(this.isRangeInRange(newChild.range, child.range)){
                    nextNode = child;
                    break;
                }
            }
        }while(nextNode);

        if(validEntryData){
            newChild.type = validEntryData.type;
            newChild.name = validEntryData.name;
            newChild.range = validEntryData.range;
        }

        if(currentNode.children){
            currentNode.children.push(newChild);
        }else{
            currentNode.children = [newChild];
        }
    }

    prepareFx(){
        let self = this;
        this.formatTraceFx =  function formatTraceFxAsD3RootNode(trace = this.trace){
            let root = {type: "Program", name: "Script", range: {start:{row: 0, column:0}, end:{row: 0, column:0}}, children : null} ;
            if(!trace){
                return root;
            }
            if(!trace.timeline){
                return root;
            }
            root.range = trace.timeline[0];
            let traceDecorationData = null;
            for( let index = 1 ; index < trace.timeline.length ; index++ ) {
                let entry = trace.timeline[ index ] ;
                traceDecorationData = self.collectTraceDecorationData(traceDecorationData, entry);
                self.addEntryToTree(root, entry);
            }
            self.decorateTree(root, traceDecorationData);
            console.log(trace.timeline);
            return root;
        };

        this.renderFx  =  function renderFx(formattedTrace, divElement) {
            if (!formattedTrace){
                return;
            }
            d3.select(divElement).html("");

            let margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = 400 - margin.left - margin.right,
            height = 250 - margin.top - margin.bottom;

            let rectWidth = 100,
                rectHeight = 40;

            let tree = d3.tree()
                .nodeSize([160, 200]);

            let diagonal = self.directionManager[self.currentDirection].linkRenderer;

            let nodeRenderer = self.directionManager[self.currentDirection].nodeRenderer;

            let svg = d3.select(divElement).append("svg")
                .attr("width", width)
                .attr("height", height)
                .attr("position","relative")
                .call(d3.zoom()
              .on("zoom", function () {
                svg.attr("transform", function() {
                    let devent = d3.event.transform;
                  return "translate(" + devent.x + ", " + devent.y + ") scale(" + devent.k +")";
                });
              }))
                .append("g");

            svg.attr("transform","translate(100,0)");

            let root = d3.hierarchy(formattedTrace),
                nodes = root.descendants(),
                links = root.descendants().slice(1);

            tree(root);
            svg.selectAll(".link")
                .data(links)
              .enter().append("path")
                .attr("class", "link")
                .attr("d", diagonal)
                .style("fill","none")
                .style("stroke","#ccc")
                .style("stroke-width","1.5px");

            let node = svg.selectAll(".node")
                .data(nodes)
              .enter().append("g")
                .attr("class", "node")
                .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
                .attr("transform", nodeRenderer)
                .style("font","10px sans-serif");

            node.append("rect")
                .attr("width", rectWidth)
                .attr("height", rectHeight)
                .attr("transform", "translate(" + (-1 * rectWidth/2) + ",0)")
                .style("fill","#fff")
                .style("stroke","steelblue")
                .style("stroke-width","1.5px");

            node.append("text")
                .attr("dx", function(d) { return d.children ? -8 : 8; })
                .attr("dy", 22.5)
                .attr("text-anchor", "middle")
                .text(function(d) { return d.data.name; });

            d3.select(self.frameElement).style("height", height + "px");
        };
    }

}
<commit_msg>Obtaining link line changes. Merge branch 'd3V4migration' of https://github.com/tlatoza/SeeCodeRun into d3V4migration<commit_after>/*global d3*/

export class CallGraph {
    currentDirection = "down";// or "right"
    directionManager = {
        right: {
            nodeRenderer: function translateRight(d) {
                return "translate(" + d.y + "," + d.x + ")";
            },
            linkRenderer: function linkRenderer(d) {
              return "M" + d.y + "," + d.x
                  + "C" + (d.parent.y + 100) + "," + d.x
                  + " " + (d.parent.y + 100) + "," + d.parent.x
                  + " " + d.parent.y + "," + d.parent.x;
            }
        },
        down: {
            nodeRenderer: function translateRight(d) {
                return "translate(" + d.x + "," + d.y + ")";
            },
            linkRenderer: function linkRenderer(d) {
              return "M" + d.x + "," + d.y
                  + "C" + (d.parent.x + 100) + "," + d.y
                  + " " + (d.parent.x + 100) + "," + d.parent.y
                  + " " + d.parent.x + "," + d.parent.y;
            }
        }
    };
    controlFlowBlocks = [
        "IfStatement",
        "WhileStatement",
        "DoWhileStatement",
        "ForStatement",
        "ForInStatement",
        "SwitchStatement",
        "SwitchCase",
        "TryStatement",
        "CatchClause"
    ];

    programCalls = [
        "CallProgram",
        "CallExpression"
    ];

    programExecutors = [
        "Program",
        "FunctionDeclaration",
        "FunctionExpression",
        "FunctionData"
    ];
    constructor() {
        this.prepareFx();
        this.config = {
            type: 'CallGraph',
            styleClass: 'call-graph',
            title: 'Call Graph',
            trace: null,
            formatTraceFx: this.formatTraceFx,
            renderFx: this.renderFx,
            errorMessage: null
        };
    }

    collectTraceDecorationData(traceDecorationData, entry){
        if(!traceDecorationData){
           traceDecorationData = [];
        }

        if(!(entry && entry.type)){
            return traceDecorationData;
        }

        if(this.programCalls.indexOf(entry.type) > -1){
            traceDecorationData.push({type: entry.type, name: entry.id, range: entry.range, isReady: false});
            return traceDecorationData;
        }

        if(this.controlFlowBlocks.indexOf(entry.type) > -1){
            traceDecorationData.push( {type: entry.type, name: entry.type.replace("Statement", "").replace("Clause", ""), range: entry.range});
             return traceDecorationData;
        }

        if(entry.type === "SwitchCase"){
            traceDecorationData.push( {type: entry.type, name: "Switch", range: entry.range});
            return traceDecorationData;
        }

        return traceDecorationData;
    }

    decorateTree(root, validEntryData){

    }

    isRangeInRange(isRange, inRange){
        return (
                (isRange.start.row >= inRange.start.row && isRange.start.column >= inRange.start.column)
    			 &&
    			(isRange.end.row <= inRange.end.row && isRange.end.column <= inRange.end.column)
    			);
    }

    addEntryToTree(root, entry, validEntryData) {
        let currentNode = root;

        if(!entry){
            return;
        }

        if(!(entry.type === "BlockStatement" && entry.range)){
            return;
        }

        let newChild = { type: entry.type, name: "entryName" , range: entry.range, children : null} ;

        let nextNode = currentNode; // root is default

        do{
            currentNode = nextNode;
            nextNode = null;
            for(let childIndex in currentNode.children){
                let child = currentNode.children[childIndex];
                if(this.isRangeInRange(newChild.range, child.range)){
                    nextNode = child;
                    break;
                }
            }
        }while(nextNode);

        if(validEntryData){
            newChild.type = validEntryData.type;
            newChild.name = validEntryData.name;
            newChild.range = validEntryData.range;
        }

        if(currentNode.children){
            currentNode.children.push(newChild);
        }else{
            currentNode.children = [newChild];
        }
    }

    prepareFx(){
        let self = this;
        this.formatTraceFx =  function formatTraceFxAsD3RootNode(trace = this.trace){
            let root = {type: "Program", name: "Script", range: {start:{row: 0, column:0}, end:{row: 0, column:0}}, children : null} ;
            if(!trace){
                return root;
            }
            if(!trace.timeline){
                return root;
            }
            root.range = trace.timeline[0];
            let traceDecorationData = null;
            for( let index = 1 ; index < trace.timeline.length ; index++ ) {
                let entry = trace.timeline[ index ] ;
                traceDecorationData = self.collectTraceDecorationData(traceDecorationData, entry);
                self.addEntryToTree(root, entry);
            }
            self.decorateTree(root, traceDecorationData);
            console.log(trace.timeline);
            return root;
        };

        this.renderFx  =  function renderFx(formattedTrace, divElement) {
            if (!formattedTrace){
                return;
            }
            d3.select(divElement).html("");

            let margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = 400 - margin.left - margin.right,
            height = 250 - margin.top - margin.bottom;

            let rectWidth = 100,
                rectHeight = 40;

            let tree = d3.tree()
                .nodeSize([160, 200]);

            let diagonal = self.directionManager[self.currentDirection].linkRenderer;

            let nodeRenderer = self.directionManager[self.currentDirection].nodeRenderer;

            let svg = d3.select(divElement).append("svg")
                .attr("width", width)
                .attr("height", height)
                .attr("position","relative")
                .call(d3.zoom()
              .on("zoom", function () {
                svg.attr("transform", function() {
                    let devent = d3.event.transform;
                  return "translate(" + devent.x + ", " + devent.y + ") scale(" + devent.k +")";
                });
              }))
                .append("g");

            svg.attr("transform","translate(100,0)");

            let root = d3.hierarchy(formattedTrace),
                nodes = root.descendants(),
                links = root.descendants().slice(1);

            tree(root);
            svg.selectAll(".link")
                .data(links)
              .enter().append("line")
                .attr("class", "link")
                .attr("x1", function(d) { return d.parent.x; })
                .attr("y1", function(d) { return d.parent.y + rectHeight; })
                .attr("x2", function(d) { return d.x; })
                .attr("y2", function(d) { return d.y; })
                .style("fill","none")
                .style("stroke","#ccc")
                .style("stroke-width","1.5px");

            let node = svg.selectAll(".node")
                .data(nodes)
              .enter().append("g")
                .attr("class", "node")
                .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
                .attr("transform", nodeRenderer)
                .style("font","10px sans-serif");

            node.append("rect")
                .attr("width", rectWidth)
                .attr("height", rectHeight)
                .attr("transform", "translate(" + (-1 * rectWidth/2) + ",0)")
                .style("fill","#fff")
                .style("stroke","steelblue")
                .style("stroke-width","1.5px");

            node.append("text")
                .attr("dy", 22.5)
                .attr("text-anchor", "middle")
                .text(function(d) { return d.data.name; });

            d3.select(self.frameElement).style("height", height + "px");
        };
    }

}
<|endoftext|>


<commit_before>import create from 'lodash/create'
import createEventRegistry from './eventRegistry'

/*
 Augment a feathers client (v2.0.1) with:
 - auto-reauthentication on disconnect/reconnect
 - new events: "authenticated" & "disconnect"
 */

export default function (feathersClient) {
  const eventRegistry = createEventRegistry()

  return create(feathersClient, {
    authenticate: function(credentials) {
      if (this.loggedIn) {
        throw "authenticate() cannot be called twice unless you logout"
      }
      return feathersClient.authenticate(credentials)
        .then(res => {
          // automatically reauthenticate on disconnect/reconnect
          eventRegistry.on(feathersClient.io, 'connect', function() {
            console.log('reconnected')
            feathersClient.authenticate(credentials).then(function() {
              feathersClient.emit('authenticated')
              console.log('reauthenticated')
            })
          })

          eventRegistry.on(feathersClient.io, 'disconnect', function() {
            console.log('feathers client disconnected')
            feathersClient.emit('disconnect')
          })

          this.loggedIn = true
          console.log('authenticated', res)
          feathersClient.emit('authenticated')
        })
    },
    logout: function() {
      // clear listeners
      eventRegistry.clear()
      feathersClient.logout()
      this.loggedIn = false
      console.log('logout')
      feathersClient.emit('logout')
    },
  })
}
<commit_msg>augmentFeathersClient exposes a "isAuthenticated" state as an observable<commit_after>import create from 'lodash/create'
import createEventRegistry from './eventRegistry'
import { observable } from 'mobservable'

/*
 Augment a feathers client (v2.0.1) with:
 - auto-reauthentication on disconnect/reconnect
 - new events: "authenticated" & "disconnect"
 */

export default function (feathersClient) {
  const eventRegistry = createEventRegistry()
  const $isAuthenticated = observable(false)

  return create(feathersClient, {
    isAuthenticated: () => $isAuthenticated(),
    authenticate: function(credentials) {
      if ($isAuthenticated()) {
        throw "authenticate() cannot be called twice unless you logout"
      }
      return feathersClient.authenticate(credentials)
        .then(res => {
          // automatically reauthenticate on disconnect/reconnect
          eventRegistry.on(feathersClient.io, 'connect', function() {
            console.log('reconnected')
            feathersClient.authenticate(credentials).then(function() {
              feathersClient.emit('authenticated')
              console.log('reauthenticated')
            })
          })

          eventRegistry.on(feathersClient.io, 'disconnect', function() {
            console.log('feathers client disconnected')
            feathersClient.emit('disconnect')
          })

          $isAuthenticated(true)
          console.log('authenticated', res)
          feathersClient.emit('authenticated')
        })
    },
    logout: function() {
      // clear listeners
      eventRegistry.clear()
      feathersClient.logout()
      $isAuthenticated(false)
      console.log('logout')
      feathersClient.emit('logout')
    },
  })
}
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";

const Schema = ({ match }) => (

            Seq-A

            Seq-B

            Seq-C

);

export default Schema;
<commit_msg>Add virus schema<commit_after>import React from "react";
//import PropTypes from "prop-types";

const Schema = () => (

            Seq-A

            Seq-B

            Seq-C

);

export default Schema;
<|endoftext|>


<commit_before>'use strict';

var benchmark = require('benchmark');
var bitcoin = require('bitcoin');
var async = require('async');
var maxTime = 20;

console.log('Benchmarking Bitcoind.js native interface versus Bitcoind JSON RPC interface');
console.log('----------------------------------------------------------------------');

// To run the benchmarks a fully synced Bitcore Core directory is needed. The RPC comands
// can be modified to match the settings in bitcoin.conf.

var fixtureData = {
  blockHashes: [
    '00000000fa7a4acea40e5d0591d64faf48fd862fa3561d111d967fc3a6a94177',
    '000000000017e9e0afc4bc55339f60ffffb9cbe883f7348a9fbc198a486d5488',
    '000000000019ddb889b534c5d85fca2c91a73feef6fd775cd228dea45353bae1',
    '0000000000977ac3d9f5261efc88a3c2d25af92a91350750d00ad67744fa8d03'
  ],
  txHashes: [
    '5523b432c1bd6c101bee704ad6c560fd09aefc483f8a4998df6741feaa74e6eb',
    'ff48393e7731507c789cfa9cbfae045b10e023ce34ace699a63cdad88c8b43f8',
    '5d35c5eebf704877badd0a131b0a86588041997d40dbee8ccff21ca5b7e5e333',
    '88842f2cf9d8659c3434f6bc0c515e22d87f33e864e504d2d7117163a572a3aa',
  ]
};

var bitcoind = require('../').daemon({
  datadir: process.env.BITCORENODE_DIR || '~/.bitcoin',
  network: 'testnet'
});

bitcoind.on('error', function(err) {
  bitcoind.log('error="%s"', err.message);
});

bitcoind.on('open', function(status) {
  bitcoind.log('status="%s"', status);
});

bitcoind.on('ready', function() {

  bitcoind.log('status="%s"', 'chaintip ready.');

  var client = new bitcoin.Client({
    host: 'localhost',
    port: 18332,
    user: 'bitcoin',
    pass: 'local321'
  });

  async.series([
    function(next) {

      var c = 0;
      var hashesLength = fixtureData.blockHashes.length;
      var txLength = fixtureData.txHashes.length;

      function bitcoindGetBlockNative(deffered) {
        if (c >= hashesLength) {
          c = 0;
        }
        var hash = fixtureData.blockHashes[c];
        bitcoind.getBlock(hash, function(err, block) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoindGetBlockJsonRpc(deffered) {
        if (c >= hashesLength) {
          c = 0;
        }
        var hash = fixtureData.blockHashes[c];
        client.getBlock(hash, false, function(err, block) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoinGetTransactionNative(deffered) {
        if (c >= txLength) {
          c = 0;
        }
        var hash = fixtureData.txHashes[c];
        bitcoind.getTransaction(hash, true, function(err, tx) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoinGetTransactionJsonRpc(deffered) {
        if (c >= txLength) {
          c = 0;
        }
        var hash = fixtureData.txHashes[c];
        client.getRawTransaction(hash, function(err, tx) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      var suite = new benchmark.Suite();

      suite.add('bitcoind getblock (native)', bitcoindGetBlockNative, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind getblock (json rpc)', bitcoindGetBlockJsonRpc, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind gettransaction (native)', bitcoinGetTransactionNative, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind gettransaction (json rpc)', bitcoinGetTransactionJsonRpc, {
        defer: true,
        maxTime: maxTime
      });

      suite
        .on('cycle', function(event) {
          console.log(String(event.target));
        })
        .on('complete', function() {
          console.log('Fastest is ' + this.filter('fastest').pluck('name'));
          console.log('----------------------------------------------------------------------');
          next();
        })
        .run();
    }
  ], function(err) {
    console.log('Finished');
    bitcoind.stop();
    process.exit();
  });
});
<commit_msg>Fix getBlock and getTransaction benchmarks.<commit_after>'use strict';

var benchmark = require('benchmark');
var bitcoin = require('bitcoin');
var async = require('async');
var maxTime = 20;

console.log('Bitcoin Service native interface vs. Bitcoin JSON RPC interface');
console.log('----------------------------------------------------------------------');

// To run the benchmarks a fully synced Bitcore Core directory is needed. The RPC comands
// can be modified to match the settings in bitcoin.conf.

var fixtureData = {
  blockHashes: [
    '00000000fa7a4acea40e5d0591d64faf48fd862fa3561d111d967fc3a6a94177',
    '000000000017e9e0afc4bc55339f60ffffb9cbe883f7348a9fbc198a486d5488',
    '000000000019ddb889b534c5d85fca2c91a73feef6fd775cd228dea45353bae1',
    '0000000000977ac3d9f5261efc88a3c2d25af92a91350750d00ad67744fa8d03'
  ],
  txHashes: [
    '5523b432c1bd6c101bee704ad6c560fd09aefc483f8a4998df6741feaa74e6eb',
    'ff48393e7731507c789cfa9cbfae045b10e023ce34ace699a63cdad88c8b43f8',
    '5d35c5eebf704877badd0a131b0a86588041997d40dbee8ccff21ca5b7e5e333',
    '88842f2cf9d8659c3434f6bc0c515e22d87f33e864e504d2d7117163a572a3aa',
  ]
};

var bitcoind = require('../').services.Bitcoin({
  node: {
    datadir: process.env.HOME + '/.bitcoin',
    network: {
      name: 'testnet'
    }
  }
});

bitcoind.on('error', function(err) {
  console.error(err.message);
});

bitcoind.start(function(err) {
  if (err) {
    throw err;
  }
  console.log('Bitcoin Core started');
});

bitcoind.on('ready', function() {

  console.log('Bitcoin Core ready');

  var client = new bitcoin.Client({
    host: 'localhost',
    port: 18332,
    user: 'bitcoin',
    pass: 'local321'
  });

  async.series([
    function(next) {

      var c = 0;
      var hashesLength = fixtureData.blockHashes.length;
      var txLength = fixtureData.txHashes.length;

      function bitcoindGetBlockNative(deffered) {
        if (c >= hashesLength) {
          c = 0;
        }
        var hash = fixtureData.blockHashes[c];
        bitcoind.getBlock(hash, function(err, block) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoindGetBlockJsonRpc(deffered) {
        if (c >= hashesLength) {
          c = 0;
        }
        var hash = fixtureData.blockHashes[c];
        client.getBlock(hash, false, function(err, block) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoinGetTransactionNative(deffered) {
        if (c >= txLength) {
          c = 0;
        }
        var hash = fixtureData.txHashes[c];
        bitcoind.getTransaction(hash, true, function(err, tx) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      function bitcoinGetTransactionJsonRpc(deffered) {
        if (c >= txLength) {
          c = 0;
        }
        var hash = fixtureData.txHashes[c];
        client.getRawTransaction(hash, function(err, tx) {
          if (err) {
            throw err;
          }
          deffered.resolve();
        });
        c++;
      }

      var suite = new benchmark.Suite();

      suite.add('bitcoind getblock (native)', bitcoindGetBlockNative, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind getblock (json rpc)', bitcoindGetBlockJsonRpc, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind gettransaction (native)', bitcoinGetTransactionNative, {
        defer: true,
        maxTime: maxTime
      });

      suite.add('bitcoind gettransaction (json rpc)', bitcoinGetTransactionJsonRpc, {
        defer: true,
        maxTime: maxTime
      });

      suite
        .on('cycle', function(event) {
          console.log(String(event.target));
        })
        .on('complete', function() {
          console.log('Fastest is ' + this.filter('fastest').pluck('name'));
          console.log('----------------------------------------------------------------------');
          next();
        })
        .run();
    }
  ], function(err) {
    if (err) {
      throw err;
    }
    console.log('Finished');
    bitcoind.stop(function(err) {
      if (err) {
        console.error('Fail to stop services: ' + err);
        process.exit(1);
      }
      process.exit(0);
    });
  });
});
<|endoftext|>


<commit_before>(function(){
  if (!("$TDP" in window)){
    console.error("Missing $TDP");
  }

  //
  // Block: Setup a simple JavaScript object configuration loader.
  //
  window.TDPF_loadConfigurationFile = function(pluginObject, fileNameUser, fileNameDefault, onSuccess, onFailure){
    let identifier = pluginObject.$id;
    let token = pluginObject.$token;

    $TDP.checkFileExists(token, fileNameUser).then(exists => {
      let fileName = exists ? fileNameUser : fileNameDefault;

      (exists ? $TDP.readFile(token, fileName, true) : $TDP.readFileRoot(token, fileName)).then(contents => {
        let obj;

        try{
          obj = eval("(" + contents + ")");
        }catch(err){
          if (!(onFailure && onFailure(err))){
            $TD.alert("warning", "Problem loading '" + fileName + "' file for '" + identifier + "' plugin, the JavaScript syntax is invalid: " + err.message);
          }

          return;
        }

        onSuccess && onSuccess(obj);
      }).catch(err => {
        if (!(onFailure && onFailure(err))){
          $TD.alert("warning", "Problem loading '" + fileName + "' file for '" + identifier + "' plugin: " + err.message);
        }
      });
    }).catch(err => {
      if (!(onFailure && onFailure(err))){
        $TD.alert("warning", "Problem checking '" + fileNameUser + "' file for '" + identifier + "' plugin: " + err.message);
      }
    });
  };

  //
  // Block: Setup a function to add/remove custom CSS.
  //
  window.TDPF_createCustomStyle = function(pluginObject){
    let element = document.createElement("style");
    element.id = "plugin-" + pluginObject.$id + "-"+Math.random().toString(36).substring(2, 7);
    document.head.appendChild(element);

    return {
      insert: (rule) => element.sheet.insertRule(rule, 0),
      remove: () => element.remove(),
      element: element
    };
  };
})();
<commit_msg>Add plugin object validation to TDPF functions<commit_after>(function(){
  if (!("$TDP" in window)){
    console.error("Missing $TDP");
  }

  const validatePluginObject = function(pluginObject){
    if (!("$token" in pluginObject)){
      throw "Invalid plugin object.";
    }
  };

  //
  // Block: Setup a simple JavaScript object configuration loader.
  //
  window.TDPF_loadConfigurationFile = function(pluginObject, fileNameUser, fileNameDefault, onSuccess, onFailure){
    validatePluginObject(pluginObject);

    let identifier = pluginObject.$id;
    let token = pluginObject.$token;

    $TDP.checkFileExists(token, fileNameUser).then(exists => {
      let fileName = exists ? fileNameUser : fileNameDefault;

      (exists ? $TDP.readFile(token, fileName, true) : $TDP.readFileRoot(token, fileName)).then(contents => {
        let obj;

        try{
          obj = eval("(" + contents + ")");
        }catch(err){
          if (!(onFailure && onFailure(err))){
            $TD.alert("warning", "Problem loading '" + fileName + "' file for '" + identifier + "' plugin, the JavaScript syntax is invalid: " + err.message);
          }

          return;
        }

        onSuccess && onSuccess(obj);
      }).catch(err => {
        if (!(onFailure && onFailure(err))){
          $TD.alert("warning", "Problem loading '" + fileName + "' file for '" + identifier + "' plugin: " + err.message);
        }
      });
    }).catch(err => {
      if (!(onFailure && onFailure(err))){
        $TD.alert("warning", "Problem checking '" + fileNameUser + "' file for '" + identifier + "' plugin: " + err.message);
      }
    });
  };

  //
  // Block: Setup a function to add/remove custom CSS.
  //
  window.TDPF_createCustomStyle = function(pluginObject){
    validatePluginObject(pluginObject);

    let element = document.createElement("style");
    element.id = "plugin-" + pluginObject.$id + "-"+Math.random().toString(36).substring(2, 7);
    document.head.appendChild(element);

    return {
      insert: (rule) => element.sheet.insertRule(rule, 0),
      remove: () => element.remove(),
      element: element
    };
  };
})();
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var p = console.log;
var assert = require('assert-plus');
var sprintf = require('extsprintf').sprintf;
var util = require('util'),
    format = util.format;
var child_process = require('child_process'),
    execFile = child_process.execFile,
    spawn = child_process.spawn;
var fs = require('fs');
var path = require('path');
var vasync = require('vasync');

var errors = require('../errors'),
    InternalError = errors.InternalError;
var common = require('../common');
var vmadm = require('../vmadm');
var svcadm = require('../svcadm');

var Procedure = require('./procedure').Procedure;
var s = require('./shared');
/**
 * First pass procedure for updating UFDS service
 * services.
 *
 * Limitations:
 * - the service must only have one instance
 * - the instance must be on the headnode (where `sdcadm` is running)
 */
function UpdateUFDSServiceV1(options) {
    assert.arrayOfObject(options.changes, 'options.changes');
    this.changes = options.changes;
}
util.inherits(UpdateUFDSServiceV1, Procedure);

UpdateUFDSServiceV1.prototype.summarize = function uufdsv1Summarize() {
    return this.changes.map(function (ch) {
        return sprintf('update "%s" service to image %s (%s@%s)',
            ch.service.name, ch.image.uuid, ch.image.name, ch.image.version);
    }).join('\n');
};

UpdateUFDSServiceV1.prototype.execute = function ufdsv1Execute(opts, cb) {
    assert.object(opts, 'opts');
    assert.object(opts.sdcadm, 'opts.sdcadm');
    assert.object(opts.plan, 'opts.plan');
    assert.object(opts.log, 'opts.log');
    assert.func(opts.logCb, 'opts.logCb');
    assert.string(opts.wrkDir, 'opts.wrkDir');
    assert.func(cb, 'cb');
    var self = this;
    var log = opts.log;
    var logCb = opts.logCb;
    // Mirroring UpdateStatelessServicesV1 above, even though here we should
    // only have one instance.
    vasync.forEachPipeline({
        inputs: self.changes,
        func: updateUFDS
    }, cb);

    function updateUFDS(change, nextSvc) {
        var arg = {
            change: change,
            opts: opts,
            userScript: false
        };
        var manateeUUID;
        vasync.pipeline({funcs: [
            function getLocalManatee(_, next) {
                logCb('Running vmadm lookup to get local manatee');
                var argv = [
                    '/usr/sbin/vmadm',
                    'lookup',
                    '-1',
                    'state=running',
                    'tags.smartdc_role=manatee'
                ];
                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        next(err);
                    } else {
                        var manatees = stdout.trim().split('\n');
                        manateeUUID = manatees[0];
                        log.debug('Local manatee instance found: %s',
                            manateeUUID);
                        next();
                    }
                });
            },
            /**
             * We want to backup UFDS data before we proceed with the upgrade.
             * If the HN manatee is the async copy, that might be outdated, and
             * our backup would be useless. Do not upgrade on such case for now
             */
            function bailIfManateeIsAsync(_, next) {
                logCb('Running manatee-stat');
                var argv = [
                    '/usr/sbin/zlogin',
                    manateeUUID,
                    'source .bashrc; manatee-stat -p $ZK_IPS'
                ];

                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        next(err);
                    } else {
                        // REVIEW: Shall we try/catch here?
                        var manateeCfg = JSON.parse(stdout);
                        if (!manateeCfg.sdc) {
                            next('Cannot find manatee sdc shard config');
                        } else {
                            if (manateeCfg.sdc.async &&
                                manateeCfg.sdc.async.zoneId === manateeUUID)
                            {
                                next('Local manatee is async, ' +
                                    'cannot backup ufds buckets');
                            } else {
                                next();
                            }
                        }
                    }
                });
            },

            function backupUFDSBuckets(_, next) {
                var bPath = '/var/sdcadm/ufds-backup';
                var t = new Date().toISOString().replace(/[-:\.Z]/g, '');
                var bFile = bPath + '/' + t + '.sql';
                var exists = fs.existsSync(bPath);
                if (!exists) {
                    fs.mkdirSync(bPath);
                }

                logCb(format('Creating ufds buckets backup %s', bFile));
                var argv = [
                    '/usr/sbin/zlogin',
                    manateeUUID,
                    '/opt/local/bin/pg_dump -U moray -t \'ufds*\' moray'
                ];

                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        return next(err);
                    }

                    return fs.writeFile(bFile, stdout, {
                        encoding: 'utf8'
                    }, function (err2) {
                        if (err2) {
                            return next(err2);
                        }
                        return next();
                    });
                });
            },
            s.getUserScript,
            s.writeOldUserScriptForRollback,
            s.updateSvcUserScript,
            s.updateVmUserScript,
            s.updateSapiSvc,
            s.imgadmInstall,
            s.reprovision,
            s.waitForInstToBeUp
        ], arg: arg}, nextSvc);
    }
};

//---- exports

module.exports = {
    UpdateUFDSServiceV1: UpdateUFDSServiceV1
};
// vim: set softtabstop=4 shiftwidth=4:
<commit_msg>TOOLS-505: Do not crash when we have more than one manatee into the same Node<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var p = console.log;
var assert = require('assert-plus');
var sprintf = require('extsprintf').sprintf;
var util = require('util'),
    format = util.format;
var child_process = require('child_process'),
    execFile = child_process.execFile,
    spawn = child_process.spawn;
var fs = require('fs');
var path = require('path');
var vasync = require('vasync');

var errors = require('../errors'),
    InternalError = errors.InternalError;
var common = require('../common');
var vmadm = require('../vmadm');
var svcadm = require('../svcadm');

var Procedure = require('./procedure').Procedure;
var s = require('./shared');
/**
 * First pass procedure for updating UFDS service
 * services.
 *
 * Limitations:
 * - the service must only have one instance
 * - the instance must be on the headnode (where `sdcadm` is running)
 */
function UpdateUFDSServiceV1(options) {
    assert.arrayOfObject(options.changes, 'options.changes');
    this.changes = options.changes;
}
util.inherits(UpdateUFDSServiceV1, Procedure);

UpdateUFDSServiceV1.prototype.summarize = function uufdsv1Summarize() {
    return this.changes.map(function (ch) {
        return sprintf('update "%s" service to image %s (%s@%s)',
            ch.service.name, ch.image.uuid, ch.image.name, ch.image.version);
    }).join('\n');
};

UpdateUFDSServiceV1.prototype.execute = function ufdsv1Execute(opts, cb) {
    assert.object(opts, 'opts');
    assert.object(opts.sdcadm, 'opts.sdcadm');
    assert.object(opts.plan, 'opts.plan');
    assert.object(opts.log, 'opts.log');
    assert.func(opts.logCb, 'opts.logCb');
    assert.string(opts.wrkDir, 'opts.wrkDir');
    assert.func(cb, 'cb');
    var self = this;
    var log = opts.log;
    var logCb = opts.logCb;
    // Mirroring UpdateStatelessServicesV1 above, even though here we should
    // only have one instance.
    vasync.forEachPipeline({
        inputs: self.changes,
        func: updateUFDS
    }, cb);

    function updateUFDS(change, nextSvc) {
        var arg = {
            change: change,
            opts: opts,
            userScript: false
        };
        var manateeUUID;
        vasync.pipeline({funcs: [
            function getLocalManatee(_, next) {
                logCb('Running vmadm lookup to get local manatee');
                var argv = [
                    '/usr/sbin/vmadm',
                    'lookup',
                    'state=running',
                    'alias=~manatee'
                ];
                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        next(err);
                    } else {
                        var manatees = stdout.trim().split('\n');
                        manateeUUID = manatees[0];
                        log.debug('Local manatee instance found: %s',
                            manateeUUID);
                        next();
                    }
                });
            },
            /**
             * We want to backup UFDS data before we proceed with the upgrade.
             * If the HN manatee is the async copy, that might be outdated, and
             * our backup would be useless. Do not upgrade on such case for now
             */
            function bailIfManateeIsAsync(_, next) {
                logCb('Running manatee-stat');
                var argv = [
                    '/usr/sbin/zlogin',
                    manateeUUID,
                    'source .bashrc; manatee-stat -p $ZK_IPS'
                ];

                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        next(err);
                    } else {
                        // REVIEW: Shall we try/catch here?
                        var manateeCfg = JSON.parse(stdout);
                        if (!manateeCfg.sdc) {
                            next('Cannot find manatee sdc shard config');
                        } else {
                            if (manateeCfg.sdc.async &&
                                manateeCfg.sdc.async.zoneId === manateeUUID)
                            {
                                next('Local manatee is async, ' +
                                    'cannot backup ufds buckets');
                            } else {
                                next();
                            }
                        }
                    }
                });
            },

            function backupUFDSBuckets(_, next) {
                var bPath = '/var/sdcadm/ufds-backup';
                var t = new Date().toISOString().replace(/[-:\.Z]/g, '');
                var bFile = bPath + '/' + t + '.sql';
                var exists = fs.existsSync(bPath);
                if (!exists) {
                    fs.mkdirSync(bPath);
                }

                logCb(format('Creating ufds buckets backup %s', bFile));
                var argv = [
                    '/usr/sbin/zlogin',
                    manateeUUID,
                    '/opt/local/bin/pg_dump -U moray -t \'ufds*\' moray'
                ];

                common.execFilePlus({
                    argv: argv,
                    log: log
                }, function (err, stdout, stderr) {
                    if (err) {
                        return next(err);
                    }

                    return fs.writeFile(bFile, stdout, {
                        encoding: 'utf8'
                    }, function (err2) {
                        if (err2) {
                            return next(err2);
                        }
                        return next();
                    });
                });
            },
            s.getUserScript,
            s.writeOldUserScriptForRollback,
            s.updateSvcUserScript,
            s.updateVmUserScript,
            s.updateSapiSvc,
            s.imgadmInstall,
            s.reprovision,
            s.waitForInstToBeUp
        ], arg: arg}, nextSvc);
    }
};

//---- exports

module.exports = {
    UpdateUFDSServiceV1: UpdateUFDSServiceV1
};
// vim: set softtabstop=4 shiftwidth=4:
<|endoftext|>