<commit_before>var app=angular.module('login',[]);
app.controller('auth',function($scope){});
var app=angular.module('registration',[]);
app.controller('create',function($scope){
    $scope.validateForm=function(){
        var fullname=$.trim(document.accountform.user_name.value);
        if(fullname!=""){
            var email=$.trim(document.accountform.user_email.value);
            if(email!=""){
                var pass1=document.accountform.user_password.value;
                if(pass1.length>=8){
                    var pass2=document.accountform.user_password2.value;
                    if(pass2===pass1){
                        $(".btn-primary").addClass("disabled");
                        document.accountform.submit();
                    }
                    else{
                        messageBox("Password Mismatch","Please ensure that the password you repeat matches the first password.");
                    }
                }
                else{
                    messageBox("Invalid Password","Please enter a valid password with at least 8 characters.");
                }
            }
            else{
                messageBox("Invalid Email","Please enter a valid email ID.");
            }
        }
        else{
            messageBox("Invalid Name","Please enter a valid full name.");
        }
    };
});
var app=angular.module('applications',[]);
app.controller('apps',function($scope,$http,$compile){
    $scope.applicationArray=[];
    $scope.application_id=null;
    $scope.appCount=0;
    $scope.getApplications=function(){
        $http({
            method: 'GET',
            url: 'getApplications'
        }).then(function success(response){
            if(typeof response=='object'){
                console.log("here");
                $scope.applicationArray=response.slice();
                $scope.displayApplications();
            }
            else{
                response=$.trim(response);
                if((response!="")&&(response!="INVALID_PARAMETERS")){
                    if(response=="INVALID_USER_ID"){
                        window.location='logout';
                    }
                    else if(response=="NO_APPLICATIONS_FOUND"){
                        var p=document.createElement("p");
                        $(p).html("No applications found.");
                        $("#appHolder").html(p);
                    }
                    else{
                        messageBox("Problem","Something went wrong while loading your list of applications. This is the error we see: "+response);
                    }
                }
                else{
                    messageBox("Problem","Something went wrong while loading your list of applications.");
                }
            }
        }, function error(response){
            messageBox("Problem","Something went wrong while loading your list of applications. Please try again later. This is the error we see: "+response);
        });
    };
    $scope.displayApplications=function(){
        var applications=$scope.applicationArray.slice();
        if(applications.length>0){
            var count=applications.length;
            $("#appCount").html(count);
            var table=document.createElement("table");
            $(table).addClass("table");
                var thead=document.createElement("thead");
                    var tr1=document.createElement("tr");
                        var th1=document.createElement("th");
                        $(th).html("Title");
                    $(tr1).append(th);
                        var th2=document.createElement("th");
                        $(th2).html("Descriptiom");
                    $(tr1).append(th2);
                        var th3=document.createElement("th");
                        $(th3).html("Status");
                    $(tr1).append(th3);
                $(thead).append(tr1);
            $(table).append(thead);
                var tbody=document.createElement("tbody");
            for(var i=0;i<applications.length;i++){
                var application=applications[i];
                var appID=application.idapplication_master;
                var appTitle=application.application_title;
                var appDesc=application.application_description;
                var stat=application.stat;
                if(stat==1){
                    stat='Live';
                }
                else if(stat==2){
                    stat='Incomplete';
                }
                else{
                    stat='Deleted';
                }
                var tr=document.createElement("tr");
                    var td1=document.createElement("td");
                    $(td1).html(appTitle);
                $(tr).append(td1);
                    var td2=document.createElement("td");
                    $(td2).html(appDesc);
                $(tr).append(td2);
                    var td3=document.createElement("td");
                    $(td3).html(stat);
                $(tr).append(td3);
                $(tbody).append(tr);
            }
            $(table).append(tbody);
            $("#appHolder").html(table);
        }
        else{
            var p=document.createElement("p");
            $(p).html("No applications found.");
            $("#appHolder").html(p);
        }
    };
    $scope.createApplicationForm=function(){
        var form=document.createElement("form");
        $(form).attr("autocomplete","off");
        $(form).attr("name","createapp");
            var appTitleGroup=document.createElement("div");
            $(appTitleGroup).addClass("form-group");
            $(appTitleGroup).attr("id","apptitlegroup");
                var appTitleLabel=document.createElement("label");
                $(appTitleLabel).attr("for","apptitle");
                $(appTitleLabel).html("Application title");
                $(appTitleGroup).append(appTitleLabel);
                var appTitle=document.createElement("input");
                $(appTitle).attr("type","text");
                $(appTitle).addClass("form-control");
                $(appTitle).attr("id","apptitle");
                $(appTitle).attr("name","apptitle");
                $(appTitle).attr("placeholder","Enter a valid application name");
                $(appTitle).attr("required","true");
                $(appTitleGroup).append(appTitle);
            $(form).append(appTitleGroup);
            var appDescGroup=document.createElement("div");
            $(appDescGroup).addClass("form-group");
            $(appDescGroup).attr("id","appdescgroup");
                var appDescLabel=document.createElement("label");
                $(appDescLabel).attr("for","appdesc");
                $(appDescLabel).html("Application description");
                $(appDescGroup).append(appDescLabel);
                var appDescTA=document.createElement("textarea");
                $(appDescTA).addClass("form-control");
                $(appDescTA).attr("rows","5");
                $(appDescTA).attr("id","appdesc");
                $(appDescTA).attr("name","appdesc");
                $(appDescTA).attr("placeholder","Enter some description of this application.");
                $(appDescGroup).append(appDescTA);
            $(form).append(appDescGroup);
            var button=document.createElement("button");
            $(button).attr("type","button");
            $(button).addClass("btn btn-primary");
            $(button).attr("ng-click","createApplication()");
            $(button).html("Create");
            $(form).append(button);
        messageBox("Create Application",form);
        $compile("#myModal")($scope);
        $("#apptitle").focus();
    };
    $scope.createApplication=function(){
        var appTitle=$.trim(document.createapp.apptitle.value);
        if(appTitle!=""){
            $("#apptitlegroup").removeClass("has-error");
            var appDesc=$.trim(document.createapp.appdesc.value);
            if(appDesc!=""){
                $("#appdescgroup").removeClass("has-error");
                var dt=new Date().getTime();
                $.ajax({
                    url:"createApplication",
                    method: "POST",
                    data: {
                        application_title: appTitle,
                        application_description: appDesc,
                        dt: dt
                    },
                    error: function(xhr,stat,err){
                        messageBox("Problem","Something went wrong while creating this application. Please try again in a bit. This is the error we see: "+err);
                    },
                    success:function(responseText){
                        responseText=$.trim(responseText);
                        $("#myModal").find(".btn-primary").removeClass("disabled");
                        if((responseText!="")&&(responseText!=null)&&(responseText!=undefined)&&(responseText!="INVALID_PARAMETERS")){
                            if(responseText=="INVALID_USER_ID"){
                                window.location="logout";
                            }
                            else if(responseText=="INVALID_APPLICATION_TITLE"){
                                $("#apptitlegroup").addClass("has-error");
                            }
                            else if(responseText=="INVALID_APPLICATION_DESCRIPTION"){
                                $("#appdescgroup").addClass("has-error");
                            }
                            else if(responseText=="APPLICATION_ALREADY_EXISTS"){
                                messageBox("Application Exists","This application already exists.");
                            }
                            else if(responseText=="APPLICATION_CREATED"){
                                messageBox("Application Created","Your application was created successfully. Once you add fields to your application, you may make it live so that potential candidates may see it.");
                                $scope.getApplications();
                            }
                            else{
                                messageBox("Problem","Something went wrong while creating your application. This is the error we see: "+responseText);
                            }
                        }
                        else{
                            messageBox("Problem","Something went wrong while searching for workspaces. Please try again in a bit. This is the error we see: "+err,0);
                        }
                    },
                    beforeSend:function(){
                        $("#myModal").find(".btn-primary").addClass("disabled");
                    }
                });
            }
            else{
                $("#appdescgroup").addClass("has-error");
            }
        }
        else{
            $("#apptitlegroup").addClass("has-error");
        }
    };
});<commit_msg>Applications display<commit_after>var app=angular.module('login',[]);
app.controller('auth',function($scope){});
var app=angular.module('registration',[]);
app.controller('create',function($scope){
    $scope.validateForm=function(){
        var fullname=$.trim(document.accountform.user_name.value);
        if(fullname!=""){
            var email=$.trim(document.accountform.user_email.value);
            if(email!=""){
                var pass1=document.accountform.user_password.value;
                if(pass1.length>=8){
                    var pass2=document.accountform.user_password2.value;
                    if(pass2===pass1){
                        $(".btn-primary").addClass("disabled");
                        document.accountform.submit();
                    }
                    else{
                        messageBox("Password Mismatch","Please ensure that the password you repeat matches the first password.");
                    }
                }
                else{
                    messageBox("Invalid Password","Please enter a valid password with at least 8 characters.");
                }
            }
            else{
                messageBox("Invalid Email","Please enter a valid email ID.");
            }
        }
        else{
            messageBox("Invalid Name","Please enter a valid full name.");
        }
    };
});
var app=angular.module('applications',[]);
app.controller('apps',function($scope,$http,$compile){
    $scope.applicationArray=[];
    $scope.application_id=null;
    $scope.appCount=0;
    $scope.getApplications=function(){
        $http({
            method: 'GET',
            url: 'getApplications'
        }).then(function success(response){
            if(typeof response=='object'){
                console.log("here");
                $scope.applicationArray=response;
                $scope.displayApplications();
            }
            else{
                response=$.trim(response);
                if((response!="")&&(response!="INVALID_PARAMETERS")){
                    if(response=="INVALID_USER_ID"){
                        window.location='logout';
                    }
                    else if(response=="NO_APPLICATIONS_FOUND"){
                        var p=document.createElement("p");
                        $(p).html("No applications found.");
                        $("#appHolder").html(p);
                    }
                    else{
                        messageBox("Problem","Something went wrong while loading your list of applications. This is the error we see: "+response);
                    }
                }
                else{
                    messageBox("Problem","Something went wrong while loading your list of applications.");
                }
            }
        }, function error(response){
            messageBox("Problem","Something went wrong while loading your list of applications. Please try again later. This is the error we see: "+response);
        });
    };
    $scope.displayApplications=function(){
        var applications=$scope.applicationArray.slice();
        if(applications.length>0){
            var count=applications.length;
            $("#appCount").html(count);
            var table=document.createElement("table");
            $(table).addClass("table");
                var thead=document.createElement("thead");
                    var tr1=document.createElement("tr");
                        var th1=document.createElement("th");
                        $(th).html("Title");
                    $(tr1).append(th);
                        var th2=document.createElement("th");
                        $(th2).html("Descriptiom");
                    $(tr1).append(th2);
                        var th3=document.createElement("th");
                        $(th3).html("Status");
                    $(tr1).append(th3);
                $(thead).append(tr1);
            $(table).append(thead);
                var tbody=document.createElement("tbody");
            for(var i=0;i<applications.length;i++){
                var application=applications[i];
                var appID=application.idapplication_master;
                var appTitle=application.application_title;
                var appDesc=application.application_description;
                var stat=application.stat;
                if(stat==1){
                    stat='Live';
                }
                else if(stat==2){
                    stat='Incomplete';
                }
                else{
                    stat='Deleted';
                }
                var tr=document.createElement("tr");
                    var td1=document.createElement("td");
                    $(td1).html(appTitle);
                $(tr).append(td1);
                    var td2=document.createElement("td");
                    $(td2).html(appDesc);
                $(tr).append(td2);
                    var td3=document.createElement("td");
                    $(td3).html(stat);
                $(tr).append(td3);
                $(tbody).append(tr);
            }
            $(table).append(tbody);
            $("#appHolder").html(table);
        }
        else{
            var p=document.createElement("p");
            $(p).html("No applications found.");
            $("#appHolder").html(p);
        }
    };
    $scope.createApplicationForm=function(){
        var form=document.createElement("form");
        $(form).attr("autocomplete","off");
        $(form).attr("name","createapp");
            var appTitleGroup=document.createElement("div");
            $(appTitleGroup).addClass("form-group");
            $(appTitleGroup).attr("id","apptitlegroup");
                var appTitleLabel=document.createElement("label");
                $(appTitleLabel).attr("for","apptitle");
                $(appTitleLabel).html("Application title");
                $(appTitleGroup).append(appTitleLabel);
                var appTitle=document.createElement("input");
                $(appTitle).attr("type","text");
                $(appTitle).addClass("form-control");
                $(appTitle).attr("id","apptitle");
                $(appTitle).attr("name","apptitle");
                $(appTitle).attr("placeholder","Enter a valid application name");
                $(appTitle).attr("required","true");
                $(appTitleGroup).append(appTitle);
            $(form).append(appTitleGroup);
            var appDescGroup=document.createElement("div");
            $(appDescGroup).addClass("form-group");
            $(appDescGroup).attr("id","appdescgroup");
                var appDescLabel=document.createElement("label");
                $(appDescLabel).attr("for","appdesc");
                $(appDescLabel).html("Application description");
                $(appDescGroup).append(appDescLabel);
                var appDescTA=document.createElement("textarea");
                $(appDescTA).addClass("form-control");
                $(appDescTA).attr("rows","5");
                $(appDescTA).attr("id","appdesc");
                $(appDescTA).attr("name","appdesc");
                $(appDescTA).attr("placeholder","Enter some description of this application.");
                $(appDescGroup).append(appDescTA);
            $(form).append(appDescGroup);
            var button=document.createElement("button");
            $(button).attr("type","button");
            $(button).addClass("btn btn-primary");
            $(button).attr("ng-click","createApplication()");
            $(button).html("Create");
            $(form).append(button);
        messageBox("Create Application",form);
        $compile("#myModal")($scope);
        $("#apptitle").focus();
    };
    $scope.createApplication=function(){
        var appTitle=$.trim(document.createapp.apptitle.value);
        if(appTitle!=""){
            $("#apptitlegroup").removeClass("has-error");
            var appDesc=$.trim(document.createapp.appdesc.value);
            if(appDesc!=""){
                $("#appdescgroup").removeClass("has-error");
                var dt=new Date().getTime();
                $.ajax({
                    url:"createApplication",
                    method: "POST",
                    data: {
                        application_title: appTitle,
                        application_description: appDesc,
                        dt: dt
                    },
                    error: function(xhr,stat,err){
                        messageBox("Problem","Something went wrong while creating this application. Please try again in a bit. This is the error we see: "+err);
                    },
                    success:function(responseText){
                        responseText=$.trim(responseText);
                        $("#myModal").find(".btn-primary").removeClass("disabled");
                        if((responseText!="")&&(responseText!=null)&&(responseText!=undefined)&&(responseText!="INVALID_PARAMETERS")){
                            if(responseText=="INVALID_USER_ID"){
                                window.location="logout";
                            }
                            else if(responseText=="INVALID_APPLICATION_TITLE"){
                                $("#apptitlegroup").addClass("has-error");
                            }
                            else if(responseText=="INVALID_APPLICATION_DESCRIPTION"){
                                $("#appdescgroup").addClass("has-error");
                            }
                            else if(responseText=="APPLICATION_ALREADY_EXISTS"){
                                messageBox("Application Exists","This application already exists.");
                            }
                            else if(responseText=="APPLICATION_CREATED"){
                                messageBox("Application Created","Your application was created successfully. Once you add fields to your application, you may make it live so that potential candidates may see it.");
                                $scope.getApplications();
                            }
                            else{
                                messageBox("Problem","Something went wrong while creating your application. This is the error we see: "+responseText);
                            }
                        }
                        else{
                            messageBox("Problem","Something went wrong while searching for workspaces. Please try again in a bit. This is the error we see: "+err,0);
                        }
                    },
                    beforeSend:function(){
                        $("#myModal").find(".btn-primary").addClass("disabled");
                    }
                });
            }
            else{
                $("#appdescgroup").addClass("has-error");
            }
        }
        else{
            $("#apptitlegroup").addClass("has-error");
        }
    };
});<|endoftext|>


