<commit_before>var OntologyAddOrEditTermView = Backbone.View.extend({
    ontologyPanel : null, //Ontology panel in ontology view
    ontologyDialog : null, //dialog (add, edit)
    ontology : null,
    $tree : null,
    $panel : null,
    $textboxName : null,
    $colorChooser : null,
    $inputOldColor : null,
    $inputNewColor : null,
    $errorMessage : null,
    $errorLabel : null,
    $addFolderButton : null,
    action : null,
    events: {
        "click .addFolder": "addFolder"
    },
    initialize: function(options) {
        this.container = options.container;
        this.ontologyPanel = options.ontologyPanel;
        this.ontology = options.ontology;
        _.bindAll(this, 'render');
    },
    render : function() {
        var self = this;
        require([
            "text!application/templates/ontology/OntologyAddOrEditTermView.tpl.html"
        ],
               function(ontologyAddOrEditTermViewTpl) {
                   self.doLayout(ontologyAddOrEditTermViewTpl);
               });
        return this;
    },
    doLayout : function(ontologyAddOrEditTermViewTpl) {

        var self = this;

        if(self.model==null) {
            //dialog to add
            self.action = "Add";
            //create an empty model (not saved)
            self.createNewEmpty();
        }
        else self.action = "Edit"; //dialog to edit

        //remove older dialog
        self.$termDialog  = $(self.el).find("#dialog-"+self.action+"-ontology-term");

        $("#dialog-Edit-ontology-term").replaceWith("");
        $("#dialog-Add-ontology-term").replaceWith("");

        var dialog = _.template(ontologyAddOrEditTermViewTpl, {
            oldColor : self.model.get('color'),
            action : self.action
        });
        console.log(dialog);
        $(self.el).append(dialog);

        self.$panel = $(self.el);
        self.$termDialog  = $(self.el).find("#dialog-"+self.action+"-ontology-term");
        self.$tree = self.$panel.find("#" + self.action +"ontologytermtree");
        self.$from = self.$panel.find($("#form-" + self.action +"-ontology-term"));
        self.$textboxName = self.$panel.find("#" + self.action +"termname");

        self.$colorChooser = self.$panel.find('#colorpicker1');
        self.$inputOldColor = self.$panel.find('#oldColor');
        self.$inputNewColor = self.$panel.find('#color1');

        self.$addFolderButton  = self.$panel.find('.addFolder');

        self.$errorMessage =  self.$panel.find("#" + self.action +"ontologytermerrormessage");
        self.$errorLabel =  self.$panel.find("#" + self.action +"ontologytermerrorlabel");

        self.$from.submit(function () {
            if(self.action == "Edit")
                self.updatedOntologyTerm();
            else  self.createOntologyTerm();
            return false;});
        self.$from.find("input").keydown(function(e){
            if (e.keyCode == 13) { //ENTER_KEY
                self.$from.submit();
                return false;
            }
        });
        self.clearOntologyTermPanel();
        self.buildNameInfo();
        self.buildColorInfo();
        self.buildParentInfo();

        //Build dialog
        console.log("OntologyTermDialog: build dialog:"+self.$termDialog.length);
        self.ontologyDialog = self.$termDialog.dialog({
            width: "1000",
            autoOpen : false,
            modal:true,
            buttons : {
                "Save" : function() {
                    self.$from.submit();
                },
                "Cancel" : function() {
                    self.$termDialog.dialog("close");
                }
            }
        });
        self.open();
        return this;
    },
    /**
     * Create new empty model with default value
     */
    createNewEmpty : function() {
        var self = this;
        console.log("createNewEmpty");
        self.model = new TermModel({id:-1,name:"",color:"#ff0000"});
    },

    buildNameInfo : function () {
        console.log("buildNameInfo");
        var self = this;
        self.$textboxName.val(self.model.get("name"));

                console.log(self.$textboxName.length);

        self.$textboxName.bind('keyup mouseup change',function(e){
            var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
            var color = "#119b04"
            var htmlNode = "{{title}}"
            var nodeTpl = _.template(htmlNode, {title : self.$textboxName.val(), color : color});
            node.setTitle(nodeTpl);
        });
    },

    buildColorInfo : function() {
        console.log("buildColorInfo");
        var self = this;

        console.log(self.$inputNewColor.attr('id'));
        var colorPicker = self.$colorChooser.farbtastic('#color1');

        var color = self.model.get('color');

        self.$inputOldColor.val(color);
        self.$inputNewColor.val(color);
        self.$inputOldColor.css("background", color);
        self.$inputNewColor.css("background", color);
        self.$inputNewColor.css("color", self.$inputOldColor.css("color"));
    },
    addFolder : function() {
        //create a new node as a folder

        //automatically put the new term node under this folder

        //MOVE IN ADD/UPDATED when you save it, check if the parent node is this new folder, if its true save the relation

    },

    buildParentInfo : function() {
        console.log("buildParentInfo");
        var self = this;
        console.log("buildOntologyTree for ontology " + self.ontology.id);

        self.$addFolderButton.button({
            icons : {secondary: "ui-icon-folder-collapsed" }
        });

        self.$tree.empty() ;
        self.$tree.dynatree({
            children: self.ontology.toJSON(),
            onExpand : function() { console.log("expanding/collapsing");},
            onRender: function(node, nodeSpan) {
                self.$tree.find("a.dynatree-title").css("color", "black");
            },
            onClick: function(node, event) {
            },
            onSelect: function(select, node) {
            },
            onCustomRender: function(node) {
            },
            onDblClick: function(node, event) {
            },
            dnd: {
                onDragStart: function(node) {
                    /** This function MUST be defined to enable dragging for the tree.
                     *  Return false to cancel dragging of node.
                     */
                    if(node.data.key!=self.model.id) return false;
                    return true;
                },
                onDragStop: function(node) {
                },
                autoExpandMS: 1000,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                onDragEnter: function(node, sourceNode) {
                    logMsg("tree.onDragEnter(%o, %o)", node, sourceNode);
                    return true;
                },
                onDragOver: function(node, sourceNode, hitMode) {
                },
                onDrop: function(node, sourceNode, hitMode, ui, draggable) {
                    logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode);
//                    if(!node.data.isFolder && hitMode=="over")
//                    {
//                        console.log("NOT A FOLDER");
//                    }
//                    else sourceNode.move(node, hitMode);
                    if(hitMode=="over") {
                        sourceNode.move(node, hitMode);
                        console.log(node);
                        node.data.isFolder = true;
                        node.render();
                    }
                },
                onDragLeave: function(node, sourceNode) {
                }
            },
            generateIds: true,
            // The following options are only required, if we have more than one tree on one page:
            initId: "" + self.action +"treeDataOntology-"+self.model.id,
            cookieId: "" + self.action +"dynatree-Ontology-"+self.model.id,
            idPrefix: "" + self.action +"dynatree-Ontology-"+self.model.id+"-" ,
            debugLevel: 0
        });
        console.log("STUFF FOR ADD");
        //if add panel, add the "temp" model to the tree (event if it's not yet a part of the ontology)
        if(self.action=="Add") {
            var node = self.$tree.dynatree("getTree").getNodeByKey(self.ontology.id);
            var childNode = node.addChild({
                title: "",
                key : -1,
                tooltip: "This folder and all child nodes were added programmatically.",
                isFolder: false
            });
        }
        console.log("CHANGE COLOR");
         //make the new term node visible
      /*  console.log("1 self.model.id="+self.model.id);
        var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
        console.log("2");
        console.log(node);
        var title = node.data.title
        console.log("3");
        var color = "#9ac400"
        console.log("4");
        var htmlNode = "{{title}}"
        console.log("5:"+htmlNode);
        var nodeTpl = _.template(htmlNode, {title : title, color : color});
        console.log("6:");
        console.log(nodeTpl);
        node.setTitle(nodeTpl);
        console.log("7");     */

        console.log("EXPAND ALL");
        //expand all nodes
        self.$tree.dynatree("getRoot").visit(function(node){
            node.expand(true);
        });

    },

    getNewName : function() {
        var self = this;
        return self.$textboxName.val();
    },
    getNewParent : function() {
        var self = this;
        var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
        return node.parent.data.id;
    },
    getNewColor : function() {
        return  this.$inputNewColor.val();
    },
    refresh : function() {

    },
    open: function() {
        var self = this;
        self.clearOntologyTermPanel();
        self.ontologyDialog.dialog("open") ;
    },
    clearOntologyTermPanel : function() {
        var self = this;
        self.$errorMessage.empty();
        self.$errorLabel.hide();
    },
    updatedOntologyTerm : function() {
        console.log("updatedOntologyTerm...");
        var self = this;

        self.$errorMessage.empty();
        self.$errorLabel.hide();

        var id = self.model.id;
        var name =  self.getNewName();
        var idOldParent = self.model.get("parent");
        var idParent = self.getNewParent();
        var isOldParentOntology = true;
        if(idOldParent!=null && window.app.models.ontologies.get(idOldParent)==undefined) {
            isOldParentOntology = false;
        }
        var isParentOntology = true;

        if(window.app.models.ontologies.get(idParent)==undefined) {
            isParentOntology = false;
        }
        console.log("isOldParentOntology="+isOldParentOntology + " isParentOntology=" + isParentOntology);
        var color = self.getNewColor();
        console.log("update term "+ name + " with parent=" + idParent + "(old parent =" + idOldParent+ ") and color="+color);

        self.model.set({name:name,color:color});
        self.model.save({name:name,color:color},{
            success: function (model, response) {
                console.log(response);
                //TODO: check it relation/term is changed
                console.log("isOldParentOntology="+isOldParentOntology + " isParentOntology=" + isParentOntology);
                if(idParent!=idOldParent)
                {
                    if(isOldParentOntology&&isParentOntology) {self.close();}
                    else if(isOldParentOntology)  self.addRelation(id,idParent); //parent was ontology so nothing to delete
                    else if(isParentOntology) self.resetRelation(id,idOldParent,null); //new parent is ontology so nothing to add
                    else {
                        self.resetRelation(id,idOldParent,idParent);
                    }
                }
                else self.close();
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }
        } ); //TODO: catch error
    },

    createOntologyTerm : function() {
        console.log("createOntologyTerm...");

        var self = this;

        self.$errorMessage.empty();
        self.$errorLabel.hide();

        var id = self.model.id;
        var name =  self.getNewName();
        var isParentOntology = true;
        var idParent = self.getNewParent();
        if(window.app.models.ontologies.get(idParent)==undefined) {
            isParentOntology = false;
        }
        console.log("isParentOntology=" + isParentOntology);
        var color = self.getNewColor();
        console.log("create term "+ name + " with parent=" + idParent + " and color="+color);

        self.model.set({name:name,color:color});
        self.model = new TermModel({name:name,color:color,ontology:self.ontology.id}).save({name:name,color:color,ontology:self.ontology.id},{
            success: function (model, response) {
                console.log(response);
                //TODO: check it relation/term is changed
                console.log("isParentOntology=" + isParentOntology);

                if(isParentOntology) {
                    //no link "parent" with a term
                    window.app.view.message("Term", response.message, "");
                    self.close();
                }
                else {
                    self.addRelation(id,idParent);
                }
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }
        } ); //TODO: catch error

    },
    resetRelation : function(child,oldParent,newParent) {
        var self = this;
        new RelationTermModel({term1:oldParent, term2:child}).destroy({
            success : function (model, response) {
                console.log("destroy old relation");
                //create relation with new parent
                if(newParent!=null) {
                    self.addRelation(child,newParent);
                }
                else {
                    window.app.view.message("Term", response.message, "");
                    self.close();
                }
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }});
    },
    addRelation : function(child,newParent) {
        var self = this;
        new RelationTermModel({}).save({term1:newParent, term2:child},{
            success : function (model, response) {
                console.log("create new relation");
                window.app.view.message("Term", response.message, "");
                self.close();
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }});
    },
    close : function() {
        var self = this;
        this.ontologyPanel.refresh();
        console.log(self.ontologyDialog.length);
        self.$termDialog.dialog("close") ;
    }
});<commit_msg>correct bug in ontology tree<commit_after>var OntologyAddOrEditTermView = Backbone.View.extend({
    ontologyPanel : null, //Ontology panel in ontology view
    ontologyDialog : null, //dialog (add, edit)
    ontology : null,
    $tree : null,
    $panel : null,
    $textboxName : null,
    $colorChooser : null,
    $inputOldColor : null,
    $inputNewColor : null,
    $errorMessage : null,
    $errorLabel : null,
    $addFolderButton : null,
    action : null,
    events: {
        "click .addFolder": "addFolder"
    },
    initialize: function(options) {
        this.container = options.container;
        this.ontologyPanel = options.ontologyPanel;
        this.ontology = options.ontology;
        _.bindAll(this, 'render');
    },
    render : function() {
        var self = this;
        require([
            "text!application/templates/ontology/OntologyAddOrEditTermView.tpl.html"
        ],
               function(ontologyAddOrEditTermViewTpl) {
                   self.doLayout(ontologyAddOrEditTermViewTpl);
               });
        return this;
    },
    doLayout : function(ontologyAddOrEditTermViewTpl) {

        var self = this;

        if(self.model==null) {
            //dialog to add
            self.action = "Add";
            //create an empty model (not saved)
            self.createNewEmpty();
        }
        else self.action = "Edit"; //dialog to edit

        //remove older dialog
        self.$termDialog  = $(self.el).find("#dialog-"+self.action+"-ontology-term");

        $("#dialog-Edit-ontology-term").replaceWith("");
        $("#dialog-Add-ontology-term").replaceWith("");

        var dialog = _.template(ontologyAddOrEditTermViewTpl, {
            oldColor : self.model.get('color'),
            action : self.action
        });
        console.log(dialog);
        $(self.el).append(dialog);

        self.$panel = $(self.el);
        self.$termDialog  = $(self.el).find("#dialog-"+self.action+"-ontology-term");
        self.$tree = self.$panel.find("#" + self.action +"ontologytermtree");
        self.$from = self.$panel.find($("#form-" + self.action +"-ontology-term"));
        self.$textboxName = self.$panel.find("#" + self.action +"termname");

        self.$colorChooser = self.$panel.find('#colorpicker1');
        self.$inputOldColor = self.$panel.find('#oldColor');
        self.$inputNewColor = self.$panel.find('#color1');

        self.$addFolderButton  = self.$panel.find('.addFolder');

        self.$errorMessage =  self.$panel.find("#" + self.action +"ontologytermerrormessage");
        self.$errorLabel =  self.$panel.find("#" + self.action +"ontologytermerrorlabel");

        self.$from.submit(function () {
            if(self.action == "Edit")
                self.updatedOntologyTerm();
            else  self.createOntologyTerm();
            return false;});
        self.$from.find("input").keydown(function(e){
            if (e.keyCode == 13) { //ENTER_KEY
                self.$from.submit();
                return false;
            }
        });
        self.clearOntologyTermPanel();
        self.buildNameInfo();
        self.buildColorInfo();
        self.buildParentInfo();

        //Build dialog
        console.log("OntologyTermDialog: build dialog:"+self.$termDialog.length);
        self.ontologyDialog = self.$termDialog.dialog({
            width: "1000",
            autoOpen : false,
            modal:true,
            buttons : {
                "Save" : function() {
                    self.$from.submit();
                },
                "Cancel" : function() {
                    self.$termDialog.dialog("close");
                }
            }
        });
        self.open();
        return this;
    },
    /**
     * Create new empty model with default value
     */
    createNewEmpty : function() {
        var self = this;
        console.log("createNewEmpty");
        self.model = new TermModel({id:-1,name:"",color:"#ff0000"});
    },

    buildNameInfo : function () {
        console.log("buildNameInfo");
        var self = this;
        self.$textboxName.val(self.model.get("name"));

                console.log(self.$textboxName.length);

        self.$textboxName.bind('keyup mouseup change',function(e){
            var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
            var color = "#119b04"
            var htmlNode = "{{title}}"
            var nodeTpl = _.template(htmlNode, {title : self.$textboxName.val(), color : color});
            node.setTitle(nodeTpl);
        });
    },

    buildColorInfo : function() {
        console.log("buildColorInfo");
        var self = this;

        console.log(self.$inputNewColor.attr('id'));
        var colorPicker = self.$colorChooser.farbtastic('#color1');

        var color = self.model.get('color');

        self.$inputOldColor.val(color);
        self.$inputNewColor.val(color);
        self.$inputOldColor.css("background", color);
        self.$inputNewColor.css("background", color);
        self.$inputNewColor.css("color", self.$inputOldColor.css("color"));
    },
    addFolder : function() {
        //create a new node as a folder

        //automatically put the new term node under this folder

        //MOVE IN ADD/UPDATED when you save it, check if the parent node is this new folder, if its true save the relation

    },

    buildParentInfo : function() {
        console.log("buildParentInfo");
        var self = this;
        console.log("buildOntologyTree for ontology " + self.ontology.id);

        self.$addFolderButton.button({
            icons : {secondary: "ui-icon-folder-collapsed" }
        });

        self.$tree.empty() ;
        self.$tree.dynatree({
            children: self.ontology.toJSON(),
            onExpand : function() { console.log("expanding/collapsing");},
            onRender: function(node, nodeSpan) {
                self.$tree.find("a.dynatree-title").css("color", "black");
            },
            onClick: function(node, event) {
            },
            onSelect: function(select, node) {
            },
            onCustomRender: function(node) {
            },
            onDblClick: function(node, event) {
            },
            dnd: {
                onDragStart: function(node) {
                    /** This function MUST be defined to enable dragging for the tree.
                     *  Return false to cancel dragging of node.
                     */
                    if(node.data.key!=self.model.id) return false;
                    return true;
                },
                onDragStop: function(node) {
                },
                autoExpandMS: 1000,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                onDragEnter: function(node, sourceNode) {
                    logMsg("tree.onDragEnter(%o, %o)", node, sourceNode);
                    return true;
                },
                onDragOver: function(node, sourceNode, hitMode) {
                },
                onDrop: function(node, sourceNode, hitMode, ui, draggable) {
                    logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode);
//                    if(!node.data.isFolder && hitMode=="over")
//                    {
//                        console.log("NOT A FOLDER");
//                    }
//                    else sourceNode.move(node, hitMode);
                    console.log("onDrop "+ hitMode);
                    if(hitMode=="over") {
                        sourceNode.move(node, hitMode);
                        console.log(node);
                        node.data.isFolder = true;
                        node.render();
                    }
                    else sourceNode.move(node, hitMode);
                },
                onDragLeave: function(node, sourceNode) {
                }
            },
            generateIds: true,
            // The following options are only required, if we have more than one tree on one page:
            initId: "" + self.action +"treeDataOntology-"+self.model.id,
            cookieId: "" + self.action +"dynatree-Ontology-"+self.model.id,
            idPrefix: "" + self.action +"dynatree-Ontology-"+self.model.id+"-" ,
            debugLevel: 0
        });
        console.log("STUFF FOR ADD");
        //if add panel, add the "temp" model to the tree (event if it's not yet a part of the ontology)
        if(self.action=="Add") {
            var node = self.$tree.dynatree("getTree").getNodeByKey(self.ontology.id);
            var childNode = node.addChild({
                title: "",
                key : -1,
                tooltip: "This folder and all child nodes were added programmatically.",
                isFolder: false
            });
        }
        console.log("CHANGE COLOR");
         //make the new term node visible
      /*  console.log("1 self.model.id="+self.model.id);
        var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
        console.log("2");
        console.log(node);
        var title = node.data.title
        console.log("3");
        var color = "#9ac400"
        console.log("4");
        var htmlNode = "{{title}}"
        console.log("5:"+htmlNode);
        var nodeTpl = _.template(htmlNode, {title : title, color : color});
        console.log("6:");
        console.log(nodeTpl);
        node.setTitle(nodeTpl);
        console.log("7");     */

        console.log("EXPAND ALL");
        //expand all nodes
        self.$tree.dynatree("getRoot").visit(function(node){
            node.expand(true);
        });

    },

    getNewName : function() {
        var self = this;
        return self.$textboxName.val();
    },
    getNewParent : function() {
        var self = this;
        var node = self.$tree.dynatree("getTree").getNodeByKey(self.model.id);
        return node.parent.data.id;
    },
    getNewColor : function() {
        return  this.$inputNewColor.val();
    },
    refresh : function() {

    },
    open: function() {
        var self = this;
        self.clearOntologyTermPanel();
        self.ontologyDialog.dialog("open") ;
    },
    clearOntologyTermPanel : function() {
        var self = this;
        self.$errorMessage.empty();
        self.$errorLabel.hide();
    },
    updatedOntologyTerm : function() {
        console.log("updatedOntologyTerm...");
        var self = this;

        self.$errorMessage.empty();
        self.$errorLabel.hide();

        var id = self.model.id;
        var name =  self.getNewName();
        var idOldParent = self.model.get("parent");
        var idParent = self.getNewParent();
        var isOldParentOntology = true;
        if(idOldParent!=null && window.app.models.ontologies.get(idOldParent)==undefined) {
            isOldParentOntology = false;
        }
        var isParentOntology = true;

        if(window.app.models.ontologies.get(idParent)==undefined) {
            isParentOntology = false;
        }
        console.log("isOldParentOntology="+isOldParentOntology + " isParentOntology=" + isParentOntology);
        var color = self.getNewColor();
        console.log("update term "+ name + " with parent=" + idParent + "(old parent =" + idOldParent+ ") and color="+color);

        self.model.set({name:name,color:color});
        self.model.save({name:name,color:color},{
            success: function (model, response) {
                console.log(response);
                //TODO: check it relation/term is changed
                console.log("isOldParentOntology="+isOldParentOntology + " isParentOntology=" + isParentOntology);
                if(idParent!=idOldParent)
                {
                    if(isOldParentOntology&&isParentOntology) {self.close();}
                    else if(isOldParentOntology)  self.addRelation(id,idParent); //parent was ontology so nothing to delete
                    else if(isParentOntology) self.resetRelation(id,idOldParent,null); //new parent is ontology so nothing to add
                    else {
                        self.resetRelation(id,idOldParent,idParent);
                    }
                }
                else self.close();
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }
        } ); //TODO: catch error
    },

    createOntologyTerm : function() {
        console.log("createOntologyTerm...");

        var self = this;

        self.$errorMessage.empty();
        self.$errorLabel.hide();

        var id = self.model.id;
        var name =  self.getNewName();
        var isParentOntology = true;
        var idParent = self.getNewParent();
        if(window.app.models.ontologies.get(idParent)==undefined) {
            isParentOntology = false;
        }
        console.log("isParentOntology=" + isParentOntology);
        var color = self.getNewColor();
        console.log("create term "+ name + " with parent=" + idParent + " and color="+color);

        self.model.set({name:name,color:color});
        self.model = new TermModel({name:name,color:color,ontology:self.ontology.id}).save({name:name,color:color,ontology:self.ontology.id},{
            success: function (model, response) {
                console.log(response);
                //TODO: check it relation/term is changed
                console.log("isParentOntology=" + isParentOntology);

                if(isParentOntology) {
                    //no link "parent" with a term
                    window.app.view.message("Term", response.message, "");
                    self.close();
                }
                else {
                    self.addRelation(id,idParent);
                }
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }
        } ); //TODO: catch error

    },
    resetRelation : function(child,oldParent,newParent) {
        var self = this;
        new RelationTermModel({term1:oldParent, term2:child}).destroy({
            success : function (model, response) {
                console.log("destroy old relation");
                //create relation with new parent
                if(newParent!=null) {
                    self.addRelation(child,newParent);
                }
                else {
                    window.app.view.message("Term", response.message, "");
                    self.close();
                }
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }});
    },
    addRelation : function(child,newParent) {
        var self = this;
        new RelationTermModel({}).save({term1:newParent, term2:child},{
            success : function (model, response) {
                console.log("create new relation");
                window.app.view.message("Term", response.message, "");
                self.close();
            },
            error: function (model, response) {
                var json = $.parseJSON(response.responseText);
                console.log("json.project="+json.errors);
                self.$errorLabel.show();
                self.$errorMessage.append(json.errors);
            }});
    },
    close : function() {
        var self = this;
        this.ontologyPanel.refresh();
        console.log(self.ontologyDialog.length);
        self.$termDialog.dialog("close") ;
    }
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         NBR_sidebar
// @version      1.2
// @description  show hide side menu on http://forum.notebookreview.com
// @author       katalin_2003
// @include      http://forum.notebookreview.com/*
// @match        http://forum.notebookreview.com/
// @grant        none
// ==/UserScript==

// Let's make it easier to add global styles
function addStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// change font style in messages
//addStyle('.messageText { font-family: sans-serif !important; }');
addStyle('* { font-family: sans-serif !important; }');

// reduce the min-height of messages to gain some vertical space in the case of small messages.
// or you can get the size of .messageUserInfo and use that value as the min-height for messages, though the former might not always have a fixed height for all users.
addStyle('.messageContent { min-height: 2em !important; }');

// add the missing right border..OCD much :)
addStyle('ol#forums { border-right: 1px solid #7B7B7B !important; }');
addStyle('div.sectionMain { border-right: 1px solid #7B7B7B !important; }');

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

// Toggle visibility function
function toggle(obj) {
    //  var el = document.getElementById(obj);
    var el = document.getElementsByClassName(obj)[0],
        mainContent = document.getElementsByClassName('mainContent')[0];
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
        sideTgl.innerHTML = '<<';
        mainContent.style.width = '100%';

        var elWidth = el.offsetWidth,
            mainContentWidth = mainContent.offsetWidth;
        console.log('katalin_2003: sidebar hidden');
        console.log('katalin_2003: mainContent width is: ' + mainContentWidth + 'px');
    }
    else {
        el.style.display = '';
        sideTgl.innerHTML = '>>';

        var elWidth = el.offsetWidth,
            mainContentWidth = mainContent.offsetWidth;
        mainContent.style.width = (mainContentWidth - elWidth-10) +'px';

        console.log('katalin_2003: sidebar visible');
        console.log('katalin_2003: mainContent width is: ' + (mainContentWidth-elWidth-10) + 'px');
    }
}

