<commit_before>/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved
 *
 * Author: Brian Broll
 *
 * Code generating interpreter for SnapGME
 */

define(['plugin/PluginConfig',
        'plugin/PluginBase'], function (PluginConfig,
                                       PluginBase){

    var SnapPlugin = function() {
        //Call base class's constructor
        PluginBase.call(this);

        //Code maps:
        //
        //Adding the mapping of node META name to code
        //% sign indicates it will be replaced with either
        //attribute of the given name or ptr tgt of the given name
        this._languages = {};
        this._languages['python'] = { 'bp': '#!/usr/bin/python2\n\n%code',
                                      'map': { 'Add': "%first + %second",
                                               'Subtract': "%first - %second",
                                               'Multiply': "(%first) * (%second)",
                                               'Divide': "(%first)/(%second)",
                                               'Less Than': "(%first) < (%second)",
                                               'Greater Than': "(%first) > (%second)",
                                               'Equals': "(%first) == (%second)",
                                               'Write': "print %text",
                                               'If': "if %cond:\n %true_next",
                                               'Repeat': "while true:\n %true_next",
                                               'Variable': "%name",
                                               'Set': '%var = %value' },
                                      'primitives': {'%var = %value': /[a-zA-Z\d._-]*/ },
                                      'ext': 'py' };

        //Change the languages to be within the map
        this._languages['javascript'] = { 'bp': '#!/usr/bin/node\n\n%code',
                                          'map': { 'Add': "%first + %second",
                                                   'Subtract': "%first - %second",
                                                   'Multiply': "(%first) * (%second)",
                                                   'Divide': "(%first)/(%second)",
                                                   'Less Than': "(%first) < (%second)",
                                                   'Greater Than': "(%first) > (%second)",
                                                   'Equals': "(%first) === (%second)",
                                                   'Write': "console.log(%text);",
                                                   'If': "if (%cond){\n %true_next\n}",
                                                   'Repeat': "while (true){\n %true_next\n}",
                                                   'Variable': "%name",
                                                   'Set': '%var = %value;' },
                                          'primitives': { 'var %var = %value;': /^[a-zA-Z\d._-]*$/ },
                                          'ext': 'js' };
    };

    //basic functions and setting for plugin inheritance
    SnapPlugin.prototype = Object.create(PluginBase.prototype);
    SnapPlugin.prototype.constructor = SnapPlugin;

    SnapPlugin.prototype.getName = function () {
        return "Pegasus Plugin";
    };

    //config options
    SnapPlugin.prototype.getConfigStructure = function () {
        return [
            {
                "name": "python",
                "displayName": "Python",
                "description": 'Generate Python Code',
                "value": false, // this is the 'default config'
                "valueType": "boolean",
                "readOnly": false
            },
            {
                "name": "javascript",
                "displayName": "Javascript",
                "description": 'Generate Javascript Code',
                "value": true, // this is the 'default config'
                "valueType": "boolean",
                "readOnly": false
            }
        ]
    };

    SnapPlugin.prototype._loadStartingNodes = function(callback){
        //we load the children of the active node
        var self = this;
        self._nodeCache = {};

        var load = function(node, fn){
            self.core.loadChildren(node,function(err,children){
                if(err){
                    fn(err)
                } else {
                    var j = children.length,
                        e = null; //error

                    if(j === 0){
                        fn(null);
                    }

                    for(var i=0;i<children.length;i++){
                        self._nodeCache[self.core.getPath(children[i])] = children[i];
                        load(children[i], function(err){
                            e = e || err;
                            if(--j === 0){//callback only on last child
                                fn(e);
                            }
                        });
                    }
                }
            });
        };

        load(self.activeNode, callback);

    };

    SnapPlugin.prototype.getNode = function(nodePath){
        //we check only our node cache
        return this._nodeCache[nodePath];
    };

    SnapPlugin.prototype._isTypeOf = function(node,type){
        //now we make the check based upon path
        if(node === undefined || node === null || type === undefined || type === null){
            return false;
        }

        var self = this;

        if (typeof node === "string"){//if the node is the nodeId
            node = self.getNode(node);
        }

        while(node){
            if(self.core.getPath(node) === self.core.getPath(type)){
                return true;
            }
            node = self.core.getBase(node);
        }
        return false;
    };

    SnapPlugin.prototype.main = function (callback) {
        var self = this;
        self.config = self.getCurrentConfig();

        if(!self._isTypeOf(self.activeNode, self.META['Project'])){
            self._errorMessages(self.activeNode,
                "Current project is an invalid type. Please run the plugin on a project.");
        }

        self._loadStartingNodes(function(err){
            if(err){
                //finishing
                self.result.success = false;
                callback(err,self.result);
            } else {
                //executing the plugin
                self.logger.info("Finished loading children");
                var err = self._runSync();
                if(err){
                    self.result.success = false;
                    callback(err,self.result);
                } else {
                    //Download language files
                    self._saveOutput(self.generatedCode, function(err){
                        if(err){
                            self.result.success = false;
                            callback(err,self.result);
                        } else {
                            if(callback){
                                self.result.success = true;
                                callback(null,self.result);
                            }
                        }
                    });
                }
            }
        });
    };

    SnapPlugin.prototype._runSync = function(){
        var err = null,
            currentNode,
            languages = [];

        this.projectName = this.core.getAttribute(this.activeNode,'name');
        this.generatedCode = {};

        for (var lang in this.config){
            if (this.config.hasOwnProperty(lang) && this.config[lang]){
                this.generatedCode[lang] = "";
                languages.push(lang);
            }
        }

        this.variables = [];

        var currentNode = null,
            nodeIds = this.core.getChildrenPaths(this.activeNode),
            i = nodeIds.length;

        //Find the hat and declare variables
        while(i-- && currentNode === null){
            if(this._isTypeOf(nodeIds[i], this.META["Hat"])
               && !this._isTypeOf(nodeIds[i], this.META["Command"]))
           currentNode = this.getNode(nodeIds[i]);
        }

        //Follow the next pointers and map each object to it's given code
        while(this.core.getPointerPath(currentNode, 'next')){
            currentNode = this.getNode(this.core.getPointerPath(currentNode, 'next'));
            for (var l in this.generatedCode){
                if(this.generatedCode.hasOwnProperty(l)){
                    this.generatedCode[l] += this._generateCode(l, currentNode) + "\n";
                }
            }
        }

        for (var l in this.generatedCode){
            if(this.generatedCode.hasOwnProperty(l)){
                this.generatedCode[l] = this._languages[l].bp.replace("%code", this.generatedCode[l]);
            }
        }

        return err;
    };

    SnapPlugin.prototype._generateCode = function(language, node){
        //Map stuff to code and return the code snippet
        var base = this.core.getBase(node),
            typeName = this.core.getAttribute(base, 'name'),
            snippet = this._languages[language].map[typeName],//Get the code for the given node...
            ptrs = this.core.getPointerNames(node),
            attributes = this.core.getAttributeNames(node),
            i = ptrs.length;

        //If ptr name is present in the snippet, swap it out with the code from the tgt
        //ptrs have precedence over attributes
        while(i--){
            if(this.core.getPointerPath(node, ptrs[i]) && snippet.indexOf('%' + ptrs[i]) !== -1){
                var nId = this.core.getPointerPath(node, ptrs[i]),
                    dec = "";

                if(this._isTypeOf(nId, this.META["Variable"]) && this.variables.indexOf(nId)){
                    //Declare the variable

                    var n = this.getNode(nId);
                    dec = this._declareVar(language, n) + "\n"; //variable declaration
                    this.variables.push(nId);
                }
                snippet = dec + snippet.replace('%' + ptrs[i], this._getBlockCode(language, nId));
            }
        }

        //If the attribute name is in the snippet, substitute the attr name with the value
        i = attributes.length;
        while(i--){
            if(snippet.indexOf('%' + attributes[i]) !== -1){
                snippet = snippet.replace('%' + attributes[i], this.core.getAttribute(node, attributes[i]));
            }
        }

        return snippet;
    };

    SnapPlugin.prototype._getBlockCode = function(language, nodeId){
        //Return code that is part of another block

        if(this._isTypeOf(nodeId, this.META["Predicate"])){
            //Return the snippet inline
            return this._generateCode(language, this.getNode(nodeId));

        }

        if(this._isTypeOf(nodeId, this.META["Command"])){//Return the snippet with an indent
            var node = this.getNode(nodeId),
                snippet = "\t" + this._generateCode(language, node).replace(/\n/g, "\n\t");

            while(this.core.getPointerPath(node, 'next')
                    && this._isTypeOf(this.core.getPointerPath(node, 'next'), this.META["Command"])){
                node = this.getNode(this.core.getPointerPath(node, 'next'));
                snippet += "\n\t" + this._generateCode(language, node);
            }

            return snippet;
        }
    };

    SnapPlugin.prototype._declareVar = function(language, node){
        var primitives = this._languages[language].primitives,
            v = { 'name': this.core.getAttribute(node, 'name'), //variable
                  'val': this.core.getAttribute(node, 'value') };
        if(primitives === null)//Not declaring variables
            return "";

        for(var type in primitives){
            if(primitives.hasOwnProperty(type)){
                //Find the var type
                if(primitives[type].exec(v.val)[0] === v.val){//matches the regex
                    var snippet = type.replace('%var', v.name);
                    return snippet.replace("%value", v.val);
                }
            }
        }
    };

    //Thanks to Tamas for the next two functions
    SnapPlugin.prototype._saveOutput = function(code, callback){
        var self = this,
            fileName = self.projectName.replace(" ", "_"),
            artifact = self.blobClient.createArtifact(fileName+"_code"),
            keys = Object.keys(code),
            i = keys.length,
            language;

            //self._addFiles(fileName, keys, artifact);
        while (i--){
            language = keys[i];
            artifact.addFile(fileName + "." + self._languages[language].ext,code[language],function(err){
                if(err){
                    callback(err);
                } else {
                    keys.pop();
                    if (keys.length === 0){
                        self.blobClient.saveAllArtifacts(function(err, hashes) {
                            if (err) {
                                callback(err);
                            } else {
                                self.logger.info('Artifacts are saved here:');
                                self.logger.info(hashes);

                                // result add hashes
                                for (var j = 0; j < hashes.length; j += 1) {
                                    self.result.addArtifact(hashes[j]);
                                }

                                self.result.setSuccess(true);
                                callback(null);
                            }
                        });
                    }
                }
            });
        }
    };

    SnapPlugin.prototype._errorMessages = function(message){
        var self = this;
        self.createMessage(self.activeNode,message);
    };

    return SnapPlugin;

});
<commit_msg>Updated syntax<commit_after>/*globals define*/
/*
 * @author brollb / https://github/brollb
 *
 * Code generating interpreter for SnapGME
 */