<commit_before>'use strict';
const path = require('path'),
    extend = require('extend'),
    Rx = require('rxjs'),
    glob = require('glob'),
    ora = require('ora'),
    chalk = require('chalk'),
    fs = require('fs-extra');

const Parser = require('./parser/parser');
const Generator = require('./generator/generator');
const DEFAULT_OPTIONS = require('./const/options');

/**
 * FrontNote
 * @param target {string|array} 解析するファイルのminimatch形式文字列またはminimatch形式文字列が入った配列
 * @param option {object} オプション
 * @param callback {callback} 全ての処理が正常に終了したときに実行するコールバック関数
 * @constructor
 */
class FrontNote {
    constructor(option) {
        this.options = extend({},DEFAULT_OPTIONS,option);
        this.options.out = path.resolve(this.options.out);
        this.Parser = new Parser();
    }

    /**
     * render styleguide
     * @param target{String|Array}
     * @returns {Observable<T>}
     */
    render(target) {
        const spinner = ora('Loading files...').start();
        let list = typeof target === 'string' ? glob.sync(target) : target;
        let obs = this.readFiles(list).map((files) => {
            spinner.text = 'Parsing files...';
            return this.parseFiles(files);
        }).flatMap((parsedFiles) => {
            spinner.text = 'Generating StyleGuide...';
            return this.createStyleGuide(parsedFiles);
        }).share();
        obs.take(1).subscribe((result) => {
            if (this.options.verbose) {
                result.forEach((filepath) => {
                    console.log(chalk.green(`[w] ${filepath}`));
                });
            }
            spinner.text = 'Generated StyleGuide';
            spinner.succeed();
        });
        return obs;
    }
    readFiles(fileList) {
        const observers = fileList.map((filepath) => {
            const readFileAsObservable = Rx.Observable.bindNodeCallback(fs.readFile);
            return readFileAsObservable(filepath, 'utf8').map((data) => {
                return {
                    file: filepath,
                    content: data
                };
            });
        });
        if (observers.length === 0) {
            return Rx.Observable.create(observer => {
                observer.next([]);
            });
        }
        return Rx.Observable.combineLatest(observers);
    }
    parseFiles(files) {
        return files.map((fileData) => {
            const value = this.Parser.parse(fileData.file,fileData.content);
            if (value) {
                return value;
            }
        }).filter((v) => {
            return (v !== undefined);
        });
    }
    /**
     * スタイルガイド作成
     * @param data
     */
    createStyleGuide(data) {
        return Rx.Observable.create(observer => {
            const gen = new Generator(data,this.options);
            gen.generate().subscribe(result => {
                let cwd = process.cwd();
                result = Array.prototype.concat.apply([],result).filter((v) => {
                    return (v);
                }).map((v) => {
                    return path.relative(cwd,v);
                });
                observer.next(result);
            },(e) => {
                observer.error(e);
            });
        });
    }
}