var sideTgl = document.createElement('div');
sideTgl.setAttribute('id', "sidebarToggle");
sideTgl.style.cssFloat = 'right';
sideTgl.style.color = '#000000';

sideTgl.innerHTML = ">>";
//var div = document.getElementsByClassName("blockLinksList")[0];
var div = document.getElementsByClassName("breadBoxTop")[0];
insertAfter(div, sideTgl);

addStyle('div#sidebarToggle { border: 1px solid #7B7B7B; }');
addStyle('div#sidebarToggle { border-radius: 2px; }');
addStyle('div#sidebarToggle { padding: 1px 10px; }');
addStyle('div#sidebarToggle { margin-top: 3px; }');
//addStyle('div#sidebarToggle { margin-right: 20px; }');
addStyle('div#sidebarToggle:hover { cursor: pointer; }');
addStyle('div#sidebarToggle:hover { background-color: #F0F0F0; }');

var sidebarToggle = document.getElementById('sidebarToggle');
sidebarToggle.setAttribute('title' , 'Toggle sidebar visibility');

// Hide the sidebar by default
(function() {
    toggle('sidebar');
    console.log('hidden');
    return false;
})();

// Toggle sidebar's visibility on click
sidebarToggle.onclick = function () {
    toggle('sidebar');
    return false;
}