define(['plugin/PluginConfig',
        'plugin/PluginBase'], function (PluginConfig,
                                       PluginBase){
   "use strict";

    var SnapPlugin = function() {
        //Call base class's constructor
        PluginBase.call(this);

        //Code maps:
        //
        //Adding the mapping of node META name to code
        //% sign indicates it will be replaced with either
        //attribute of the given name or ptr tgt of the given name
        this._languages = {};
        this._languages.python = { 'bp': '#!/usr/bin/python2\n\n%code',
                                      'map': { 'Add': "%first + %second",
                                               'Subtract': "%first - %second",
                                               'Multiply': "(%first) * (%second)",
                                               'Divide': "(%first)/(%second)",
                                               'Less Than': "(%first) < (%second)",
                                               'Greater Than': "(%first) > (%second)",
                                               'Equals': "(%first) == (%second)",
                                               'Write': "print %text",
                                               'If': "if %cond:\n %true_next",
                                               'Repeat': "while true:\n %true_next",
                                               'Variable': "%name",
                                               'Set': '%var = %value' },
                                      'primitives': {'%var = %value': /[a-zA-Z\d._-]*/ },
                                      'ext': 'py' };

        //Change the languages to be within the map
        this._languages.javascript = { 'bp': '#!/usr/bin/node\n\n%code',
                                          'map': { 'Add': "%first + %second",
                                                   'Subtract': "%first - %second",
                                                   'Multiply': "(%first) * (%second)",
                                                   'Divide': "(%first)/(%second)",
                                                   'Less Than': "(%first) < (%second)",
                                                   'Greater Than': "(%first) > (%second)",
                                                   'Equals': "(%first) === (%second)",
                                                   'Write': "console.log(%text);",
                                                   'If': "if (%cond){\n %true_next\n}",
                                                   'Repeat': "while (true){\n %true_next\n}",
                                                   'Variable': "%name",
                                                   'Set': '%var = %value;' },
                                          'primitives': { 'var %var = %value;': /^[a-zA-Z\d._-]*$/ },
                                          'ext': 'js' };
    };

    //basic functions and setting for plugin inheritance
    SnapPlugin.prototype = Object.create(PluginBase.prototype);
    SnapPlugin.prototype.constructor = SnapPlugin;

    SnapPlugin.prototype.getName = function () {
        return "Pegasus Plugin";
    };

    //config options
    SnapPlugin.prototype.getConfigStructure = function () {
        return [
            {
                "name": "python",
                "displayName": "Python",
                "description": 'Generate Python Code',
                "value": false, // this is the 'default config'
                "valueType": "boolean",
                "readOnly": false
            },
            {
                "name": "javascript",
                "displayName": "Javascript",
                "description": 'Generate Javascript Code',
                "value": true, // this is the 'default config'
                "valueType": "boolean",
                "readOnly": false
            }
        ];
    };

    SnapPlugin.prototype._loadStartingNodes = function(callback){
        //we load the children of the active node
        var self = this;
        self._nodeCache = {};

        var load = function(node, fn){
            self.core.loadChildren(node,function(err,children){
                if(err){
                    fn(err);
                } else {
                    var j = children.length,
                        e = null; //error

                    if(j === 0){
                        fn(null);
                    }
                    var cb = function(err){
                            e = e || err;
                            if(--j === 0){//callback only on last child
                                fn(e);
                            }
                        };

                    for(var i=0;i<children.length;i++){
                        self._nodeCache[self.core.getPath(children[i])] = children[i];
                        load(children[i], cb(err));
                    }
                }
            });
        };

        load(self.activeNode, callback);

    };

    SnapPlugin.prototype.getNode = function(nodePath){
        //we check only our node cache
        return this._nodeCache[nodePath];
    };

    SnapPlugin.prototype._isTypeOf = function(node,type){
        //now we make the check based upon path
        if(node === undefined || node === null || type === undefined || type === null){
            return false;
        }

        var self = this;

        if (typeof node === "string"){//if the node is the nodeId
            node = self.getNode(node);
        }

        while(node){
            if(self.core.getPath(node) === self.core.getPath(type)){
                return true;
            }
            node = self.core.getBase(node);
        }
        return false;
    };

    SnapPlugin.prototype.main = function (callback) {
        var self = this;
        self.config = self.getCurrentConfig();

        if(!self._isTypeOf(self.activeNode, self.META.Project)){
            self._errorMessages(self.activeNode,
                "Current project is an invalid type. Please run the plugin on a project.");
        }

        self._loadStartingNodes(function(err){
            if(err){
                //finishing
                self.result.success = false;
                callback(err,self.result);
            } else {
                //executing the plugin
                self.logger.info("Finished loading children");
                err = self._runSync();
                if(err){
                    self.result.success = false;
                    callback(err,self.result);
                } else {
                    //Download language files
                    self._saveOutput(self.generatedCode, function(err){
                        if(err){
                            self.result.success = false;
                            callback(err,self.result);
                        } else {
                            if(callback){
                                self.result.success = true;
                                callback(null,self.result);
                            }
                        }
                    });
                }
            }
        });
    };

    SnapPlugin.prototype._runSync = function(){
        var err = null,
            currentNode = null,
            languages = [];

        this.projectName = this.core.getAttribute(this.activeNode,'name');
        this.generatedCode = {};

        for (var lang in this.config){
            if (this.config.hasOwnProperty(lang) && this.config[lang]){
                this.generatedCode[lang] = "";
                languages.push(lang);
            }
        }

        this.variables = [];

        var nodeIds = this.core.getChildrenPaths(this.activeNode),
            i = nodeIds.length,
            l;

        //Find the hat and declare variables
        while(i-- && currentNode === null){
            if(this._isTypeOf(nodeIds[i], this.META.Hat) && !this._isTypeOf(nodeIds[i], this.META.Command)){
                currentNode = this.getNode(nodeIds[i]);
            }
        }

        //Follow the next pointers and map each object to it's given code
        while(this.core.getPointerPath(currentNode, 'next')){
            currentNode = this.getNode(this.core.getPointerPath(currentNode, 'next'));
            for (l in this.generatedCode){
                if(this.generatedCode.hasOwnProperty(l)){
                    this.generatedCode[l] += this._generateCode(l, currentNode) + "\n";
                }
            }
        }

        for (l in this.generatedCode){
            if(this.generatedCode.hasOwnProperty(l)){
                this.generatedCode[l] = this._languages[l].bp.replace("%code", this.generatedCode[l]);
            }
        }

        return err;
    };

    SnapPlugin.prototype._generateCode = function(language, node){
        //Map stuff to code and return the code snippet
        var base = this.core.getBase(node),
            typeName = this.core.getAttribute(base, 'name'),
            snippet = this._languages[language].map[typeName],//Get the code for the given node...
            ptrs = this.core.getPointerNames(node),
            attributes = this.core.getAttributeNames(node),
            i = ptrs.length;

        //If ptr name is present in the snippet, swap it out with the code from the tgt
        //ptrs have precedence over attributes
        while(i--){
            if(this.core.getPointerPath(node, ptrs[i]) && snippet.indexOf('%' + ptrs[i]) !== -1){
                var nId = this.core.getPointerPath(node, ptrs[i]),
                    dec = "";

                if(this._isTypeOf(nId, this.META.Variable) && this.variables.indexOf(nId)){
                    //Declare the variable

                    var n = this.getNode(nId);
                    dec = this._declareVar(language, n) + "\n"; //variable declaration
                    this.variables.push(nId);
                }
                snippet = dec + snippet.replace('%' + ptrs[i], this._getBlockCode(language, nId));
            }
        }

        //If the attribute name is in the snippet, substitute the attr name with the value
        i = attributes.length;
        while(i--){
            if(snippet.indexOf('%' + attributes[i]) !== -1){
                snippet = snippet.replace('%' + attributes[i], this.core.getAttribute(node, attributes[i]));
            }
        }

        return snippet;
    };

    SnapPlugin.prototype._getBlockCode = function(language, nodeId){
        //Return code that is part of another block

        if(this._isTypeOf(nodeId, this.META.Predicate)){
            //Return the snippet inline
            return this._generateCode(language, this.getNode(nodeId));

        }

        if(this._isTypeOf(nodeId, this.META.Command)){//Return the snippet with an indent
            var node = this.getNode(nodeId),
                snippet = "\t" + this._generateCode(language, node).replace(/\n/g, "\n\t");

            while(this.core.getPointerPath(node, 'next') && this._isTypeOf(this.core.getPointerPath(node, 'next'), this.META.Command)){
                node = this.getNode(this.core.getPointerPath(node, 'next'));
                snippet += "\n\t" + this._generateCode(language, node);
            }

            return snippet;
        }
    };

    SnapPlugin.prototype._declareVar = function(language, node){
        var primitives = this._languages[language].primitives,
            v = { 'name': this.core.getAttribute(node, 'name'), //variable
                  'val': this.core.getAttribute(node, 'value') };
        if(primitives === null){//Not declaring variables
            return "";
    }

        for(var type in primitives){
            if(primitives.hasOwnProperty(type)){
                //Find the var type
                if(primitives[type].exec(v.val)[0] === v.val){//matches the regex
                    var snippet = type.replace('%var', v.name);
                    return snippet.replace("%value", v.val);
                }
            }
        }
    };

    //Thanks to Tamas for the next two functions
    SnapPlugin.prototype._saveOutput = function(code, callback){
        var self = this,
            fileName = self.projectName.replace(" ", "_"),
            artifact = self.blobClient.createArtifact(fileName+"_code"),
            keys = Object.keys(code),
            i = keys.length,
            language,

            //self._addFiles(fileName, keys, artifact);
            cb = function(err){
                if(err){
                    callback(err);
                } else {
                    keys.pop();
                    if (keys.length === 0){
                        self.blobClient.saveAllArtifacts(function(err, hashes) {
                            if (err) {
                                callback(err);
                            } else {
                                self.logger.info('Artifacts are saved here:');
                                self.logger.info(hashes);

                                // result add hashes
                                for (var j = 0; j < hashes.length; j += 1) {
                                    self.result.addArtifact(hashes[j]);
                                }

                                self.result.setSuccess(true);
                                callback(null);
                            }
                        });
                    }
                }
            };

        while (i--){
            language = keys[i];
            artifact.addFile(fileName + "." + self._languages[language].ext,code[language], cb);
        }
    };

    SnapPlugin.prototype._errorMessages = function(message){
        var self = this;
        self.createMessage(self.activeNode,message);
    };

    return SnapPlugin;

});
<|endoftext|>