// プラグイン関数をエクスポート
module.exports = FrontNote;<commit_msg>fix: render関数に*の含まれたパスを配列で渡すとエラーになる #11<commit_after>'use strict';
const path = require('path'),
    extend = require('extend'),
    Rx = require('rxjs'),
    glob = require('glob'),
    ora = require('ora'),
    chalk = require('chalk'),
    fs = require('fs-extra');

const Parser = require('./parser/parser');
const Generator = require('./generator/generator');
const DEFAULT_OPTIONS = require('./const/options');

/**
 * FrontNote
 * @param target {string|array} 解析するファイルのminimatch形式文字列またはminimatch形式文字列が入った配列
 * @param option {object} オプション
 * @param callback {callback} 全ての処理が正常に終了したときに実行するコールバック関数
 * @constructor
 */
class FrontNote {
    constructor(option) {
        this.options = extend({},DEFAULT_OPTIONS,option);
        this.options.out = path.resolve(this.options.out);
        this.Parser = new Parser();
    }

    /**
     * render styleguide
     * @param target{String|Array}
     * @returns {Observable<T>}
     */
    render(target) {
        const spinner = ora('Loading files...').start();
        let list = typeof target === 'string' ? glob.sync(target) : target.reduce((previous,current) => {
            return previous.concat(glob.sync(current));
        },[]);
        let obs = this.readFiles(list).map((files) => {
            spinner.text = 'Parsing files...';
            return this.parseFiles(files);
        }).flatMap((parsedFiles) => {
            spinner.text = 'Generating StyleGuide...';
            return this.createStyleGuide(parsedFiles);
        }).share();
        obs.take(1).subscribe((result) => {
            if (this.options.verbose) {
                result.forEach((filepath) => {
                    console.log(chalk.green(`[w] ${filepath}`));
                });
            }
            spinner.text = 'Generated StyleGuide';
            spinner.succeed();
        });
        return obs;
    }
    readFiles(fileList) {
        const observers = fileList.map((filepath) => {
            const readFileAsObservable = Rx.Observable.bindNodeCallback(fs.readFile);
            return readFileAsObservable(filepath, 'utf8').map((data) => {
                return {
                    file: filepath,
                    content: data
                };
            });
        });
        if (observers.length === 0) {
            return Rx.Observable.create(observer => {
                observer.next([]);
            });
        }
        return Rx.Observable.combineLatest(observers);
    }
    parseFiles(files) {
        return files.map((fileData) => {
            const value = this.Parser.parse(fileData.file,fileData.content);
            if (value) {
                return value;
            }
        }).filter((v) => {
            return (v !== undefined);
        });
    }
    /**
     * スタイルガイド作成
     * @param data
     */
    createStyleGuide(data) {
        return Rx.Observable.create(observer => {
            const gen = new Generator(data,this.options);
            gen.generate().subscribe(result => {
                let cwd = process.cwd();
                result = Array.prototype.concat.apply([],result).filter((v) => {
                    return (v);
                }).map((v) => {
                    return path.relative(cwd,v);
                });
                observer.next(result);
            },(e) => {
                observer.error(e);
            });
        });
    }
}

// プラグイン関数をエクスポート
module.exports = FrontNote;<|endoftext|>