// remove "Latest" string in front of thread titles
addStyle('span.lastThreadTitle > span { display:none; }');
// increase the width of the element containig the latest thread in a sub forum
addStyle('.node .nodeLastPost { width: 30%; }');
// push the nodeControl icons (RSS etc..) to the left to compensate
addStyle('.node .nodeControls { right: 32%; }');
<commit_msg>Update nbr_sidebar.js<commit_after>// ==UserScript==
// @name         nbr_sidebar.js
// @version      1.3
// @description  show hide side menu on http://forum.notebookreview.com
// @author       katalin_2003
// @include      http://forum.notebookreview.com/*
// @match        http://forum.notebookreview.com/
// @grant        none
// ==/UserScript==

// Let's make it easier to add global styles
function addStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// change font style in messages
//addStyle('.messageText { font-family: sans-serif !important; }');
addStyle('* { font-family: sans-serif !important; }');

// reduce the min-height of messages to gain some vertical space in the case of small messages.
// or you can get the size of .messageUserInfo and use that value as the min-height for messages, though the former might not always have a fixed height for all users.
addStyle('.messageContent { min-height: 2em !important; }');

// add the missing right border..OCD much :)
addStyle('ol#forums { border-right: 1px solid #7B7B7B !important; }');
addStyle('div.sectionMain { border-right: 1px solid #7B7B7B !important; }');

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

// Toggle visibility function
function toggle(obj) {
    //  var el = document.getElementById(obj);
    var el = document.getElementsByClassName(obj)[0],
        mainContent = document.getElementsByClassName('mainContent')[0];
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
        sideTgl.innerHTML = '<<';
        mainContent.style.width = '100%';

        var elWidth = el.offsetWidth,
            mainContentWidth = mainContent.offsetWidth;
        console.log('katalin_2003: sidebar hidden');
        console.log('katalin_2003: mainContent width is: ' + mainContentWidth + 'px');
    }
    else {
        el.style.display = '';
        sideTgl.innerHTML = '>>';

        var elWidth = el.offsetWidth,
            mainContentWidth = mainContent.offsetWidth;
        mainContent.style.width = (mainContentWidth - elWidth-10) +'px';

        console.log('katalin_2003: sidebar visible');
        console.log('katalin_2003: mainContent width is: ' + (mainContentWidth-elWidth-10) + 'px');
    }
}

var sideTgl = document.createElement('div');
sideTgl.setAttribute('id', "sidebarToggle");
sideTgl.style.cssFloat = 'right';
sideTgl.style.color = '#000000';

