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

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    var str     = view[param],
                        regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');

                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*?}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         *
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [];

            if (!Array.isArray(arr))
                throw(Error('arr should be array!'));

            ret = arr.map(function(item) {
                return item.name;
            });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret;

             if (!Array.isArray(array))
                throw(Error('array should be array!'));

            if (typeof name !== 'string')
                throw(Error('name should be string!'));

            array.some(function(item) {
                var is = item.name === name,
                    isArray = Util.type.array(item);

                if (is)
                    ret = item;
                else if (isArray)
                    item.some(function(item) {
                        is = item.name === name;

                        if (is)
                            ret = item.data;

                        return is;
                    });

                return is;
            });

            return ret;
        };

        /**
         * Gets current time in format hh:mm:ss
         */
        this.getTime                    = function() {
            var ret,
                date        = new Date(),
                hours       = date.getHours(),
                minutes     = date.getMinutes(),
                seconds     = date.getSeconds();

            minutes         = minutes < 10 ? '0' + minutes : minutes;
            seconds         = seconds < 10 ? '0' + seconds : seconds;

            ret            = hours + ':' + minutes + ':' + seconds;

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<commit_msg>feature(util) rm getTime<commit_after>(function(scope) {
    'use strict';

    var Scope = scope.window ? window : global;

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = Util.render(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        /**
         * function render template with view and own symbols
         *
         * @param templ
         * @param view
         */
        this.render = function(templ, view) {
            var result  = templ;

            Object
                .keys(view)
                .forEach(function(param) {
                    var str     = view[param],
                        regExp  = RegExp('{{\\s' + param + '\\s}}', 'g');

                    result  = result.replace(regExp, str);
                });

            if (~result.indexOf('{{'))
                result = result.replace(/{{.*?}}/g, '');

            return result;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */

            exec.with           =  function(callback) {
                var result,
                    bind        = Function.bind;

                arguments[0]    = null;
                result          = bind.apply(callback, arguments);

                return result;
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         *
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [];

            if (!Array.isArray(arr))
                throw(Error('arr should be array!'));

            ret = arr.map(function(item) {
                return item.name;
            });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret;

             if (!Array.isArray(array))
                throw(Error('array should be array!'));

            if (typeof name !== 'string')
                throw(Error('name should be string!'));

            array.some(function(item) {
                var is = item.name === name,
                    isArray = Util.type.array(item);

                if (is)
                    ret = item;
                else if (isArray)
                    item.some(function(item) {
                        is = item.name === name;

                        if (is)
                            ret = item.data;

                        return is;
                    });

                return is;
            });

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<|endoftext|>


<commit_before>var config = require("config")
var exec = require('child_process').exec

var exports = module.exports = {};

exports.checkBibUpdateTime = function(returnTimeOnly){

	var runWindow = config['BibUpdate']['runWindow']
	var date = new Date()
	var currentHour = date.getHours()

	if (returnTimeOnly) return (runWindow)

	if (runWindow.indexOf(parseInt(currentHour)) == -1 ){
		return false
	}else{
		return true
	}

}

exports.checkItemUpdateTime = function(returnTimeOnly){

	var runWindow = config['ItemUpdate']['runWindow']
	var date = new Date()
	var currentHour = date.getHours()

	if (returnTimeOnly) return (runWindow)

	if (runWindow.indexOf(parseInt(currentHour)) == -1 ){
		return false
	}else{
		return true
	}

}

//check for the filename of the script running in ps aux output and return true if it is already listed
exports.checkIfRunning = function(cb,threshold){

	//on linux servers running this as a cron job it will be 3
	if (!threshold) threshold = 3

	var child = exec("ps aux",
		function (error, stdout, stderr) {
			if (stdout.split(__filename).length > threshold){
				//console.log("Already running ",stdout.split(__filename).length)
				//log.info('[update_bib] Already running instance count: ', stdout.split('update_bib_new.js').length )
				//console.log("Already running")
				cb(true)
			}else{
				//console.log("Not running",__filename,stdout.split(__filename).length)
				cb(false)
			}
	})

}

//our own exit method to kill the process but allow the logger to finish up anything it is doing
exports.exit = function(){
	setTimeout(function(){process.exit()},2000)
}
<commit_msg>checkIfRunning fix<commit_after>var config = require("config")
var exec = require('child_process').exec

var exports = module.exports = {};

exports.checkBibUpdateTime = function(returnTimeOnly){

	var runWindow = config['BibUpdate']['runWindow']
	var date = new Date()
	var currentHour = date.getHours()

	if (returnTimeOnly) return (runWindow)

	if (runWindow.indexOf(parseInt(currentHour)) == -1 ){
		return false
	}else{
		return true
	}

}

exports.checkItemUpdateTime = function(returnTimeOnly){

	var runWindow = config['ItemUpdate']['runWindow']
	var date = new Date()
	var currentHour = date.getHours()

	if (returnTimeOnly) return (runWindow)

	if (runWindow.indexOf(parseInt(currentHour)) == -1 ){
		return false
	}else{
		return true
	}

}

//check for the filename of the script running in ps aux output and return true if it is already listed
exports.checkIfRunning = function(cb,threshold){

	//on linux servers running this as a cron job it will be 3
	if (!threshold) threshold = 3

	var scriptName = __filename.split("/")[__filename.split("/").length-1]

	var child = exec("ps aux",
		function (error, stdout, stderr) {
			if (stdout.split(scriptName).length > threshold){
				cb(true)
			}else{
				cb(false)
			}
	})

}

//our own exit method to kill the process but allow the logger to finish up anything it is doing
exports.exit = function(){
	setTimeout(function(){process.exit()},2000)
}
<|endoftext|>


<commit_before>import React from 'react';
import { Icon } from 'react-native-elements';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Keyboard,
} from 'react-native';
import md5 from 'react-native-md5';
import PropTypes from 'prop-types';
import { NavButton } from 'react-native-nav';
import { Actions } from 'react-native-router-flux';
import AppUtil from '../../lib/util';
import { AppStyles, AppColors } from '../../theme/';
import Group from '../../models/group';
import Network from '../../network';
import Application from '../../constants/config';
import { ListItemAvatar } from './';
import Constants from '../../models/constants';

const styles = StyleSheet.create({
  navContainer: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    flex: 1,
    paddingLeft: 0,
    flexDirection: 'row',
    paddingRight: 10,
    alignItems: 'center',
  },
  navButton: {
    width: 35,
    paddingRight: 15,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  roomInformation: {
    flex: 1,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleContainer: {
    flex: 1,
    zIndex: 200,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  avIcon: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  nameText: {
    textAlign: 'left',
    flex: 1,
    fontSize: 14,
  },
  titleText: {
    color: 'rgba(255,255,255,0.5)',
    fontSize: 12,
    marginBottom: 5,
    paddingLeft: 2,
    textAlign: 'left',
  },
  avatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',

  },
  avatarImage: {
    width: 36,
    height: 36,
    borderRadius: 18,
    position: 'absolute',
    zIndex: 20,
    left: 0,
    top: 0,
  },
  userAvatar: {
    position: 'absolute',
    zIndex: 10,
    left: -18,
    top: -18,
  },
  noAvatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noUserAvatar: {
    position: 'absolute',
    zIndex: 20,
    left: -18,
    top: -18,
  },
  iconWidth: {
    width: 20,
  },
  iconViews: {
    width: 40,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class ChatNavBar extends React.Component {
  constructor(props) {
    super(props);
    const obj = this.props.obj;
    this._net = new Network();
    this.displayName = obj.name;
    this.displayTitle = obj.title;
    this.roomType = obj.type;
    this.avatarUri = obj.avatar;
    this.state = {
      obj,
      displayName: this.displayName,
      displayTitle: this.displayTitle,
      avatarUri: this.avatarUri,
      showAvatar: true,
      roomType: this.roomType,
      icon: '',
      status: '',
    };
    this.goToRoomInfo = this.goToRoomInfo.bind(this);
  }

  componentWillMount() {
    let icon = '';
    let usr = {};
    switch (this.state.roomType) {
      case Constants.G_DIRECT:
        icon = 'at';
        break;
      case Constants.G_PUBLIC:
        icon = 'pound';
        break;
      case Constants.G_PRIVATE:
        icon = 'lock';
        break;
      default:
        icon = 'pound';
    }
    if (this.state.roomType === Constants.G_DIRECT) {
      usr = this._net.chat.service.db.users.findByUserName(this.state.displayName);
    } else {
      usr.status = Constants.U_OFFLINE;
    }
    this.setState({
      icon,
      status: (usr && usr.status) || Constants.U_OFFLINE,
    });
  }

  _renderAvatar() {
    if (this.state.showAvatar) {
      if (this.state.roomType === Constants.G_DIRECT) {
        let statColor = '#a8a8a8';
        switch (this.state.status) {
          case Constants.U_ONLINE:
            statColor = AppColors.status().online; break;
          case Constants.U_AWAY:
            statColor = AppColors.status().away; break;
          case Constants.U_BUSY:
            statColor = AppColors.status().busy; break;
          default:
            statColor = AppColors.status().default;
        }
        return (
          <View>
            <ListItemAvatar
              source={this.avatarUri}
              name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
              size={36}
            />
            <View style={{
              width: 10,
              height: 10,
              borderRadius: 5,
              position: 'absolute',
              left: 0,
              top: 0,
              backgroundColor: statColor,
            }}
            />
          </View>
        );
      }
      return (
        <View>
          <ListItemAvatar
            source={this.avatarUri}
            name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
            size={36}
          />
        </View>
      );
    }
  }

  _hideAvatarView() {
    this.setState({
      showAvatar: false,
    });
  }

  iconColor() {
    return 'rgba(255, 255, 255, 0.7)';
  }

  goToRoomInfo() {
    Keyboard.dismiss();
    if (this.state.roomType !== Constants.G_DIRECT) {
      Actions.roomInfo({
        group: this.state.obj,
        roomName: this.state.displayName,
        roomTitle: this.state.displayTitle,
        duration: 0,
      });
    } else {
      const user = this._net.chat.service.db.users.findByUserName(this.state.displayName);
      if (user) {
        Actions.memberDetail({ memberId: user._id, duration: 0 });
      }
    }
  }

  renderSearchIcon() {
    return (
      <NavButton
        style={[styles.iconViews]}
        onPress={() => Actions.messageSearch({ group: this.state.obj })}
      >
        <Icon
          name="search"
          size={24}
          color={'#FFF'}
        />
      </NavButton>
    );
  }

  renderGeoIcon = () => (
    <NavButton
      style={[styles.iconViews]}
      onPress={() => {
        Keyboard.dismiss();
        Actions.geoView();
      }}
    >
      <Icon
        type={'material-community'}
        name={'map-marker-plus'}
        size={28}
        color={'#FFF'}
      />
    </NavButton>
  )

  renderVideoConfIcon() {
    const mgvcConf = this._net.getServerSetting('MGVC_Enabled');
    const mgvcEnabled = mgvcConf && mgvcConf.value;
    if (mgvcEnabled === true) {
      const gname = this.state.obj.name;
      const gid = this.state.obj._id;
      const user = this._net.service.loggedInUserObj;
      const _super = this;
      const gtype = this.state.roomType;
      return (
        <NavButton
          style={[styles.iconViews]}
          onPress={() => {
            Keyboard.dismiss();
            const vcuserID = user ? md5.hex_md5(user._id) : '0';
            // const tempMsg = '@all Started Video conference';
            // _super._net.chat.sendMessage(gid, tempMsg);
            if (gtype === Constants.G_DIRECT) {
              _super._net.service.updateVideoCallStatus(gid, 'mgcall_init');
              Actions.directConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            } else {
              _super._net.service.startVideoConference(gid);
              Actions.videoConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            }
          }}
        >
          <Icon
            name={gtype === Constants.G_DIRECT ? 'phone' : 'videocam'}
            size={28}
            color={'#FFF'}
          />
        </NavButton>
      );
    }
    return null;
  }

  render() {
    return (
      <View
        style={[AppStyles.navbar, AppStyles.navbarHeight, styles.navContainer, {
          backgroundColor: AppColors.brand().secondary,
        },
        ]}
      >
        <NavButton
          style={[styles.navButton]}
          // onPress={() => { Actions.groups({ type: 'replace', duration: 0 }); }}
          onPress={() => { Actions.pop(); }}
        >
          <Icon
            name="keyboard-arrow-left"
            size={32}
            color={'#FFF'}
          />
        </NavButton>
        <TouchableOpacity
          style={[styles.roomInformation]}
          onPress={this.goToRoomInfo}
        >
          {this._renderAvatar()}
          <View style={[styles.titleContainer]}>
            <View style={styles.avIcon}>
              <Icon
                name={this.state.icon}
                type="material-community"
                size={14}
                style={{ height: 14 }}
                color={this.iconColor()}
              />
              <Text
                numberOfLines={1}
                style={[AppStyles.navbarTitle, styles.nameText]}
              >
                {this.state.roomType === Constants.G_DIRECT ? this.state.displayTitle : this.state.displayName}
              </Text>
            </View>
            <Text
              numberOfLines={1}
              style={[AppStyles.navbarTitle, styles.titleText]}
            >{this.state.status && this.state.roomType === Constants.G_DIRECT ?
              this.state.status : this.state.displayTitle}
            </Text>
          </View>
        </TouchableOpacity>
        {this.renderVideoConfIcon()}
        {this.renderGeoIcon()}
      </View>
    );
  }
}

ChatNavBar.defaultProps = {
  obj: null,
};

ChatNavBar.propTypes = {
  obj: PropTypes.instanceOf(Group),
};

/* Export Component ==================================================================== */
export default ChatNavBar;

<commit_msg>Removed VC and Geo buttons and created customButtons function<commit_after>import React from 'react';
import { Icon } from 'react-native-elements';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Keyboard,
} from 'react-native';

import PropTypes from 'prop-types';
import { NavButton } from 'react-native-nav';
import { Actions } from 'react-native-router-flux';
import AppUtil from '../../lib/util';
import { AppStyles, AppColors } from '../../theme/';
import Group from '../../models/group';
import Network from '../../network';

import { ListItemAvatar } from './';
import Constants from '../../models/constants';

const styles = StyleSheet.create({
  navContainer: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    flex: 1,
    paddingLeft: 0,
    flexDirection: 'row',
    paddingRight: 10,
    alignItems: 'center',
  },
  navButton: {
    width: 35,
    paddingRight: 15,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  roomInformation: {
    flex: 1,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleContainer: {
    flex: 1,
    zIndex: 200,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  avIcon: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  nameText: {
    textAlign: 'left',
    flex: 1,
    fontSize: 14,
  },
  titleText: {
    color: 'rgba(255,255,255,0.5)',
    fontSize: 12,
    marginBottom: 5,
    paddingLeft: 2,
    textAlign: 'left',
  },
  avatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',

  },
  avatarImage: {
    width: 36,
    height: 36,
    borderRadius: 18,
    position: 'absolute',
    zIndex: 20,
    left: 0,
    top: 0,
  },
  userAvatar: {
    position: 'absolute',
    zIndex: 10,
    left: -18,
    top: -18,
  },
  noAvatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noUserAvatar: {
    position: 'absolute',
    zIndex: 20,
    left: -18,
    top: -18,
  },
  iconWidth: {
    width: 20,
  },
  iconViews: {
    width: 40,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class ChatNavBar extends React.Component {
  constructor(props) {
    super(props);
    const obj = this.props.obj;
    this._net = new Network();
    this.customButtons = this.props.customButtons;
    this.displayName = obj.name;
    this.displayTitle = obj.title;
    this.roomType = obj.type;
    this.avatarUri = obj.avatar;
    this.state = {
      obj,
      displayName: this.displayName,
      displayTitle: this.displayTitle,
      avatarUri: this.avatarUri,
      showAvatar: true,
      roomType: this.roomType,
      icon: '',
      status: '',
    };
    this.goToRoomInfo = this.goToRoomInfo.bind(this);
  }

  componentWillMount() {
    let icon = '';
    let usr = {};
    switch (this.state.roomType) {
      case Constants.G_DIRECT:
        icon = 'at';
        break;
      case Constants.G_PUBLIC:
        icon = 'pound';
        break;
      case Constants.G_PRIVATE:
        icon = 'lock';
        break;
      default:
        icon = 'pound';
    }
    if (this.state.roomType === Constants.G_DIRECT) {
      usr = this._net.chat.service.db.users.findByUserName(this.state.displayName);
    } else {
      usr.status = Constants.U_OFFLINE;
    }
    this.setState({
      icon,
      status: (usr && usr.status) || Constants.U_OFFLINE,
    });
  }

  _renderAvatar() {
    if (this.state.showAvatar) {
      if (this.state.roomType === Constants.G_DIRECT) {
        let statColor = '#a8a8a8';
        switch (this.state.status) {
          case Constants.U_ONLINE:
            statColor = AppColors.status().online; break;
          case Constants.U_AWAY:
            statColor = AppColors.status().away; break;
          case Constants.U_BUSY:
            statColor = AppColors.status().busy; break;
          default:
            statColor = AppColors.status().default;
        }
        return (
          <View>
            <ListItemAvatar
              source={this.avatarUri}
              name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
              size={36}
            />
            <View style={{
              width: 10,
              height: 10,
              borderRadius: 5,
              position: 'absolute',
              left: 0,
              top: 0,
              backgroundColor: statColor,
            }}
            />
          </View>
        );
      }
      return (
        <View>
          <ListItemAvatar
            source={this.avatarUri}
            name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
            size={36}
          />
        </View>
      );
    }
  }

  _hideAvatarView() {
    this.setState({
      showAvatar: false,
    });
  }

  iconColor() {
    return 'rgba(255, 255, 255, 0.7)';
  }

  goToRoomInfo() {
    Keyboard.dismiss();
    if (this.state.roomType !== Constants.G_DIRECT) {
      Actions.roomInfo({
        group: this.state.obj,
        roomName: this.state.displayName,
        roomTitle: this.state.displayTitle,
        duration: 0,
      });
    } else {
      const user = this._net.chat.service.db.users.findByUserName(this.state.displayName);
      if (user) {
        Actions.memberDetail({ memberId: user._id, duration: 0 });
      }
    }
  }

  renderSearchIcon() {
    return (
      <NavButton
        style={[styles.iconViews]}
        onPress={() => Actions.messageSearch({ group: this.state.obj })}
      >
        <Icon
          name="search"
          size={24}
          color={'#FFF'}
        />
      </NavButton>
    );
  }

  render() {
    return (
      <View
        style={[AppStyles.navbar, AppStyles.navbarHeight, styles.navContainer, {
          backgroundColor: AppColors.brand().secondary,
        },
        ]}
      >
        <NavButton
          style={[styles.navButton]}
          // onPress={() => { Actions.groups({ type: 'replace', duration: 0 }); }}
          onPress={() => { Actions.pop(); }}
        >
          <Icon
            name="keyboard-arrow-left"
            size={32}
            color={'#FFF'}
          />
        </NavButton>
        <TouchableOpacity
          style={[styles.roomInformation]}
          onPress={this.goToRoomInfo}
        >
          {this._renderAvatar()}
          <View style={[styles.titleContainer]}>
            <View style={styles.avIcon}>
              <Icon
                name={this.state.icon}
                type="material-community"
                size={14}
                style={{ height: 14 }}
                color={this.iconColor()}
              />
              <Text
                numberOfLines={1}
                style={[AppStyles.navbarTitle, styles.nameText]}
              >
                {this.state.roomType === Constants.G_DIRECT ? this.state.displayTitle : this.state.displayName}
              </Text>
            </View>
            <Text
              numberOfLines={1}
              style={[AppStyles.navbarTitle, styles.titleText]}
            >{this.state.status && this.state.roomType === Constants.G_DIRECT ?
              this.state.status : this.state.displayTitle}
            </Text>
          </View>
        </TouchableOpacity>
        {this.customButtons()}
      </View>
    );
  }
}

ChatNavBar.defaultProps = {
  obj: null,
  customButtons: () => {},
};

ChatNavBar.propTypes = {
  obj: PropTypes.instanceOf(Group),
  customButtons: PropTypes.func,
};

/* Export Component ==================================================================== */
export default ChatNavBar;

<|endoftext|>


<commit_before>var util = require('util');

var noble = require('noble');

var NobleDevice = require('./noble-device');

function Util() {
}

Util.inherits = function(constructor, superConstructor, methods) {
  util.inherits(constructor, superConstructor);

  if (superConstructor === NobleDevice) {
    constructor.SCAN_UUIDS = constructor.SCAN_UUIDS || [];
    constructor.SCAN_DUPLICATES = constructor.SCAN_DUPLICATES || false;

    constructor.is = constructor.is || function(peripheral) {
      return true;
    };

    constructor.discover = function(callback) {
      var startScanningOnPowerOn = function() {
        if (noble.state === 'poweredOn') {
          var onDiscover = function(peripheral) {
            if (constructor.is(peripheral)) {
              noble.removeListener('discover', onDiscover);
              noble.stopScanning();

              var device = new constructor(peripheral);
              callback(device);
            }
          };

          noble.on('discover', onDiscover);

          noble.startScanning(constructor.SCAN_UUIDS, constructor.SCAN_DUPLICATES);
        } else {
          noble.once('stateChange', startScanningOnPowerOn);
        }
      };

      startScanningOnPowerOn();
    };
  }
};

Util.mixin = function(constructor, mixin, methods) {
  var allMethods = (methods === undefined);

  for (var i in mixin.prototype) {
    if (allMethods || methods.indexOf(i) !== -1) {
      constructor.prototype[i] = mixin.prototype[i];
    }
  }
};

module.exports = Util;
<commit_msg>- add exclude argument to Util.mixin<commit_after>var util = require('util');

var noble = require('noble');

var NobleDevice = require('./noble-device');

function Util() {
}

Util.inherits = function(constructor, superConstructor) {
  util.inherits(constructor, superConstructor);

  if (superConstructor === NobleDevice) {
    constructor.SCAN_UUIDS = constructor.SCAN_UUIDS || [];
    constructor.SCAN_DUPLICATES = constructor.SCAN_DUPLICATES || false;

    constructor.is = constructor.is || function(peripheral) {
      return true;
    };

    constructor.discover = function(callback) {
      var startScanningOnPowerOn = function() {
        if (noble.state === 'poweredOn') {
          var onDiscover = function(peripheral) {
            if (constructor.is(peripheral)) {
              noble.removeListener('discover', onDiscover);
              noble.stopScanning();

              var device = new constructor(peripheral);
              callback(device);
            }
          };

          noble.on('discover', onDiscover);

          noble.startScanning(constructor.SCAN_UUIDS, constructor.SCAN_DUPLICATES);
        } else {
          noble.once('stateChange', startScanningOnPowerOn);
        }
      };

      startScanningOnPowerOn();
    };
  }
};

Util.mixin = function(constructor, mixin, includedMethods, excludedMethods) {
  excludedMethods = excludedMethods || [];

  for (var i in mixin.prototype) {
    var include = (!includedMethods) || (includedMethods.indexOf(i) !== -1);
    var exclude = (excludedMethods.indexOf(i) !== -1);

    if (include && !exclude) {
      constructor.prototype[i] = mixin.prototype[i];
    }
  }
};

module.exports = Util;
<|endoftext|>


<commit_before>import React from 'react';
import { Icon } from 'react-native-elements';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Keyboard,
} from 'react-native';
import md5 from 'react-native-md5';
import PropTypes from 'prop-types';
import { NavButton } from 'react-native-nav';
import { Actions } from 'react-native-router-flux';
import AppUtil from '../../lib/util';
import { AppStyles, AppColors } from '../../theme/';
import Group from '../../models/group';
import Network from '../../network';
import Application from '../../constants/config';
import { ListItemAvatar } from './';
import Constants from '../../models/constants';

const styles = StyleSheet.create({
  navContainer: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    flex: 1,
    paddingLeft: 0,
    flexDirection: 'row',
    paddingRight: 10,
    alignItems: 'center',
  },
  navButton: {
    width: 35,
    paddingRight: 15,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  roomInformation: {
    flex: 1,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleContainer: {
    flex: 1,
    zIndex: 200,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  avIcon: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  nameText: {
    textAlign: 'left',
    flex: 1,
    fontSize: 14,
  },
  titleText: {
    color: 'rgba(255,255,255,0.5)',
    fontSize: 12,
    marginBottom: 5,
    paddingLeft: 2,
    textAlign: 'left',
  },
  avatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',

  },
  avatarImage: {
    width: 36,
    height: 36,
    borderRadius: 18,
    position: 'absolute',
    zIndex: 20,
    left: 0,
    top: 0,
  },
  userAvatar: {
    position: 'absolute',
    zIndex: 10,
    left: -18,
    top: -18,
  },
  noAvatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noUserAvatar: {
    position: 'absolute',
    zIndex: 20,
    left: -18,
    top: -18,
  },
  iconWidth: {
    width: 20,
  },
  iconViews: {
    width: 40,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class ChatNavBar extends React.Component {
  constructor(props) {
    super(props);
    const obj = this.props.obj;
    this._net = new Network();
    this.displayName = obj.name;
    this.displayTitle = obj.title;
    this.roomType = obj.type;
    this.avatarUri = obj.avatar;
    this.state = {
      obj,
      displayName: this.displayName,
      displayTitle: this.displayTitle,
      avatarUri: this.avatarUri,
      showAvatar: true,
      roomType: this.roomType,
      icon: '',
      status: '',
    };
    this.goToRoomInfo = this.goToRoomInfo.bind(this);
  }

  componentWillMount() {
    let icon = '';
    let usr = {};
    switch (this.state.roomType) {
      case Constants.G_DIRECT:
        icon = 'at';
        break;
      case Constants.G_PUBLIC:
        icon = 'pound';
        break;
      case Constants.G_PRIVATE:
        icon = 'lock';
        break;
      default:
        icon = 'pound';
    }
    if (this.state.roomType === Constants.G_DIRECT) {
      usr = this._net.chat.service.db.users.findByUserName(this.state.displayName);
    } else {
      usr.status = Constants.U_OFFLINE;
    }
    this.setState({
      icon,
      status: usr.status,
    });
  }

  _renderAvatar() {
    if (this.state.showAvatar) {
      if (this.state.roomType === Constants.G_DIRECT) {
        let statColor = '#a8a8a8';
        switch (this.state.status) {
          case Constants.U_ONLINE:
            statColor = AppColors.status().online; break;
          case Constants.U_AWAY:
            statColor = AppColors.status().away; break;
          case Constants.U_BUSY:
            statColor = AppColors.status().busy; break;
          default:
            statColor = AppColors.status().default;
        }
        return (
          <View>
            <ListItemAvatar
              source={this.avatarUri}
              name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
              size={36}
            />
            <View style={{
              width: 10,
              height: 10,
              borderRadius: 5,
              position: 'absolute',
              left: 0,
              top: 0,
              backgroundColor: statColor,
            }}
            />
          </View>
        );
      }
      return (
        <View>
          <ListItemAvatar
            source={this.avatarUri}
            name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
            size={36}
          />
        </View>
      );
    }
  }

  _hideAvatarView() {
    this.setState({
      showAvatar: false,
    });
  }

  iconColor() {
    return 'rgba(255, 255, 255, 0.7)';
  }

  goToRoomInfo() {
    Keyboard.dismiss();
    if (this.state.roomType !== Constants.G_DIRECT) {
      Actions.roomInfo({
        group: this.state.obj,
        roomName: this.state.displayName,
        roomTitle: this.state.displayTitle,
        duration: 0,
      });
    } else {
      const user = this._net.chat.service.db.users.findByUserName(this.state.displayName);
      if (user) {
        Actions.memberDetail({ memberId: user._id, duration: 0 });
      }
    }
  }

  renderSearchIcon() {
    return (
      <NavButton
        style={[styles.iconViews]}
        onPress={() => Actions.messageSearch({ group: this.state.obj })}
      >
        <Icon
          name="search"
          size={24}
          color={'#FFF'}
        />
      </NavButton>
    );
  }

  renderVideoConfIcon() {
    const mgvcConf = this._net.getServerSetting('MGVC_Enabled');
    const mgvcEnabled = mgvcConf && mgvcConf.value;
    if (mgvcEnabled === true) {
      const gname = this.state.obj.name;
      const gid = this.state.obj._id;
      const user = this._net.service.loggedInUserObj;
      const _super = this;
      const gtype = this.state.roomType;
      return (
        <NavButton
          style={[styles.iconViews]}
          onPress={() => {
            Keyboard.dismiss();
            const vcuserID = user ? md5.hex_md5(user._id) : '0';
            _super._net.service.startVideoConference(gid);
            // const tempMsg = '@all Started Video conference';
            // _super._net.chat.sendMessage(gid, tempMsg);
            if (gtype === Constants.G_DIRECT) {
              Actions.directConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            } else {
              Actions.videoConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            }
          }}
        >
          <Icon
            name={gtype === Constants.G_DIRECT ? 'phone' : 'videocam'}
            size={28}
            color={'#FFF'}
          />
        </NavButton>
      );
    }
    return null;
  }

  render() {
    return (
      <View
        style={[AppStyles.navbar, AppStyles.navbarHeight, styles.navContainer, {
          backgroundColor: AppColors.brand().secondary,
        },
        ]}
      >
        <NavButton
          style={[styles.navButton]}
          // onPress={() => { Actions.groups({ type: 'replace', duration: 0 }); }}
          onPress={() => { Actions.pop(); }}
        >
          <Icon
            name="keyboard-arrow-left"
            size={32}
            color={'#FFF'}
          />
        </NavButton>
        <TouchableOpacity
          style={[styles.roomInformation]}
          onPress={this.goToRoomInfo}
        >
          {this._renderAvatar()}
          <View style={[styles.titleContainer]}>
            <View style={styles.avIcon}>
              <Icon
                name={this.state.icon}
                type="material-community"
                size={14}
                style={{ height: 14 }}
                color={this.iconColor()}
              />
              <Text
                numberOfLines={1}
                style={[AppStyles.navbarTitle, styles.nameText]}
              >
                {this.state.roomType === Constants.G_DIRECT ? this.state.displayTitle : this.state.displayName}
              </Text>
            </View>
            <Text
              numberOfLines={1}
              style={[AppStyles.navbarTitle, styles.titleText]}
            >{this.state.status && this.state.roomType === Constants.G_DIRECT ?
              this.state.status : this.state.displayTitle}
            </Text>
          </View>
        </TouchableOpacity>
        {this.renderVideoConfIcon()}
      </View>
    );
  }
}

ChatNavBar.defaultProps = {
  obj: null,
};

ChatNavBar.propTypes = {
  obj: PropTypes.instanceOf(Group),
};

/* Export Component ==================================================================== */
export default ChatNavBar;

<commit_msg>Temporary map icon added for geo testing route<commit_after>import React from 'react';
import { Icon } from 'react-native-elements';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Keyboard,
} from 'react-native';
import md5 from 'react-native-md5';
import PropTypes from 'prop-types';
import { NavButton } from 'react-native-nav';
import { Actions } from 'react-native-router-flux';
import AppUtil from '../../lib/util';
import { AppStyles, AppColors } from '../../theme/';
import Group from '../../models/group';
import Network from '../../network';
import Application from '../../constants/config';
import { ListItemAvatar } from './';
import Constants from '../../models/constants';

const styles = StyleSheet.create({
  navContainer: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    flex: 1,
    paddingLeft: 0,
    flexDirection: 'row',
    paddingRight: 10,
    alignItems: 'center',
  },
  navButton: {
    width: 35,
    paddingRight: 15,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  roomInformation: {
    flex: 1,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleContainer: {
    flex: 1,
    zIndex: 200,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  avIcon: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  nameText: {
    textAlign: 'left',
    flex: 1,
    fontSize: 14,
  },
  titleText: {
    color: 'rgba(255,255,255,0.5)',
    fontSize: 12,
    marginBottom: 5,
    paddingLeft: 2,
    textAlign: 'left',
  },
  avatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',

  },
  avatarImage: {
    width: 36,
    height: 36,
    borderRadius: 18,
    position: 'absolute',
    zIndex: 20,
    left: 0,
    top: 0,
  },
  userAvatar: {
    position: 'absolute',
    zIndex: 10,
    left: -18,
    top: -18,
  },
  noAvatarView: {
    width: 36,
    height: 36,
    paddingHorizontal: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  noUserAvatar: {
    position: 'absolute',
    zIndex: 20,
    left: -18,
    top: -18,
  },
  iconWidth: {
    width: 20,
  },
  iconViews: {
    width: 40,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

class ChatNavBar extends React.Component {
  constructor(props) {
    super(props);
    const obj = this.props.obj;
    this._net = new Network();
    this.displayName = obj.name;
    this.displayTitle = obj.title;
    this.roomType = obj.type;
    this.avatarUri = obj.avatar;
    this.state = {
      obj,
      displayName: this.displayName,
      displayTitle: this.displayTitle,
      avatarUri: this.avatarUri,
      showAvatar: true,
      roomType: this.roomType,
      icon: '',
      status: '',
    };
    this.goToRoomInfo = this.goToRoomInfo.bind(this);
  }

  componentWillMount() {
    let icon = '';
    let usr = {};
    switch (this.state.roomType) {
      case Constants.G_DIRECT:
        icon = 'at';
        break;
      case Constants.G_PUBLIC:
        icon = 'pound';
        break;
      case Constants.G_PRIVATE:
        icon = 'lock';
        break;
      default:
        icon = 'pound';
    }
    if (this.state.roomType === Constants.G_DIRECT) {
      usr = this._net.chat.service.db.users.findByUserName(this.state.displayName);
    } else {
      usr.status = Constants.U_OFFLINE;
    }
    this.setState({
      icon,
      status: usr.status,
    });
  }

  _renderAvatar() {
    if (this.state.showAvatar) {
      if (this.state.roomType === Constants.G_DIRECT) {
        let statColor = '#a8a8a8';
        switch (this.state.status) {
          case Constants.U_ONLINE:
            statColor = AppColors.status().online; break;
          case Constants.U_AWAY:
            statColor = AppColors.status().away; break;
          case Constants.U_BUSY:
            statColor = AppColors.status().busy; break;
          default:
            statColor = AppColors.status().default;
        }
        return (
          <View>
            <ListItemAvatar
              source={this.avatarUri}
              name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
              size={36}
            />
            <View style={{
              width: 10,
              height: 10,
              borderRadius: 5,
              position: 'absolute',
              left: 0,
              top: 0,
              backgroundColor: statColor,
            }}
            />
          </View>
        );
      }
      return (
        <View>
          <ListItemAvatar
            source={this.avatarUri}
            name={AppUtil.avatarInitials(this.state.displayTitle ? this.state.displayTitle : this.state.displayName)}
            size={36}
          />
        </View>
      );
    }
  }

  _hideAvatarView() {
    this.setState({
      showAvatar: false,
    });
  }

  iconColor() {
    return 'rgba(255, 255, 255, 0.7)';
  }

  goToRoomInfo() {
    Keyboard.dismiss();
    if (this.state.roomType !== Constants.G_DIRECT) {
      Actions.roomInfo({
        group: this.state.obj,
        roomName: this.state.displayName,
        roomTitle: this.state.displayTitle,
        duration: 0,
      });
    } else {
      const user = this._net.chat.service.db.users.findByUserName(this.state.displayName);
      if (user) {
        Actions.memberDetail({ memberId: user._id, duration: 0 });
      }
    }
  }

  renderSearchIcon() {
    return (
      <NavButton
        style={[styles.iconViews]}
        onPress={() => Actions.messageSearch({ group: this.state.obj })}
      >
        <Icon
          name="search"
          size={24}
          color={'#FFF'}
        />
      </NavButton>
    );
  }

  renderGeoIcon = () => {
    return (
      <NavButton
        style={[styles.iconViews]}
        onPress={() => {
          Keyboard.dismiss();
          Actions.geoView();
        }}
      >
        <Icon
          type={'material-community'}
          name={'map-marker-plus'}
          size={28}
          color={'#FFF'}
        />
      </NavButton>
    );
  }

  renderVideoConfIcon() {
    const mgvcConf = this._net.getServerSetting('MGVC_Enabled');
    const mgvcEnabled = mgvcConf && mgvcConf.value;
    if (mgvcEnabled === true) {
      const gname = this.state.obj.name;
      const gid = this.state.obj._id;
      const user = this._net.service.loggedInUserObj;
      const _super = this;
      const gtype = this.state.roomType;
      return (
        <NavButton
          style={[styles.iconViews]}
          onPress={() => {
            Keyboard.dismiss();
            const vcuserID = user ? md5.hex_md5(user._id) : '0';
            _super._net.service.startVideoConference(gid);
            // const tempMsg = '@all Started Video conference';
            // _super._net.chat.sendMessage(gid, tempMsg);
            if (gtype === Constants.G_DIRECT) {
              Actions.directConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            } else {
              Actions.videoConference({
                instance: Application.instance,
                groupName: gname,
                groupID: gid,
                groupType: gtype,
                userID: vcuserID,
                callType: 'OUTGOING',
              });
            }
          }}
        >
          <Icon
            name={gtype === Constants.G_DIRECT ? 'phone' : 'videocam'}
            size={28}
            color={'#FFF'}
          />
        </NavButton>
      );
    }
    return null;
  }

  render() {
    return (
      <View
        style={[AppStyles.navbar, AppStyles.navbarHeight, styles.navContainer, {
          backgroundColor: AppColors.brand().secondary,
        },
        ]}
      >
        <NavButton
          style={[styles.navButton]}
          // onPress={() => { Actions.groups({ type: 'replace', duration: 0 }); }}
          onPress={() => { Actions.pop(); }}
        >
          <Icon
            name="keyboard-arrow-left"
            size={32}
            color={'#FFF'}
          />
        </NavButton>
        <TouchableOpacity
          style={[styles.roomInformation]}
          onPress={this.goToRoomInfo}
        >
          {this._renderAvatar()}
          <View style={[styles.titleContainer]}>
            <View style={styles.avIcon}>
              <Icon
                name={this.state.icon}
                type="material-community"
                size={14}
                style={{ height: 14 }}
                color={this.iconColor()}
              />
              <Text
                numberOfLines={1}
                style={[AppStyles.navbarTitle, styles.nameText]}
              >
                {this.state.roomType === Constants.G_DIRECT ? this.state.displayTitle : this.state.displayName}
              </Text>
            </View>
            <Text
              numberOfLines={1}
              style={[AppStyles.navbarTitle, styles.titleText]}
            >{this.state.status && this.state.roomType === Constants.G_DIRECT ?
              this.state.status : this.state.displayTitle}
            </Text>
          </View>
        </TouchableOpacity>
        {this.renderVideoConfIcon()}
        {this.renderGeoIcon()}
      </View>
    );
  }
}

ChatNavBar.defaultProps = {
  obj: null,
};

ChatNavBar.propTypes = {
  obj: PropTypes.instanceOf(Group),
};

/* Export Component ==================================================================== */
export default ChatNavBar;

<|endoftext|>


<commit_before>var c = require('chalk')
var fs = require('fs-extra')
var isDir = require('is-directory')
var YAML = require('yamljs')

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

var util = module.exports = {

  script: {
    apatani: 'aldc',
    galo: 'gws',
    nyishi: 'nes',
    adi: 'abk'
  },

  ignore: [
    '.DS_Store',
    '*-all.txt',
    'notes.txt',
    'meta.yml'
  ],

  concepts: {
    'n': 'noun',
    'nm': 'noun modifier',
    'v': 'verb',
    'vm': 'verb modifier',
    'adj': 'adjective',
    'adjm': 'adjective modifier',
    'conj': 'conjunctions',
    'intjn': 'interjection',
    'intrg': 'interrogation',
    'prn': 'pronoun'
  },

  errors: {
    notFound: function (localityPath) {
      console.log('\n '+  c.bold(localityPath) +' not found\n')
    },
    invalidFormat: function (command) {
      console.log(c.red('\n Invalid format\n'))
      console.log(' Use the format ' + c.bold('tani % <tribe/locality>', command))
      console.log(' Ex: tani %s adi/geling\n', command)
    }
  },

  // change the index of a file in a dir
  moveFileIndex: function(targetDir, fromIndex, toIndex) {

    fromIndex = +fromIndex
    toIndex = +toIndex

    // increment not required
    if (fromIndex == toIndex) return

    var fileToBeMoved = targetDir + '/' + fromIndex + '.txt'
    var tempName = fileToBeMoved + '_'
    fs.renameSync(fileToBeMoved, tempName)

    if (fromIndex > toIndex) {

      var counter = fromIndex - 1
      while (counter >= toIndex) {
        fs.renameSync(targetDir + '/' + counter + '.txt', targetDir + '/' + (counter + 1) + '.txt')
        counter--
      }

    } else {

      var counter = fromIndex + 1
      while (counter <= toIndex) {
        fs.renameSync(targetDir + '/' + counter + '.txt', targetDir + '/' + (counter - 1) + '.txt')
        counter++
      }

    }

    fs.renameSync(tempName, targetDir + '/' + toIndex + '.txt')

  },

  // what would be the file id (name) for the next file to be created in the dir?
  getNextFileId: function(targetDir) {

    if (!fs.existsSync(targetDir)) return 1;

    var highestNumber = 0
    fs.readdirSync(targetDir).forEach(function (file) {
      var filePath = targetDir + '/' + file
      if (!isDir.sync(filePath)) {
        var candidate = parseInt(file)
        if (candidate > highestNumber) {
          highestNumber = candidate
        }
      }
    })

    return ++highestNumber

  },

  hasDialectEntry: function hasDialectEntry(string) {
    return getEntry(string).length
  },

  getDialectEntry: function checkDialectEntry(string) {
    return getEntry(string)
  },

  getGlobalIdFromFile: function getGlobalIdFromFile(dialectFilePath, localityPath) {
    return dialectFilePath.split(localityPath)[1].replace(/\//g, '').replace('.txt', '').toUpperCase()
  },

  generateDialectFile: function generateDialectFile(conceptFilelocalityPath, dialectFilelocalityPath) {

    var entry = YAML.load(conceptFilelocalityPath)
    fs.createFileSync(dialectFilelocalityPath)

    var includeString = 'Concept: ' + entry.Concept + '\n'
    if (entry.Note) includeString += 'Note: ' + entry.Note + '\n'
    if (entry.Examples) {
      includeString += 'Examples:\n'
      entry.Examples.forEach(function (example) {
        var dialect = Object.keys(example)[0]
        var exampleString = example[dialect]
        includeString += '  - ' + dialect + ': ' + exampleString + '\n'
      })
    }
    includeString += '------------\n'
    includeString += 'Translation: \n'
    includeString += 'Example: \n'

    fs.writeFileSync(dialectFilelocalityPath, includeString)

  },

  updateDialectFile: function updateDialectFile(conceptFilelocalityPath, dialectFilelocalityPath) {

    var entry = YAML.load(conceptFilelocalityPath)
    var dialectFileContent = fs.readFileSync(dialectFilelocalityPath).toString()
    var temp = dialectFileContent.split('------------')
    var conceptYaml = temp[0]
    var dialectEntry = temp[1]
    var dialectYamlObj = YAML.parse(conceptYaml)

    // update
    if (entry.Concept !== dialectYamlObj.Concept
      || (entry.Note && entry.Note !== dialectYamlObj.Note)
      || (entry.Examples && entry.Examples !== dialectYamlObj.Examples)) {

        var includeString = 'Concept: ' + entry.Concept + '\n'
        if (entry.Note) includeString += 'Note: ' + entry.Note + '\n'
        if (entry.Examples) {
          includeString += 'Examples:\n'
          entry.Examples.forEach(function (example) {
            var dialect = Object.keys(example)[0]
            var exampleString = example[dialect]
            includeString += '  - ' + dialect + ': ' + exampleString + '\n'
          })
        }

        includeString += '------------'
        includeString += dialectEntry

        fs.writeFileSync(dialectFilelocalityPath, includeString)
    }

  },

}

function getEntry(string) {
  var temp = string.split('Root:')
  var entry = temp[1].split('\n')[0]
  return entry.trim()
}
<commit_msg>refactor move<commit_after>var c = require('chalk')
var fs = require('fs-extra')
var isDir = require('is-directory')
var YAML = require('yamljs')

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

var util = module.exports = {

  script: {
    apatani: 'aldc',
    galo: 'gws',
    nyishi: 'nes',
    adi: 'abk'
  },

  ignore: [
    '.DS_Store',
    '*-all.txt',
    'notes.txt',
    'meta.yml'
  ],

  concepts: {
    'n': 'noun',
    'nm': 'noun modifier',
    'v': 'verb',
    'vm': 'verb modifier',
    'adj': 'adjective',
    'adjm': 'adjective modifier',
    'conj': 'conjunctions',
    'intjn': 'interjection',
    'intrg': 'interrogation',
    'prn': 'pronoun'
  },

  errors: {
    notFound: function (localityPath) {
      console.log('\n '+  c.bold(localityPath) +' not found\n')
    },
    invalidFormat: function (command) {
      console.log(c.red('\n Invalid format\n'))
      console.log(' Use the format ' + c.bold('tani % <tribe/locality>', command))
      console.log(' Ex: tani %s adi/geling\n', command)
    }
  },

  // change the index of a file in a dir
  moveFileIndex: function(targetDir, fromIndex, toIndex) {

    fromIndex = +fromIndex
    toIndex = +toIndex

    // increment not required
    if (fromIndex == toIndex) return

    var fileToBeMoved = targetDir + '/' + fromIndex + '.txt'
    var tempName = fileToBeMoved + '_'
    fs.renameSync(fileToBeMoved, tempName)
    var destinationName = targetDir + '/' + toIndex + '.txt'

    if (fromIndex > toIndex) {

      var counter = fromIndex - 1
      while (counter >= toIndex) {
        var oldName = targetDir + '/' + counter + '.txt'
        var newName = targetDir + '/' + (counter + 1) + '.txt'
        fs.renameSync(oldName, newName)
        counter--
      }

    } else {

      var counter = fromIndex + 1
      while (counter <= toIndex) {
        var oldName = targetDir + '/' + counter + '.txt'
        var newName = targetDir + '/' + (counter - 1) + '.txt'
        fs.renameSync(oldName, newName)
        counter++
      }

    }

    fs.renameSync(tempName, destinationName)

  },

  // what would be the file id (name) for the next file to be created in the dir?
  getNextFileId: function(targetDir) {

    if (!fs.existsSync(targetDir)) return 1;

    var highestNumber = 0
    fs.readdirSync(targetDir).forEach(function (file) {
      var filePath = targetDir + '/' + file
      if (!isDir.sync(filePath)) {
        var candidate = parseInt(file)
        if (candidate > highestNumber) {
          highestNumber = candidate
        }
      }
    })

    return ++highestNumber

  },

  hasDialectEntry: function hasDialectEntry(string) {
    return getEntry(string).length
  },

  getDialectEntry: function checkDialectEntry(string) {
    return getEntry(string)
  },

  getGlobalIdFromFile: function getGlobalIdFromFile(dialectFilePath, localityPath) {
    return dialectFilePath.split(localityPath)[1].replace(/\//g, '').replace('.txt', '').toUpperCase()
  },

  generateDialectFile: function generateDialectFile(conceptFilelocalityPath, dialectFilelocalityPath) {

    var entry = YAML.load(conceptFilelocalityPath)
    fs.createFileSync(dialectFilelocalityPath)

    var includeString = 'Concept: ' + entry.Concept + '\n'
    if (entry.Note) includeString += 'Note: ' + entry.Note + '\n'
    if (entry.Examples) {
      includeString += 'Examples:\n'
      entry.Examples.forEach(function (example) {
        var dialect = Object.keys(example)[0]
        var exampleString = example[dialect]
        includeString += '  - ' + dialect + ': ' + exampleString + '\n'
      })
    }
    includeString += '------------\n'
    includeString += 'Translation: \n'
    includeString += 'Example: \n'

    fs.writeFileSync(dialectFilelocalityPath, includeString)

  },

  updateDialectFile: function updateDialectFile(conceptFilelocalityPath, dialectFilelocalityPath) {

    var entry = YAML.load(conceptFilelocalityPath)
    var dialectFileContent = fs.readFileSync(dialectFilelocalityPath).toString()
    var temp = dialectFileContent.split('------------')
    var conceptYaml = temp[0]
    var dialectEntry = temp[1]
    var dialectYamlObj = YAML.parse(conceptYaml)

    // update
    if (entry.Concept !== dialectYamlObj.Concept
      || (entry.Note && entry.Note !== dialectYamlObj.Note)
      || (entry.Examples && entry.Examples !== dialectYamlObj.Examples)) {

        var includeString = 'Concept: ' + entry.Concept + '\n'
        if (entry.Note) includeString += 'Note: ' + entry.Note + '\n'
        if (entry.Examples) {
          includeString += 'Examples:\n'
          entry.Examples.forEach(function (example) {
            var dialect = Object.keys(example)[0]
            var exampleString = example[dialect]
            includeString += '  - ' + dialect + ': ' + exampleString + '\n'
          })
        }

        includeString += '------------'
        includeString += dialectEntry

        fs.writeFileSync(dialectFilelocalityPath, includeString)
    }

  },

}

function getEntry(string) {
  var temp = string.split('Root:')
  var entry = temp[1].split('\n')[0]
  return entry.trim()
}
<|endoftext|>


<commit_before>var path  = require("path"),
    fs = require("fs");

/**
 * @namespace Generic utility class.
 * @name Util
 */
module.exports = /** @lends Util.prototype */ {

  /**
   * Creates the given path, along with any missing paths in the hierarchy in a synchronous manner.  See FileSystem.mkdirSync in the node documentation.
   */
  mkdirpSync: function(_path, mode) {
    mode = mode || 0755;

    if (!_path || _path.length < 1) {
      return {result:false, err:"path is required"};
    } else {

      var absolute = path.resolve(_path),
          parts = absolute.split(path.sep),
          curr = parts[0] || path.resolve(path.sep);

      while (parts.length > 0) {
        curr = path.resolve(curr, parts.shift());
        if (! path.existsSync(curr)) {
          try {
            fs.mkdirSync(curr, mode);
          } catch (ex) {
            console.error(ex.message);
            return {result:false, err:ex.message};
          }
        }
      }
      return {result:true};
    } // end else
  },

  /**
   * This function should allow the original object to be extended in such a way that if the
   * new object (n) already contains a property of the old (o) and it is an object, it delves
   * into the old object and overrides individual properties instead of replacing the whole
   * object.  Likewise, if a property is an array, it should concatenate the new onto the old
   * rather than replacing the entire array (think config.json: resources.packages property).
   *
   * NOTE: This is a simple implementation, in that we're not extending getters and setters properly.
   * Only use this for simple data model type objects.
   *
   * @param {Object} n The object to augment
   * @param {Object} o The object to augment from
   */
  recursiveExtend: function(n, o) {
    var type = null;
    for (var p in o) {

      if (n[p] && typeof(n[p]) === "object") {
        n[p] = module.exports.recursiveExtend(n[p], o[p]);
      } else if (n[p] && typeof(n[p]) === "array" && o[p] && typeof(o[p]) === "array") {
        n[p] = o[p].concat(n[p]);
      } else {
        n[p] = o[p];
      }
    }
    return n;
  }
};

/**
 * Converts a Date instance to an array with index of descending granularity (year, month, day, hour, min, sec).  This is useful for storing dates in document databases, since Date serializes to Object.
 * @augments Date
 * @returns {Array}
 */
Date.prototype.toArray = function(){
  return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()];
};

/**
 * Deserializes an array back into a date object.  Months (index 1) /must/ be one-based!
 * @augments Date
 * @static
 * @returns {Date}
 */
Date.fromArray = function(array) {
  if (array) {
    if (array.length < 7) {
      for (var i = array.length; i <= 7; i++) { array.push(0); }
      if (array[2] === 0) array[2] = 1; // Months are 1-based in Date
    }
    return new Date(array[0], array[1], array[2], array[3], array[4]. array[5], array[6]);
  }
  return null;
};<commit_msg>Fix fromArray syntax problem<commit_after>var path  = require("path"),
    fs = require("fs");

/**
 * @namespace Generic utility class.
 * @name Util
 */
module.exports = /** @lends Util.prototype */ {

  /**
   * Creates the given path, along with any missing paths in the hierarchy in a synchronous manner.  See FileSystem.mkdirSync in the node documentation.
   */
  mkdirpSync: function(_path, mode) {
    mode = mode || 0755;

    if (!_path || _path.length < 1) {
      return {result:false, err:"path is required"};
    } else {

      var absolute = path.resolve(_path),
          parts = absolute.split(path.sep),
          curr = parts[0] || path.resolve(path.sep);

      while (parts.length > 0) {
        curr = path.resolve(curr, parts.shift());
        if (! path.existsSync(curr)) {
          try {
            fs.mkdirSync(curr, mode);
          } catch (ex) {
            console.error(ex.message);
            return {result:false, err:ex.message};
          }
        }
      }
      return {result:true};
    } // end else
  },

  /**
   * This function should allow the original object to be extended in such a way that if the
   * new object (n) already contains a property of the old (o) and it is an object, it delves
   * into the old object and overrides individual properties instead of replacing the whole
   * object.  Likewise, if a property is an array, it should concatenate the new onto the old
   * rather than replacing the entire array (think config.json: resources.packages property).
   *
   * NOTE: This is a simple implementation, in that we're not extending getters and setters properly.
   * Only use this for simple data model type objects.
   *
   * @param {Object} n The object to augment
   * @param {Object} o The object to augment from
   */
  recursiveExtend: function(n, o) {
    var type = null;
    for (var p in o) {

      if (n[p] && typeof(n[p]) === "object") {
        n[p] = module.exports.recursiveExtend(n[p], o[p]);
      } else if (n[p] && typeof(n[p]) === "array" && o[p] && typeof(o[p]) === "array") {
        n[p] = o[p].concat(n[p]);
      } else {
        n[p] = o[p];
      }
    }
    return n;
  }
};

/**
 * Converts a Date instance to an array with index of descending granularity (year, month, day, hour, min, sec).  This is useful for storing dates in document databases, since Date serializes to Object.
 * @augments Date
 * @returns {Array}
 */
Date.prototype.toArray = function(){
  return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()];
};

/**
 * Deserializes an array back into a date object.  Months (index 1) /must/ be one-based!
 * @augments Date
 * @static
 * @returns {Date}
 */
Date.fromArray = function(array) {
  if (array) {
    if (array.length < 7) {
      for (var i = array.length; i <= 7; i++) { array.push(0); }
      if (array[2] === 0) array[2] = 1; // Months are 1-based in Date
    }
    return new Date(array[0], array[1], array[2], array[3], array[4], array[5], array[6]);
  }
  return null;
};<|endoftext|>