<commit_before>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.2.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var push             = Array.prototype.push,
        slice            = Array.prototype.slice,
        unshift          = Array.prototype.unshift,
        toString         = Object.prototype.toString,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeMap          = Array.prototype.map,
        nativeReduce       = Array.prototype.reduce,
        nativeReduceRight  = Array.prototype.reduceRight,
        nativeFilter       = Array.prototype.filter,
        nativeEvery        = Array.prototype.every,
        nativeSome         = Array.prototype.some,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = Function.prototype.bind;

    var _jSQL, jSQL, _DB = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this,arguments);
    };

    jSQL.prototype = {
        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
        },

        /**
        * create a new database
        * @param dbname [String]
        * @param db [Object]
        */

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(this._isArray(db)) {
                indexList = this._listSlice(arguments, '2:');
                this._appendKey(db, indexList);
            }

            if(this._isObject(db)) {
                db = this._objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        /**
        * select an exist database as current
        * @param dbname [String]
        */

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            return this;
        },

        /**
        * drop an exist database
        * @param dbname [String]
        */

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        /**
        * select object from currentDB
        * @param key
            '*':     return all
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        */

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key==='*') {
                return this;
            }

            this.where(function(data) {
                return typeof(this._deep(data, key)) !== 'undefined';
            });

            return this;
        },

        /**
        * get the count of current result set
        */

        count: function() {
            return this._buffer.length;
        },

        /**
        * calculate the total of spec key
        * @param key
            '*':     return first package key count
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        * @use [jSQL instance].total('a.b.c')
        */

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            this._deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        /**
        * sort the current result set
        * @param field [String]
        * @param callback [function]
        * @param order [String <asc | desc>]
        */

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = _this._deep(a, field);
                b = _this._deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(this._isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp[i] = this._buffer[i];
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        /**
        * return the current result set
        * @return [Object]
        */

        findAll: function() {
            return this._clone(this._buffer);
        },

        /**
        * return a specified item of current result set
        * if the key doesn't given, it'll return the first item
        * @return [Object]
        */

        find: function(key) {
            if(!key) {
                for(var i in this._buffer) {
                    if(key) {
                        break;
                    }

                    if(this._buffer.hasOwnProperty(i)) {
                        key = i;
                    }
                }
            }

            return this._clone(this._buffer[key]);
        },

        /**
        * return the current result set as array list
        * @return [Object]
        */

        listAll: function() {
            return this._clone(this._buffer);
        },

        /**
        * update the current result set
        * @param key [String]
        * @param data [Object]
        */

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        /**
        * limit the current result set
        * @param start [Number]
        * @param end [Number]
        */

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = this._listSlice(_tmp, limit);
            return this;
        },

        /**
        * private methods
        */

        _deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        _isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        _isObject: function(obj) {
            return obj === Object(obj);
        },

        _clone: function(obj) {
            var _tmp = {};

            if (!this._isObject(obj)) return obj;
            if(this._isArray(obj)) return obj.slice();

            for(var i in obj) {
                if(obj.hasOwnProperty(i)) {
                    _tmp[i] = obj[i];
                }
            }
            return _tmp;
        },

        _objectToArray: function(object) {
            var array = [], object = this._clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i].jSQL_Key = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        _arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || 'jSQL_Key']] = array[i];
                delete object[array[i][key || 'jSQL_Key']][key || 'jSQL_Key'];
            };

            return object;
        },

        _each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        _keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that._isArray(indexList)) {
                baseRef = indexList;
            }

            that._each(baseRef, function(o, i, r) {
                key += object[o];
            });

            return key;
        },

        _listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        _appendKey: function(list, indexList) {
            var that = this;
            that._each(list, function(o, i, r) {
                o['jSQL_Key'] = that._keygen(o, indexList);
            });
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();
<commit_msg>update comment text.<commit_after>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.2.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var push             = Array.prototype.push,
        slice            = Array.prototype.slice,
        unshift          = Array.prototype.unshift,
        toString         = Object.prototype.toString,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeMap          = Array.prototype.map,
        nativeReduce       = Array.prototype.reduce,
        nativeReduceRight  = Array.prototype.reduceRight,
        nativeFilter       = Array.prototype.filter,
        nativeEvery        = Array.prototype.every,
        nativeSome         = Array.prototype.some,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = Function.prototype.bind;

    var _jSQL, jSQL, _DB = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this,arguments);
    };

    jSQL.prototype = {
        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
        },

        /**
        * create a new database
        * @param dbname [String]
        * @param db [Object]
        */

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(this._isArray(db)) {
                indexList = this._listSlice(arguments, '2:');
                this._appendKey(db, indexList);
            }

            if(this._isObject(db)) {
                db = this._objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        /**
        * select an exist database as current
        * @param dbname [String]
        */

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            return this;
        },

        /**
        * drop an exist database
        * @param dbname [String]
        */

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        /**
        * select object from currentDB
        * @param key
            '*':     return all
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        */

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key==='*') {
                return this;
            }

            this.where(function(data) {
                return typeof(this._deep(data, key)) !== 'undefined';
            });

            return this;
        },

        /**
        * get the count of current result set
        */

        count: function() {
            return this._buffer.length;
        },

        /**
        * calculate the total of spec key
        * @param key
            '*':     return first package key count
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        * @use [jSQL instance].total('a.b.c')
        */

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            this._deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        /**
        * sort the current result set
        * @param field [String]
        * @param callback [function]
        * @param order [String <asc | desc>]
        */

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = _this._deep(a, field);
                b = _this._deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(this._isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp[i] = this._buffer[i];
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        /**
        * return the current result set
        * @return [Object]
        */

        findAll: function() {
            return this._clone(this._arrayToObject(this._buffer));
        },

        /**
        * return a specified item of current result set
        * if the key doesn't given, it'll return the first item
        * @return [Object]
        */

        find: function(key) {
            if(!key) {
                for(var i in this._buffer) {
                    if(key) {
                        break;
                    }

                    if(this._buffer.hasOwnProperty(i)) {
                        key = i;
                    }
                }
            }

            return this._clone(this._buffer[key]);
        },

        /**
        * return the current result set as array list
        * @return [Object]
        */

        listAll: function() {
            return this._clone(this._buffer);
        },

        /**
        * update the current result set
        * @param key [String]
        * @param data [Object]
        */

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        /**
        * limit the current result set
        * @param start [Number]
        * @param end [Number]
        */

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = this._listSlice(_tmp, limit);
            return this;
        },

        /**
        * private methods
        */

        _deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        _isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        _isObject: function(obj) {
            return obj === Object(obj);
        },

        _clone: function(obj) {
            var _tmp = {};

            if (!this._isObject(obj)) return obj;
            if(this._isArray(obj)) return obj.slice();

            for(var i in obj) {
                if(obj.hasOwnProperty(i)) {
                    _tmp[i] = obj[i];
                }
            }
            return _tmp;
        },

        _objectToArray: function(object) {
            var array = [], object = this._clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i].jSQL_Key = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        _arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || 'jSQL_Key']] = array[i];
                delete object[array[i][key || 'jSQL_Key']][key || 'jSQL_Key'];
            };

            return object;
        },

        _each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        _keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that._isArray(indexList)) {
                baseRef = indexList;
            }

            that._each(baseRef, function(o, i, r) {
                key += object[o];
            });

            return key;
        },

        _listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        _appendKey: function(list, indexList) {
            var that = this;
            that._each(list, function(o, i, r) {
                o['jSQL_Key'] = that._keygen(o, indexList);
            });
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();
<|endoftext|>


<commit_before><commit_msg>fixed image size for stable incremental loading<commit_after><|endoftext|>


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

Reports = new Meteor.Collection('reports');

/**
 * Determines success category by calculating the mean score and map to three equal intervals
 * 1 - 2.66 is RED (1), 2.66 - 4.32 is ORANGE (2), and 4.32-6 is GREEN (3)
 */
evaluateProject = function(evaluations) {

    var meanScore = getMeanScore(evaluations);

    if(meanScore > (8/3) && meanScore <= (13/3)) {
        success = 2;
    } else if(meanScore > (13/3)) {
        success = 3;
    }

    return success;
}

getMeanScore = function(evaluations) {
    var criteriaCount = 0;
    var meanScore = 0;

    for(k = 0; k < evaluations.length; k++) {
        criteriaCount += (evaluations[k] && 1);
        meanScore += evaluations[k] || 0;
    }

    meanScore /= criteriaCount;

    return meanScore;
}

createMofidiers = function(modifier, tmpl) {
    "use strict";

    var coords = locationObject.getCoordinates();
    var lat = "";
    var lng = "";

    if(coords.lat && coords.lng) {
        lat = coords.lat.toString();
        lng = coords.lng.toString();
    }

    var productivityValue = parseInt(tmpl.find('input[name="num-eval-productivity"]:checked').value);
    var achievementValue = parseInt(tmpl.find('input[name="num-eval-achievement"]:checked').value);
    var effectsValue = parseInt(tmpl.find('input[name="num-eval-effects"]:checked').value);
    var relevanceValue = parseInt(tmpl.find('input[name="num-eval-relevance"]:checked').value);
    var viabilityValue = parseInt(tmpl.find('input[name="num-eval-viability"]:checked').value);
    var profitabilityValue = parseInt(tmpl.find('input[name="num-eval-profitability"]:checked').value);

    var operationalEvaluations = [productivityValue];
    var strategicalEvaluations = [achievementValue, effectsValue, relevanceValue, viabilityValue, profitabilityValue];

    var operationalSuccess = evaluateProject(operationalEvaluations);
    var strategicalSuccess = evaluateProject(strategicalEvaluations);

    // omit invalid $unset variables, those who are required
    modifier.$unset = _.omit(modifier.$unset, [
        "project.location",
        "evaluation.productivity",
        "evaluation.achievement",
        "evaluation.effects",
        "evaluation.relevance",
        "evaluation.viability",
        "evaluation.profitability",
        "project.managementBudget",
        "project.costBudget",
        "project.costFinal",
        "responsible",
        "evaluation.overall",
        "project.location.coordinates"
    ]);

    var mods = {
        "project.location.coordinates.lat": lat || null,
        "project.location.coordinates.lng": lng || null,
        "project.operationalSuccess": operationalSuccess,
        "project.strategicalSuccess": strategicalSuccess,
        "evaluation.productivity.value": productivityValue,
        "evaluation.achievement.value": achievementValue,
        "evaluation.effects.value": effectsValue,
        "evaluation.relevance.value": relevanceValue,
        "evaluation.viability.value": viabilityValue,
        "evaluation.profitability.value": profitabilityValue,
        "_public": parseInt(tmpl.find('input[name="public-var"]:checked').value) === 1
    };

    var imgsIds = uploadObject.getImages();
    var imgs = [];

    if(imgsIds.length > 0) {
      for (var i = 0; i < imgsIds.length; i++){
        var img = {
            fileId: imgsIds[i],
            title: tmpl.find('#title-' + imgsIds[i]) && tmpl.find('#title-' + imgsIds[i]).value || null,
            copyright: tmpl.find('#copyright-' + imgsIds[i]) && tmpl.find('#copyright-' + imgsIds[i]).value || null,
            link: tmpl.find('#link-' + imgsIds[i]) &&  tmpl.find('#link-' + imgsIds[i]).value || null
        };
        if(Images.findOne({ _id: imgsIds[i]}))
          imgs.push(img);
      }
    }

    mods.images = imgs;

    var filesIds = uploadObject.getReferences();
    var files = [];

    if(filesIds.length > 0) {
      for (var i = 0; i < filesIds.length; i++){
        var file = {
            fileId: filesIds[i],
            title: tmpl.find('#title-' + filesIds[i]) && tmpl.find('#title-' + filesIds[i]).value || null,
            typedoc: tmpl.find('#typedoc-' + filesIds[i]) && tmpl.find('#typedoc-' + filesIds[i]).value || null,
            date: tmpl.find('#date-' + filesIds[i]) && tmpl.find('#date-' + filesIds[i]).value || null
        };
      if(Files.findOne({ _id: filesIds[i]}))
        files.push(file);
      }
    }

    mods.references = files;

    if(_.isEmpty(modifier.$unset)) {
        modifier = _.omit(modifier, "$unset");
    }

    modifier.$set = _.extend(modifier.$set, mods);

    return modifier;
};

createReport = function(tmpl) {
    "use strict";

    // our report document
    var report = {
        project: {},
        evaluation: {}
    };

    // get all variables, and build the document
    report.project.name = tmpl.find('#name').value;
    report.project.projectNumber = parseInt(tmpl.find('#project-num').value);
    report.project.sector = tmpl.find('#sector').value;

    report.project.location = {};

    report.project.location.name = tmpl.find('#location').value || "";

    var coords = locationObject.getCoordinates();

    report.project.location.coordinates = {};

    report.project.location.coordinates.lat = coords.lat;
    report.project.location.coordinates.lng = coords.lng;

    report.project.projectDescription = {};
    report.project.projectDescription.short = tmpl.find('#project-desc-short').value;
    report.project.projectDescription.long = tmpl.find('#project-desc-long').value;

    report.project.finishingYear = parseInt(tmpl.find('#finishing-year').value) || null;
    report.project.evaluationYear = parseInt(tmpl.find('#eval-year').value) || null;
    report.project.decisionYear = parseInt(tmpl.find('#decision-year').value) || null;

    report.project.managementBudget = {};
    report.project.costBudget = {};
    report.project.costFinal = {};

    report.project.managementBudget.year = parseInt(tmpl.find('#management-budget-year').value) || null;
    report.project.costBudget.year = parseInt(tmpl.find('#cost-budget-year').value) || null;
    report.project.costFinal.year = parseInt(tmpl.find('#cost-final-year').value) || null;

    report.project.managementBudget.amount = parseInt(tmpl.find('#management-budget').value) || null;
    report.project.costBudget.amount = parseInt(tmpl.find('#cost-budget').value) || null;
    report.project.costFinal.amount = parseInt(tmpl.find('#cost-final').value) || null;

    report.responsible = {};
    report.responsible.organization = tmpl.find('#eval-responsible-org').value || "";
    report.responsible.person = tmpl.find('#eval-responsible-person').value || "";

    report.evaluation.overall = {};
    report.evaluation.productivity = {};
    report.evaluation.achievement = {};
    report.evaluation.effects = {};
    report.evaluation.relevance = {};
    report.evaluation.viability = {};
    report.evaluation.profitability = {};

    report.evaluation.overall.short = tmpl.find('#eval-overall-short').value || "";
    report.evaluation.overall.long = tmpl.find('#eval-overall-long').value || "";

    report.evaluation.productivity.short = tmpl.find('#eval-productivity-short').value || "";
    report.evaluation.productivity.long = tmpl.find('#eval-productivity-long').value || "";

    report.evaluation.achievement.short = tmpl.find('#eval-achievement-short').value || "";
    report.evaluation.achievement.long = tmpl.find('#eval-achievement-long').value || "";

    report.evaluation.effects.short = tmpl.find('#eval-effects-short').value || "";
    report.evaluation.effects.long = tmpl.find('#eval-effects-long').value || "";

    report.evaluation.relevance.short = tmpl.find('#eval-relevance-short').value || "";
    report.evaluation.relevance.long = tmpl.find('#eval-relevance-long').value || "";

    report.evaluation.viability.short = tmpl.find('#eval-viability-short').value || "";
    report.evaluation.viability.long = tmpl.find('#eval-viability-long').value || "";

    report.evaluation.profitability.short = tmpl.find('#eval-profitability-short').value || "";
    report.evaluation.profitability.long = tmpl.find('#eval-profitability-long').value || "";

    var productivityValue = parseInt(tmpl.find('input[name="num-eval-productivity"]:checked').value);
    var achievementValue = parseInt(tmpl.find('input[name="num-eval-achievement"]:checked').value);
    var effectsValue = parseInt(tmpl.find('input[name="num-eval-effects"]:checked').value);
    var relevanceValue = parseInt(tmpl.find('input[name="num-eval-relevance"]:checked').value);
    var viabilityValue = parseInt(tmpl.find('input[name="num-eval-viability"]:checked').value);
    var profitabilityValue = parseInt(tmpl.find('input[name="num-eval-profitability"]:checked').value);

    report.evaluation.productivity.value = productivityValue;
    report.evaluation.achievement.value = achievementValue;
    report.evaluation.effects.value = effectsValue;
    report.evaluation.relevance.value = relevanceValue;
    report.evaluation.viability.value = viabilityValue;
    report.evaluation.profitability.value = profitabilityValue;

    var operationalEvaluations = [productivityValue];
    var strategicalEvaluations = [achievementValue, effectsValue, relevanceValue, viabilityValue, profitabilityValue];

    var operationalSuccess = evaluateProject(operationalEvaluations);
    var strategicalSuccess = evaluateProject(strategicalEvaluations);

    report.project.operationalSuccess = operationalSuccess;
    report.project.strategicalSuccess = strategicalSuccess;

    var imgsIds = uploadObject.getImages();
    var imgs = [];

    if(imgsIds.length > 0) {
      for (var i = 0; i < imgsIds.length; i++){
        var img = {
            fileId: imgsIds[i],
            title: tmpl.find('#title-' + imgsIds[i]).value,
            copyright: tmpl.find('#copyright-' + imgsIds[i]).value,
            link: tmpl.find('#link-' + imgsIds[i]).value
        };
        imgs.push(img);
      }
    }

    report.images = imgs;

    var filesIds = uploadObject.getReferences();
    var files = [];

    if(filesIds.length > 0) {
      for (var i = 0; i < filesIds.length; i++){
        var file = {
            fileId: filesIds[i],
            title: tmpl.find('#title-' + filesIds[i]).value,
            typedoc: tmpl.find('#typedoc-' + filesIds[i]).value,
            date: tmpl.find('#date-' + filesIds[i]).value
        };
        files.push(file);
      }
    }

    report.references = files;
    report._public = parseInt(tmpl.find('input[name="public-var"]:checked').value) === 1;

    return report;
};
<commit_msg>Fixes bug with success value not found, the success variable got removed from the evaluate method.<commit_after>/*
 * Copyright 2015 Concept
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Reports Collection
 */

Reports = new Meteor.Collection('reports');

/**
 * Determines success category by calculating the mean score and map to three equal intervals
 * 1 - 2.66 is RED (1), 2.66 - 4.32 is ORANGE (2), and 4.32-6 is GREEN (3)
 */
evaluateProject = function(evaluations) {

    var success = 1;

    var meanScore = getMeanScore(evaluations);

    if(meanScore > (8/3) && meanScore <= (13/3)) {
        success = 2;
    } else if(meanScore > (13/3)) {
        success = 3;
    }

    return success;
}

getMeanScore = function(evaluations) {
    var criteriaCount = 0;
    var meanScore = 0;

    for(k = 0; k < evaluations.length; k++) {
        criteriaCount += (evaluations[k] && 1);
        meanScore += evaluations[k] || 0;
    }

    meanScore /= criteriaCount;

    return meanScore;
}

createMofidiers = function(modifier, tmpl) {
    "use strict";

    var coords = locationObject.getCoordinates();
    var lat = "";
    var lng = "";

    if(coords.lat && coords.lng) {
        lat = coords.lat.toString();
        lng = coords.lng.toString();
    }

    var productivityValue = parseInt(tmpl.find('input[name="num-eval-productivity"]:checked').value);
    var achievementValue = parseInt(tmpl.find('input[name="num-eval-achievement"]:checked').value);
    var effectsValue = parseInt(tmpl.find('input[name="num-eval-effects"]:checked').value);
    var relevanceValue = parseInt(tmpl.find('input[name="num-eval-relevance"]:checked').value);
    var viabilityValue = parseInt(tmpl.find('input[name="num-eval-viability"]:checked').value);
    var profitabilityValue = parseInt(tmpl.find('input[name="num-eval-profitability"]:checked').value);

    var operationalEvaluations = [productivityValue];
    var strategicalEvaluations = [achievementValue, effectsValue, relevanceValue, viabilityValue, profitabilityValue];

    var operationalSuccess = evaluateProject(operationalEvaluations);
    var strategicalSuccess = evaluateProject(strategicalEvaluations);

    // omit invalid $unset variables, those who are required
    modifier.$unset = _.omit(modifier.$unset, [
        "project.location",
        "evaluation.productivity",
        "evaluation.achievement",
        "evaluation.effects",
        "evaluation.relevance",
        "evaluation.viability",
        "evaluation.profitability",
        "project.managementBudget",
        "project.costBudget",
        "project.costFinal",
        "responsible",
        "evaluation.overall",
        "project.location.coordinates"
    ]);

    var mods = {
        "project.location.coordinates.lat": lat || null,
        "project.location.coordinates.lng": lng || null,
        "project.operationalSuccess": operationalSuccess,
        "project.strategicalSuccess": strategicalSuccess,
        "evaluation.productivity.value": productivityValue,
        "evaluation.achievement.value": achievementValue,
        "evaluation.effects.value": effectsValue,
        "evaluation.relevance.value": relevanceValue,
        "evaluation.viability.value": viabilityValue,
        "evaluation.profitability.value": profitabilityValue,
        "_public": parseInt(tmpl.find('input[name="public-var"]:checked').value) === 1
    };

    var imgsIds = uploadObject.getImages();
    var imgs = [];

    if(imgsIds.length > 0) {
      for (var i = 0; i < imgsIds.length; i++){
        var img = {
            fileId: imgsIds[i],
            title: tmpl.find('#title-' + imgsIds[i]) && tmpl.find('#title-' + imgsIds[i]).value || null,
            copyright: tmpl.find('#copyright-' + imgsIds[i]) && tmpl.find('#copyright-' + imgsIds[i]).value || null,
            link: tmpl.find('#link-' + imgsIds[i]) &&  tmpl.find('#link-' + imgsIds[i]).value || null
        };
        if(Images.findOne({ _id: imgsIds[i]}))
          imgs.push(img);
      }
    }

    mods.images = imgs;

    var filesIds = uploadObject.getReferences();
    var files = [];

    if(filesIds.length > 0) {
      for (var i = 0; i < filesIds.length; i++){
        var file = {
            fileId: filesIds[i],
            title: tmpl.find('#title-' + filesIds[i]) && tmpl.find('#title-' + filesIds[i]).value || null,
            typedoc: tmpl.find('#typedoc-' + filesIds[i]) && tmpl.find('#typedoc-' + filesIds[i]).value || null,
            date: tmpl.find('#date-' + filesIds[i]) && tmpl.find('#date-' + filesIds[i]).value || null
        };
      if(Files.findOne({ _id: filesIds[i]}))
        files.push(file);
      }
    }

    mods.references = files;

    if(_.isEmpty(modifier.$unset)) {
        modifier = _.omit(modifier, "$unset");
    }

    modifier.$set = _.extend(modifier.$set, mods);

    return modifier;
};

createReport = function(tmpl) {
    "use strict";

    // our report document
    var report = {
        project: {},
        evaluation: {}
    };

    // get all variables, and build the document
    report.project.name = tmpl.find('#name').value;
    report.project.projectNumber = parseInt(tmpl.find('#project-num').value);
    report.project.sector = tmpl.find('#sector').value;

    report.project.location = {};

    report.project.location.name = tmpl.find('#location').value || "";

    var coords = locationObject.getCoordinates();

    report.project.location.coordinates = {};

    report.project.location.coordinates.lat = coords.lat;
    report.project.location.coordinates.lng = coords.lng;

    report.project.projectDescription = {};
    report.project.projectDescription.short = tmpl.find('#project-desc-short').value;
    report.project.projectDescription.long = tmpl.find('#project-desc-long').value;

    report.project.finishingYear = parseInt(tmpl.find('#finishing-year').value) || null;
    report.project.evaluationYear = parseInt(tmpl.find('#eval-year').value) || null;
    report.project.decisionYear = parseInt(tmpl.find('#decision-year').value) || null;

    report.project.managementBudget = {};
    report.project.costBudget = {};
    report.project.costFinal = {};

    report.project.managementBudget.year = parseInt(tmpl.find('#management-budget-year').value) || null;
    report.project.costBudget.year = parseInt(tmpl.find('#cost-budget-year').value) || null;
    report.project.costFinal.year = parseInt(tmpl.find('#cost-final-year').value) || null;

    report.project.managementBudget.amount = parseInt(tmpl.find('#management-budget').value) || null;
    report.project.costBudget.amount = parseInt(tmpl.find('#cost-budget').value) || null;
    report.project.costFinal.amount = parseInt(tmpl.find('#cost-final').value) || null;

    report.responsible = {};
    report.responsible.organization = tmpl.find('#eval-responsible-org').value || "";
    report.responsible.person = tmpl.find('#eval-responsible-person').value || "";

    report.evaluation.overall = {};
    report.evaluation.productivity = {};
    report.evaluation.achievement = {};
    report.evaluation.effects = {};
    report.evaluation.relevance = {};
    report.evaluation.viability = {};
    report.evaluation.profitability = {};

    report.evaluation.overall.short = tmpl.find('#eval-overall-short').value || "";
    report.evaluation.overall.long = tmpl.find('#eval-overall-long').value || "";

    report.evaluation.productivity.short = tmpl.find('#eval-productivity-short').value || "";
    report.evaluation.productivity.long = tmpl.find('#eval-productivity-long').value || "";

    report.evaluation.achievement.short = tmpl.find('#eval-achievement-short').value || "";
    report.evaluation.achievement.long = tmpl.find('#eval-achievement-long').value || "";

    report.evaluation.effects.short = tmpl.find('#eval-effects-short').value || "";
    report.evaluation.effects.long = tmpl.find('#eval-effects-long').value || "";

    report.evaluation.relevance.short = tmpl.find('#eval-relevance-short').value || "";
    report.evaluation.relevance.long = tmpl.find('#eval-relevance-long').value || "";

    report.evaluation.viability.short = tmpl.find('#eval-viability-short').value || "";
    report.evaluation.viability.long = tmpl.find('#eval-viability-long').value || "";

    report.evaluation.profitability.short = tmpl.find('#eval-profitability-short').value || "";
    report.evaluation.profitability.long = tmpl.find('#eval-profitability-long').value || "";

    var productivityValue = parseInt(tmpl.find('input[name="num-eval-productivity"]:checked').value);
    var achievementValue = parseInt(tmpl.find('input[name="num-eval-achievement"]:checked').value);
    var effectsValue = parseInt(tmpl.find('input[name="num-eval-effects"]:checked').value);
    var relevanceValue = parseInt(tmpl.find('input[name="num-eval-relevance"]:checked').value);
    var viabilityValue = parseInt(tmpl.find('input[name="num-eval-viability"]:checked').value);
    var profitabilityValue = parseInt(tmpl.find('input[name="num-eval-profitability"]:checked').value);

    report.evaluation.productivity.value = productivityValue;
    report.evaluation.achievement.value = achievementValue;
    report.evaluation.effects.value = effectsValue;
    report.evaluation.relevance.value = relevanceValue;
    report.evaluation.viability.value = viabilityValue;
    report.evaluation.profitability.value = profitabilityValue;

    var operationalEvaluations = [productivityValue];
    var strategicalEvaluations = [achievementValue, effectsValue, relevanceValue, viabilityValue, profitabilityValue];

    var operationalSuccess = evaluateProject(operationalEvaluations);
    var strategicalSuccess = evaluateProject(strategicalEvaluations);

    report.project.operationalSuccess = operationalSuccess;
    report.project.strategicalSuccess = strategicalSuccess;

    var imgsIds = uploadObject.getImages();
    var imgs = [];

    if(imgsIds.length > 0) {
      for (var i = 0; i < imgsIds.length; i++){
        var img = {
            fileId: imgsIds[i],
            title: tmpl.find('#title-' + imgsIds[i]).value,
            copyright: tmpl.find('#copyright-' + imgsIds[i]).value,
            link: tmpl.find('#link-' + imgsIds[i]).value
        };
        imgs.push(img);
      }
    }

    report.images = imgs;

    var filesIds = uploadObject.getReferences();
    var files = [];

    if(filesIds.length > 0) {
      for (var i = 0; i < filesIds.length; i++){
        var file = {
            fileId: filesIds[i],
            title: tmpl.find('#title-' + filesIds[i]).value,
            typedoc: tmpl.find('#typedoc-' + filesIds[i]).value,
            date: tmpl.find('#date-' + filesIds[i]).value
        };
        files.push(file);
      }
    }

    report.references = files;
    report._public = parseInt(tmpl.find('input[name="public-var"]:checked').value) === 1;

    return report;
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import classnames from 'classnames';

export default class YearPicker extends Component {
  constructor(props) {
    super(props);

    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);

    const year = props.calendarTempDate.getFullYear();
    const halfed = parseInt(props.initialYearsDisplayed / 2);
    this.state = {
      startYear: props.minDate ? props.minDate.getFullYear() : year - halfed,
      endYear: props.maxDate ? props.maxDate.getFullYear() : year + halfed,
    };
  }

  static propTypes = {
    calendarTempDate: PropTypes.instanceOf(Date).isRequired,
    onCalendarYearClick: PropTypes.func.isRequired,
    initialYearsDisplayed: PropTypes.number.isRequired,
    minDate: PropTypes.instanceOf(Date),
    maxDate: PropTypes.instanceOf(Date),
  };

  componentDidMount() {
    const { container } = this.refs;
    const active = container.querySelector('.md-year.active');

    let scrollTop = container.scrollHeight - active.offsetTop - active.offsetHeight / 2;
    if(container.offsetHeight < container.offsetWidth) {
      // landscape
      scrollTop -= container.offsetHeight / 2;
    }

    container.scrollTop = scrollTop;
  }

  render() {
    const { startYear, endYear } = this.state;

    const currentYear = this.props.calendarTempDate.getFullYear();
    let years = [];
    for(let year = startYear; year <= endYear; year++) {
      years.push(
        <button
          type="button"
          key={`year-${year}`}
          className={classnames('md-year', { 'active': year === currentYear })}
          onClick={this.props.onCalendarYearClick.bind(this, year)}
          >
          {year}
        </button>
      );
    }
    return (

          {years}

    );
  }
}
<commit_msg>Fixed the year picker so that the active date is in the middle of the picker<commit_after>import React, { Component, PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import classnames from 'classnames';

export default class YearPicker extends Component {
  constructor(props) {
    super(props);

    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);

    const year = props.calendarTempDate.getFullYear();
    const halfed = parseInt(props.initialYearsDisplayed / 2);
    this.state = {
      startYear: props.minDate ? props.minDate.getFullYear() : year - halfed,
      endYear: props.maxDate ? props.maxDate.getFullYear() : year + halfed,
    };
  }

  static propTypes = {
    calendarTempDate: PropTypes.instanceOf(Date).isRequired,
    onCalendarYearClick: PropTypes.func.isRequired,
    initialYearsDisplayed: PropTypes.number.isRequired,
    minDate: PropTypes.instanceOf(Date),
    maxDate: PropTypes.instanceOf(Date),
  };

  componentDidMount() {
    const { container } = this.refs;
    const active = container.querySelector('.md-year.active');

    // Position the active year in the center of the picker
    let scrollTop = active.offsetTop - (container.offsetHeight * 1.5);
    if(container.offsetHeight < container.offsetWidth) {
      // Landscape is off by a bit for some reason
      scrollTop -= (active.offsetHeight / 2);
    }

    container.scrollTop = scrollTop;
  }

  render() {
    const { startYear, endYear } = this.state;

    const currentYear = this.props.calendarTempDate.getFullYear();
    let years = [];
    for(let year = startYear; year <= endYear; year++) {
      years.push(
        <button
          type="button"
          key={`year-${year}`}
          className={classnames('md-year', { 'active': year === currentYear })}
          onClick={this.props.onCalendarYearClick.bind(this, year)}
          >
          {year}
        </button>
      );
    }
    return (

          {years}

    );
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Regents of the University of Michigan.
// All rights reserved. See LICENSE.txt for details.

// Authored by Jon Earley (earleyj@umich.edu)

var app = app || {}

app.status = m.prop('loading')

app.Home = {
  view: function() {

    switch(app.status()) {
      case 'loading':
        return m('p.loading', 'Loading ...')
      case 'success':
        return m("div", [
          m("header", [
            m.component(app.Messages),
            m(".site-title-container", [
              m(".container", [
                m("h1.site-title", "Search Alpha [Technical Prototype]"),
                m.component(app.Feedback)
              ])
            ]),
            m(".container", [
              m.component(app.Search)
            ])
          ]),
          m(".container", [
            m("aside", [
              m.component(app.Searchables),
              m.component(app.Facets)
            ]),
            m("main", [
              m.component(app.Pagination),
              m(".search-results-container", [
                m.component(app.Records)
              ])
            ])
          ])
        ])
      case 'failure':
        return m('p.loading', 'Failed to load page.')
    }
  }
}<commit_msg>updated title<commit_after>// Copyright (c) 2016, Regents of the University of Michigan.
// All rights reserved. See LICENSE.txt for details.

// Authored by Jon Earley (earleyj@umich.edu)

var app = app || {}

app.status = m.prop('loading')

app.Home = {
  view: function() {

    switch(app.status()) {
      case 'loading':
        return m('p.loading', 'Loading ...')
      case 'success':
        return m("div", [
          m("header", [
            m.component(app.Messages),
            m(".site-title-container", [
              m(".container", [
                m("h1.site-title", "Search Alpha"),
                m.component(app.Feedback)
              ])
            ]),
            m(".container", [
              m.component(app.Search)
            ])
          ]),
          m(".container", [
            m("aside", [
              m.component(app.Searchables),
              m.component(app.Facets)
            ]),
            m("main", [
              m.component(app.Pagination),
              m(".search-results-container", [
                m.component(app.Records)
              ])
            ])
          ])
        ])
      case 'failure':
        return m('p.loading', 'Failed to load page.')
    }
  }
}<|endoftext|>


<commit_before>(function () {
    'use strict';

    var setProto = Object.setPrototypeOf,
        Err_new_setProto = {};

    if (!setProto) {
        Err_new_setProto.noSupport = true;
    } else {
        Err_new_setProto = function Err_new_setProto(message) {
            var err = new Error(message);
            Object.setPrototypeOf(err, Err_new_setProto.prototype);

            Object.defineProperty(err, 'name', {
                enumerable: false,
                writable: false,
                value: 'Err_new_setProto'
            });
            return err;
        }
        Object.setPrototypeOf(Err_new_setProto.prototype, Error.prototype);
        // Err_new_setProto.prototype = Object.create(Error.prototype, {
        //     constructor: { value: Err_new_setProto }
        // });
    }

    // EXPORT

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = Err_new_setProto;
    } else {
        window.errors = window.errors || [];
        window.errors.push(Err_new_setProto);
    }

})();<commit_msg>update Err_new_setProto<commit_after>(function () {
    'use strict';

    var setProto = Object.setPrototypeOf,
        Err_new_setProto = {};

    if (!setProto) {
        Err_new_setProto.noSupport = true;
    } else {
        Err_new_setProto = function Err_new_setProto(message) {
            var err = new Error(message);
            setProto(err, Err_new_setProto.prototype);

            Object.defineProperty(err, 'name', {
                enumerable: false,
                writable: false,
                value: 'Err_new_setProto'
            });
            return err;
        }
        setProto(Err_new_setProto.prototype, Error.prototype);
    }

    // EXPORT

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = Err_new_setProto;
    } else {
        window.errors = window.errors || [];
        window.errors.push(Err_new_setProto);
    }

})();<|endoftext|>


<commit_before>import classNames from 'classnames';
import GeminiScrollbar from 'react-gemini-scrollbar';
import {Link, routerShape} from 'react-router';
import React from 'react';
import {Tooltip} from 'reactjs-components';
import PluginSDK from 'PluginSDK';

import {keyCodes} from '../utils/KeyboardUtil';
import ClusterHeader from './ClusterHeader';
import EventTypes from '../constants/EventTypes';
import Icon from './Icon';
import InternalStorageMixin from '../mixins/InternalStorageMixin';
import MesosSummaryStore from '../stores/MesosSummaryStore';
import MetadataStore from '../stores/MetadataStore';
import PrimarySidebarLink from '../components/PrimarySidebarLink';
import SaveStateMixin from '../mixins/SaveStateMixin';
import SidebarActions from '../events/SidebarActions';

const {
  NavigationService,
  EventTypes: {NAVIGATION_CHANGE}} = PluginSDK.get('navigation');

let defaultMenuItems = [
  '/dashboard',
  '/services',
  '/jobs',
  '/universe',
  '/nodes',
  '/network',
  '/security',
  '/cluster',
  '/components',
  '/settings',
  '/organization'
];

let {Hooks} = PluginSDK;

var Sidebar = React.createClass({

  displayName: 'Sidebar',

  saveState_key: 'sidebar',

  saveState_properties: ['sidebarExpanded'],

  mixins: [SaveStateMixin, InternalStorageMixin],

  contextTypes: {
    router: routerShape
  },

  getInitialState() {
    return {sidebarExpanded: true};
  },

  componentDidMount() {
    NavigationService.on(NAVIGATION_CHANGE, this.onNavigationChange);

    this.internalStorage_update({
      mesosInfo: MesosSummaryStore.get('states').lastSuccessful()
    });

    MetadataStore.addChangeListener(
      EventTypes.DCOS_METADATA_CHANGE,
      this.onDCOSMetadataChange
    );

    global.window.addEventListener('keydown', this.handleKeyPress, true);
  },

  componentWillUnmount() {
    NavigationService.removeListener(
      NAVIGATION_CHANGE,
      this.onNavigationChange
    );
    MetadataStore.removeChangeListener(
      EventTypes.DCOS_METADATA_CHANGE,
      this.onDCOSMetadataChange
    );

    global.window.removeEventListener('keydown', this.handleKeyPress, true);
  },

  onDCOSMetadataChange() {
    this.forceUpdate();
  },

  onNavigationChange() {
    this.forceUpdate();
  },

  handleInstallCLI() {
    SidebarActions.close();
    SidebarActions.openCliInstructions();
  },

  handleKeyPress(event) {
    let nodeName = event.target.nodeName;

    if (event.keyCode === keyCodes.leftBracket
      && !(nodeName === 'INPUT' || nodeName === 'TEXTAREA')
      && !(event.ctrlKey || event.metaKey || event.shiftKey)) {
      // #sidebarWidthChange is passed as a callback so that the sidebar
      // has had a chance to update before Gemini re-renders.
      this.setState({sidebarExpanded: !this.state.sidebarExpanded}, () => {
        SidebarActions.sidebarWidthChange();
        this.saveState_save();
      });
    }
  },

  handleVersionClick() {
    SidebarActions.close();
    SidebarActions.showVersions();
  },

  getNavigationSections() {
    const definition = NavigationService.getDefinition();

    return definition.map((group, index) => {
      let heading = null;

      if (group.category !== 'root') {
        heading = (

            {group.category}

        );
      }

      return (

          {heading}
          {this.getNavigationGroup(group)}

      );
    });
  },

  getNavigationGroup(group) {
    const menuItems = Hooks
      .applyFilter('sidebarNavigation', defaultMenuItems)
      .reduce((routesMap, path) => routesMap.set(path, true), new Map());

    const filteredItems = group.children
     .filter((route) => menuItems.has(route.path));

    let groupMenuItems = filteredItems.map((element, index) => {
      let {pathname} = this.props.location;

      let hasChildren = element.children && element.children.length !== 0;
      let isParentActive = pathname.startsWith(element.path);

      let submenu;
      let isChildActive = false;
      if (isParentActive && hasChildren) {
        [submenu, isChildActive] = this.getGroupSubmenu(
          group.path, element.children);
      }

      let linkElement = element.link;
      if (typeof linkElement === 'string') {
        linkElement = (
          <PrimarySidebarLink
            to={element.path}
            icon={element.options.icon}>
            {linkElement}
          </PrimarySidebarLink>
        );
      }

      let itemClassSet = classNames({
        'sidebar-menu-item': true,
        selected: isParentActive && !isChildActive,
        open: isParentActive && hasChildren
      });

      return (

          {linkElement}
          {submenu}

      );
    });

    return
{groupMenuItems}
;
  },

  getGroupSubmenu(path, children) {
    const {pathname} = this.props.location;
    let isChildActive = false;

    const childRoutesPaths = children.map(({path}) => path);
    const childRoutes = Hooks
        .applyFilter('secondaryNavigation', path, childRoutesPaths) || [];
    const childRoutesMap = childRoutes.reduce((routesMap, path) => {
      return routesMap.set(path, true);
    }, new Map());
    const filteredChildRoutes =
        children.filter(({path}) => childRoutesMap.has(path));

    let menuItems = filteredChildRoutes.reduce(function (children, currentChild, index) {
      let isActive = pathname.startsWith(currentChild.path);

      let menuItemClasses = classNames({selected: isActive});

      // First matched active child wins,
      // ie in /path/child and /path/child-path without this conditional /path/child-path
      // will always overrule /path/child
      if (!isChildActive && isActive) {
        isChildActive = true;
      }

      let linkElement = currentChild.link;
      if (typeof linkElement === 'string') {
        linkElement = <Link to={currentChild.path}>{linkElement}</Link>;
      }

      children.push(

          {linkElement}

      );

      return children;
    }, []);

    return [
{menuItems}
, isChildActive];
  },

  getVersion() {
    let data = MetadataStore.get('dcosMetadata');
    if (data == null || data.version == null) {
      return null;
    }

    return (
      v.{data.version}
    );
  },

  getFooter() {
    let defaultButtonSet = [(
      <Tooltip content="Documentation" key="button-docs" elementTag="a"
        href={MetadataStore.buildDocsURI('/')} target="_blank"
        wrapperClassName="button button-link tooltip-wrapper">
        <Icon className="clickable" id="pages" />
      </Tooltip>
    ), (
      <Tooltip content="Install CLI"
        key="button-cli" elementTag="a" onClick={this.handleInstallCLI}
        wrapperClassName="button button-link tooltip-wrapper">
        <Icon className="clickable" id="cli" />
      </Tooltip>
    )];

    let buttonSet = Hooks.applyFilter(
      'sidebarFooterButtonSet', defaultButtonSet
    );
    let footer = null;

    if (buttonSet && buttonSet.length) {
      footer =
{buttonSet}
;
    }

    return Hooks.applyFilter('sidebarFooter', footer, defaultButtonSet);
  },

  render() {
    let sidebarClasses = classNames('sidebar flex flex-direction-top-to-bottom',
      'flex-item-shrink-0', {
        'is-expanded': this.state.sidebarExpanded
      });

    return (

            <ClusterHeader />

        <GeminiScrollbar autoshow={true}
          className="navigation flex-item-grow-1 flex-item-shrink-1 gm-scrollbar-container-flex">

            {this.getNavigationSections()}

        </GeminiScrollbar>

              {this.getFooter()}

    );
  }

});

module.exports = Sidebar;
<commit_msg>Fallback to unfiltered version<commit_after>import classNames from 'classnames';
import GeminiScrollbar from 'react-gemini-scrollbar';
import {Link, routerShape} from 'react-router';
import React from 'react';
import {Tooltip} from 'reactjs-components';
import PluginSDK from 'PluginSDK';

import {keyCodes} from '../utils/KeyboardUtil';
import ClusterHeader from './ClusterHeader';
import EventTypes from '../constants/EventTypes';
import Icon from './Icon';
import InternalStorageMixin from '../mixins/InternalStorageMixin';
import MesosSummaryStore from '../stores/MesosSummaryStore';
import MetadataStore from '../stores/MetadataStore';
import PrimarySidebarLink from '../components/PrimarySidebarLink';
import SaveStateMixin from '../mixins/SaveStateMixin';
import SidebarActions from '../events/SidebarActions';

const {
  NavigationService,
  EventTypes: {NAVIGATION_CHANGE}} = PluginSDK.get('navigation');

let defaultMenuItems = [
  '/dashboard',
  '/services',
  '/jobs',
  '/universe',
  '/nodes',
  '/network',
  '/security',
  '/cluster',
  '/components',
  '/settings',
  '/organization'
];

let {Hooks} = PluginSDK;

var Sidebar = React.createClass({

  displayName: 'Sidebar',

  saveState_key: 'sidebar',

  saveState_properties: ['sidebarExpanded'],

  mixins: [SaveStateMixin, InternalStorageMixin],

  contextTypes: {
    router: routerShape
  },

  getInitialState() {
    return {sidebarExpanded: true};
  },

  componentDidMount() {
    NavigationService.on(NAVIGATION_CHANGE, this.onNavigationChange);

    this.internalStorage_update({
      mesosInfo: MesosSummaryStore.get('states').lastSuccessful()
    });

    MetadataStore.addChangeListener(
      EventTypes.DCOS_METADATA_CHANGE,
      this.onDCOSMetadataChange
    );

    global.window.addEventListener('keydown', this.handleKeyPress, true);
  },

  componentWillUnmount() {
    NavigationService.removeListener(
      NAVIGATION_CHANGE,
      this.onNavigationChange
    );
    MetadataStore.removeChangeListener(
      EventTypes.DCOS_METADATA_CHANGE,
      this.onDCOSMetadataChange
    );

    global.window.removeEventListener('keydown', this.handleKeyPress, true);
  },

  onDCOSMetadataChange() {
    this.forceUpdate();
  },

  onNavigationChange() {
    this.forceUpdate();
  },

  handleInstallCLI() {
    SidebarActions.close();
    SidebarActions.openCliInstructions();
  },

  handleKeyPress(event) {
    let nodeName = event.target.nodeName;

    if (event.keyCode === keyCodes.leftBracket
      && !(nodeName === 'INPUT' || nodeName === 'TEXTAREA')
      && !(event.ctrlKey || event.metaKey || event.shiftKey)) {
      // #sidebarWidthChange is passed as a callback so that the sidebar
      // has had a chance to update before Gemini re-renders.
      this.setState({sidebarExpanded: !this.state.sidebarExpanded}, () => {
        SidebarActions.sidebarWidthChange();
        this.saveState_save();
      });
    }
  },

  handleVersionClick() {
    SidebarActions.close();
    SidebarActions.showVersions();
  },

  getNavigationSections() {
    const definition = NavigationService.getDefinition();

    return definition.map((group, index) => {
      let heading = null;

      if (group.category !== 'root') {
        heading = (

            {group.category}

        );
      }

      return (

          {heading}
          {this.getNavigationGroup(group)}

      );
    });
  },

  getNavigationGroup(group) {
    const menuItems = Hooks
      .applyFilter('sidebarNavigation', defaultMenuItems)
      .reduce((routesMap, path) => routesMap.set(path, true), new Map());

    const filteredItems = group.children
     .filter((route) => menuItems.has(route.path));

    let groupMenuItems = filteredItems.map((element, index) => {
      let {pathname} = this.props.location;

      let hasChildren = element.children && element.children.length !== 0;
      let isParentActive = pathname.startsWith(element.path);

      let submenu;
      let isChildActive = false;
      if (isParentActive && hasChildren) {
        [submenu, isChildActive] = this.getGroupSubmenu(
          group.path, element.children);
      }

      let linkElement = element.link;
      if (typeof linkElement === 'string') {
        linkElement = (
          <PrimarySidebarLink
            to={element.path}
            icon={element.options.icon}>
            {linkElement}
          </PrimarySidebarLink>
        );
      }

      let itemClassSet = classNames({
        'sidebar-menu-item': true,
        selected: isParentActive && !isChildActive,
        open: isParentActive && hasChildren
      });

      return (

          {linkElement}
          {submenu}

      );
    });

    return
{groupMenuItems}
;
  },

  getGroupSubmenu(path, children) {
    const {pathname} = this.props.location;
    let isChildActive = false;

    const childRoutesPaths = children.map(({path}) => path);
    const filteredPaths = Hooks
        .applyFilter('secondaryNavigation', path, childRoutesPaths);

    // Defaulting to unfiltered set of paths
    const childRoutesMap = (filteredPaths || childRoutesPaths)
        .reduce((routesMap, path) => routesMap.set(path, true), new Map());

    const filteredChildRoutes =
        children.filter(({path}) => childRoutesMap.has(path));

    let menuItems = filteredChildRoutes.reduce(function (children, currentChild, index) {
      let isActive = pathname.startsWith(currentChild.path);

      let menuItemClasses = classNames({selected: isActive});

      // First matched active child wins,
      // ie in /path/child and /path/child-path without this conditional /path/child-path
      // will always overrule /path/child
      if (!isChildActive && isActive) {
        isChildActive = true;
      }

      let linkElement = currentChild.link;
      if (typeof linkElement === 'string') {
        linkElement = <Link to={currentChild.path}>{linkElement}</Link>;
      }

      children.push(

          {linkElement}

      );

      return children;
    }, []);

    return [
{menuItems}
, isChildActive];
  },

  getVersion() {
    let data = MetadataStore.get('dcosMetadata');
    if (data == null || data.version == null) {
      return null;
    }

    return (
      v.{data.version}
    );
  },

  getFooter() {
    let defaultButtonSet = [(
      <Tooltip content="Documentation" key="button-docs" elementTag="a"
        href={MetadataStore.buildDocsURI('/')} target="_blank"
        wrapperClassName="button button-link tooltip-wrapper">
        <Icon className="clickable" id="pages" />
      </Tooltip>
    ), (
      <Tooltip content="Install CLI"
        key="button-cli" elementTag="a" onClick={this.handleInstallCLI}
        wrapperClassName="button button-link tooltip-wrapper">
        <Icon className="clickable" id="cli" />
      </Tooltip>
    )];

    let buttonSet = Hooks.applyFilter(
      'sidebarFooterButtonSet', defaultButtonSet
    );
    let footer = null;

    if (buttonSet && buttonSet.length) {
      footer =
{buttonSet}
;
    }

    return Hooks.applyFilter('sidebarFooter', footer, defaultButtonSet);
  },

  render() {
    let sidebarClasses = classNames('sidebar flex flex-direction-top-to-bottom',
      'flex-item-shrink-0', {
        'is-expanded': this.state.sidebarExpanded
      });

    return (

            <ClusterHeader />

        <GeminiScrollbar autoshow={true}
          className="navigation flex-item-grow-1 flex-item-shrink-1 gm-scrollbar-container-flex">

            {this.getNavigationSections()}

        </GeminiScrollbar>

              {this.getFooter()}

    );
  }

});

module.exports = Sidebar;
<|endoftext|>