sideTgl.innerHTML = ">>";
//var div = document.getElementsByClassName("blockLinksList")[0];
var div = document.getElementsByClassName("breadBoxTop")[0];
insertAfter(div, sideTgl);

addStyle('div#sidebarToggle { border: 1px solid #7B7B7B; }');
addStyle('div#sidebarToggle { border-radius: 2px; }');
addStyle('div#sidebarToggle { padding: 1px 10px; }');
addStyle('div#sidebarToggle { margin-top: 3px; }');
//addStyle('div#sidebarToggle { margin-right: 20px; }');
addStyle('div#sidebarToggle:hover { cursor: pointer; }');
addStyle('div#sidebarToggle:hover { background-color: #F0F0F0; }');

var sidebarToggle = document.getElementById('sidebarToggle');
sidebarToggle.setAttribute('title' , 'Toggle sidebar visibility');

// Hide the sidebar by default
(function() {
    toggle('sidebar');
    console.log('hidden');
    return false;
})();

// Toggle sidebar's visibility on click
sidebarToggle.onclick = function () {
    toggle('sidebar');
    return false;
}

// remove "Latest" string in front of thread titles
addStyle('span.lastThreadTitle > span { display:none; }');
// increase the width of the element containig the latest thread in a sub forum
addStyle('.node .nodeLastPost { width: 30%; }');
// push the nodeControl icons (RSS etc..) to the left to compensate
addStyle('.node .nodeControls { right: 32%; }');
<|endoftext|>


<commit_before>// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var request = require('request');

function NGALMClient() {
  this.sourceProperties = [
    {
      name: "ngalm_url",
      optional: false
    },
    {
      name: "client_id",
      optional: false
    },
    {
      name: "client_secret",
      optional: false
    }
  ];
  this.paramProperties = [
    {
      name: "color",
      optional: true
    },
    {
      name: "from",
      optional: false
    },
    {
      name: "message",
      optional: false
    },
    {
      name: "message_format",
      optional: true
    },
    {
      name: "notify",
      optional: true
    }
  ];
  this.validInput = true;
  this.failOnError = true;
}

NGALMClient.prototype.checkArgument = function (argumentName, argumentValue) {
  if (!argumentValue || argumentValue.length === 0) {
    console.error("Please provide a value for", argumentName);
    this.validInput = false;
  }
};

// NGALMClient.prototype.connectALM = function (source, params, done) {
//   //First auth so that we can perform API calls
//   var requestUrl = '${source.ngalm_url}/authentication/sign_in',
//     authBody = {
//       client_id: source.client_id,
//       client_secret: source.client_secret,
//     },
//     requestOptions = {
//       url: requestUrl,
//       method: "POST",
//       json: authBody
//     };

//   request(requestOptions, (err, response) => {
//     if (err || response.statusCode > 200) {
//       return done(err || response.body)
//     }

//     //return done(err);
//   });

// };

// NGALMClient.prototype.pipelineVersion = function (source, params, done) {
// //Now let's create a CI server.  This is idempotent so we should be able to do it on every check
// var requestUrl = '${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers',
//   postBody = {
//     instance_id: "0",
//     name: "Concourse_test_sam",
//     url: "http://192.168.1.100:3000",
//     server_type: "Concourse server"
//   },
//   requestOptions = {
//     url: requestUrl,
//     method: "POST",
//     json: {"data":[postBody]}//,
//     // headers: {
//     // "HPSSO-HEADER-CSRF": 'figure out how to generate CSFF, if needed'
//     // }
//   };

// request(requestOptions, (err, response) => {
//   if (err || response.statusCode > 200) {
//     return done(err || response.body)
//   }

//   return done(err);
// });

//}

NGALMClient.prototype.checkProperties = function (values, properties) {
  for (property of properties) {
    if (!property.optional) {
      this.checkArgument(property.name, values[property.name]);
    }
  }
};

NGALMClient.prototype.sendMessage = function (source, params, done) {
  //First auth so that we can perform API calls
  var requestUrl = `${source.ngalm_url}/authentication/sign_in`,
    authBody = {
      client_id: source.client_id,
      client_secret: source.client_secret,
    },
    requestOptions = {
      url: requestUrl,
      method: "POST",
      json: authBody
    };

  request(requestOptions, (err, response) => {
    if (err || response.statusCode > 200) {
      return done(err || response.body)
    }
    //return done(err);
    //Now let's create a CI server.  This is idempotent so we should be able to do it on every check
    var requestUrl = `${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers`,
      postBody = {
        instance_id: "0",
        name: "Concourse_test_sam",
        url: "http://192.168.1.100:3000",
        server_type: "Concourse server"
      },
      requestOptions = {
        url: requestUrl,
        method: "POST",
        json: {"data":[postBody]}//,
        // headers: {
        // "HPSSO-HEADER-CSRF": 'figure out how to generate CSFF, if needed'
        // }
      };

    request(requestOptions, (err, response) => {
      if (err || response.statusCode > 200) {
        console.error('nope CI server failed');
        console.error(err);
        return done(err || response.body)
      }
      console.error('looks like weve created a CI server');
      console.error(response);
      return done(err);
    });
  });

};

NGALMClient.prototype.run = function (source, params) {
  var self = this;
  if (source.fail_on_error === undefined) {
    source.fail_on_error = true;
  }

  self.failOnError = source.fail_on_error;
  self.validInput = true;

  self.checkProperties(source, this.sourceProperties);
  self.checkProperties(params, this.paramProperties);

  if (!self.validInput) {
    console.error("Please provide valid input and try again");
    return process.exit(1);
  }
  self.sendMessage(source, params, (error, result) => {
    if (error) {
      console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
      if (self.failOnError) {
        process.exit(1);
      }
    }
    // Concourse expects this output from stdout, do not use console.dir
    console.log(JSON.stringify({
      version: {
        ref: "none"
      }
    }));
    process.exit(0);
  });
}

// NGALMClient.prototype.connect = function (source, params) {
//   var self = this;
//   if (source.fail_on_error === undefined) {
//     source.fail_on_error = true;
//   }

//   self.failOnError = source.fail_on_error;
//   self.validInput = true;

//   self.checkProperties(source, this.sourceProperties);
//   self.checkProperties(params, this.paramProperties);

//   if (!self.validInput) {
//     console.error("Please provide valid input and try again");
//     return process.exit(1);
//   }

//   self.connectALM(source, params, (error, result) => {
//     if (error) {
//       console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
//       console.error(error);
//       if (self.failOnError) {
//         process.exit(1);
//       }
//     }
//   });
//   self.pipelineVersion(source, params, (error, result) => {
//   if (error) {
//     console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
//     console.error(error);
//     if (self.failOnError) {
//       process.exit(1);
//     }
//   }
//   // Concourse expects this output from stdout, do not use console.dir
//   console.log('this should work-printing out result');
//   console.log(result);
//   console.log(JSON.stringify({
//     version: {
//       ref: "test"
//     }
//   }));
//   process.exit(0);
// });
// };

module.exports = NGALMClient;<commit_msg>even more logging<commit_after>// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var request = require('request');

function NGALMClient() {
  this.sourceProperties = [
    {
      name: "ngalm_url",
      optional: false
    },
    {
      name: "client_id",
      optional: false
    },
    {
      name: "client_secret",
      optional: false
    }
  ];
  this.paramProperties = [
    {
      name: "color",
      optional: true
    },
    {
      name: "from",
      optional: false
    },
    {
      name: "message",
      optional: false
    },
    {
      name: "message_format",
      optional: true
    },
    {
      name: "notify",
      optional: true
    }
  ];
  this.validInput = true;
  this.failOnError = true;
}

NGALMClient.prototype.checkArgument = function (argumentName, argumentValue) {
  if (!argumentValue || argumentValue.length === 0) {
    console.error("Please provide a value for", argumentName);
    this.validInput = false;
  }
};

// NGALMClient.prototype.connectALM = function (source, params, done) {
//   //First auth so that we can perform API calls
//   var requestUrl = '${source.ngalm_url}/authentication/sign_in',
//     authBody = {
//       client_id: source.client_id,
//       client_secret: source.client_secret,
//     },
//     requestOptions = {
//       url: requestUrl,
//       method: "POST",
//       json: authBody
//     };

//   request(requestOptions, (err, response) => {
//     if (err || response.statusCode > 200) {
//       return done(err || response.body)
//     }

//     //return done(err);
//   });

// };

// NGALMClient.prototype.pipelineVersion = function (source, params, done) {
// //Now let's create a CI server.  This is idempotent so we should be able to do it on every check
// var requestUrl = '${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers',
//   postBody = {
//     instance_id: "0",
//     name: "Concourse_test_sam",
//     url: "http://192.168.1.100:3000",
//     server_type: "Concourse server"
//   },
//   requestOptions = {
//     url: requestUrl,
//     method: "POST",
//     json: {"data":[postBody]}//,
//     // headers: {
//     // "HPSSO-HEADER-CSRF": 'figure out how to generate CSFF, if needed'
//     // }
//   };

// request(requestOptions, (err, response) => {
//   if (err || response.statusCode > 200) {
//     return done(err || response.body)
//   }

//   return done(err);
// });

//}

NGALMClient.prototype.checkProperties = function (values, properties) {
  for (property of properties) {
    if (!property.optional) {
      this.checkArgument(property.name, values[property.name]);
    }
  }
};

NGALMClient.prototype.sendMessage = function (source, params, done) {
  //First auth so that we can perform API calls
  var requestUrl = `${source.ngalm_url}/authentication/sign_in`,
    authBody = {
      client_id: source.client_id,
      client_secret: source.client_secret,
    },
    requestOptions = {
      url: requestUrl,
      method: "POST",
      json: authBody
    };

  request(requestOptions, (err, response) => {
    if (err || response.statusCode > 200) {
      return done(err || response.body)
    }
    //return done(err);
    //Now let's create a CI server.  This is idempotent so we should be able to do it on every check
    var requestUrl = `${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers`,
      postBody = {
        instance_id: "0",
        name: "Concourse_test_sam",
        url: "http://192.168.1.100:3000",
        server_type: "Concourse server"
      },
      requestOptions = {
        url: requestUrl,
        method: "POST",
        json: {"data":[postBody]}//,
        // headers: {
        // "HPSSO-HEADER-CSRF": 'figure out how to generate CSFF, if needed'
        // }
      };

    request(requestOptions, (err, response) => {
      if (err || response.statusCode > 200) {
        console.error('nope CI server failed');
        console.error(response.body);
        console.error(response);
        console.error(response.statusCode);
        return done(err || response.body)
      }
      console.error('looks like weve created a CI server');
      console.error(response);
      return done(err);
    });
  });

};