<commit_before>define([
    '../../components/vue/dist/vue',
], function (Vue) {
    'use strict';

    var ApplicationListView = Vue.extend({
        template:
              '
' +
              '  ' +
              '  <confirm-dialog v-if="showErrorDialog"' +
              '                  :title="getErrorTitle()"' +
              '                  :okCallback="closeDialog">' +
              '
' +
              '      Code: {{stoppingError.code}}' +
              '      {{stoppingError.message}}' +
              '
' +
              '  </confirm-dialog>' +

              '' +
              '<form action="#" class="sidebar-form">' +
              '  <input type="text" name="q" class="form-control" placeholder="Search..." v-model="searchInput">' +
              '</form>' +

              '' +
              '
' +
              '
APPLICATIONS
' +
              '
' +

              '
' +
              '
' +
              '    No applications found' +
              '
' +

              '  ' +
              '
' +
              '    ' +
              '      ' +
              '      Loading' +
              '    ' +
              '
' +
              '
' +

              '  ' +
              '<transition-group name="list" tag="ul" id="applistentries" class="sidebar-menu">' +
              '
' +

              '    ' +

              '    ' +
              '      ' +

              '      <button class="stop-button"' +
              '              v-if="app.isRunning()"' +
              '              @click="stopApplication(indexOf(app))"' +
              '              :disabled="app.isStopping()">' +
              '        ' +
              '      </button>' +
              '      {{ app.appData.image | appName }}' +
              '    ' +
              '
' +
              '</transition-group>' +
              '' +
            '
' +
            '',

        data: function() {
            return {
                'searchInput': '',
                showErrorDialog: false,
                stoppingError: {}
            };
        },

        computed: {
            visibleList: function() {
                return this.model.appList.filter(function(app) {
                    var appName = this.$options.filters.appName(app.appData.image).toLowerCase();
                    return appName.indexOf(this.searchInput.toLowerCase()) !== -1;
                }.bind(this));
            }
        },

        methods: {
            stopApplication: function(index) {
                var stoppingAppName = this.$options.filters.appName(
                    this.model.appList[index].appData.image);
                this.model.stopApplication(index).fail(function(error) {
                    this.stoppingError = error;
                    this.stoppingError.appName = stoppingAppName;
                    this.showErrorDialog = true;
                }.bind(this));
            },
            getErrorTitle: function() {
                return 'Error when stopping ' + this.stoppingError.appName;
            },
            closeDialog: function() {
                this.showErrorDialog = false;
            },
            indexOf: function(app) {
                return this.model.appList.indexOf(app);
            }
        }
    });

    return {
        ApplicationListView : ApplicationListView
    };
});
<commit_msg>Fix import<commit_after>define([
    "../../components/vue/dist/vue",
    "admin/vue-components/toolkit/toolkit"
], function (Vue) {
    'use strict';

    var ApplicationListView = Vue.extend({
        template:
              '
' +
              '  ' +
              '  <confirm-dialog v-if="showErrorDialog"' +
              '                  :title="getErrorTitle()"' +
              '                  :okCallback="closeDialog">' +
              '
' +
              '      Code: {{stoppingError.code}}' +
              '      {{stoppingError.message}}' +
              '
' +
              '  </confirm-dialog>' +

              '' +
              '<form action="#" class="sidebar-form">' +
              '  <input type="text" name="q" class="form-control" placeholder="Search..." v-model="searchInput">' +
              '</form>' +

              '' +
              '
' +
              '
APPLICATIONS
' +
              '
' +

              '
' +
              '
' +
              '    No applications found' +
              '
' +

              '  ' +
              '
' +
              '    ' +
              '      ' +
              '      Loading' +
              '    ' +
              '
' +
              '
' +

              '  ' +
              '<transition-group name="list" tag="ul" id="applistentries" class="sidebar-menu">' +
              '
' +

              '    ' +

              '    ' +
              '      ' +

              '      <button class="stop-button"' +
              '              v-if="app.isRunning()"' +
              '              @click="stopApplication(indexOf(app))"' +
              '              :disabled="app.isStopping()">' +
              '        ' +
              '      </button>' +
              '      {{ app.appData.image | appName }}' +
              '    ' +
              '
' +
              '</transition-group>' +
              '' +
            '
' +
            '',

        data: function() {
            return {
                'searchInput': '',
                showErrorDialog: false,
                stoppingError: {}
            };
        },

        computed: {
            visibleList: function() {
                return this.model.appList.filter(function(app) {
                    var appName = this.$options.filters.appName(app.appData.image).toLowerCase();
                    return appName.indexOf(this.searchInput.toLowerCase()) !== -1;
                }.bind(this));
            }
        },

        methods: {
            stopApplication: function(index) {
                var stoppingAppName = this.$options.filters.appName(
                    this.model.appList[index].appData.image);
                this.model.stopApplication(index).fail(function(error) {
                    this.stoppingError = error;
                    this.stoppingError.appName = stoppingAppName;
                    this.showErrorDialog = true;
                }.bind(this));
            },
            getErrorTitle: function() {
                return 'Error when stopping ' + this.stoppingError.appName;
            },
            closeDialog: function() {
                this.showErrorDialog = false;
            },
            indexOf: function(app) {
                return this.model.appList.indexOf(app);
            }
        }
    });

    return {
        ApplicationListView : ApplicationListView
    };
});
<|endoftext|>


<commit_before>"use strict";

function escapeHTML(unsafe) {
  if(unsafe == null) return "";
  return unsafe.toString()
   .replace(/&/g, "&")
   .replace(/</g, "<")
   .replace(/>/g, ">")
   .replace(/"/g, """)
   .replace(/'/g, "'");
}

var renderCount = 0;
var elementCount = 0;
var arrayCount = 0;
var objectCount = 0;
var tree = null;

function doStats() {
  var out = "<input type='button' id='statst' onclick='showStats();' value='Show Statistics' style='float: right;' />\n"
   + "

\n"
    + "
\n
\n
\nNumber of Arrays:	\n" + arrayCount + "	\n
\n"
    + "
\nNumber of Objects:	\n" + objectCount + "	\n
\n"
     + "
\nTotal number of all elements:	\n" + elementCount + "	\n
\n"
      + "
\nNesting depth:	\n" + tree.nestingLevel + "	\n
\n"
      + "
\n
\n
\n";
  return out;
}

function parse(str) {
  try {
    return JSON.parse(str);
  }
  catch(e) {
    if(e instanceof SyntaxError) {
      alert("There was a syntax error in your JSON string.\n" + e.message + "\nPlease check your syntax and try again.");
    }
    else {
      alert("There was an unknown error. Perhaps the JSON string contained a deep level of nesting.");
    }

    $("#text").focus();
    return;
  }
}

function render(val) {
  elementCount = 0;
  arrayCount = 0;
  objectCount = 0;
  renderCount = 0;

  if(val.type == "array") return renderArray(val);
  if(val.type == "object") return renderObject(val);
  elementCount++;
  return "" + escapeHTML(val.value) + "";
}

function renderTuples(tuples) {
  var out = "";

  tuples.forEach(function(tuple) {
    var value = tuple.value;
    out += "
" + escapeHTML(tuple.name) + "	";
    out += "";

    if(value.simple) {
      elementCount++;
      out += escapeHTML(value.value);
    }
    else if(value.type == "array") {
      out += renderArray(value);
    }
    else if(value.type == "object") {
      out += renderObject(value);
    }
    out += "
";
  });

  return out;
}

function renderArray(array) {
  elementCount++;
  arrayCount++;
  renderCount++;
  if(!array.tuples.length) return "
(empty Array)
";

  var out = "
= 1000 ? " minimised" : "") + "' data-index='" + array.index + "'>

Array
";
  out += "

Index	Value
";
  out += renderTuples(array.tuples);
  out += "

";
  return out;
}

function renderObject(object) {
  elementCount++;
  objectCount++;
  renderCount++;
  if(!object.tuples.length) return "
(empty Object)
";

  var out = "
= 1000 ? " minimised" : "") + "' data-index='" + object.index + "'>

Object
";
  out += "

Name	Value
";
  out += renderTuples(object.tuples);
  out += "

";
  return out;
}

function json2html(str) {
  var parseTree = parse(str);
  if(!parseTree) return;
  tree = transformTree(parseTree);
  var result = render(tree.root);

  $("#output").innerHTML = result;

  $("#stats").innerHTML = doStats();
  $("#stats").className = "";

  $("#submit").value = "json 2 html";
  $("#submit").disabled = null;

  $("#output").scrollIntoView();
}

function doParse() {
  $("#submit").value = "processing...";
  $("#submit").disabled = "disabled";

  setTimeout(doParse2, 50);
}

function doParse2() {
  var value = $("#text").value;
  if(value.substr(0, 4) == "http" || value.substr(0, 4) == "file" || value.substr(0, 3) == "ftp") {
    getURL(value);
  }
  else {
    json2html(value);
  }
}

function getURL(str) {
  var http = new XMLHttpRequest();
  http.open("get", "get.php?url=" + str);
  http.onreadystatechange = function() {
    if(http.readyState == 4) json2html(http.responseText);
  };
  http.send(null);
}

function showStats() {
  if($("#statscon").style.display != "block") {
    $("#statscon").style.display = "block";
    $("#stats").className = "statson";
    $("#statst").value = "Hide Statistics";
  }
  else {
    $("#statscon").style.display = "none";
    $("#stats").className = "";
    $("#statst").value = "Show Statistics";
  }
}

function itemPath(item) {
  var path = ["<root>"];

  if(item.address) {
    item.address.full().forEach(function(address) {
      path.push(address.parent.type == "array" ? "[" + address.prop + "]" : "." + address.prop);
    });
  }

  return path.join("");
}