NGALMClient.prototype.run = function (source, params) {
  var self = this;
  if (source.fail_on_error === undefined) {
    source.fail_on_error = true;
  }

  self.failOnError = source.fail_on_error;
  self.validInput = true;

  self.checkProperties(source, this.sourceProperties);
  self.checkProperties(params, this.paramProperties);

  if (!self.validInput) {
    console.error("Please provide valid input and try again");
    return process.exit(1);
  }
  self.sendMessage(source, params, (error, result) => {
    if (error) {
      console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
      if (self.failOnError) {
        process.exit(1);
      }
    }
    // Concourse expects this output from stdout, do not use console.dir
    console.log(JSON.stringify({
      version: {
        ref: "none"
      }
    }));
    process.exit(0);
  });
}

// NGALMClient.prototype.connect = function (source, params) {
//   var self = this;
//   if (source.fail_on_error === undefined) {
//     source.fail_on_error = true;
//   }

//   self.failOnError = source.fail_on_error;
//   self.validInput = true;

//   self.checkProperties(source, this.sourceProperties);
//   self.checkProperties(params, this.paramProperties);

//   if (!self.validInput) {
//     console.error("Please provide valid input and try again");
//     return process.exit(1);
//   }

//   self.connectALM(source, params, (error, result) => {
//     if (error) {
//       console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
//       console.error(error);
//       if (self.failOnError) {
//         process.exit(1);
//       }
//     }
//   });
//   self.pipelineVersion(source, params, (error, result) => {
//   if (error) {
//     console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
//     console.error(error);
//     if (self.failOnError) {
//       process.exit(1);
//     }
//   }
//   // Concourse expects this output from stdout, do not use console.dir
//   console.log('this should work-printing out result');
//   console.log(result);
//   console.log(JSON.stringify({
//     version: {
//       ref: "test"
//     }
//   }));
//   process.exit(0);
// });
// };

module.exports = NGALMClient;<|endoftext|>


<commit_before>const yargs = require('yargs');
const execa = require('execa');
const fs = require('fs-extra');
const path = require('path');

let argv = yargs
.usage('$0 [-r|--release-tag] [-s|--semver-keyword]')
.command({
  command: '*',
  builder: (yargs) => {
      return yargs.option('r', {
        alias: 'release-tag',
        describe: 'the npm release tag',
        default: 'latest'
      }).option('s', {
        alias: 'semver-keyword',
        describe: 'the semver keyword',
        default: 'patch'
      })
    },
    handler: argv => {
      console.log(argv)

      const releaseTag = argv.releaseTag;
      const semverKeyword = releaseTag !== 'latest' ?
        argv.semverKeyword == 'patch' ? 'prerelease' : argv.semverKeyword
        : argv.semverKeyword;

      const lernaCmd = releaseTag == 'latest' ?
        `lerna version ${semverKeyword} --force-publish --no-push` :
        `lerna version ${semverKeyword} --preid ${releaseTag} --force-publish --no-push`;
      execa(lernaCmd, {shell: true, stdio: 'inherit' }).then(async ({exitCode})=>{
        if (exitCode===0) {
          const latestTagId = (await execa('git rev-list --tags --max-count=1', {shell: true})).stdout;
          const latestTag = (await execa(`git describe --tags ${latestTagId}`, {shell: true})).stdout;
          console.log(`deleting tag ${latestTag}`);
          await execa(`git tag -d ${latestTag}`, {shell: true, stdio: 'inherit' });
          console.log(`soft resetting head one rev`);
          await execa(`git reset --soft HEAD~1`, {shell: true, stdio: 'inherit' });
          console.log(`running pre-publish-all`);
          await execa(`yarn pre-publish-all`, {shell: true, stdio: 'inherit' });
          console.log(`comitting pre-publish-all changes`);
          await execa(`git commit -am "published ${latestTag}"`, {shell: true, stdio: 'inherit' });
          console.log(`retagging release`);
          await execa(`git tag -am "${latestTag}" ${latestTag}`, {shell: true, stdio: 'inherit' });
          console.log(`pushing to origin`);
          await execa(`git push origin`, {shell: true, stdio: 'inherit' });
          console.log(`pushing tags to origin`);
          await execa(`git push --tags origin`, {shell: true, stdio: 'inherit' });
          console.log(`done`);
        }
      });
    }
  })
  .help()
  .argv
<commit_msg>dev-infra: use  --no-commit-hooks<commit_after>const yargs = require('yargs');
const execa = require('execa');
const fs = require('fs-extra');
const path = require('path');

let argv = yargs
.usage('$0 [-r|--release-tag] [-s|--semver-keyword]')
.command({
  command: '*',
  builder: (yargs) => {
      return yargs.option('r', {
        alias: 'release-tag',
        describe: 'the npm release tag',
        default: 'latest'
      }).option('s', {
        alias: 'semver-keyword',
        describe: 'the semver keyword',
        default: 'patch'
      })
    },
    handler: argv => {
      console.log(argv)

      const releaseTag = argv.releaseTag;
      const semverKeyword = releaseTag !== 'latest' ?
        argv.semverKeyword == 'patch' ? 'prerelease' : argv.semverKeyword
        : argv.semverKeyword;

      const lernaCmd = releaseTag == 'latest' ?
        `lerna version ${semverKeyword} --force-publish --no-push --no-commit-hooks` :
        `lerna version ${semverKeyword} --preid ${releaseTag} --force-publish --no-push --no-commit-hooks`;
      execa(lernaCmd, {shell: true, stdio: 'inherit' }).then(async ({exitCode})=>{
        if (exitCode===0) {
          const latestTagId = (await execa('git rev-list --tags --max-count=1', {shell: true})).stdout;
          const latestTag = (await execa(`git describe --tags ${latestTagId}`, {shell: true})).stdout;
          console.log(`deleting tag ${latestTag}`);
          await execa(`git tag -d ${latestTag}`, {shell: true, stdio: 'inherit' });
          console.log(`soft resetting head one rev`);
          await execa(`git reset --soft HEAD~1`, {shell: true, stdio: 'inherit' });
          console.log(`running pre-publish-all`);
          await execa(`yarn pre-publish-all`, {shell: true, stdio: 'inherit' });
          console.log(`comitting pre-publish-all changes`);
          await execa(`git commit -am "published ${latestTag}"`, {shell: true, stdio: 'inherit' });
          console.log(`retagging release`);
          await execa(`git tag -am "${latestTag}" ${latestTag}`, {shell: true, stdio: 'inherit' });
          console.log(`pushing to origin`);
          await execa(`git push origin`, {shell: true, stdio: 'inherit' });
          console.log(`pushing tags to origin`);
          await execa(`git push --tags origin`, {shell: true, stdio: 'inherit' });
          console.log(`done`);
        }
      });
    }
  })
  .help()
  .argv
<|endoftext|>


<commit_before>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

'use strict';

/**
 * This script prepares a release version of react-native and may publish to NPM.
 * It is supposed to run in CI environment, not on a developer's machine.
 *
 * For a dry run (commitly), this script will:
 *  * Version the commitly of the form `1000.0.0-<commitSha>`
 *  * Create Android artifacts
 *  * It will not publish to npm
 *
 * For a nightly run, this script will:
 *  * Version the nightly release of the form `0.0.0-<dateIdentifier>-<commitSha>`
 *  * Create Android artifacts
 *  * Publish to npm using `nightly` tag
 *
 * For a release run, this script will:
 *  * Version the release by the tag version that triggered CI
 *  * Create Android artifacts
 *  * Publish to npm
 *     * using `latest` tag if commit is currently tagged `latest`
 *     * or otherwise `{major}.{minor}-stable`
 */

const {exec, echo, exit, test, env} = require('shelljs');
const {parseVersion, isTaggedLatest} = require('./version-utils');
const fs = require('fs');
const os = require('os');
const path = require('path');
const yargs = require('yargs');

const buildTag = process.env.CIRCLE_TAG;
const otp = process.env.NPM_CONFIG_OTP;

const argv = yargs
  .option('n', {
    alias: 'nightly',
    type: 'boolean',
    default: false,
  })
  .option('d', {
    alias: 'dry-run',
    type: 'boolean',
    default: false,
  })
  .option('h', {
    alias: 'include-hermes',
    type: 'boolean',
    default: false,
  }).argv;
const nightlyBuild = argv.nightly;
const dryRunBuild = argv.dryRun;
const includeHermes = argv.includeHermes;
const isCommitly = nightlyBuild || dryRunBuild;

if (includeHermes) {
  const HERMES_INSTALL_LOCATION = 'sdks';
  const HERMES_SOURCE_DEST_PATH = `${HERMES_INSTALL_LOCATION}/hermes`;

  let hermesReleaseTag;
  let hermesReleaseURI;
  if (isCommitly) {
    // use latest commit / tarball
    hermesReleaseURI = 'https://github.com/facebook/hermes/tarball/main';
  } else {
    // use one configured in disk
    fs.readFile(
      `${HERMES_INSTALL_LOCATION}/.hermesversion`,
      {
        encoding: 'utf8',
        flag: 'r',
      },
      function (err, data) {
        if (err) {
          echo('Failed to read current Hermes release tag.');
          // TODO: We'll need to make sure every release going forward has one of these.
          exit(1);
        } else {
          hermesReleaseTag = data.trim();
          hermesReleaseURI = `https://github.com/facebook/hermes/archive/refs/tags/${hermesReleaseTag}.tar.gz`;
        }
      },
    );
  }

  const tmpDownloadDir = fs.mkdtempSync(
    path.join(os.tmpdir(), 'hermes-tarball'),
  );
  const tmpExtractDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes'));

  const hermesInstallScript = `
    mkdir -p ${HERMES_SOURCE_DEST_PATH} && \
    wget ${hermesReleaseURI} -O ${tmpDownloadDir}/hermes.tar.gz && \
    tar -xzf ${tmpDownloadDir}/hermes.tar.gz -C ${tmpExtractDir} && \
    HERMES_SOURCE_EXTRACT_PATH=$(ls -d ${tmpExtractDir}/*) && \
    mv $HERMES_SOURCE_EXTRACT_PATH ${HERMES_SOURCE_DEST_PATH}
  `;

  if (fs.existsSync(`${HERMES_SOURCE_DEST_PATH}`)) {
    if (exec(`rm -rf ./${HERMES_SOURCE_DEST_PATH}`).code) {
      echo('Failed to clean up previous Hermes installation.');
      exit(1);
    }
  }
  if (exec(hermesInstallScript).code) {
    echo('Failed to include Hermes in release.');
    exit(1);
  }
}

// 34c034298dc9cad5a4553964a5a324450fda0385
const currentCommit = exec('git rev-parse HEAD', {
  silent: true,
}).stdout.trim();
const shortCommit = currentCommit.slice(0, 9);

const rawVersion =
  // 0.0.0 triggers issues with cocoapods for codegen when building template project.
  dryRunBuild
    ? '1000.0.0'
    : // For nightly we continue to use 0.0.0 for clarity for npm
    nightlyBuild
    ? '0.0.0'
    : // For pre-release and stable releases, we use the git tag of the version we're releasing (set in bump-oss-version)
      buildTag;

let version,
  major,
  minor,
  prerelease = null;
try {
  ({version, major, minor, prerelease} = parseVersion(rawVersion));
} catch (e) {
  echo(e.message);
  exit(1);
}

let releaseVersion;
if (dryRunBuild) {
  releaseVersion = `${version}-${shortCommit}`;
} else if (nightlyBuild) {
  // 2021-09-28T05:38:40.669Z -> 20210928-0538
  const dateIdentifier = new Date()
    .toISOString()
    .slice(0, -8)
    .replace(/[-:]/g, '')
    .replace(/[T]/g, '-');
  releaseVersion = `${version}-${dateIdentifier}-${shortCommit}`;
} else {
  releaseVersion = version;
}

// Bump version number in various files (package.json, gradle.properties etc)
// For stable, pre-release releases, we rely on CircleCI job `prepare_package_for_release` to handle this
if (isCommitly) {
  if (
    exec(`node scripts/set-rn-version.js --to-version ${releaseVersion}`).code
  ) {
    echo(`Failed to set version number to ${releaseVersion}`);
    exit(1);
  }
}

// -------- Generating Android Artifacts with JavaDoc
if (exec('./gradlew :ReactAndroid:installArchives').code) {
  echo('Could not generate artifacts');
  exit(1);
}

// -------- Generating the Hermes Engine Artifacts
env.REACT_NATIVE_HERMES_SKIP_PREFAB = true;
if (exec('./gradlew :ReactAndroid:hermes-engine:installArchives').code) {
  echo('Could not generate artifacts');
  exit(1);
}

// undo uncommenting javadoc setting
exec('git checkout ReactAndroid/gradle.properties');

echo('Generated artifacts for Maven');

let artifacts = [
  '.module',
  '.pom',
  '-debug.aar',
  '-release.aar',
  '-debug-sources.jar',
  '-release-sources.jar',
  '-debug-javadoc.jar',
  '-release-javadoc.jar',
].map(suffix => {
  return `react-native-${releaseVersion}${suffix}`;
});

artifacts.forEach(name => {
  if (
    !test(
      '-e',
      `./android/com/facebook/react/react-native/${releaseVersion}/${name}`,
    )
  ) {
    echo(`Failing as expected file: ${name} was not correctly generated.`);
    exit(1);
  }
});

if (dryRunBuild) {
  echo('Skipping `npm publish` because --dry-run is set.');
  exit(0);
}

// Running to see if this commit has been git tagged as `latest`
const isLatest = isTaggedLatest(currentCommit);

const releaseBranch = `${major}.${minor}-stable`;

// Set the right tag for nightly and prerelease builds
// If a release is not git-tagged as `latest` we use `releaseBranch` to prevent
// npm from overriding the current `latest` version tag, which it will do if no tag is set.
const tagFlag = nightlyBuild
  ? '--tag nightly'
  : prerelease != null
  ? '--tag next'
  : isLatest
  ? '--tag latest'
  : `--tag ${releaseBranch}`;

// use otp from envvars if available
const otpFlag = otp ? `--otp ${otp}` : '';