function itemTrailLabel(item) {
  return item.typeLabel + " (" + item.tuples.length + " item" + (item.tuples.length != 1 ? "s)" : ")");
}

function itemTrail(item) {
  var trail = ["Root"];

  if(item.address) {
    item.address.full().forEach(function(address) {
      trail.push(itemTrailLabel(address.parent));
    });
  }

  if(!item.simple) trail.push(itemTrailLabel(item));

  return trail.join(" > ");
}

var currentFocusElement = null;
function focusObject(element) {
  if(element == currentFocusElement) return;

  currentFocusElement = element;

  var item = tree.fromIndex(parseInt(element.dataset.index));

  $("#focus-path").textContent = itemPath(item);
  $("#focus-trail").textContent = itemTrail(item);
}

var currentOutlineElement = null;
function outlineObject(element) {
  if(element == currentOutlineElement) return;

  if(currentOutlineElement) currentOutlineElement.style.outline = "none";

  currentOutlineElement = element;

  if(element) element.style.outline = "1px solid #ffa000";
}

//code from Painfully Obvious.
//based on code from quirksmode.org
var Client = {
  viewportWidth: function() {
  return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
  },

  viewportHeight: function() {
   return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
  },

  viewportSize: function() {
   return { width: this.viewportWidth(), height: this.viewportHeight() };
  }
};

function doHelp() {
  $("#help-content").style.display = "block";
  var bodySize = Client.viewportSize();

  $("#backdrop").style.display = "block";

  $("#help-content").style.left = ((bodySize.width / 2) - ($("#help-content").offsetWidth / 2)) + "px";
  $("#help-content").style.top = ((bodySize.height / 2) - ($("#help-content").offsetHeight / 2)) + "px";
  $("body").scrollIntoView();
}

function hideHelp() {
  $("#help-content").style.display = "none";
  $("#backdrop").style.display = "none";
  $("#text").focus();
}

function clearPage() {
  $("#stats").innerHTML = "";
  $("#output").innerHTML = "";
}

function handleFocusOutline(event) {
  var focusable = event.target.closest("div[data-index], tr[data-index]");
  if(focusable) focusObject(focusable);

  var outlinable = event.target.closest("div[data-index]");
  outlineObject(outlinable);
}

function load() {
  window.$ = document.querySelector.bind(document);

  document.body.addEventListener("click", function(event) {
    handleFocusOutline(event);

    if(event.target.matches(".widget")) event.target.parentNode.classList.toggle("minimised");
  });

  document.body.addEventListener("mousemove", handleFocusOutline);

  if($("#text").focus) $("#text").focus();
}

window.onload = load;<commit_msg>Remove trailing whitespace in parse.js<commit_after>"use strict";

function escapeHTML(unsafe) {
  if(unsafe == null) return "";
  return unsafe.toString()
   .replace(/&/g, "&")
   .replace(/</g, "<")
   .replace(/>/g, ">")
   .replace(/"/g, """)
   .replace(/'/g, "'");
}

var renderCount = 0;
var elementCount = 0;
var arrayCount = 0;
var objectCount = 0;
var tree = null;

function doStats() {
  var out = "<input type='button' id='statst' onclick='showStats();' value='Show Statistics' style='float: right;' />\n"
   + "

\n"
    + "
\n
\n
\nNumber of Arrays:	\n" + arrayCount + "	\n
\n"
    + "
\nNumber of Objects:	\n" + objectCount + "	\n
\n"
     + "
\nTotal number of all elements:	\n" + elementCount + "	\n
\n"
      + "
\nNesting depth:	\n" + tree.nestingLevel + "	\n
\n"
      + "
\n
\n
\n";
  return out;
}

function parse(str) {
  try {
    return JSON.parse(str);
  }
  catch(e) {
    if(e instanceof SyntaxError) {
      alert("There was a syntax error in your JSON string.\n" + e.message + "\nPlease check your syntax and try again.");
    }
    else {
      alert("There was an unknown error. Perhaps the JSON string contained a deep level of nesting.");
    }

    $("#text").focus();
    return;
  }
}

function render(val) {
  elementCount = 0;
  arrayCount = 0;
  objectCount = 0;
  renderCount = 0;

  if(val.type == "array") return renderArray(val);
  if(val.type == "object") return renderObject(val);
  elementCount++;
  return "" + escapeHTML(val.value) + "";
}

function renderTuples(tuples) {
  var out = "";

  tuples.forEach(function(tuple) {
    var value = tuple.value;
    out += "
" + escapeHTML(tuple.name) + "	";
    out += "";

    if(value.simple) {
      elementCount++;
      out += escapeHTML(value.value);
    }
    else if(value.type == "array") {
      out += renderArray(value);
    }
    else if(value.type == "object") {
      out += renderObject(value);
    }
    out += "
";
  });

  return out;
}

function renderArray(array) {
  elementCount++;
  arrayCount++;
  renderCount++;
  if(!array.tuples.length) return "
(empty Array)
";

  var out = "
= 1000 ? " minimised" : "") + "' data-index='" + array.index + "'>

Array
";
  out += "

Index	Value
";
  out += renderTuples(array.tuples);
  out += "

";
  return out;
}

function renderObject(object) {
  elementCount++;
  objectCount++;
  renderCount++;
  if(!object.tuples.length) return "
(empty Object)
";

  var out = "
= 1000 ? " minimised" : "") + "' data-index='" + object.index + "'>

Object
";
  out += "

Name	Value
";
  out += renderTuples(object.tuples);
  out += "

";
  return out;
}

function json2html(str) {
  var parseTree = parse(str);
  if(!parseTree) return;
  tree = transformTree(parseTree);
  var result = render(tree.root);

  $("#output").innerHTML = result;

  $("#stats").innerHTML = doStats();
  $("#stats").className = "";

  $("#submit").value = "json 2 html";
  $("#submit").disabled = null;

  $("#output").scrollIntoView();
}

function doParse() {
  $("#submit").value = "processing...";
  $("#submit").disabled = "disabled";

  setTimeout(doParse2, 50);
}

function doParse2() {
  var value = $("#text").value;
  if(value.substr(0, 4) == "http" || value.substr(0, 4) == "file" || value.substr(0, 3) == "ftp") {
    getURL(value);
  }
  else {
    json2html(value);
  }
}

function getURL(str) {
  var http = new XMLHttpRequest();
  http.open("get", "get.php?url=" + str);
  http.onreadystatechange = function() {
    if(http.readyState == 4) json2html(http.responseText);
  };
  http.send(null);
}

function showStats() {
  if($("#statscon").style.display != "block") {
    $("#statscon").style.display = "block";
    $("#stats").className = "statson";
    $("#statst").value = "Hide Statistics";
  }
  else {
    $("#statscon").style.display = "none";
    $("#stats").className = "";
    $("#statst").value = "Show Statistics";
  }
}

function itemPath(item) {
  var path = ["<root>"];

  if(item.address) {
    item.address.full().forEach(function(address) {
      path.push(address.parent.type == "array" ? "[" + address.prop + "]" : "." + address.prop);
    });
  }

  return path.join("");
}

function itemTrailLabel(item) {
  return item.typeLabel + " (" + item.tuples.length + " item" + (item.tuples.length != 1 ? "s)" : ")");
}

function itemTrail(item) {
  var trail = ["Root"];

  if(item.address) {
    item.address.full().forEach(function(address) {
      trail.push(itemTrailLabel(address.parent));
    });
  }

  if(!item.simple) trail.push(itemTrailLabel(item));

  return trail.join(" > ");
}

var currentFocusElement = null;
function focusObject(element) {
  if(element == currentFocusElement) return;

  currentFocusElement = element;

  var item = tree.fromIndex(parseInt(element.dataset.index));

  $("#focus-path").textContent = itemPath(item);
  $("#focus-trail").textContent = itemTrail(item);
}

var currentOutlineElement = null;
function outlineObject(element) {
  if(element == currentOutlineElement) return;

  if(currentOutlineElement) currentOutlineElement.style.outline = "none";

  currentOutlineElement = element;

  if(element) element.style.outline = "1px solid #ffa000";
}

//code from Painfully Obvious.
//based on code from quirksmode.org
var Client = {
  viewportWidth: function() {
  return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
  },

  viewportHeight: function() {
   return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
  },

  viewportSize: function() {
   return { width: this.viewportWidth(), height: this.viewportHeight() };
  }
};

function doHelp() {
  $("#help-content").style.display = "block";
  var bodySize = Client.viewportSize();

  $("#backdrop").style.display = "block";

  $("#help-content").style.left = ((bodySize.width / 2) - ($("#help-content").offsetWidth / 2)) + "px";
  $("#help-content").style.top = ((bodySize.height / 2) - ($("#help-content").offsetHeight / 2)) + "px";
  $("body").scrollIntoView();
}

function hideHelp() {
  $("#help-content").style.display = "none";
  $("#backdrop").style.display = "none";
  $("#text").focus();
}

function clearPage() {
  $("#stats").innerHTML = "";
  $("#output").innerHTML = "";
}

function handleFocusOutline(event) {
  var focusable = event.target.closest("div[data-index], tr[data-index]");
  if(focusable) focusObject(focusable);

  var outlinable = event.target.closest("div[data-index]");
  outlineObject(outlinable);
}

function load() {
  window.$ = document.querySelector.bind(document);

  document.body.addEventListener("click", function(event) {
    handleFocusOutline(event);

    if(event.target.matches(".widget")) event.target.parentNode.classList.toggle("minimised");
  });

  document.body.addEventListener("mousemove", handleFocusOutline);

  if($("#text").focus) $("#text").focus();
}

window.onload = load;<|endoftext|>


<commit_before>'use strict'

const BigQuery = require('@google-cloud/bigquery')
const fs = require('fs')
const param = require('commander')
const {flow, map, first, isNumber, defaultTo} = require('lodash/fp')

const query = (sql) => {
    const options = {
        query: sql,
        timeoutMs: 1000000,
        useLegacySql: true
    }
    return BigQuery({ projectId: process.env.GCLOUD_PROJECT }).query(options)
}