if (exec(`npm publish ${tagFlag} ${otpFlag}`).code) {
  echo('Failed to publish package to npm');
  exit(1);
} else {
  echo(`Published to npm ${releaseVersion}`);
  exit(0);
}
<commit_msg>Do not fail if -javadoc.jar are missing in the final NPM package (#33869)<commit_after>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

'use strict';

/**
 * This script prepares a release version of react-native and may publish to NPM.
 * It is supposed to run in CI environment, not on a developer's machine.
 *
 * For a dry run (commitly), this script will:
 *  * Version the commitly of the form `1000.0.0-<commitSha>`
 *  * Create Android artifacts
 *  * It will not publish to npm
 *
 * For a nightly run, this script will:
 *  * Version the nightly release of the form `0.0.0-<dateIdentifier>-<commitSha>`
 *  * Create Android artifacts
 *  * Publish to npm using `nightly` tag
 *
 * For a release run, this script will:
 *  * Version the release by the tag version that triggered CI
 *  * Create Android artifacts
 *  * Publish to npm
 *     * using `latest` tag if commit is currently tagged `latest`
 *     * or otherwise `{major}.{minor}-stable`
 */

const {exec, echo, exit, test, env} = require('shelljs');
const {parseVersion, isTaggedLatest} = require('./version-utils');
const fs = require('fs');
const os = require('os');
const path = require('path');
const yargs = require('yargs');

const buildTag = process.env.CIRCLE_TAG;
const otp = process.env.NPM_CONFIG_OTP;

const argv = yargs
  .option('n', {
    alias: 'nightly',
    type: 'boolean',
    default: false,
  })
  .option('d', {
    alias: 'dry-run',
    type: 'boolean',
    default: false,
  })
  .option('h', {
    alias: 'include-hermes',
    type: 'boolean',
    default: false,
  }).argv;
const nightlyBuild = argv.nightly;
const dryRunBuild = argv.dryRun;
const includeHermes = argv.includeHermes;
const isCommitly = nightlyBuild || dryRunBuild;

if (includeHermes) {
  const HERMES_INSTALL_LOCATION = 'sdks';
  const HERMES_SOURCE_DEST_PATH = `${HERMES_INSTALL_LOCATION}/hermes`;

  let hermesReleaseTag;
  let hermesReleaseURI;
  if (isCommitly) {
    // use latest commit / tarball
    hermesReleaseURI = 'https://github.com/facebook/hermes/tarball/main';
  } else {
    // use one configured in disk
    fs.readFile(
      `${HERMES_INSTALL_LOCATION}/.hermesversion`,
      {
        encoding: 'utf8',
        flag: 'r',
      },
      function (err, data) {
        if (err) {
          echo('Failed to read current Hermes release tag.');
          // TODO: We'll need to make sure every release going forward has one of these.
          exit(1);
        } else {
          hermesReleaseTag = data.trim();
          hermesReleaseURI = `https://github.com/facebook/hermes/archive/refs/tags/${hermesReleaseTag}.tar.gz`;
        }
      },
    );
  }

  const tmpDownloadDir = fs.mkdtempSync(
    path.join(os.tmpdir(), 'hermes-tarball'),
  );
  const tmpExtractDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes'));

  const hermesInstallScript = `
    mkdir -p ${HERMES_SOURCE_DEST_PATH} && \
    wget ${hermesReleaseURI} -O ${tmpDownloadDir}/hermes.tar.gz && \
    tar -xzf ${tmpDownloadDir}/hermes.tar.gz -C ${tmpExtractDir} && \
    HERMES_SOURCE_EXTRACT_PATH=$(ls -d ${tmpExtractDir}/*) && \
    mv $HERMES_SOURCE_EXTRACT_PATH ${HERMES_SOURCE_DEST_PATH}
  `;

  if (fs.existsSync(`${HERMES_SOURCE_DEST_PATH}`)) {
    if (exec(`rm -rf ./${HERMES_SOURCE_DEST_PATH}`).code) {
      echo('Failed to clean up previous Hermes installation.');
      exit(1);
    }
  }
  if (exec(hermesInstallScript).code) {
    echo('Failed to include Hermes in release.');
    exit(1);
  }
}

// 34c034298dc9cad5a4553964a5a324450fda0385
const currentCommit = exec('git rev-parse HEAD', {
  silent: true,
}).stdout.trim();
const shortCommit = currentCommit.slice(0, 9);

const rawVersion =
  // 0.0.0 triggers issues with cocoapods for codegen when building template project.
  dryRunBuild
    ? '1000.0.0'
    : // For nightly we continue to use 0.0.0 for clarity for npm
    nightlyBuild
    ? '0.0.0'
    : // For pre-release and stable releases, we use the git tag of the version we're releasing (set in bump-oss-version)
      buildTag;

let version,
  major,
  minor,
  prerelease = null;
try {
  ({version, major, minor, prerelease} = parseVersion(rawVersion));
} catch (e) {
  echo(e.message);
  exit(1);
}

let releaseVersion;
if (dryRunBuild) {
  releaseVersion = `${version}-${shortCommit}`;
} else if (nightlyBuild) {
  // 2021-09-28T05:38:40.669Z -> 20210928-0538
  const dateIdentifier = new Date()
    .toISOString()
    .slice(0, -8)
    .replace(/[-:]/g, '')
    .replace(/[T]/g, '-');
  releaseVersion = `${version}-${dateIdentifier}-${shortCommit}`;
} else {
  releaseVersion = version;
}

// Bump version number in various files (package.json, gradle.properties etc)
// For stable, pre-release releases, we rely on CircleCI job `prepare_package_for_release` to handle this
if (isCommitly) {
  if (
    exec(`node scripts/set-rn-version.js --to-version ${releaseVersion}`).code
  ) {
    echo(`Failed to set version number to ${releaseVersion}`);
    exit(1);
  }
}

// -------- Generating Android Artifacts
if (exec('./gradlew :ReactAndroid:installArchives').code) {
  echo('Could not generate artifacts');
  exit(1);
}

// -------- Generating the Hermes Engine Artifacts
env.REACT_NATIVE_HERMES_SKIP_PREFAB = true;
if (exec('./gradlew :ReactAndroid:hermes-engine:installArchives').code) {
  echo('Could not generate artifacts');
  exit(1);
}

// undo uncommenting javadoc setting
exec('git checkout ReactAndroid/gradle.properties');

echo('Generated artifacts for Maven');

let artifacts = [
  '.module',
  '.pom',
  '-debug.aar',
  '-release.aar',
  '-debug-sources.jar',
  '-release-sources.jar',
].map(suffix => {
  return `react-native-${releaseVersion}${suffix}`;
});

artifacts.forEach(name => {
  if (
    !test(
      '-e',
      `./android/com/facebook/react/react-native/${releaseVersion}/${name}`,
    )
  ) {
    echo(`Failing as expected file: ${name} was not correctly generated.`);
    exit(1);
  }
});

if (dryRunBuild) {
  echo('Skipping `npm publish` because --dry-run is set.');
  exit(0);
}

// Running to see if this commit has been git tagged as `latest`
const isLatest = isTaggedLatest(currentCommit);

const releaseBranch = `${major}.${minor}-stable`;

// Set the right tag for nightly and prerelease builds
// If a release is not git-tagged as `latest` we use `releaseBranch` to prevent
// npm from overriding the current `latest` version tag, which it will do if no tag is set.
const tagFlag = nightlyBuild
  ? '--tag nightly'
  : prerelease != null
  ? '--tag next'
  : isLatest
  ? '--tag latest'
  : `--tag ${releaseBranch}`;

// use otp from envvars if available
const otpFlag = otp ? `--otp ${otp}` : '';

if (exec(`npm publish ${tagFlag} ${otpFlag}`).code) {
  echo('Failed to publish package to npm');
  exit(1);
} else {
  echo(`Published to npm ${releaseVersion}`);
  exit(0);
}
<|endoftext|>


<commit_before>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define(['knockout', 'jquery', 'd3', 'ovs/generic'], function(ko, $, d3, generic) {
    "use strict";
    ko.bindingHandlers.status = {
        init: function(element) {
            var id = 'id_' + generic.getTimestamp() + '_' + Math.random().toString().substr(2, 10), svg;
            $(element).html('

');
            $($(element).children()[0]).attr('id', id);
            svg = d3.select('#' + id).append('svg')
                .attr('class', 'svg')
                .attr('width', 14)
                .attr('height', 14);
            svg.append('circle')
                .attr('class', 'circle')
                .attr('cx', 6)
                .attr('cy', 8)
                .attr('r', 6)
                .style('fill', 'gray');
        },
        update: function(element, valueAccessor) {
            var value, colorOption, color, id;
            value = valueAccessor();
            for (colorOption in value.colors) {
                if (value.colors.hasOwnProperty(colorOption) && value.colors[colorOption]) {
                    color = colorOption;
                }
            }
            if (color === undefined) {
                color = value.defaultColor;
            }
            id = $($(element).children()[0]).attr('id');
            d3.select('#' + id).select('.circle')
                .style('fill', color);
        }
    };
    ko.bindingHandlers.gauge = {
        init: function(element) {
            var id = 'id_' + generic.getTimestamp() + '_' + Math.random().toString().substr(2, 10),
                svg, arc;
            $(element).html('

');
            $($(element).children()[0]).attr('id', id);
            svg = d3.select('#' + id).append('svg')
                .attr('class', 'svg')
                .style('display', 'block')
                .style('margin', 'auto')
                .attr('width', 300)
                .attr('height', 200);
            arc = d3.svg.arc()
                .innerRadius(80)
                .outerRadius(150)
                .startAngle(generic.deg2rad(-90))
                .endAngle(generic.deg2rad(90));
            svg.append('path')
                .attr('class', 'background-arc')
                .attr('d', arc)
                .style('fill', '#edebeb')
                .attr('transform', 'translate(150, 160)');
            svg.append('path')
                .attr('class', 'foreground-arc');
            svg.append('text')
                .text('0.00 ' + $.t('ovs:generic.iops'))
                .attr('class', 'secondary-text')
                .attr('text-anchor', 'middle')
                .style('font-weight', 'bold')
                .style('font-size', 25)
                .style('fill', 'grey')
                .attr('transform', 'translate(150, 195)');
            svg.append('text')
                .text('0.00 %')
                .attr('class', 'primary-text')
                .attr('text-anchor', 'middle')
                .style('font-weight', 'bold')
                .style('font-size', 25)
                .attr('transform', 'translate(150, 150)');
        },
        update: function(element, valueAccessor) {
            var value, id, arc, percentage, color;
            value = valueAccessor();
            if (value.primary.initialized()) {
                percentage = value.primary.raw();
                id = $($(element).children()[0]).attr('id');
                color = d3.scale.linear().domain([0, 50, 100]).range(['red', 'orange', 'green']);
                arc = d3.svg.arc()
                    .innerRadius(80)
                    .outerRadius(150)
                    .startAngle(generic.deg2rad(-90))
                    .endAngle(generic.deg2rad((180 / 100 * percentage) - 90));
                d3.select('#' + id).select('.foreground-arc')
                    .attr('d', arc)
                    .style('fill', color(percentage))
                    .attr('transform', 'translate(150, 160)');
                d3.select('#' + id).select('.primary-text')
                    .text(value.primary());
                if (value.secondary.initialized()) {
                    d3.select('#' + id).select('.secondary-text')
                        .text(value.secondary() + ' ' + $.t('ovs:generic.iops'));
                }
            }
        }
    };
    ko.bindingHandlers.popover = {
        init: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).popover({
                html: true,
                placement: 'auto',
                trigger: 'click',
                title: $.t(value.title),
                content: $.t(value.content)
            });
        }
    };
    ko.bindingHandlers.icon = {
        init: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).html($.t(value));
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).html($.t(value));
        }
    };
    ko.bindingHandlers.shortText = {
        init: function(element, valueAccessor, allBindings) {
            var value = valueAccessor(),
                maxLength = allBindings.get('maxLength');
            if (maxLength !== undefined) {
                if (value.length > maxLength - 3) {
                    value = value.substr(0, maxLength - 3) + '...';
                }
            }
            $(element).text(value);
        },
        update: function(element, valueAccessor, allBindings) {
            var value = valueAccessor(),
                maxLength = allBindings.get('maxLength');
            if (maxLength !== undefined) {
                if (value.length > maxLength - 3) {
                    value = value.substr(0, maxLength - 3) + '…';
                }
            }
            $(element).html(value);
        }
    }
});
<commit_msg>OVS-93 - Forgot to change ... to ... (…) +review OPVS-2<commit_after>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define(['knockout', 'jquery', 'd3', 'ovs/generic'], function(ko, $, d3, generic) {
    "use strict";
    ko.bindingHandlers.status = {
        init: function(element) {
            var id = 'id_' + generic.getTimestamp() + '_' + Math.random().toString().substr(2, 10), svg;
            $(element).html('

');
            $($(element).children()[0]).attr('id', id);
            svg = d3.select('#' + id).append('svg')
                .attr('class', 'svg')
                .attr('width', 14)
                .attr('height', 14);
            svg.append('circle')
                .attr('class', 'circle')
                .attr('cx', 6)
                .attr('cy', 8)
                .attr('r', 6)
                .style('fill', 'gray');
        },
        update: function(element, valueAccessor) {
            var value, colorOption, color, id;
            value = valueAccessor();
            for (colorOption in value.colors) {
                if (value.colors.hasOwnProperty(colorOption) && value.colors[colorOption]) {
                    color = colorOption;
                }
            }
            if (color === undefined) {
                color = value.defaultColor;
            }
            id = $($(element).children()[0]).attr('id');
            d3.select('#' + id).select('.circle')
                .style('fill', color);
        }
    };
    ko.bindingHandlers.gauge = {
        init: function(element) {
            var id = 'id_' + generic.getTimestamp() + '_' + Math.random().toString().substr(2, 10),
                svg, arc;
            $(element).html('

');
            $($(element).children()[0]).attr('id', id);
            svg = d3.select('#' + id).append('svg')
                .attr('class', 'svg')
                .style('display', 'block')
                .style('margin', 'auto')
                .attr('width', 300)
                .attr('height', 200);
            arc = d3.svg.arc()
                .innerRadius(80)
                .outerRadius(150)
                .startAngle(generic.deg2rad(-90))
                .endAngle(generic.deg2rad(90));
            svg.append('path')
                .attr('class', 'background-arc')
                .attr('d', arc)
                .style('fill', '#edebeb')
                .attr('transform', 'translate(150, 160)');
            svg.append('path')
                .attr('class', 'foreground-arc');
            svg.append('text')
                .text('0.00 ' + $.t('ovs:generic.iops'))
                .attr('class', 'secondary-text')
                .attr('text-anchor', 'middle')
                .style('font-weight', 'bold')
                .style('font-size', 25)
                .style('fill', 'grey')
                .attr('transform', 'translate(150, 195)');
            svg.append('text')
                .text('0.00 %')
                .attr('class', 'primary-text')
                .attr('text-anchor', 'middle')
                .style('font-weight', 'bold')
                .style('font-size', 25)
                .attr('transform', 'translate(150, 150)');
        },
        update: function(element, valueAccessor) {
            var value, id, arc, percentage, color;
            value = valueAccessor();
            if (value.primary.initialized()) {
                percentage = value.primary.raw();
                id = $($(element).children()[0]).attr('id');
                color = d3.scale.linear().domain([0, 50, 100]).range(['red', 'orange', 'green']);
                arc = d3.svg.arc()
                    .innerRadius(80)
                    .outerRadius(150)
                    .startAngle(generic.deg2rad(-90))
                    .endAngle(generic.deg2rad((180 / 100 * percentage) - 90));
                d3.select('#' + id).select('.foreground-arc')
                    .attr('d', arc)
                    .style('fill', color(percentage))
                    .attr('transform', 'translate(150, 160)');
                d3.select('#' + id).select('.primary-text')
                    .text(value.primary());
                if (value.secondary.initialized()) {
                    d3.select('#' + id).select('.secondary-text')
                        .text(value.secondary() + ' ' + $.t('ovs:generic.iops'));
                }
            }
        }
    };
    ko.bindingHandlers.popover = {
        init: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).popover({
                html: true,
                placement: 'auto',
                trigger: 'click',
                title: $.t(value.title),
                content: $.t(value.content)
            });
        }
    };
    ko.bindingHandlers.icon = {
        init: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).html($.t(value));
        },
        update: function(element, valueAccessor) {
            var value = valueAccessor();
            $(element).html($.t(value));
        }
    };
    ko.bindingHandlers.shortText = {
        init: function(element, valueAccessor, allBindings) {
            var value = valueAccessor(),
                maxLength = allBindings.get('maxLength');
            if (maxLength !== undefined) {
                if (value.length > maxLength - 3) {
                    value = value.substr(0, maxLength - 3) + '…';
                }
            }
            $(element).text(value);
        },
        update: function(element, valueAccessor, allBindings) {
            var value = valueAccessor(),
                maxLength = allBindings.get('maxLength');
            if (maxLength !== undefined) {
                if (value.length > maxLength - 3) {
                    value = value.substr(0, maxLength - 3) + '…';
                }
            }
            $(element).html(value);
        }
    }
});
<|endoftext|>


<commit_before>var core = require('./index.js');

function createConnection (opts) {
  var coreConnection = core.createConnection(opts);
  var Promise = opts.Promise || global.Promise;
  if (!Promise) {
    throw new Error('no Promise implementation available.' +
      'Use promise-enabled node version or pass userland Promise' +
      ' implementation as parameter, for example: { Promise: require(\'bluebird\') }');
  }
  return new Promise(function (resolve, reject) {
    coreConnection.once('connect', function (connectParams) {
      resolve(new PromiseConnection(coreConnection, Promise));
    });
    coreConnection.once('error', reject);
  });
}

function PromiseConnection (connection, promiseImpl) {
  this.connection = connection;
  this.Promise = promiseImpl;
}

PromiseConnection.prototype.release = function () {
  this.connection.release();
};

function makeDoneCb (resolve, reject) {
  return function (err, rows, fields) {
    if (err) {
      reject(err);
    } else {
      resolve([rows, fields]);
    }
  };
}

PromiseConnection.prototype.query = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.query(query, params, done);
    } else {
      c.query(query, done);
    }
  });
};

PromiseConnection.prototype.execute = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.execute(query, params, done);
    } else {
      c.execute(query, done);
    }
  });
};

PromiseConnection.prototype.end = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.end(function () {
      resolve();
    });
  });
};

PromiseConnection.prototype.beginTransaction = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.beginTransaction(done);
  });
};

PromiseConnection.prototype.commit = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.commit(done);
  });
};

PromiseConnection.prototype.rollback = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.rollback(done);
  });
};

PromiseConnection.prototype.ping = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.ping(resolve);
  });
};

PromiseConnection.prototype.connect = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.connect(function (error, param) {
      if (error) {
        reject(error);
      } else {
        resolve(param);
      }
    });
  });
};

PromiseConnection.prototype.prepare = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.prepare(function (error, statement) {
      if (error) {
        reject(error);
      } else {
        resolve(statement);
      }
    });
  });
};

// note: the callback of "changeUser" is not called on success
// hence there is no possibility to call "resolve"

// patching PromiseConnection
// create facade functions for prototype functions on "Connection" that are not yet
// implemented with PromiseConnection

// proxy synchronous functions only
(function (functionsToWrap) {

  for (var i = 0; functionsToWrap && i < functionsToWrap.length; i++) {
    var func = functionsToWrap[i];

    if (
      typeof core.Connection.prototype[func] === 'function'
      && PromiseConnection.prototype[func] === undefined
    ) {
      PromiseConnection.prototype[func] = (function factory (funcName) {
        return function () {
          return core.Connection
            .prototype[funcName].apply(this.connection, arguments);
        };
      })(func);
    }
  }

})([
// synchronous functions
  'close',
  'createBinlogStream',
  'destroy',
  'escape',
  'escapeId',
  'format',
  'pause',
  'pipe',
  'resume',
  'unprepare'
]);

function createPool (opts) {
  var corePool = core.createPool(opts);
  var Promise = opts.Promise || global.Promise || require('bluebird');

  var promisePool = {
    getConnection: function () {
      return new Promise(function (resolve, reject) {
        corePool.getConnection(function (err, coreConnection) {
          if (err) {
            reject(err);
          } else {
            resolve(new PromiseConnection(coreConnection, Promise));
          }
        });
      });
    },

    query: function (sql, args) {
      return new Promise(function (resolve, reject) {
        var done = makeDoneCb(resolve, reject);
        if (args) {
          corePool.query(sql, args, done);
        } else {
          corePool.query(sql, done);
        }
      });
    },

    execute: function (sql, values) {
      return new Promise(function (resolve, reject) {
        corePool.execute(sql, values, makeDoneCb(resolve, reject));
      });
    },

    end: function () {
      return new Promise(function (resolve, reject) {
        corePool.end(function (err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
  };

  return promisePool;
}

module.exports.createConnection = createConnection;
module.exports.createPool = createPool;
<commit_msg>drop es6-promise and return better error message for users<commit_after>var core = require('./index.js');

function createConnection (opts) {
  var coreConnection = core.createConnection(opts);
  var Promise = opts.Promise || global.Promise;
  if (!Promise) {
    throw new Error('no Promise implementation available.' +
      'Use promise-enabled node version or pass userland Promise' +
      ' implementation as parameter, for example: { Promise: require(\'bluebird\') }');
  }
  return new Promise(function (resolve, reject) {
    coreConnection.once('connect', function (connectParams) {
      resolve(new PromiseConnection(coreConnection, Promise));
    });
    coreConnection.once('error', reject);
  });
}

function PromiseConnection (connection, promiseImpl) {
  this.connection = connection;
  this.Promise = promiseImpl;
}

PromiseConnection.prototype.release = function () {
  this.connection.release();
};

function makeDoneCb (resolve, reject) {
  return function (err, rows, fields) {
    if (err) {
      reject(err);
    } else {
      resolve([rows, fields]);
    }
  };
}

PromiseConnection.prototype.query = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.query(query, params, done);
    } else {
      c.query(query, done);
    }
  });
};

PromiseConnection.prototype.execute = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.execute(query, params, done);
    } else {
      c.execute(query, done);
    }
  });
};

PromiseConnection.prototype.end = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.end(function () {
      resolve();
    });
  });
};

PromiseConnection.prototype.beginTransaction = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.beginTransaction(done);
  });
};

PromiseConnection.prototype.commit = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.commit(done);
  });
};

PromiseConnection.prototype.rollback = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.rollback(done);
  });
};

PromiseConnection.prototype.ping = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.ping(resolve);
  });
};

PromiseConnection.prototype.connect = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.connect(function (error, param) {
      if (error) {
        reject(error);
      } else {
        resolve(param);
      }
    });
  });
};

PromiseConnection.prototype.prepare = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.prepare(function (error, statement) {
      if (error) {
        reject(error);
      } else {
        resolve(statement);
      }
    });
  });
};

// note: the callback of "changeUser" is not called on success
// hence there is no possibility to call "resolve"

// patching PromiseConnection
// create facade functions for prototype functions on "Connection" that are not yet
// implemented with PromiseConnection

// proxy synchronous functions only
(function (functionsToWrap) {

  for (var i = 0; functionsToWrap && i < functionsToWrap.length; i++) {
    var func = functionsToWrap[i];

    if (
      typeof core.Connection.prototype[func] === 'function'
      && PromiseConnection.prototype[func] === undefined
    ) {
      PromiseConnection.prototype[func] = (function factory (funcName) {
        return function () {
          return core.Connection
            .prototype[funcName].apply(this.connection, arguments);
        };
      })(func);
    }
  }

})([
// synchronous functions
  'close',
  'createBinlogStream',
  'destroy',
  'escape',
  'escapeId',
  'format',
  'pause',
  'pipe',
  'resume',
  'unprepare'
]);

function createPool (opts) {
  var corePool = core.createPool(opts);
  var Promise = opts.Promise || global.Promise;
  if (!Promise) {
    throw new Error('no Promise implementation available.' +
      'Use promise-enabled node version or pass userland Promise' +
      ' implementation as parameter, for example: { Promise: require(\'bluebird\') }');
  }

  var promisePool = {
    getConnection: function () {
      return new Promise(function (resolve, reject) {
        corePool.getConnection(function (err, coreConnection) {
          if (err) {
            reject(err);
          } else {
            resolve(new PromiseConnection(coreConnection, Promise));
          }
        });
      });
    },

    query: function (sql, args) {
      return new Promise(function (resolve, reject) {
        var done = makeDoneCb(resolve, reject);
        if (args) {
          corePool.query(sql, args, done);
        } else {
          corePool.query(sql, done);
        }
      });
    },

    execute: function (sql, values) {
      return new Promise(function (resolve, reject) {
        corePool.execute(sql, values, makeDoneCb(resolve, reject));
      });
    },

    end: function () {
      return new Promise(function (resolve, reject) {
        corePool.end(function (err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
  };

  return promisePool;
}

module.exports.createConnection = createConnection;
module.exports.createPool = createPool;
<|endoftext|>