const writeJsonToFile = q => async (json) => {
    const format = string => string.split(' ').pop().replace(/'/g,'')
    const fileName = format(q) + '.json'
    const lineEndings = (json) => String(json).replace(/},{/g, '}\r\n{')
    await fs.writeFile(fileName, lineEndings(json), (err) => {
        if (err)
            process.stdout.write('Could not write to ' + fileName + ' File ' + err + '\n')
        else
            process.stdout.write(fileName + ' successfully written\n')
    }
  )
}

const queryBuilder = (tables) => {
    const types = ['PullRequestEvent', 'IssuesEvent', 'PushEvent', 'WatchEvent']
    const sqlQuery = (type) =>
          `SELECT language as name, year, quarter, count FROM ( SELECT * FROM (
          SELECT lang as language, y as year, q as quarter, type,
          COUNT(*) as count FROM (SELECT a.type type, b.lang lang, a.y y, a.q q FROM (
          SELECT type, YEAR(created_at) as y, QUARTER(created_at) as q,
          STRING(REGEXP_REPLACE(repo.url, r'https:\/\/github\.com\/|https:\/\/api\.github\.com\/repos\/', '')) as name
          FROM ${tables} ) a
          JOIN ( SELECT repo_name as name, lang FROM ( SELECT * FROM (
          SELECT *, ROW_NUMBER() OVER (PARTITION BY repo_name ORDER BY lang) as num FROM (
          SELECT repo_name, FIRST_VALUE(language.name) OVER (
          partition by repo_name order by language.bytes DESC) AS lang
          FROM [bigquery-public-data:github_repos.languages]))
          WHERE num = 1 order by repo_name)
          WHERE lang != 'null') b ON a.name = b.name)
          GROUP by type, language, year, quarter
          order by year, quarter, count DESC)
          WHERE count >= 100) WHERE type = '${type}'`
    return map(sqlQuery)(types)
}

const numToStrReplacer = (key, value) => isNumber(value) ? JSON.stringify(value) : value
const stringifyFP = x => y => JSON.stringify(y, x)

const stringify = flow(
      JSON.stringify,
      JSON.parse,
      stringifyFP(numToStrReplacer)
  )

const exec = async (q) =>
      flow(
          first,
          map(stringify),
          writeJsonToFile(q)
      )(await query(q))

const main = async () => {
    param
      .version('1.0.0')
      .option('-t, --tables <string>',
        'The GitHub Archive tables that you want query example usage:' +
        'node query.js -t "[githubarchive:day.20130818], [githubarchive:day.20140118]"')
      .parse(process.argv)

    const tables = defaultTo('[githubarchive:day.20130118], [githubarchive:day.20140118]')(param.tables)
    const queries = queryBuilder(tables)

    try {
        await Promise.all(map(exec)(queries))
    } catch (err) {
        process.stdout.write('Error while querying the BigQuery Google API ' + err + '\n')
    }
}

main()
<commit_msg>add auto file append function<commit_after>'use strict'

const BigQuery = require('@google-cloud/bigquery')
const fs = require('fs')
const param = require('commander')
const {flow, map, first, isNumber, defaultTo} = require('lodash/fp')

const query = (sql) => {
    const options = {
        query: sql,
        timeoutMs: 1000000,
        useLegacySql: true
    }
    return BigQuery({ projectId: process.env.GCLOUD_PROJECT }).query(options)
}

const writeJsonToFile = q => async (json) => {
    const format = string => string.split(' ').pop().replace(/'/g,'')
    const fileName = format(q) + '.json'
    const lineEndings = (json) => String(json).replace(/},{/g, '}\r\n{')
    await fs.writeFile(fileName, lineEndings(json), (err) => {
        if (err)
            process.stdout.write('Could not write to ' + fileName + ' File ' + err + '\n')
        else
            process.stdout.write(fileName + ' successfully written\n')
    })

    const getAppendFileName = fileName => {
        if (fileName == 'PullRequestEvent.json')
            return 'gh-pull-request.json'
        if (fileName == 'PushEvent.json')
            return 'gh-push-event.json'
        if (fileName == 'IssuesEvent.json')
            return 'gh-issue-event.json'
        if (fileName == 'WatchEvent.json')
            return 'gh-star-event.json'
        throw 'cannot find append file'
    }

    await fs.appendFile('../src/data/' + getAppendFileName(fileName), "\n" + lineEndings(json), (err) => {
        if (err) throw 'could not append file'
    })
}

const queryBuilder = (tables) => {
    const types = ['PullRequestEvent', 'IssuesEvent', 'PushEvent', 'WatchEvent']
    const sqlQuery = (type) =>
        `SELECT language as name, year, quarter, count FROM ( SELECT * FROM (
          SELECT lang as language, y as year, q as quarter, type,
          COUNT(*) as count FROM (SELECT a.type type, b.lang lang, a.y y, a.q q FROM (
          SELECT type, YEAR(created_at) as y, QUARTER(created_at) as q,
          STRING(REGEXP_REPLACE(repo.url, r'https:\/\/github\.com\/|https:\/\/api\.github\.com\/repos\/', '')) as name
          FROM ${tables} ) a
          JOIN ( SELECT repo_name as name, lang FROM ( SELECT * FROM (
          SELECT *, ROW_NUMBER() OVER (PARTITION BY repo_name ORDER BY lang) as num FROM (
          SELECT repo_name, FIRST_VALUE(language.name) OVER (
          partition by repo_name order by language.bytes DESC) AS lang
          FROM [bigquery-public-data:github_repos.languages]))
          WHERE num = 1 order by repo_name)
          WHERE lang != 'null') b ON a.name = b.name)
          GROUP by type, language, year, quarter
          order by year, quarter, count DESC)
          WHERE count >= 100) WHERE type = '${type}'`
    return map(sqlQuery)(types)
}

const numToStrReplacer = (key, value) => isNumber(value) ? JSON.stringify(value) : value
const stringifyFP = x => y => JSON.stringify(y, x)

const stringify = flow(
    JSON.stringify,
    JSON.parse,
    stringifyFP(numToStrReplacer)
)

const exec = async (q) =>
    flow(
        first,
        map(stringify),
        writeJsonToFile(q)
    )(await query(q))

const main = async () => {
    param
        .version('1.0.0')
        .option('-t, --tables <string>',
            'The GitHub Archive tables that you want query example usage:' +
            'node query.js -t "[githubarchive:day.20130818], [githubarchive:day.20140118]"')
        .parse(process.argv)

    const tables = defaultTo('[githubarchive:day.20130118], [githubarchive:day.20140118]')(param.tables)
    const queries = queryBuilder(tables)

    try {
        await Promise.all(map(exec)(queries))
    } catch (err) {
        process.stdout.write('Error while querying the BigQuery Google API ' + err + '\n')
    }
}

main()
<|endoftext|>


<commit_before>const shell = require('shelljs');

// Store installation start date.
const installationStartDate = new Date();

// Remove existing binary.
shell.rm('-f', '/usr/local/bin/strapi.js');

shell.echo('Linking Strapi CLI...');

shell.cd('packages/strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-generate');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-admin');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-generate-admin');
shell.exec('npm install ../strapi-admin');
shell.exec('npm link');

shell.cd('../strapi-generate-new');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-mongoose');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi');
shell.exec('npm install ../strapi-generate ../strapi-generate-admin ../strapi-generate-api ../strapi-generate-new ../strapi-generate-policy ../strapi-generate-service ../strapi-mongoose ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-helper-plugin');
shell.exec('npm install');

shell.cd('../strapi-plugin-content-manager');
shell.exec('npm install ../strapi-helper-plugin');
shell.rm('-f', 'package-lock.json');
shell.exec('npm link');

shell.cd('../strapi-plugin-settings-manager');
shell.exec('npm install ../strapi-helper-plugin');
shell.rm('-f', 'package-lock.json');
shell.exec('npm link');

// Log installation duration.
const installationEndDate = new Date();
const duration = (installationEndDate.getTime() - installationStartDate.getTime()) / 1000;
shell.echo('Strapi has been succesfully installed.');
shell.echo(`Installation took ${Math.floor(duration / 60) > 0 ? `${Math.floor(duration / 60)} minutes and ` : ''}${duration % 60} seconds.`);
<commit_msg>Link strapi-helper-plugin during setup<commit_after>const shell = require('shelljs');

// Store installation start date.
const installationStartDate = new Date();

// Remove existing binary.
shell.rm('-f', '/usr/local/bin/strapi.js');

shell.echo('Linking Strapi CLI...');

shell.cd('packages/strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-generate');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-admin');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-generate-admin');
shell.exec('npm install ../strapi-admin');
shell.exec('npm link');

shell.cd('../strapi-generate-new');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-mongoose');
shell.exec('npm install ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi');
shell.exec('npm install ../strapi-generate ../strapi-generate-admin ../strapi-generate-api ../strapi-generate-new ../strapi-generate-policy ../strapi-generate-service ../strapi-mongoose ../strapi-utils');
shell.exec('npm link');

shell.cd('../strapi-helper-plugin');
shell.exec('npm link');

shell.cd('../strapi-plugin-content-manager');
shell.exec('npm install ../strapi-helper-plugin');
shell.rm('-f', 'package-lock.json');
shell.exec('npm link');

shell.cd('../strapi-plugin-settings-manager');
shell.exec('npm install ../strapi-helper-plugin');
shell.rm('-f', 'package-lock.json');
shell.exec('npm link');

// Log installation duration.
const installationEndDate = new Date();
const duration = (installationEndDate.getTime() - installationStartDate.getTime()) / 1000;
shell.echo('Strapi has been succesfully installed.');
shell.echo(`Installation took ${Math.floor(duration / 60) > 0 ? `${Math.floor(duration / 60)} minutes and ` : ''}${duration % 60} seconds.`);
<|endoftext|>


<commit_before>var namespace_info_table_DataTable, zk_cluster_info_table_DataTable, namespace_zkcluster_manager_table_DataTable;
var namespace_zkcluster_manager_operation = '【请务必同时只能一个人并且只使用一个浏览器来操作】  ' +
                                            '<button class="btn btn-success" id="batch-move-namespace">批量迁移</button>  ' +
                                            '<button class="btn btn-warning" id="init-namespace-zkcluster-mapping">初始化映射表</button>  ';
$(function() {
    window.parent.setActiveTab("#regTab");
	window.parent.releaseRegName();

	$("#refresh_registry_center").on("click", function() {
		var $btn = $(this).button("loading");
		$.get("registry_center/refreshRegCenter", function(data) {
			if(data.success == true) {
				window.parent.reloadTreeData();
                window.parent.contentFrame.location.href="registry_center_page";
			} else {
				showFailureDialogWithMsg("failure-dialog", data.message);
			}
		}).always(function() { $btn.button('reset'); });
	});

	$('[href="#namespace_info_tabpanel"]').on("click", function() {
		refreshNamespaceInfo();
    });
	$('[href="#zk_cluster_info_tabpanel"]').on("click", function() {
		refreshZkClusterInfo();
	});
	$('[href="#namespace_zkcluster_manager_tabpanel"]').on("click", function() {
		refreshNamespaceZkClusterMappingList();
    });
	if ($("#namespace_info_tabpanel").is(':visible')) {
		refreshNamespaceInfo();
	} else if ($("#zk_cluster_info_tabpanel").is(':visible')) {
		refreshZkClusterInfo();
	} else if ($("#namespace_zkcluster_manager_tabpanel").is(':visible')) {
		refreshNamespaceZkClusterMappingList();
	}

	$("#namespace_zkcluster_manager_table_select_all").on('click', function(event) {
	    if($(this).is(":checked")){
            $('.batchInput').prop('checked',true);// jquery1.9以后的版本，用attr有点问题，要用prop
        }else{
            $('.batchInput').prop('checked',false);
        }
    });

    $("#move-namespace-batch-dialog").on("shown.bs.modal", function (event) {
        $("#move-namespace-batch-dialog-confirm-btn").unbind('click').click(function() {
            var namespaces = $("#move-namespace-batch-dialog-namespace").html();
            var zkClusterKeyNew = "";
            if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
                zkClusterKeyNew = $("#move-namespace-batch-dialog-zkCluster").val();
            } else {
                zkClusterKeyNew = $("#move-namespace-batch-dialog-zkCluster-input").val();
            }
            var updateDBOnly = $("#move-namespace-batch-dialog-updateDBOnly").is(":checked");
            $("#confirm-yes-dialog-title").html('域名：
' + namespaces + '
目标集群：
' + zkClusterKeyNew + '
只更新映射表：
' + updateDBOnly + '
确认批量迁移，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    $("#move-namespace-batch-dialog").modal("hide");
                    $("#confirm-yes-dialog").modal("hide");
                    $("#move-namespace-batch-status-dialog-zkCluster").html(zkClusterKeyNew);
                    var split = namespaces.split(",");
                    if(split && split instanceof Array) {
                        var id = parseInt(Math.random() * 10000000);
                        $.post("registry_center/moveNamespaceBatch", {namespaces: namespaces, zkClusterKeyNew: zkClusterKeyNew, updateDBOnly: updateDBOnly, id: id}, function(data) {
                            if(data.success) {
                                var size = split.length;
                                $("#move-namespace-batch-status-dialog-data").html("成功：" + 0 + "
失败：" + 0 + "
忽略：" + 0 + "
未做：" + size + "
总共：" + size);
                                $("#move-namespace-batch-status-dialog-message").html("");
                                $("#move-namespace-batch-status-dialog-tips").css("display", "inline");
                                $("#move-namespace-batch-status-dialog-x").css("display", "none");
                                $("#move-namespace-batch-status-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-status-dialog").modal("show");
                                getMoveNamespaceBatchStatus(id);
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        alert("请选择要迁移的域");
                    }
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });
    });

    $("#move-namespace-batch-dialog-manual").on('click', function(event) {
        if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
            $("#move-namespace-batch-dialog-zkCluster").attr("style", "display:none");
            $("#move-namespace-batch-dialog-zkCluster-input").removeAttr("style");
            $("#move-namespace-batch-dialog-manual").attr("status", "manual");
            $("#move-namespace-batch-dialog-manual").html("在线的集群");
        } else {
            $("#move-namespace-batch-dialog-zkCluster").removeAttr("style");
            $("#move-namespace-batch-dialog-zkCluster-input").attr("style", "display:none");
            $("#move-namespace-batch-dialog-manual").attr("status", "auto");
            $("#move-namespace-batch-dialog-manual").html("手动输入");
        }
    });

    $("#confirm-yes-dialog").on("shown.bs.modal", function (event) {
        $("#giveMeYes").focus();
    });

    $("#move-namespace-batch-status-dialog-x").on("click", function() {
        $("#move-namespace-batch-status-dialog").modal("hide");
        var id = parseInt($("#move-namespace-batch-status-dialog-x").attr("id2"));
        if(!isNaN(id)) {
            $.post("registry_center/clearMoveNamespaceBatchStatus", {id: id}, function(data) {});
        }
        refreshNamespaceZkClusterMappingList();
    });

    refreshNamespaceInfo();
});

function refreshNamespaceInfo() {
    $loading.show();
	$.get("registry_center/getNamespaceInfo", {}, function(data) {
		if(namespace_info_table_DataTable) {
			namespace_info_table_DataTable.destroy();
		}
        $("#namespace_info_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var cluster = list[i];
            		var key = cluster.zkClusterKey;
            		var regCenterConfList = cluster.regCenterConfList;
            		if(regCenterConfList && regCenterConfList instanceof Array) {
            			for(var j=0; j < regCenterConfList.length; j++) {
	        				var regCenterConf = regCenterConfList[j];
			                var baseTd = "" + regCenterConf.namespace + "	"
			                    + regCenterConf.name + "	"
			                    + regCenterConf.version + "	"
			                    + key + "	";
			                $("#namespace_info_table tbody").append("
" + baseTd + "
");
            			}
            		}
	            }
	        }
	        namespace_info_table_DataTable = $("#namespace_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function refreshNamespaceZkClusterMappingList() {
    $loading.show();
	$.get("registry_center/getNamespaceZkclusterMappingList", {}, function(data) {
		if(namespace_zkcluster_manager_table_DataTable) {
			namespace_zkcluster_manager_table_DataTable.destroy();
		}
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);
        $("#namespace_zkcluster_manager_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var mapping = list[i];
                    var baseTd = "<input class='batchInput' type='checkbox' onclick='clickNamespace_zkcluster_manager_table_select_all(this);' namespace='" + mapping.namespace + "'/>	"
                        + "" + mapping.namespace + "	"
                        + mapping.zkClusterKey + "	";
                    $("#namespace_zkcluster_manager_table tbody").append("
" + baseTd + "
");
	            }
	        }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
        namespace_zkcluster_manager_table_DataTable = $("#namespace_zkcluster_manager_table").DataTable({
            "oLanguage": language,
            "aoColumnDefs": [{"bSortable":false,"aTargets":[0]}], // set the first column unSort
            "aaSorting": [[1, "desc"]], // set sort from the second column
            "displayLength":100
            });
        $("#namespace_zkcluster_manager_table_filter label").before(namespace_zkcluster_manager_operation);

        $("#init-namespace-zkcluster-mapping").on("click", function() {
            $("#confirm-yes-dialog-title").html('确认初始化映射表，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    var $btn = $(this).button('loading');
                    $.post("registry_center/initNamespaceZkClusterMapping", {}, function(data) {
                        $("#confirm-yes-dialog").modal("hide");
                        if(data.success) {
                            showSuccessDialog();
                            refreshNamespaceZkClusterMappingList();
                        } else {
                            showFailureDialogWithMsg("failure-dialog", data.message);
                        }
                    }).always(function() {$btn.button('reset');});
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });

        $("#batch-move-namespace").on("click", function() {
            var namespaces = "";
            $(".batchInput").each(function() {
                if($(this).is(":checked")) {
                    if(namespaces == "") {
                        namespaces = $(this).attr("namespace") ;
                    } else {
                        namespaces = namespaces + "," + $(this).attr("namespace") ;
                    }
                }
            });
            if(namespaces == "") {
                showFailureDialogWithMsg("failure-dialog", "请选择要迁移的域");
            } else {
                $.get("registry_center/getZkClusterListWithOnline", {}, function(data) {
                    if(data.success) {
                        $("#move-namespace-batch-dialog-namespace").html(namespaces);
                        $.get("registry_center/getZkClusterListWithOnline", {}, function(data2) {
                            if(data2.success) {
                                var zkClusterListWithOnlineFromCfg = data2.obj;
                                var options = "";
                                if(zkClusterListWithOnlineFromCfg && zkClusterListWithOnlineFromCfg instanceof Array) {
                                    for(var i in zkClusterListWithOnlineFromCfg) {
                                        var zkClusterWithOnlineFromCfg = zkClusterListWithOnlineFromCfg[i];
                                        options += "<option value='"+ zkClusterWithOnlineFromCfg +"'>" + zkClusterWithOnlineFromCfg + "</option>";
                                    }
                                }
                                $("#move-namespace-batch-dialog-zkCluster").empty();
                                $("#move-namespace-batch-dialog-zkCluster").append(options);
                                $("#move-namespace-batch-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-dialog").modal("show");
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        showFailureDialogWithMsg("failure-dialog", data.message);
                    }
                });
            }
        });
    }).always(function() { $loading.hide(); });
}

function clickNamespace_zkcluster_manager_table_select_all(obj){
	var chooseCheckBox = $(obj).is(":checked");
	if(!chooseCheckBox){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
		return false;
	}
	var checkChoose = true;
	$(".batchInput").each(function(){
    	if(!$(this).is(":checked")){
    		checkChoose = false;
		}
	});
	if(checkChoose){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',true);// 只有全部都选中，全选复选框才置为true
	}else{
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
	}
}

function refreshZkClusterInfo() {
    $loading.show();
    $.get("registry_center/getAllZkClusterInfo", {}, function(data) {
        if(data.success) {
            if(zk_cluster_info_table_DataTable) {
                zk_cluster_info_table_DataTable.destroy();
            }
            $("#zk_cluster_info_table tbody").empty();
            var list = data.obj;
            if(list && list instanceof Array) {
                for(var i=0; i<list.length; i++) {
                    var zkClusterInfo = list[i];
                    var baseTd = "" + zkClusterInfo.zkClusterKey + "	" +
                                "" + zkClusterInfo.alias + "	" +
                                "" + zkClusterInfo.connectString + "	";
                    $("#zk_cluster_info_table tbody").append("
" + baseTd + "
");
                }
            }
            zk_cluster_info_table_DataTable = $("#zk_cluster_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function getMoveNamespaceBatchStatus(id) {
    $.get("registry_center/getMoveNamespaceBatchStatus", {id: id}, function(data) {
        if(data.success) {
            var status = data.obj;
            $("#move-namespace-batch-status-dialog-data").html("成功：" + status.successCount + "
失败：" + status.failCount + "
忽略：" + status.ignoreCount + "
未做：" + status.unDoCount + "
总共：" + status.totalCount);
            var message = "失败的域：";
            var failList = status.failList;
            if(failList.length > 0) {
                message = message + failList;
            } else {
                message = message + "无";
            }
            message = message + "
忽略的域：";
            var ignoreList = status.ignoreList;
            if(ignoreList.length > 0) {
                message = message + ignoreList;
            } else {
                message = message + "无";
            }
            $("#move-namespace-batch-status-dialog-message").html(message);
            if(!status.finished) {
                $("#move-namespace-batch-status-dialog-moving").html(status.moving);
                getMoveNamespaceBatchStatus(id);
            } else {
                $("#move-namespace-batch-status-dialog-moving").html("无");
                $("#move-namespace-batch-status-dialog-tips").css("display", "none");
                $("#move-namespace-batch-status-dialog-x").css("display", "inline");
            }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
            $("#move-namespace-batch-status-dialog-x").attr("id2", id);
            $("#move-namespace-batch-status-dialog-tips").css("display", "none");
            $("#move-namespace-batch-status-dialog-x").css("display", "inline");
        }
    });
}
<commit_msg>#190 support the selection of zkClusterKey<commit_after>var namespace_info_table_DataTable, zk_cluster_info_table_DataTable, namespace_zkcluster_manager_table_DataTable;
var namespace_zkcluster_manager_operation = '【请务必同时只能一个人并且只使用一个浏览器来操作】  ' +
                                            '<button class="btn btn-success" id="batch-move-namespace">批量迁移</button>  ' +
                                            '<button class="btn btn-warning" id="init-namespace-zkcluster-mapping">初始化映射表</button>  ';
$(function() {
    window.parent.setActiveTab("#regTab");
	window.parent.releaseRegName();

	$("#refresh_registry_center").on("click", function() {
		var $btn = $(this).button("loading");
		$.get("registry_center/refreshRegCenter", function(data) {
			if(data.success == true) {
				window.parent.reloadTreeData();
                window.parent.contentFrame.location.href="registry_center_page";
			} else {
				showFailureDialogWithMsg("failure-dialog", data.message);
			}
		}).always(function() { $btn.button('reset'); });
	});

	$('[href="#namespace_info_tabpanel"]').on("click", function() {
		refreshNamespaceInfo();
    });
	$('[href="#zk_cluster_info_tabpanel"]').on("click", function() {
		refreshZkClusterInfo();
	});
	$('[href="#namespace_zkcluster_manager_tabpanel"]').on("click", function() {
		refreshNamespaceZkClusterMappingList();
    });
	if ($("#namespace_info_tabpanel").is(':visible')) {
		refreshNamespaceInfo();
	} else if ($("#zk_cluster_info_tabpanel").is(':visible')) {
		refreshZkClusterInfo();
	} else if ($("#namespace_zkcluster_manager_tabpanel").is(':visible')) {
		refreshNamespaceZkClusterMappingList();
	}

	$("#namespace_zkcluster_manager_table_select_all").on('click', function(event) {
	    if($(this).is(":checked")){
            $('.batchInput').prop('checked',true);// jquery1.9以后的版本，用attr有点问题，要用prop
        }else{
            $('.batchInput').prop('checked',false);
        }
    });

    $("#move-namespace-batch-dialog").on("shown.bs.modal", function (event) {
        $("#move-namespace-batch-dialog-confirm-btn").unbind('click').click(function() {
            var namespaces = $("#move-namespace-batch-dialog-namespace").html();
            var zkClusterKeyNew = "";
            if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
                zkClusterKeyNew = $("#move-namespace-batch-dialog-zkCluster").val();
            } else {
                zkClusterKeyNew = $("#move-namespace-batch-dialog-zkCluster-input").val();
            }
            var updateDBOnly = $("#move-namespace-batch-dialog-updateDBOnly").is(":checked");
            $("#confirm-yes-dialog-title").html('域名：
' + namespaces + '
目标集群：
' + zkClusterKeyNew + '
只更新映射表：
' + updateDBOnly + '
确认批量迁移，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    $("#move-namespace-batch-dialog").modal("hide");
                    $("#confirm-yes-dialog").modal("hide");
                    $("#move-namespace-batch-status-dialog-zkCluster").html(zkClusterKeyNew);
                    var split = namespaces.split(",");
                    if(split && split instanceof Array) {
                        var id = parseInt(Math.random() * 10000000);
                        $.post("registry_center/moveNamespaceBatch", {namespaces: namespaces, zkClusterKeyNew: zkClusterKeyNew, updateDBOnly: updateDBOnly, id: id}, function(data) {
                            if(data.success) {
                                var size = split.length;
                                $("#move-namespace-batch-status-dialog-data").html("成功：" + 0 + "
失败：" + 0 + "
忽略：" + 0 + "
未做：" + size + "
总共：" + size);
                                $("#move-namespace-batch-status-dialog-message").html("");
                                $("#move-namespace-batch-status-dialog-tips").css("display", "inline");
                                $("#move-namespace-batch-status-dialog-x").css("display", "none");
                                $("#move-namespace-batch-status-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-status-dialog").modal("show");
                                getMoveNamespaceBatchStatus(id);
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        alert("请选择要迁移的域");
                    }
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });
    });

    $("#move-namespace-batch-dialog-manual").on('click', function(event) {
        if($("#move-namespace-batch-dialog-manual").attr("status") == "auto") {
            $("#move-namespace-batch-dialog-zkCluster").attr("style", "display:none");
            $("#move-namespace-batch-dialog-zkCluster-input").removeAttr("style");
            $("#move-namespace-batch-dialog-manual").attr("status", "manual");
            $("#move-namespace-batch-dialog-manual").html("在线的集群");
        } else {
            $("#move-namespace-batch-dialog-zkCluster").removeAttr("style");
            $("#move-namespace-batch-dialog-zkCluster-input").attr("style", "display:none");
            $("#move-namespace-batch-dialog-manual").attr("status", "auto");
            $("#move-namespace-batch-dialog-manual").html("手动输入");
        }
    });

    $("#confirm-yes-dialog").on("shown.bs.modal", function (event) {
        $("#giveMeYes").focus();
    });

    $("#move-namespace-batch-status-dialog-x").on("click", function() {
        $("#move-namespace-batch-status-dialog").modal("hide");
        var id = parseInt($("#move-namespace-batch-status-dialog-x").attr("id2"));
        if(!isNaN(id)) {
            $.post("registry_center/clearMoveNamespaceBatchStatus", {id: id}, function(data) {});
        }
        refreshNamespaceZkClusterMappingList();
    });

    refreshNamespaceInfo();
});

function refreshNamespaceInfo() {
    $loading.show();
	$.get("registry_center/getNamespaceInfo", {}, function(data) {
		if(namespace_info_table_DataTable) {
			namespace_info_table_DataTable.destroy();
		}
        $("#namespace_info_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var cluster = list[i];
            		var key = cluster.zkClusterKey;
            		var regCenterConfList = cluster.regCenterConfList;
            		if(regCenterConfList && regCenterConfList instanceof Array) {
            			for(var j=0; j < regCenterConfList.length; j++) {
	        				var regCenterConf = regCenterConfList[j];
			                var baseTd = "" + regCenterConf.namespace + "	"
			                    + regCenterConf.name + "	"
			                    + regCenterConf.version + "	"
			                    + key + "	";
			                $("#namespace_info_table tbody").append("
" + baseTd + "
");
            			}
            		}
	            }
	        }
	        namespace_info_table_DataTable = $("#namespace_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function refreshNamespaceZkClusterMappingList() {
    $loading.show();
	$.get("registry_center/getNamespaceZkclusterMappingList", {}, function(data) {
		if(namespace_zkcluster_manager_table_DataTable) {
			namespace_zkcluster_manager_table_DataTable.destroy();
		}
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);
        $("#namespace_zkcluster_manager_table tbody").empty();
        if(data.success) {
    		var list = data.obj;
	        if(list && list instanceof Array) {
	            for (var i = 0;i < list.length;i++) {
            		var mapping = list[i];
                    var baseTd = "<input class='batchInput' type='checkbox' onclick='clickNamespace_zkcluster_manager_table_select_all(this);' namespace='" + mapping.namespace + "'/>	"
                        + "" + mapping.namespace + "	"
                        + mapping.zkClusterKey + "	";
                    $("#namespace_zkcluster_manager_table tbody").append("
" + baseTd + "
");
	            }
	        }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
        namespace_zkcluster_manager_table_DataTable = $("#namespace_zkcluster_manager_table").DataTable({
            "oLanguage": language,
            "aoColumnDefs": [{"bSortable":false,"aTargets":[0, 2]}], // set the 0,2 column unSort
            "aaSorting": [[1, "asc"]], // set sort from the second column
            "displayLength":100,
            "initComplete": function () {
                var column = this.api().column(2);
                var column_header = $(column.header());
                column_header.find("select").remove();
                var select = $('<select><option value=""></option></select>')
                    .appendTo( column_header )
                    .on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex($(this).val());
                        column.search( val ? '^'+val+'$' : '', true, false ).draw();
                    } );
                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                } );
            }
        });
        $("#namespace_zkcluster_manager_table_filter label").before(namespace_zkcluster_manager_operation);

        $("#init-namespace-zkcluster-mapping").on("click", function() {
            $("#confirm-yes-dialog-title").html('确认初始化映射表，请输入yes！');
            $("#giveMeYes").val("");
            $("#confirm-yes-dialog-confirm-btn").unbind('click').on("click", function() {
                var yes = $("#giveMeYes").val();
                if (yes === "yes") {
                    var $btn = $(this).button('loading');
                    $.post("registry_center/initNamespaceZkClusterMapping", {}, function(data) {
                        $("#confirm-yes-dialog").modal("hide");
                        if(data.success) {
                            showSuccessDialog();
                            refreshNamespaceZkClusterMappingList();
                        } else {
                            showFailureDialogWithMsg("failure-dialog", data.message);
                        }
                    }).always(function() {$btn.button('reset');});
                } else {
                    alert("确认请输入yes");
                }
            });
            $("#confirm-yes-dialog").modal({backdrop:"static", keyboard: false});
            $("#confirm-yes-dialog").modal("show");
        });

        $("#batch-move-namespace").on("click", function() {
            var namespaces = "";
            $(".batchInput").each(function() {
                if($(this).is(":checked")) {
                    if(namespaces == "") {
                        namespaces = $(this).attr("namespace") ;
                    } else {
                        namespaces = namespaces + "," + $(this).attr("namespace") ;
                    }
                }
            });
            if(namespaces == "") {
                showFailureDialogWithMsg("failure-dialog", "请选择要迁移的域");
            } else {
                $.get("registry_center/getZkClusterListWithOnline", {}, function(data) {
                    if(data.success) {
                        $("#move-namespace-batch-dialog-namespace").html(namespaces);
                        $.get("registry_center/getZkClusterListWithOnline", {}, function(data2) {
                            if(data2.success) {
                                var zkClusterListWithOnlineFromCfg = data2.obj;
                                var options = "";
                                if(zkClusterListWithOnlineFromCfg && zkClusterListWithOnlineFromCfg instanceof Array) {
                                    for(var i in zkClusterListWithOnlineFromCfg) {
                                        var zkClusterWithOnlineFromCfg = zkClusterListWithOnlineFromCfg[i];
                                        options += "<option value='"+ zkClusterWithOnlineFromCfg +"'>" + zkClusterWithOnlineFromCfg + "</option>";
                                    }
                                }
                                $("#move-namespace-batch-dialog-zkCluster").empty();
                                $("#move-namespace-batch-dialog-zkCluster").append(options);
                                $("#move-namespace-batch-dialog").modal({backdrop:"static", keyboard: false});
                                $("#move-namespace-batch-dialog").modal("show");
                            } else {
                                showFailureDialogWithMsg("failure-dialog", data.message);
                            }
                        });
                    } else {
                        showFailureDialogWithMsg("failure-dialog", data.message);
                    }
                });
            }
        });
    }).always(function() { $loading.hide(); });
}

function clickNamespace_zkcluster_manager_table_select_all(obj){
	var chooseCheckBox = $(obj).is(":checked");
	if(!chooseCheckBox){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
		return false;
	}
	var checkChoose = true;
	$(".batchInput").each(function(){
    	if(!$(this).is(":checked")){
    		checkChoose = false;
		}
	});
	if(checkChoose){
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',true);// 只有全部都选中，全选复选框才置为true
	}else{
		$("#namespace_zkcluster_manager_table_select_all").prop('checked',false);// 只要有一个没选中，全选复选框就置为false
	}
}

function refreshZkClusterInfo() {
    $loading.show();
    $.get("registry_center/getAllZkClusterInfo", {}, function(data) {
        if(data.success) {
            if(zk_cluster_info_table_DataTable) {
                zk_cluster_info_table_DataTable.destroy();
            }
            $("#zk_cluster_info_table tbody").empty();
            var list = data.obj;
            if(list && list instanceof Array) {
                for(var i=0; i<list.length; i++) {
                    var zkClusterInfo = list[i];
                    var baseTd = "" + zkClusterInfo.zkClusterKey + "	" +
                                "" + zkClusterInfo.alias + "	" +
                                "" + zkClusterInfo.connectString + "	";
                    $("#zk_cluster_info_table tbody").append("
" + baseTd + "
");
                }
            }
            zk_cluster_info_table_DataTable = $("#zk_cluster_info_table").DataTable({"oLanguage": language, "displayLength":100});
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
        }
    }).always(function() { $loading.hide(); });
}

function getMoveNamespaceBatchStatus(id) {
    $.get("registry_center/getMoveNamespaceBatchStatus", {id: id}, function(data) {
        if(data.success) {
            var status = data.obj;
            $("#move-namespace-batch-status-dialog-data").html("成功：" + status.successCount + "
失败：" + status.failCount + "
忽略：" + status.ignoreCount + "
未做：" + status.unDoCount + "
总共：" + status.totalCount);
            var message = "失败的域：";
            var failList = status.failList;
            if(failList.length > 0) {
                message = message + failList;
            } else {
                message = message + "无";
            }
            message = message + "
忽略的域：";
            var ignoreList = status.ignoreList;
            if(ignoreList.length > 0) {
                message = message + ignoreList;
            } else {
                message = message + "无";
            }
            $("#move-namespace-batch-status-dialog-message").html(message);
            if(!status.finished) {
                $("#move-namespace-batch-status-dialog-moving").html(status.moving);
                getMoveNamespaceBatchStatus(id);
            } else {
                $("#move-namespace-batch-status-dialog-moving").html("无");
                $("#move-namespace-batch-status-dialog-tips").css("display", "none");
                $("#move-namespace-batch-status-dialog-x").css("display", "inline");
            }
        } else {
            showFailureDialogWithMsg("failure-dialog", data.message);
            $("#move-namespace-batch-status-dialog-x").attr("id2", id);
            $("#move-namespace-batch-status-dialog-tips").css("display", "none");
            $("#move-namespace-batch-status-dialog-x").css("display", "inline");
        }
    });
}
<|endoftext|>


<commit_before>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.view.people.details.Courses', {
    extend: 'SlateAdmin.view.people.details.AbstractDetails',
    xtype: 'people-details-courses',
    requires: [
        'Ext.grid.Panel',
        'Ext.grid.column.Template',
        'Ext.form.field.ComboBox',
        'Slate.model.course.SectionParticipant',
        'Slate.proxy.courses.SectionParticipants'
    ],

    title: 'Courses',
    glyph: 0xf073,
    itemId: 'courses',

    // panel config
    layout: 'fit',

    tbar: [{
        xtype: 'combobox',
        fieldLabel: 'Term',
        labelWidth: 36,
        editable: false,
        emptyText: 'Current Term',
        valueField: 'ID',
        flex: 1,
        itemId: 'courseTermSelector',
        queryMode: 'local',
        name: 'courseTermSelector',
        displayField: 'Title',
        store: 'Terms'
    }],

    items: {
        xtype: 'grid',
        border: false,
        viewConfig: {
            emptyText: 'No courses for selected term',
            getRowClass: function(record){
                return record.get('isInactive') === true ? 'participant-inactive' : '';
            }
        },
        plugins: {
            ptype: 'cellediting',
            clicksToEdit: 1
        },
        store: {
            model: 'Slate.model.course.SectionParticipant',
            proxy: {
                type: 'slate-courses-participants',
                include: ['Section.Location', 'Section.Schedule', 'Section.Term']
            },
            pageSize: 0,
            sorters: [{
                property: 'isInactive',
                direction: 'ASC'
            }],
            autoSync: true
        },
        columns: {
            defaults: {
                menuDisabled: true
            },
            items: [{
                width: 120,

                header: 'Section',
                dataIndex: 'Code',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section">{Code}</tpl>'
            },{
                width: 110,

                xtype: 'datecolumn',
                header: 'Start',
                dataIndex: 'StartDate',
                format:'Y-m-d',
                editor: 'datefield'
            },{
                width: 110,

                xtype: 'datecolumn',
                header: 'End',
                dataIndex: 'EndDate',
                format:'Y-m-d',
                editor: 'datefield'
            },{
                flex: 2,

                header: 'Term',
                dataIndex: 'Term',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Term">{Handle}</tpl></tpl>'
            },{
                flex: 2,

                header: 'Schedule',
                dataIndex: 'Schedule',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Schedule">{Title}</tpl></tpl>'
            },{
                flex: 2,

                header: 'Location',
                dataIndex: 'Location',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Location">{Title}</tpl></tpl>'
            }]
        }
    }
});<commit_msg>feat: enable column menus and statefulness for a person's courses grid<commit_after>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.view.people.details.Courses', {
    extend: 'SlateAdmin.view.people.details.AbstractDetails',
    xtype: 'people-details-courses',
    requires: [
        'Ext.grid.Panel',
        'Ext.grid.column.Template',
        'Ext.form.field.ComboBox',
        'Slate.model.course.SectionParticipant',
        'Slate.proxy.courses.SectionParticipants'
    ],

    title: 'Courses',
    glyph: 0xf073,
    itemId: 'courses',

    // panel config
    layout: 'fit',

    tbar: [{
        xtype: 'combobox',
        fieldLabel: 'Term',
        labelSeparator: '',
        labelWidth: 36,
        editable: false,
        emptyText: 'Current Term',
        valueField: 'ID',
        flex: 1,
        itemId: 'courseTermSelector',
        queryMode: 'local',
        name: 'courseTermSelector',
        displayField: 'Title',
        store: 'Terms'
    }],

    items: {
        xtype: 'grid',
        border: false,
        stateful: true,
        stateId: 'peopleCoursesGrid',
        viewConfig: {
            emptyText: 'No courses for selected term',
            getRowClass: function(record){
                return record.get('isInactive') === true ? 'participant-inactive' : '';
            }
        },
        plugins: {
            ptype: 'cellediting',
            clicksToEdit: 1
        },
        store: {
            model: 'Slate.model.course.SectionParticipant',
            proxy: {
                type: 'slate-courses-participants',
                include: ['Section.Location', 'Section.Schedule', 'Section.Term']
            },
            pageSize: 0,
            sorters: [{
                property: 'isInactive',
                direction: 'ASC'
            }],
            autoSync: true
        },
        columns: {
            items: [{
                width: 120,

                header: 'Section',
                dataIndex: 'Code',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section">{Code}</tpl>'
            },{
                width: 110,

                xtype: 'datecolumn',
                header: 'Start',
                dataIndex: 'StartDate',
                format:'Y-m-d',
                editor: 'datefield'
            },{
                width: 110,

                xtype: 'datecolumn',
                header: 'End',
                dataIndex: 'EndDate',
                format:'Y-m-d',
                editor: 'datefield'
            },{
                flex: 2,

                header: 'Term',
                dataIndex: 'Term',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Term">{Handle}</tpl></tpl>'
            },{
                flex: 2,

                header: 'Schedule',
                dataIndex: 'Schedule',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Schedule">{Title}</tpl></tpl>'
            },{
                flex: 2,

                header: 'Location',
                dataIndex: 'Location',
                xtype: 'templatecolumn',
                tpl: '<tpl for="Section"><tpl for="Location">{Title}</tpl></tpl>'
            }]
        }
    }
});
<|endoftext|>