<commit_before>/**
 * Beautify code written in javascript.
 * @memberof module:apeman-task-js-beautify/lib
 * @function define
 * @param {object} [options] - Optional settings.
 * @returns {function} - Defined task function.
 */

'use strict';

var _ = require('underscore'),
    fs = require('fs'),
    argx = require('argx'),
    async = require('async'),
    objnest = require('objnest'),
    writeout = require('writeout'),
    beautify = require('js-beautify').js_beautify,
    expandglob = require('expandglob');

/** @lends define */
function define(options) {
    var args = argx(arguments);
    options = objnest.expand(args.pop('object') || {});

    /** base directory */
    var basedir = [].concat(options.basedir || process.cwd());

    /** file encoding */
    var encoding = options.encoding || 'utf8';

    /** options of js-beautify */
    var beautifyOpts = options.options || {};

    /**
     * Defined task.
     * @function task
     * @param {object} context - Apeman task context.
     * @param {function} callback - Callback when done.
     */
    function task(context, callback) {
        var logger = context.logger,
            verbose = context.verbose;

        asunc.waterfall([
            function (callback) {
                expandglob(basedir, callback);
            },
            function (filenames, callback) {
                async.eachSeries(filenames, function (filename, callback) {
                    async.waterfall([
                        function (callback) {
                            fs.readFile(filename, encoding, callback);
                        },
                        function (content, callback) {
                            callback(null, beautify(content, beautifyOpts));
                        },
                        function (content, callback) {
                            writeout(filename, content, {
                                skipIfIdentical: true
                            }, callback);
                        },
                        function (writeResult, callback) {
                            if (!writeResult.skipped) {
                                logger.debug('JS beautified:', writeResult.filename);
                            }
                            callback();
                        }
                    ], callback);
                }, callback);
            }
        ], callback);
    }

    // Description of this task.
    task.$desc = 'Beautify source file written in javascript.';
    return task;
}

module.exports = define;
<commit_msg>fix typo<commit_after>/**
 * Beautify code written in javascript.
 * @memberof module:apeman-task-js-beautify/lib
 * @function define
 * @param {object} [options] - Optional settings.
 * @returns {function} - Defined task function.
 */

'use strict';

var _ = require('underscore'),
    fs = require('fs'),
    argx = require('argx'),
    async = require('async'),
    objnest = require('objnest'),
    writeout = require('writeout'),
    beautify = require('js-beautify').js_beautify,
    expandglob = require('expandglob');

/** @lends define */
function define(options) {
    var args = argx(arguments);
    options = objnest.expand(args.pop('object') || {});

    /** base directory */
    var basedir = [].concat(options.basedir || process.cwd());

    /** file encoding */
    var encoding = options.encoding || 'utf8';

    /** options of js-beautify */
    var beautifyOpts = options.options || {};

    /**
     * Defined task.
     * @function task
     * @param {object} context - Apeman task context.
     * @param {function} callback - Callback when done.
     */
    function task(context, callback) {
        var logger = context.logger,
            verbose = context.verbose;

        async.waterfall([
            function (callback) {
                expandglob(basedir, callback);
            },
            function (filenames, callback) {
                async.eachSeries(filenames, function (filename, callback) {
                    async.waterfall([
                        function (callback) {
                            fs.readFile(filename, encoding, callback);
                        },
                        function (content, callback) {
                            callback(null, beautify(content, beautifyOpts));
                        },
                        function (content, callback) {
                            writeout(filename, content, {
                                skipIfIdentical: true
                            }, callback);
                        },
                        function (writeResult, callback) {
                            if (!writeResult.skipped) {
                                logger.debug('JS beautified:', writeResult.filename);
                            }
                            callback();
                        }
                    ], callback);
                }, callback);
            }
        ], callback);
    }

    // Description of this task.
    task.$desc = 'Beautify source file written in javascript.';
    return task;
}

module.exports = define;
<|endoftext|>


<commit_before>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

function upload(receiver, to, release, content, subpath, callback){
    fis.util.upload(
        //url, request options, post data, file
        receiver, null, { to : to + release }, content, subpath,
        function(err, res){
            if(err || res != '0'){
                fis.log.error('upload file [' + subpath + '] to [' + to +
                    '] by receiver [' + receiver + '] error [' + (err || res) + ']');
            } else {
                var time = '[' + fis.log.now(true) + ']';
                process.stdout.write(
                    ' - '.green.bold +
                    time.grey + ' ' +
                    subpath.replace(/^\//, '') +
                    ' >> '.yellow.bold +
                    to + release +
                    '\n'
                );
                callback();
            }
        }
    );
}

function deliver(output, md5, release, content, file, callback){
    if(!release){
        fis.log.error('unable to get release path of file['
            + file.realpath
            + ']: Maybe this file is neither in current project or releasable');
    }
    if(fis.util.exists(output) && !fis.util.isDir(output)){
        fis.log.error('unable to deliver file['
            + file.realpath + '] to dir['
            + output + ']: invalid output dir.');
    }
    var target;
    if(md5 == 0 || !file.useHash){
        target = fis.util(output, release);
        fis.util.write(target, content);
    } else if(md5 == 1){
        target = fis.util(output, file.getHashRelease(release));
        fis.util.write(target, content);
    } else {
        target = fis.util(output, release);
        fis.util.write(target, content);

        target = fis.util(output, file.getHashRelease(release));
        fis.util.write(target, content);
    }
    callback();
}

function replaceFrom(path, from, subOnly){
    if(path.indexOf(from) === 0){
        from = from.replace(/\/$/, '');
        if(subOnly){
            return path.substring(from.length);
        } else {
            var index = from.lastIndexOf('/');
            if(index < 1){
                return path;
            } else {
                return path.substring(index);
            }
        }
    }
    return path;
}

function deploy(dest, file, callback){
    if(file.release){
        var release = replaceFrom(file.release, dest.from, dest.subOnly);
        var content = file.getContent();
        var charset = file.charset;
        if(file.isText() && content.length){
            if(dest.replace && dest.replace.from && dest.replace.to){
                var reg = dest.replace.from;
                if(typeof reg === 'string'){
                    reg = new RegExp(fis.util.escapeReg(reg), 'g');
                } else if(!(reg instanceof RegExp)){
                    fis.log.error('invalid deploy.replace.from [' + reg + ']');
                }
                content = content.replace(reg, dest.replace.to);
            }
            if(charset !== 'utf8' && charset !== 'utf-8'){
                content = fis.util.toEncoding(content, charset);
            }
        }
        if(dest.receiver){
            if(!file.useHash || dest.md5 != 1){
                upload(dest.receiver, dest.to, release, content, file.subpath, callback);
            }
            if(file.useHash && dest.md5 > 0){
                upload(dest.receiver, dest.to, file.getHashRelease(release), content, file.subpath, callback);
            }
        } else {
            deliver(dest.to, dest.md5, release, content, file, callback);
        }
    } else {
        fis.log.error('unreleasable file [' + file.realpath + ']');
    }
}

function normilize(str){
    str = (str || '').trim();
    if(str[0] !== '/'){
        str = '/' + str;
    }
    return str.replace(/\/$/, '') + '/';
}

var cwd = process.cwd();
function factory(opt, md5, root){
    var ret = fis.util.clone(opt);
    ret.md5 = md5;
    ret.root = ret.root || root;
    ret.from = normilize(ret.from);
    if(ret.to[0] === '.'){
        ret.to = fis.util(cwd + '/' +  ret.to);
    } else if(/^output\b/.test(ret.to)){
        ret.to = fis.util(root + '/' +  ret.to);
    } else if(ret.to === 'preview'){
        ret.to = fis.project.getTempPath('www');
    } else {
        ret.to = fis.util(ret.to);
    }
    return ret;
}

var tasks = [];
var running = 0;

function doTask(){
    if(tasks.length){
        if(running < exports.MAX_TASK_SIZE){
            var task = tasks.shift();
            running++;
            deploy(task.dest, task.file, function(){
                running--;
                setTimeout(doTask, 0);
            });
        } else {
            setTimeout(doTask, 1000);
        }
    } else {
        running = 0;
        exports.done();
    }
}

exports = module.exports = function(dest, md5, collection){
    var settings = fis.config.get('deploy', {});
    var root = fis.project.getProjectPath();
    var dests = [];
    dest.split(/,/g).forEach(function(d){
        var opt = settings[d] || {};
        if(fis.util.is(opt, 'Array')){
            opt.forEach(function(item){
                dests.push(factory(item, md5, root));
            });
        } else {
            if(!opt.to){
                if(
                    d === 'preview' ||              //release to preivew
                    /^(?:\.|output\b)/.test(d) ||  //release to output
                    fis.util.isAbsolute(d)          //absolute path
                ){
                    opt.to = d;
                } else {
                    fis.log.error('invalid deploy destination options [' + d + ']');
                }
            }
            dests.push(factory(opt, md5, root));
        }
    });
    fis.util.map(collection, function(subpath, file){
        dests.forEach(function(d){
            if(
                file.release &&
                file.release.indexOf(d.from) === 0 &&   //relate to replaceFrom
                fis.util.filter(file.release, d.include, d.exclude)
            ){
                tasks.push({dest : d, file : file });
            }
        });
    });
    doTask();
};

//for callback
exports.done = function(){};
exports.MAX_TASK_SIZE = 5;<commit_msg>hotfix<commit_after>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

function upload(receiver, to, release, content, subpath, callback){
    fis.util.upload(
        //url, request options, post data, file
        receiver, null, { to : to + release }, content, subpath,
        function(err, res){
            if(err || res != '0'){
                fis.log.error('upload file [' + subpath + '] to [' + to +
                    '] by receiver [' + receiver + '] error [' + (err || res) + ']');
            } else {
                var time = '[' + fis.log.now(true) + ']';
                process.stdout.write(
                    ' - '.green.bold +
                    time.grey + ' ' +
                    subpath.replace(/^\//, '') +
                    ' >> '.yellow.bold +
                    to + release +
                    '\n'
                );
                callback();
            }
        }
    );
}

function deliver(output, md5, release, content, file, callback){
    if(!release){
        fis.log.error('unable to get release path of file['
            + file.realpath
            + ']: Maybe this file is neither in current project or releasable');
    }
    if(fis.util.exists(output) && !fis.util.isDir(output)){
        fis.log.error('unable to deliver file['
            + file.realpath + '] to dir['
            + output + ']: invalid output dir.');
    }
    var target;
    if(md5 == 0 || !file.useHash){
        target = fis.util(output, release);
        fis.util.write(target, content);
    } else if(md5 == 1){
        target = fis.util(output, file.getHashRelease(release));
        fis.util.write(target, content);
    } else {
        target = fis.util(output, release);
        fis.util.write(target, content);

        target = fis.util(output, file.getHashRelease(release));
        fis.util.write(target, content);
    }
    callback();
}

function replaceFrom(path, from, subOnly){
    if(path.indexOf(from) === 0){
        from = from.replace(/\/$/, '');
        if(subOnly){
            return path.substring(from.length);
        } else {
            var index = from.lastIndexOf('/');
            if(index < 1){
                return path;
            } else {
                return path.substring(index);
            }
        }
    }
    return path;
}

function deploy(dest, file, callback){
    if(file.release){
        var release = replaceFrom(file.release, dest.from, dest.subOnly);
        var content = file.getContent();
        var charset = file.charset;
        if(file.isText() && content.length){
            if(dest.replace && dest.replace.from){
                var reg = dest.replace.from;
                if(typeof reg === 'string'){
                    reg = new RegExp(fis.util.escapeReg(reg), 'g');
                } else if(!(reg instanceof RegExp)){
                    fis.log.error('invalid deploy.replace.from [' + reg + ']');
                }
                content = content.replace(reg, dest.replace.to);
            }
            if(charset !== 'utf8' && charset !== 'utf-8'){
                content = fis.util.toEncoding(content, charset);
            }
        }
        if(dest.receiver){
            if(!file.useHash || dest.md5 != 1){
                upload(dest.receiver, dest.to, release, content, file.subpath, callback);
            }
            if(file.useHash && dest.md5 > 0){
                upload(dest.receiver, dest.to, file.getHashRelease(release), content, file.subpath, callback);
            }
        } else {
            deliver(dest.to, dest.md5, release, content, file, callback);
        }
    } else {
        fis.log.error('unreleasable file [' + file.realpath + ']');
    }
}

function normilize(str){
    str = (str || '').trim();
    if(str[0] !== '/'){
        str = '/' + str;
    }
    return str.replace(/\/$/, '') + '/';
}

var cwd = process.cwd();
function factory(opt, md5, root){
    var ret = fis.util.clone(opt);
    ret.md5 = md5;
    ret.root = ret.root || root;
    ret.from = normilize(ret.from);
    if(ret.to[0] === '.'){
        ret.to = fis.util(cwd + '/' +  ret.to);
    } else if(/^output\b/.test(ret.to)){
        ret.to = fis.util(root + '/' +  ret.to);
    } else if(ret.to === 'preview'){
        ret.to = fis.project.getTempPath('www');
    } else {
        ret.to = fis.util(ret.to);
    }
    return ret;
}

var tasks = [];
var running = 0;

function doTask(){
    if(tasks.length){
        if(running < exports.MAX_TASK_SIZE){
            var task = tasks.shift();
            running++;
            deploy(task.dest, task.file, function(){
                running--;
                setTimeout(doTask, 0);
            });
        } else {
            setTimeout(doTask, 1000);
        }
    } else {
        running = 0;
        exports.done();
    }
}

exports = module.exports = function(dest, md5, collection){
    var settings = fis.config.get('deploy', {});
    var root = fis.project.getProjectPath();
    var dests = [];
    dest.split(/,/g).forEach(function(d){
        var opt = settings[d] || {};
        if(fis.util.is(opt, 'Array')){
            opt.forEach(function(item){
                dests.push(factory(item, md5, root));
            });
        } else {
            if(!opt.to){
                if(
                    d === 'preview' ||              //release to preivew
                    /^(?:\.|output\b)/.test(d) ||  //release to output
                    fis.util.isAbsolute(d)          //absolute path
                ){
                    opt.to = d;
                } else {
                    fis.log.error('invalid deploy destination options [' + d + ']');
                }
            }
            dests.push(factory(opt, md5, root));
        }
    });
    fis.util.map(collection, function(subpath, file){
        dests.forEach(function(d){
            if(
                file.release &&
                file.release.indexOf(d.from) === 0 &&   //relate to replaceFrom
                fis.util.filter(file.release, d.include, d.exclude)
            ){
                tasks.push({dest : d, file : file });
            }
        });
    });
    doTask();
};

//for callback
exports.done = function(){};
exports.MAX_TASK_SIZE = 5;<|endoftext|>


<commit_before>/* Deploy a website from templates + data to static pages. */
var api = require('./api/lib'),
	build = require('./build'),
	// diff = require('./diff'),
	// order = require('./order'),
	publish = require('./publish');

/* Main method for deploying the whole website. */
module.exports = (id) => {
	/* Load data from the API. */
	let about = api.about(id);
	let photos = api.photos(id);
	let videos = api.videos(id);

	/* Deploy partials with data. */
	var partials = [
		build.partial('index', about),
		build.partial('about', about),
		build.partial('photos', about, photos),
		build.partial('videos', about, videos)
	];

	/* Deploy static pages with partials. */
	build.pages(partials)
		// .pipe(diff)
		// .pipe(order)
		.pipe(publish);
};
<commit_msg>Fix API design.<commit_after>/* Deploy a website from templates + data to static pages. */
var api = require('./api/lib'),
	build = require('./build'),
	// diff = require('./diff'),
	// order = require('./order'),
	publish = require('./publish');

/* Main method for deploying the whole website. */
module.exports = (id) => {
	/* Load data from the API. */
	let about = api.about.get(id);
	let photos = api.photos.get(id);
	let videos = api.videos.get(id);

	/* Deploy partials with data. */
	var partials = [
		build.partial('index', about),
		build.partial('about', about),
		build.partial('photos', about, photos),
		build.partial('videos', about, videos)
	];

	/* Deploy static pages with partials. */
	build.pages(partials)
		// .pipe(diff)
		// .pipe(order)
		.pipe(publish);
};
<|endoftext|>


<commit_before>// Инициализация класса
var Rtc = function(i2c) {
  this._time = undefined;
  this._i2c = i2c || PrimaryI2C;
  this._address = 0x68;
  this.start();
};

// Метод записывает данные data в регистр reg
Rtc.prototype.write = function(reg, data) {
  this._i2c.writeTo(this._address, [reg, data]);
};

// Метод производит чтение из регистра reg количестов байт count
Rtc.prototype.read = function(reg, count) {
  if (count === undefined) {
    count = 1;
  }
  this._i2c.writeTo(this._address, reg);
  return this._i2c.readFrom(this._address, count);
};

Rtc.prototype._decToBcd = function(val) {
  return Math.floor(val / 10) * 16 + (val % 10);
};

Rtc.prototype._bcdToDec = function(val) {
  return Math.floor(val / 16) * 10 + (val % 16);
};

Rtc.prototype.setTime = function(time) {
  if (time instanceof Date) {
    this._time = time;
  } else if (time instanceof Object){
    this._time = new Date(
      time.year,
      time.month,
      time.day,
      time.hour,
      time.minute,
      time.second
    );
  } else if (typeof time === 'number') {
    this._time = new Date(time * 1000);
  } else if (typeof time === 'string') {
    this._time = new Date(Date.parse(time));
  } else {
    this._time = new Date(getTime()*1000);
  }

  var halt = this.read(0x00, 1)[0] >> 7;
  this.write(0x00, [
    this._decToBcd(this._time.getSeconds()) | (halt << 7),
    this._decToBcd(this._time.getMinutes()),
    this._decToBcd(this._time.getHours()),
    this._decToBcd(this._time.getDay() + 1),
    this._decToBcd(this._time.getDate()),
    this._decToBcd(this._time.getMonth() + 1),
    this._decToBcd(this._time.getFullYear() - 2000)
  ]);
};

Rtc.prototype.getTime = function(unit) {
  var time = this.read(0x00, 7);
  this._time = new Date(
    this._bcdToDec(time[6]) + 2000,
    this._bcdToDec(time[5]) - 1,
    this._bcdToDec(time[4]),
    this._bcdToDec(time[2] & 0x3f),
    this._bcdToDec(time[1]),
    this._bcdToDec(time[0] & 0x7f)
  );

  var res = this._time;
  switch (unit) {
    case 'unixtime':
      res = Math.ceil(res.getTime() / 1000);
      break;
    case 'iso':
      res = res.getFullYear() + '-' + res.getMonth() + 1 +
         '-' + res.getDay() + 'T' + res.getHours() +
         ':' + res.getMinutes() + ':' + res.getSeconds();
      break;
    default: break;
  }
  return res;
};

Rtc.prototype.start = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7) {
    this.write(0x00, byte ^ 0x80);
  }
};

Rtc.prototype.stop = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7 === 0) {
    this.write(0x00, byte ^ 0x80);
  }
};

// Экспортируем класс
exports.connect = function(i2c) {
  return new Rtc(i2c);
};
<commit_msg>fixed iso format<commit_after>// Инициализация класса
var Rtc = function(i2c) {
  this._time = undefined;
  this._i2c = i2c || PrimaryI2C;
  this._address = 0x68;
  this.start();
};

// Метод записывает данные data в регистр reg
Rtc.prototype.write = function(reg, data) {
  this._i2c.writeTo(this._address, [reg, data]);
};

// Метод производит чтение из регистра reg количестов байт count
Rtc.prototype.read = function(reg, count) {
  if (count === undefined) {
    count = 1;
  }
  this._i2c.writeTo(this._address, reg);
  return this._i2c.readFrom(this._address, count);
};

Rtc.prototype._decToBcd = function(val) {
  return Math.floor(val / 10) * 16 + (val % 10);
};

Rtc.prototype._bcdToDec = function(val) {
  return Math.floor(val / 16) * 10 + (val % 16);
};

Rtc.prototype._leadZero = function(val) {
  if (val < 10) {
    return '0'+val;
  } else {
    return ''+val;
  }
};

Rtc.prototype.setTime = function(time) {
  if (time instanceof Date) {
    this._time = time;
  } else if (time instanceof Object){
    this._time = new Date(
      time.year,
      time.month,
      time.day,
      time.hour,
      time.minute,
      time.second
    );
  } else if (typeof time === 'number') {
    this._time = new Date(time * 1000);
  } else if (typeof time === 'string') {
    this._time = new Date(Date.parse(time));
  } else {
    this._time = new Date(getTime()*1000);
  }

  var halt = this.read(0x00, 1)[0] >> 7;
  this.write(0x00, [
    this._decToBcd(this._time.getSeconds()) | (halt << 7),
    this._decToBcd(this._time.getMinutes()),
    this._decToBcd(this._time.getHours()),
    this._decToBcd(this._time.getDay() + 1),
    this._decToBcd(this._time.getDate()),
    this._decToBcd(this._time.getMonth() + 1),
    this._decToBcd(this._time.getFullYear() - 2000)
  ]);
};

Rtc.prototype.getTime = function(unit) {
  var time = this.read(0x00, 7);
  this._time = new Date(
    this._bcdToDec(time[6]) + 2000,
    this._bcdToDec(time[5]) - 1,
    this._bcdToDec(time[4]),
    this._bcdToDec(time[2] & 0x3f),
    this._bcdToDec(time[1]),
    this._bcdToDec(time[0] & 0x7f)
  );

  var res = this._time;
  switch (unit) {
    case 'unixtime':
      res = Math.ceil(res.getTime() / 1000);
      break;
    case 'iso':
      res = res.getFullYear() + '-' + this._leadZero(res.getMonth() + 1) +
         '-' + this._leadZero(res.getDate()) + 'T' + this._leadZero(res.getHours()) +
         ':' + this._leadZero(res.getMinutes()) + ':' + this._leadZero(res.getSeconds());
      break;
    default: break;
  }
  return res;
};

Rtc.prototype.start = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7) {
    this.write(0x00, byte ^ 0x80);
  }
};

Rtc.prototype.stop = function() {
  var byte = this.read(0x00, 1)[0];
  if (byte >> 7 === 0) {
    this.write(0x00, byte ^ 0x80);
  }
};

// Экспортируем класс
exports.connect = function(i2c) {
  return new Rtc(i2c);
};
<|endoftext|>


<commit_before>/*    Copyright 2016-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const Platform = require('../Platform.js');
const f = require('../../net2/Firewalla.js')
const exec = require('child-process-promise').exec;
const log = require('../../net2/logger.js')(__filename);

const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile)

const cpuProfilePath = "/etc/default/cpufrequtils";

class NavyPlatform extends Platform {

  getName() {
    return "navy";
  }

  getLicenseTypes() {
    return ["a3"];
  }

  getBoardSerial() {
    // use mac address as unique serial number
    return this.getSignatureMac();
  }

  getB4Binary() {
    return `${f.getFirewallaHome()}/bin/real.navy/bitbridge7`;
  }

  getB6Binary() {
    return `${f.getFirewallaHome()}/bin/real.navy/bitbridge6`;
  }

  getGCMemoryForMain() {
    return 200;
  }

  getDHKeySize() {
    return 2048;
  }

  getLedPaths() {
    return [
      "/sys/devices/platform/gpio-leds/leds/status_led"
    ];
  }

  async turnOnPowerLED() {
    try {
      for (const path of this.getLedPaths()) {
        const trigger = `${path}/trigger`;
        const brightness = `${path}/brightness`;
        await exec(`sudo bash -c 'echo none > ${trigger}'`);
        await exec(`sudo bash -c 'echo 255 > ${brightness}'`);
      }
    } catch(err) {
      log.error("Error turning on LED", err)
    }
  }

  getCPUDefaultFile() {
    return `${__dirname}/files/cpu_default.conf`;
  }

  async applyCPUDefaultProfile() {
    log.info("Applying CPU default profile...");
    const cmd = `sudo cp ${this.getCPUDefaultFile()} ${cpuProfilePath}`;
    await exec(cmd);
    return this.reload();
  }

  async reload() {
    return exec("sudo systemctl reload cpufrequtils");
  }

  getCPUBoostFile() {
    return `${__dirname}/files/cpu_boost.conf`;
  }

  async applyCPUBoostProfile() {
    log.info("Applying CPU boost profile...");
    const cmd = `sudo cp ${this.getCPUBoostFile()} ${cpuProfilePath}`;
    await exec(cmd);
    return this.reload();
  }

  getSubnetCapacity() {
    return 19;
  }

  // via /etc/update-motd.d/30-armbian-sysinfo
  async getCpuTemperature() {
    try {
      const source = '/sys/class/thermal/thermal_zone0/temp';
      return Number(await readFileAsync(source)) / 1000;
    } catch(err) {
      log.error("Failed to get cpu temperature, use 0 as default, err:", err);
      return 0;
    }
  }

  getPolicyCapacity() {
    return 3000;
  }

  isFireRouterManaged() {
    return false;
  }
  getAllowCustomizedProfiles(){
    return 1;
  }
  getRatelimitConfig(){
    return {
      "appMax": 120,
      "webMax": 240,
      "duration": 60
    }
  }

  defaultPassword() {
    return "firewalla"
  }

  getSystemResetAllOverlayfsScriptName() {
    return "system-reset-all-overlayfs-navy.sh";
  }

  getRetentionTimeMultiplier() {
    return 7;
  }

  getRetentionCountMultiplier() {
    return 5;
  }

}

module.exports = NavyPlatform;
<commit_msg>disable customized script for navy reset<commit_after>/*    Copyright 2016-2020 Firewalla Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const Platform = require('../Platform.js');
const f = require('../../net2/Firewalla.js')
const exec = require('child-process-promise').exec;
const log = require('../../net2/logger.js')(__filename);

const fs = require('fs');
const util = require('util');
const readFileAsync = util.promisify(fs.readFile)

const cpuProfilePath = "/etc/default/cpufrequtils";

class NavyPlatform extends Platform {

  getName() {
    return "navy";
  }

  getLicenseTypes() {
    return ["a3"];
  }

  getBoardSerial() {
    // use mac address as unique serial number
    return this.getSignatureMac();
  }

  getB4Binary() {
    return `${f.getFirewallaHome()}/bin/real.navy/bitbridge7`;
  }

  getB6Binary() {
    return `${f.getFirewallaHome()}/bin/real.navy/bitbridge6`;
  }

  getGCMemoryForMain() {
    return 200;
  }

  getDHKeySize() {
    return 2048;
  }

  getLedPaths() {
    return [
      "/sys/devices/platform/gpio-leds/leds/status_led"
    ];
  }

  async turnOnPowerLED() {
    try {
      for (const path of this.getLedPaths()) {
        const trigger = `${path}/trigger`;
        const brightness = `${path}/brightness`;
        await exec(`sudo bash -c 'echo none > ${trigger}'`);
        await exec(`sudo bash -c 'echo 255 > ${brightness}'`);
      }
    } catch(err) {
      log.error("Error turning on LED", err)
    }
  }

  getCPUDefaultFile() {
    return `${__dirname}/files/cpu_default.conf`;
  }

  async applyCPUDefaultProfile() {
    log.info("Applying CPU default profile...");
    const cmd = `sudo cp ${this.getCPUDefaultFile()} ${cpuProfilePath}`;
    await exec(cmd);
    return this.reload();
  }

  async reload() {
    return exec("sudo systemctl reload cpufrequtils");
  }

  getCPUBoostFile() {
    return `${__dirname}/files/cpu_boost.conf`;
  }

  async applyCPUBoostProfile() {
    log.info("Applying CPU boost profile...");
    const cmd = `sudo cp ${this.getCPUBoostFile()} ${cpuProfilePath}`;
    await exec(cmd);
    return this.reload();
  }

  getSubnetCapacity() {
    return 19;
  }

  // via /etc/update-motd.d/30-armbian-sysinfo
  async getCpuTemperature() {
    try {
      const source = '/sys/class/thermal/thermal_zone0/temp';
      return Number(await readFileAsync(source)) / 1000;
    } catch(err) {
      log.error("Failed to get cpu temperature, use 0 as default, err:", err);
      return 0;
    }
  }

  getPolicyCapacity() {
    return 3000;
  }

  isFireRouterManaged() {
    return false;
  }
  getAllowCustomizedProfiles(){
    return 1;
  }
  getRatelimitConfig(){
    return {
      "appMax": 120,
      "webMax": 240,
      "duration": 60
    }
  }

  defaultPassword() {
    return "firewalla"
  }

  /*
  getSystemResetAllOverlayfsScriptName() {
    return "system-reset-all-overlayfs-navy.sh";
  }
  */

  getRetentionTimeMultiplier() {
    return 7;
  }

  getRetentionCountMultiplier() {
    return 5;
  }

}

module.exports = NavyPlatform;
<|endoftext|>


<commit_before>const utils = require('./utils');
const _ = require('underscore');

const api = {

  exec: function exec(container, command, callback, paramsInput) {
    const paramsProto = {
      detached: false,
    };
    // Get the params
    const params = _.extend({}, paramsProto, paramsInput);
    let options = '';
    if (params.detached)
      { options += '-d '; }

    return utils.cmd(`docker exec ${options}${container} ${command}`, callback);
  },
// Get container infos
  getInfoContainer(id, callback) {
    return utils.curl(`/containers/${id}/json`, 'GET', callback);
  },

// Call docker cp
  cp(container, src, dst, callback) {
    return utils.cmd(`docker cp  ${src} ${container}:${dst}`, callback);
  },

// Run a container
  run(image, callback, paramsInput) {
    const paramsProto = {
      detached: false,
    };

    const params = _.extend({}, paramsProto, paramsInput);

    let flags = '';
    let cmd = '';
    if (params.detached)
      { flags += ' -d '; }
    if (params.cmd)
      { cmd = params.cmd; }
    if (params.name)
      { flags += ` --name=${params.name}`; }
    if (params.net)
     { flags += ` --net=${params.net}`; }
    if (params.interactive)
     { flags += ' -it '; }

    const toExec = `docker run ${flags} ${image} ${cmd}`;
    console.log(toExec);
    return utils.cmd(toExec, callback);
  },

// Start all containers
  startAll(callback) {
    const cmd = 'for i in $(docker ps -a -q); do docker start $i ; done';
    return utils.cmd(cmd, callback);
  },

  stopAll(callback) {
    const cmd = 'for i in $(docker ps -a -q); do docker stop $i ; done';
    return utils.cmd(cmd, callback);
  },

// Remove all containers
  rmAll(callback) {
    return utils.cmd(' docker rm -f $(docker ps -a -q) ', callback);
  },

// Returns active containers
  ps(callback) {
    return utils.cmd('curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json', callback);
  },

  createNetwork(name, callback, paramsInput) {
    const paramsProto = {};
    const params = _.extend({}, paramsProto, paramsInput);
    const flags = utils.addFlags(params);
    console.log(flags);
    const cmd = `docker network create ${flags} ${name}`;

    return utils.cmd(cmd, callback);
  },
  removeNetwork(name, callback) {
    const cmd = `docker network rm ${name}`;
    return utils.cmd(cmd, callback);
  },
// Remove all unused networks
  networkPrune(callback) {
    const cmd = 'docker network prune -f';
    return utils.cmd(cmd, callback);
  },

  networkList(callback) {
    return utils.curl('/networks', 'GET', callback);
  },

};

module.exports = api;
<commit_msg>Add interactive in exec<commit_after>const utils = require('./utils');
const _ = require('underscore');

const api = {

  exec: function exec(container, command, callback, paramsInput) {
    const paramsProto = {
      detached: false,
    };
    // Get the params
    const params = _.extend({}, paramsProto, paramsInput);
    let options = '';
    if (params.detached)
      { options += '-d '; }
    if (params.interactive)
     { options += '-it '; }

    return utils.cmd(`docker exec ${options}${container} ${command}`, callback);
  },
// Get container infos
  getInfoContainer(id, callback) {
    return utils.curl(`/containers/${id}/json`, 'GET', callback);
  },

// Call docker cp
  cp(container, src, dst, callback) {
    return utils.cmd(`docker cp  ${src} ${container}:${dst}`, callback);
  },

// Run a container
  run(image, callback, paramsInput) {
    const paramsProto = {
      detached: false,
    };

    const params = _.extend({}, paramsProto, paramsInput);

    let flags = '';
    let cmd = '';
    if (params.detached)
      { flags += ' -d '; }
    if (params.cmd)
      { cmd = params.cmd; }
    if (params.name)
      { flags += ` --name=${params.name}`; }
    if (params.net)
     { flags += ` --net=${params.net}`; }
    if (params.interactive)
     { flags += ' -it '; }

    const toExec = `docker run ${flags} ${image} ${cmd}`;
    console.log(toExec);
    return utils.cmd(toExec, callback);
  },

// Start all containers
  startAll(callback) {
    const cmd = 'for i in $(docker ps -a -q); do docker start $i ; done';
    return utils.cmd(cmd, callback);
  },

  stopAll(callback) {
    const cmd = 'for i in $(docker ps -a -q); do docker stop $i ; done';
    return utils.cmd(cmd, callback);
  },

// Remove all containers
  rmAll(callback) {
    return utils.cmd(' docker rm -f $(docker ps -a -q) ', callback);
  },

// Returns active containers
  ps(callback) {
    return utils.cmd('curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json', callback);
  },

  createNetwork(name, callback, paramsInput) {
    const paramsProto = {};
    const params = _.extend({}, paramsProto, paramsInput);
    const flags = utils.addFlags(params);
    console.log(flags);
    const cmd = `docker network create ${flags} ${name}`;

    return utils.cmd(cmd, callback);
  },
  removeNetwork(name, callback) {
    const cmd = `docker network rm ${name}`;
    return utils.cmd(cmd, callback);
  },
// Remove all unused networks
  networkPrune(callback) {
    const cmd = 'docker network prune -f';
    return utils.cmd(cmd, callback);
  },

  networkList(callback) {
    return utils.curl('/networks', 'GET', callback);
  },

};

module.exports = api;
<|endoftext|>


<commit_before>var http = require('http');
var Database = require('./database').Database;

exports.MINIMUM_DOMAIN_NAME_LENGTH = 3;
exports.MAXIMUM_DOMAIN_NAME_LENGTH = 28;
exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;

function assertValidDomainName(domain) {
  if (typeof domain != 'string')
    throw new Error('domain name must be a string');

  if (domain.length < exports.MINIMUM_DOMAIN_NAME_LENGTH)
    throw new Error('too short domain name (minimum length = ' +
                    exports.MINIMUM_DOMAIN_NAME_LENGTH + ')');

  if (domain.length > exports.MAXIMUM_DOMAIN_NAME_LENGTH)
    throw new Error('too long domain name (max length = ' +
                   exports.MAXIMUM_DOMAIN_NAME_LENGTH + ')');

  var invalidCharacter = domain.match(exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN) ||
                         domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a domain name');
  }
}

function Domain(source) {
  if (source instanceof Domain)
    return source;

  this.initialize(source);
}
Domain.prototype = {
  initialize: function(source) {
    this.name = this.getName(source);
    this.indexFields = {};
    // for validation
    this.tableName;
    this.termsTableName;
  },
  getName: function(source) {
    if (typeof source == 'string')
      return source;

    if (source.query && source.query.DomainName)
      return source.query.DomainName;

    if (source.headers && source.headers.host) {
      var host = source.headers.host;
      var domainNameFromHost = Domain.getNameFromHost(host);
      if (domainNameFromHost)
        return domainNameFromHost;
    }

    throw new Error('no domain name');
  },
  get tableName() {
    if (!this._tableName) {
      assertValidDomainName(this.name);
      this._tableName = this.name;
    }
    return this._tableName;
  },
  get termsTableName() {
    if (!this._termsTableName)
      this._termsTableName = this.tableName + '_BigramTerms';
    return this._termsTableName;
  },
  getIndexField: function(field) {
    return this.indexFields[field] ||
           (this.indexFields[field] = new IndexField(field, this));
  },
  getIndexFieldsSync: function(database) {
    var tableName = ;
    var columns = database.ordinalColumnsSync(this.tableName);
    var fields = columns.map(this.columnToIndexField);
    return fields;
  },
  columnToIndexField: function(column) {
    // XXX The "name" must be the field name given by the user,
    // not normalized. Because there is no such information in the
    // database and currently the column name is luckly equals to the
    // given field name, we can use the column name.
    var name = column.name;

    var type;
    if (column.type == 'var') {
      if (column.range == Database.ShortText)
        type = 'text';
    } else if (column.type == 'fix') {
      if (column.range == Database.UInt32)
        type = 'uint';
      else if (column.range == Database.ShortText)
        type = 'literal';
    }
    if (!type)
      throw new Error('unknown unfixed column '+column.name);

    return {
      name: name,
      columnName: column.name,
      type: type
    };
  },
  get synonymTableName() {
    if (!this._synonymTableName)
      this._synonymTableName = this.tableName + '_synonyms';
    return this._synonymTableName;
  }
};

exports.Domain = Domain;

Domain.getNameFromHost = function(host) {
  var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
  var match = host.match(domainMatcher);
  if (match)
    return match[1];

  return '';
};

exports.MINIMUM_FIELD_NAME_LENGTH = 3;
exports.MAXIMUM_FIELD_NAME_LENGTH = 64;
exports.INVALID_FIELD_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
exports.INVALID_COLUMN_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
exports.RESERVED_FIELD_NAMES = [
  'body',
  'docid',
  'text_relevance'
];
exports.RESERVED_COLUMN_NAMES = [
  '_key'
];

function assertValidFieldName(field) {
  if (typeof field != 'string')
    throw new Error('field name must be a string');

  if (field.length < exports.MINIMUM_FIELD_NAME_LENGTH)
    throw new Error('too short field name (minimum length = ' +
                    exports.MINIMUM_FIELD_NAME_LENGTH + ')');

  if (field.length > exports.MAXIMUM_FIELD_NAME_LENGTH)
    throw new Error('too long field name (max length = ' +
                   exports.MAXIMUM_FIELD_NAME_LENGTH + ')');

  var invalidCharacter = field.match(exports.INVALID_FIELD_NAME_CHARACTER_PATTERN) ||
                         field.match(exports.INVALID_COLUMN_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a field name');
  }

  var index = exports.RESERVED_FIELD_NAMES.indexOf(field);
  if (index > -1) index = exports.RESERVED_COLUMN_NAMES.indexOf(field);
  if (index > -1)
    throw new Error(field + ' is a reserved field name');
}

function IndexField(name, domain) {
  this.domain = domain;
  this.name = name;
  this.initialize();
};
IndexField.prototype = {
  initialize: function() {
    // for validation
    this.columnName;
    this.indexColumnName;
  },
  get columnName() {
    if (!this._columnName) {
      assertValidFieldName(this.name);
      this._columnName = this.name;
    }
    return this._columnName;
  },
  get indexColumnName() {
    if (!this._indexColumnName)
      this._indexColumnName = this.domain.tableName + '_' + this.columnName;
    return this._indexColumnName;
  },
  get alterTableName() {
    if (!this._alterTableName)
      this._alterTableName = this.domain.tableName + '_' + this.columnName;
    return this._alterTableName;
  },
  fieldTypeToColumnType: function(fieldType) {
    switch (fieldType) {
      case 'text':
        return Database.ShortText;
      case 'uint':
        return Database.UInt32;
      case 'literal':
        return this.alterTableName;
      default:
        throw new Error('Unsupported index field type '+fieldType);
    }
  },
  columnTypeToFieldType: function(columnType) {
    switch (columnType) {
      case Database.ShortText:
        return 'text';
      case Database.UInt32:
        return 'uint';
      case this.alterTableName:
        return 'literal';
      default:
        throw new Error('Unsupported column type '+columnType);
    }
  },
  fieldTypeToAlterTableKeyType: function(fieldType) {
    switch (fieldType) {
      case 'uint':
        return Database.UInt32;
      case 'literal':
        return Database.ShortText;
      default:
        throw new Error('Unsupported index field type '+fieldType+
                        ' for alter table');
    }
  }
};

exports.IndexField = IndexField;
<commit_msg>Fix syntax error (delete obsolete code)<commit_after>var http = require('http');
var Database = require('./database').Database;

exports.MINIMUM_DOMAIN_NAME_LENGTH = 3;
exports.MAXIMUM_DOMAIN_NAME_LENGTH = 28;
exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN = /[^\-a-z0-9]/g;
exports.INVALID_TABLE_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;

function assertValidDomainName(domain) {
  if (typeof domain != 'string')
    throw new Error('domain name must be a string');

  if (domain.length < exports.MINIMUM_DOMAIN_NAME_LENGTH)
    throw new Error('too short domain name (minimum length = ' +
                    exports.MINIMUM_DOMAIN_NAME_LENGTH + ')');

  if (domain.length > exports.MAXIMUM_DOMAIN_NAME_LENGTH)
    throw new Error('too long domain name (max length = ' +
                   exports.MAXIMUM_DOMAIN_NAME_LENGTH + ')');

  var invalidCharacter = domain.match(exports.INVALID_DOMAIN_NAME_CHARACTER_PATTERN) ||
                         domain.match(exports.INVALID_TABLE_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a domain name');
  }
}

function Domain(source) {
  if (source instanceof Domain)
    return source;

  this.initialize(source);
}
Domain.prototype = {
  initialize: function(source) {
    this.name = this.getName(source);
    this.indexFields = {};
    // for validation
    this.tableName;
    this.termsTableName;
  },
  getName: function(source) {
    if (typeof source == 'string')
      return source;

    if (source.query && source.query.DomainName)
      return source.query.DomainName;

    if (source.headers && source.headers.host) {
      var host = source.headers.host;
      var domainNameFromHost = Domain.getNameFromHost(host);
      if (domainNameFromHost)
        return domainNameFromHost;
    }

    throw new Error('no domain name');
  },
  get tableName() {
    if (!this._tableName) {
      assertValidDomainName(this.name);
      this._tableName = this.name;
    }
    return this._tableName;
  },
  get termsTableName() {
    if (!this._termsTableName)
      this._termsTableName = this.tableName + '_BigramTerms';
    return this._termsTableName;
  },
  getIndexField: function(field) {
    return this.indexFields[field] ||
           (this.indexFields[field] = new IndexField(field, this));
  },
  getIndexFieldsSync: function(database) {
    var columns = database.ordinalColumnsSync(this.tableName);
    var fields = columns.map(this.columnToIndexField);
    return fields;
  },
  columnToIndexField: function(column) {
    // XXX The "name" must be the field name given by the user,
    // not normalized. Because there is no such information in the
    // database and currently the column name is luckly equals to the
    // given field name, we can use the column name.
    var name = column.name;

    var type;
    if (column.type == 'var') {
      if (column.range == Database.ShortText)
        type = 'text';
    } else if (column.type == 'fix') {
      if (column.range == Database.UInt32)
        type = 'uint';
      else if (column.range == Database.ShortText)
        type = 'literal';
    }
    if (!type)
      throw new Error('unknown unfixed column '+column.name);

    return {
      name: name,
      columnName: column.name,
      type: type
    };
  },
  get synonymTableName() {
    if (!this._synonymTableName)
      this._synonymTableName = this.tableName + '_synonyms';
    return this._synonymTableName;
  }
};

exports.Domain = Domain;

Domain.getNameFromHost = function(host) {
  var domainMatcher = /^(?:doc|search)-([^\.]+)-([^\.\-]+)\./;
  var match = host.match(domainMatcher);
  if (match)
    return match[1];

  return '';
};

exports.MINIMUM_FIELD_NAME_LENGTH = 3;
exports.MAXIMUM_FIELD_NAME_LENGTH = 64;
exports.INVALID_FIELD_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
exports.INVALID_COLUMN_NAME_CHARACTER_PATTERN = /[^_a-z0-9]/g;
exports.RESERVED_FIELD_NAMES = [
  'body',
  'docid',
  'text_relevance'
];
exports.RESERVED_COLUMN_NAMES = [
  '_key'
];

function assertValidFieldName(field) {
  if (typeof field != 'string')
    throw new Error('field name must be a string');

  if (field.length < exports.MINIMUM_FIELD_NAME_LENGTH)
    throw new Error('too short field name (minimum length = ' +
                    exports.MINIMUM_FIELD_NAME_LENGTH + ')');

  if (field.length > exports.MAXIMUM_FIELD_NAME_LENGTH)
    throw new Error('too long field name (max length = ' +
                   exports.MAXIMUM_FIELD_NAME_LENGTH + ')');

  var invalidCharacter = field.match(exports.INVALID_FIELD_NAME_CHARACTER_PATTERN) ||
                         field.match(exports.INVALID_COLUMN_NAME_CHARACTER_PATTERN);
  if (invalidCharacter) {
    var characters = Array.prototype.map.call(invalidCharacter, function(aCharacter) {
                       return '"' + aCharacter + '"';
                     });
    throw new Error(characters.join(', ') + ' cannot appear in a field name');
  }

  var index = exports.RESERVED_FIELD_NAMES.indexOf(field);
  if (index > -1) index = exports.RESERVED_COLUMN_NAMES.indexOf(field);
  if (index > -1)
    throw new Error(field + ' is a reserved field name');
}

function IndexField(name, domain) {
  this.domain = domain;
  this.name = name;
  this.initialize();
};
IndexField.prototype = {
  initialize: function() {
    // for validation
    this.columnName;
    this.indexColumnName;
  },
  get columnName() {
    if (!this._columnName) {
      assertValidFieldName(this.name);
      this._columnName = this.name;
    }
    return this._columnName;
  },
  get indexColumnName() {
    if (!this._indexColumnName)
      this._indexColumnName = this.domain.tableName + '_' + this.columnName;
    return this._indexColumnName;
  },
  get alterTableName() {
    if (!this._alterTableName)
      this._alterTableName = this.domain.tableName + '_' + this.columnName;
    return this._alterTableName;
  },
  fieldTypeToColumnType: function(fieldType) {
    switch (fieldType) {
      case 'text':
        return Database.ShortText;
      case 'uint':
        return Database.UInt32;
      case 'literal':
        return this.alterTableName;
      default:
        throw new Error('Unsupported index field type '+fieldType);
    }
  },
  columnTypeToFieldType: function(columnType) {
    switch (columnType) {
      case Database.ShortText:
        return 'text';
      case Database.UInt32:
        return 'uint';
      case this.alterTableName:
        return 'literal';
      default:
        throw new Error('Unsupported column type '+columnType);
    }
  },
  fieldTypeToAlterTableKeyType: function(fieldType) {
    switch (fieldType) {
      case 'uint':
        return Database.UInt32;
      case 'literal':
        return Database.ShortText;
      default:
        throw new Error('Unsupported index field type '+fieldType+
                        ' for alter table');
    }
  }
};

exports.IndexField = IndexField;
<|endoftext|>


<commit_before>var creep_work = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if ((creep.memory.building && creep.carry.energy == 0) || (creep.memory.storing && creep.carry.energy == 0) || (creep.memory.upgrading && creep.carry.energy == 0)) {
            creep.memory.building = false;
            creep.memory.storing = false;
            creep.memory.upgrading = false;
            creep.memory.structureTarget = undefined;
            creep.say('harvesting');
        }
        if (!creep.memory.building && !creep.memory.storing && !creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
            switch (creep.memory.priority) {
                case 'builder':
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
                case 'harvester':
                    creep.memory.storing = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('storing');
                    break;
                case 'upgrader':
                    creep.memory.upgrading = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('upgrading');
                    break;
                default:
                    //fucking what
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
            }

        }

        if (creep.memory.building) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //site ID changes when construction is complete, simply check if valid.
            if (savedTarget) {
                if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(savedTarget);
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                if (targets.length) {
                    creep.memory.structureTarget = targets[0].id;
                    if (creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Store in container
                    if (creep.memory.priority == 'harvester') {
                        //Already tried to store, upgrade.
                        creep.memory.building = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    } else {
                        creep.memory.building = false;
                        creep.memory.storing = true;
                        creep.say('storing');
                    }
                }
            }
        } else if (creep.memory.storing) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //If target is destroyed, this will prevent creep from locking up
            if (savedTarget) {
                if (savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                } else {
                    //Target is invalid, clear from memory.
                    creep.memory.structureTarget = undefined;
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                    }
                });
                if (targets.length > 0) {
                    creep.memory.structureTarget = targets[0].id;

                    if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Nowhere to store. Change action.
                    if (creep.memory.priority == 'harvester') {
                        //Try to build first
                        creep.memory.storing = false;
                        creep.memory.building = true;
                        creep.say('building');
                    } else {
                        creep.memory.storing = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    }
                }
            }

        } else if (creep.memory.upgrading) {
            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller);
            }
        } else {
            //Harvest
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
            if (savedTarget) {
                if (savedTarget.structureType == STRUCTURE_CONTAINER || savedTarget.structureType == STRUCTURE_STORAGE) {
                    if (savedTarget.energy > 0) {
                        if (creep.withdraw(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget);
                        }
                    }
                } else {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_STORAGE) && structure.energy > 0;
                    }
                });
                if (targets.length > 0) {
                    //Get from container
                    creep.memory.structureTarget = targets[0].id;
                    if (creep.withdraw(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                    }
                } else {
                    //Mine it yourself
                    var sources = creep.pos.findClosestByRange(FIND_DROPPED_ENERGY);
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
                    }
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES);
                    }
                    creep.memory.structureTarget = sources.id;
                    if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(sources[0]);
                    }
                }
            }
        }
    }
};

module.exports = creep_work;<commit_msg>..and the following code<commit_after>var creep_work = {

    /** @param {Creep} creep **/
    run: function(creep) {

        if ((creep.memory.building && creep.carry.energy == 0) || (creep.memory.storing && creep.carry.energy == 0) || (creep.memory.upgrading && creep.carry.energy == 0)) {
            creep.memory.building = false;
            creep.memory.storing = false;
            creep.memory.upgrading = false;
            creep.memory.structureTarget = undefined;
            creep.say('harvesting');
        }
        if (!creep.memory.building && !creep.memory.storing && !creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
            switch (creep.memory.priority) {
                case 'builder':
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
                case 'harvester':
                    creep.memory.storing = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('storing');
                    break;
                case 'upgrader':
                    creep.memory.upgrading = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('upgrading');
                    break;
                default:
                    //fucking what
                    creep.memory.building = true;
                    creep.memory.structureTarget = undefined;
                    creep.say('building');
                    break;
            }

        }

        if (creep.memory.building) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //site ID changes when construction is complete, simply check if valid.
            if (savedTarget) {
                if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(savedTarget);
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                if (targets) {
                    creep.memory.structureTarget = targets.id;
                    if (creep.build(targets) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets);
                    }
                } else {
                    //Store in container
                    if (creep.memory.priority == 'harvester') {
                        //Already tried to store, upgrade.
                        creep.memory.building = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    } else {
                        creep.memory.building = false;
                        creep.memory.storing = true;
                        creep.say('storing');
                    }
                }
            }
        } else if (creep.memory.storing) {
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
                //If target is destroyed, this will prevent creep from locking up
            if (savedTarget) {
                if (savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                } else {
                    //Target is invalid, clear from memory.
                    creep.memory.structureTarget = undefined;
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                    }
                });
                if (targets) {
                    creep.memory.structureTarget = targets.id;

                    if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets);
                    }
                } else {
                    //Nowhere to store. Change action.
                    if (creep.memory.priority == 'harvester') {
                        //Try to build first
                        creep.memory.storing = false;
                        creep.memory.building = true;
                        creep.say('building');
                    } else {
                        creep.memory.storing = false;
                        creep.memory.upgrading = true;
                        creep.say('upgrading');
                    }
                }
            }

        } else if (creep.memory.upgrading) {
            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller);
            }
        } else {
            //Harvest
            var savedTarget = Game.getObjectById(creep.memory.structureTarget)
            if (savedTarget) {
                if (savedTarget.structureType == STRUCTURE_CONTAINER || savedTarget.structureType == STRUCTURE_STORAGE) {
                    if (savedTarget.energy > 0) {
                        if (creep.withdraw(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget);
                        }
                    }
                } else {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_STORAGE) && structure.energy > 0;
                    }
                });
                if (targets) {
                    //Get from container
                    creep.memory.structureTarget = targets.id;
                    if (creep.withdraw(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets);
                    }
                } else {
                    //Mine it yourself
                    var sources = creep.pos.findClosestByRange(FIND_DROPPED_ENERGY);
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
                    }
                    if (!sources) {
                        sources = creep.pos.findClosestByRange(FIND_SOURCES);
                    }
                    creep.memory.structureTarget = sources.id;
                    if (creep.harvest(sources) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(sources);
                    }
                }
            }
        }
    }
};

module.exports = creep_work;<|endoftext|>


<commit_before>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    14 July, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Look for lines ending in ; { } )

        * If found, Locate the first Code Block Line
        * If found, Locate the last Code Block Line
        *
        * RePost the message surrounded by code formatting ```csharp ```

    EXAMPLE-----------------------------------------------------------------

    ```csharp
    using UnityEngine;

    /// <summary>
    /// Class summary
    /// </summary>
    public class MyClass
    {
        /// <summary>   Summary of myFloat. </summary>
        public float myFloat;
        /// <summary>   Summary of myOtherFloat.</summary>
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _myFloat;
            this.myOtherFLoat = _myOtherFLoat;
        }
    }
    ```
    ------------------------------------------------------------------------

    Discord Markdown 101 for more formatting guidelines:
    https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-?page=4
*/

const Discord = require('discord.js');
const GlassBot = require('../bot.js')
const bot = GlassBot.bot
const config = GlassBot.config

// Salt to taste
var codeElements = [';', '{', '}', ')'] // Could be in config
var repostThreshold = 4
var codeLang = 'csharp'

// Variables
var isFormatted = false
var totalLinesOfCode = 0
var firstLine = false
var lastLine = 0
var lines = []

bot.on('message', message => {
    if(message.author.bot) return

    if(message.content.length > 1900) return

    InitVariables()

    lines = message.content.split('\n')

    ParseMessage(lines)

    if(IsBadCode() && !isFormatted){

        lines[lastLine] = FormatLastLine(lines[lastLine])

        let formattedMessage = ""

        // Recreate the message.content with the code wrapped in ```
        for(let j = 0; j < lines.length; j++)
           formattedMessage += lines[j] + '\n'

        PostNewMessage(message, formattedMessage)
    }
    return
});

// Loop through each line in message and check for
// code-like characters. If code formatting is found
// return, else keep checking.
function ParseMessage(inputLines){
    for(let i = 0; i < inputLines.length; i++){
        if(inputLines[i].search("```") >= 0){
            isFormatted = true
            return
        }else
            FindCodeElements(i, inputLines[i])
    }
    return
}

// Post the formatted message in the appropriate channel
function PostNewMessage(oldMessage, newMessage){
    let channel = oldMessage.guild.channels.find("name", "programing_help")
    let channelName = oldMessage.channel.name
    let isHelp = channelName.indexOf('help') > 0

    if(channel != null && channel != oldMessage.channel && !isHelp){
        // TODO: Would like to add alink to #programming help for user friendliness :D
        // TODO: Would like to add some color to this message also
        // Maybe make it bold
        oldMessage.channel.send(':nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '.\n`Which makes sense...` :nerd:')
        channel.send(oldMessage.author + ' **`★★ I have formatted your code and placed it here. Good Luck! ★★.`**')
        channel.send(newMessage);
    }else{
        oldMessage.channel.send(oldMessage.author + ' **`★★ I see you forgot to format your code... Let me help you. ★★`**')
        oldMessage.channel.send(newMessage)
    }
}

// Checks the last character in a string to see of it machess a code-like character
function FindCodeElements(index, inLine){
    let lineLength = inLine.length - 1
    for(let i = 0; i < codeElements.length; i++){
        if (inLine.charAt(lineLength).valueOf() == codeElements[i].valueOf()){
            if(!firstLine){
                lines[index] = FormatFirstLine(inLine)
                return
            }else{
                lastLine = index
                totalLinesOfCode += 1
                return
            }
        }
    }
    return
}

// Adds code formatting block start to the first line of code
function FormatFirstLine(inLine){
    firstLine = true
    return '```' + codeLang + '\n' + inLine
}

// Add formatting code bock end to the last line of code
function FormatLastLine(inLine){
    return inLine + '\n```'
}

// If total line of code is greater than repostThreshold return true
function IsBadCode(){
    return (totalLinesOfCode >= repostThreshold)
}

// Initalize variables
function InitVariables(){
    isFormatted = false
    totalLinesOfCode = 0;
    firstLine = false
    lastLine = 0
}<commit_msg>Test delete<commit_after>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    14 July, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Look for lines ending in ; { } )

        * If found, Locate the first Code Block Line
        * If found, Locate the last Code Block Line
        *
        * RePost the message surrounded by code formatting ```csharp ```

    EXAMPLE-----------------------------------------------------------------

    ```csharp
    using UnityEngine;

    /// <summary>
    /// Class summary
    /// </summary>
    public class MyClass
    {
        /// <summary>   Summary of myFloat. </summary>
        public float myFloat;
        /// <summary>   Summary of myOtherFloat.</summary>
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _myFloat;
            this.myOtherFLoat = _myOtherFLoat;
        }
    }
    ```
    ------------------------------------------------------------------------

    Discord Markdown 101 for more formatting guidelines:
    https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-?page=4
*/

const Discord = require('discord.js');
const GlassBot = require('../bot.js')
const bot = GlassBot.bot
const config = GlassBot.config

// Salt to taste
var codeElements = [';', '{', '}', ')'] // Could be in config
var repostThreshold = 4
var codeLang = 'csharp'

// Variables
var isFormatted = false
var totalLinesOfCode = 0
var firstLine = false
var lastLine = 0
var lines = []

bot.on('message', message => {
    if(message.author.bot) return

    if(message.content.length > 1900) return

    InitVariables()

    lines = message.content.split('\n')

    ParseMessage(lines)

    if(IsBadCode() && !isFormatted){

        lines[lastLine] = FormatLastLine(lines[lastLine])

        let formattedMessage = ""

        // Recreate the message.content with the code wrapped in ```
        for(let j = 0; j < lines.length; j++)
           formattedMessage += lines[j] + '\n'

        PostNewMessage(message, formattedMessage)

        let canDelete = message.channel.permissionsFor(bot).hasPermission("MANAGE_MESSAGES");
        if(canDelete){
            console.log("Gonna delete your messge son")
            bot.delete(message)
        }else{
            console.log("Bot cannot delete your message")
            message.channel.send('Tell the owner to grant me permission to delete your old message, thank\'s :wink:')
        }
    }
    return
});

// Loop through each line in message and check for
// code-like characters. If code formatting is found
// return, else keep checking.
function ParseMessage(inputLines){
    for(let i = 0; i < inputLines.length; i++){
        if(inputLines[i].search("```") >= 0){
            isFormatted = true
            return
        }else
            FindCodeElements(i, inputLines[i])
    }
    return
}

// Post the formatted message in the appropriate channel
function PostNewMessage(oldMessage, newMessage){
    let channel = oldMessage.guild.channels.find("name", "programing_help")
    let channelName = oldMessage.channel.name
    let isHelp = channelName.indexOf('help') > 0

    if(channel != null && channel != oldMessage.channel && !isHelp){
        // TODO: Would like to add alink to #programming help for user friendliness :D
        // TODO: Would like to add some color to this message also
        // Maybe make it bold
        oldMessage.channel.send(':nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '. `Which makes sense...` :nerd:')
        channel.send(oldMessage.author + ' **★★ I have formatted your code and placed it here. Good Luck! ★★**')
        channel.send(newMessage);
    }else{
        oldMessage.channel.send(oldMessage.author + ' **★★ I see you forgot to format your code... Let me help you. ★★**')
        oldMessage.channel.send(newMessage)
    }
}

// Checks the last character in a string to see of it machess a code-like character
function FindCodeElements(index, inLine){
    let lineLength = inLine.length - 1
    for(let i = 0; i < codeElements.length; i++){
        if (inLine.charAt(lineLength).valueOf() == codeElements[i].valueOf()){
            if(!firstLine){
                lines[index] = FormatFirstLine(inLine)
                return
            }else{
                lastLine = index
                totalLinesOfCode += 1
                return
            }
        }
    }
    return
}

// Adds code formatting block start to the first line of code
function FormatFirstLine(inLine){
    firstLine = true
    return '```' + codeLang + '\n' + inLine
}

// Add formatting code bock end to the last line of code
function FormatLastLine(inLine){
    return inLine + '\n```'
}

// If total line of code is greater than repostThreshold return true
function IsBadCode(){
    return (totalLinesOfCode >= repostThreshold)
}

// Initalize variables
function InitVariables(){
    isFormatted = false
    totalLinesOfCode = 0;
    firstLine = false
    lastLine = 0
}<|endoftext|>


<commit_before>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    14 July, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Look for lines ending in ; { } )

        * If found, Locate the first Code Block Line
        * If found, Locate the last Code Block Line
        *
        * RePost the message surrounded by code formatting ```csharp ```

    EXAMPLE-----------------------------------------------------------------

    ```csharp
    using UnityEngine;

    /// <summary>
    /// Class summary
    /// </summary>
    public class MyClass
    {
        /// <summary>   Summary of myFloat. </summary>
        public float myFloat;
        /// <summary>   Summary of myOtherFloat.</summary>
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _newAngle;
            this.myOtherFLoat = _changeTime;
        }
    }
    ```
    ------------------------------------------------------------------------
*/

const Discord = require('discord.js');
const Confax = require('../bot.js')
const bot = GlassBot.bot
const config = GlassBot.config

var isFormatted = false
var totalLinesOfCode = 0
var originalLines = []

var lines = []
var codeLines = []

// Create an event listener for messages to parse
bot.on('message', message => {
    if (message.author.bot){
        //console.log("This is a bot message :D")
        return
    }
    if(message.content.length > 1900){
        return
    }

    isFormatted = false
    totalLinesOfCode = 0;

    lines = message.content.split('\n')
    originalLines = message.content.split('\n')

    checkMessageForCode(lines)

    if(isBadCode() && !isFormatted){

        let firstLine = Math.min.apply(Math, codeLines)
        let lastLine  = Math.max.apply(Math, codeLines) + 2
        console.log("First Line is: " + firstLine)
        originalLines.splice(firstLine, 0, '```csharp\n')
        originalLines.splice(lastLine,  0, '\n```\n'    )

        let strmessage = ""

        for (let j = 0; j < originalLines.length; j++){
           strmessage += originalLines[j] + '\n'
        }

        // TODO: Check if channel name contains help, if so just paste the new code here
        // else paste it in programing_help
        let channel = message.guild.channels.find("name", "programing_help")

        if(channel != null && channel != message.channel){
            // TODO: Would like to add alink to #programming help for user friendliness :D
            // TODO: Would like to add some color to this message also
            // Maybe make it bold
            message.channel.send('__`Your unformatted code has been formatted and moved to`__ ' + '#'+ channel.name + '.\n`Which makes sense...`')
            channel.send('**`I have formated your code and placed it here. Good Luck!.`**')
            channel.send(strmessage);
        }
        else{
                message.channel.send('**`I see you forgot to format your code... Let me help you.`**')
                message.channel.send(strmessage)
            }
        return
    }
    return

});

// Loop through each line in message and check for
// code-like characters. If code formaatting is found
// return else keep checking.
function checkMessageForCode(inputLines){
    for(let i = 0; i < inputLines.length; i++){
        //let line = inputLines[i].replace(/\s"/,'')
        let line = inputLines[i]
        if(line.search("```") >= 0){
            isFormatted = true
            return
        }
        else{
            checkLastCharacter(i, line, ';')
            checkLastCharacter(i, line, '{')
            checkLastCharacter(i, line, '}')
            checkLastCharacter(i, line, ')')
        }
    }
    return
}

// Checks the last character in a string to see of it machess a code-like character (inChar)
function checkLastCharacter(index, inLine, inChar){
    if(inLine.charAt(inLine.length-1).valueOf() == inChar.valueOf()){
        codeLines.push(index)
        console.log(inLine)
        totalLinesOfCode += 1
        console.log("Total Lines of Code: " + totalLinesOfCode)
        return
    }
    return
}

// Checks the total number of code like elements in an unformatted
// code block. If greater than 5 than this is bad code lol, return true
function isBadCode(){
    if (totalLinesOfCode >= 5){
        //console.log("Bad code")
        return true
    }
    else{
        return false
    }
}<commit_msg>GlassBot<commit_after>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    14 July, 2017
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Look for lines ending in ; { } )

        * If found, Locate the first Code Block Line
        * If found, Locate the last Code Block Line
        *
        * RePost the message surrounded by code formatting ```csharp ```

    EXAMPLE-----------------------------------------------------------------

    ```csharp
    using UnityEngine;

    /// <summary>
    /// Class summary
    /// </summary>
    public class MyClass
    {
        /// <summary>   Summary of myFloat. </summary>
        public float myFloat;
        /// <summary>   Summary of myOtherFloat.</summary>
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _newAngle;
            this.myOtherFLoat = _changeTime;
        }
    }
    ```
    ------------------------------------------------------------------------
*/

const Discord = require('discord.js');
const GlassBot = require('../bot.js')
const bot = GlassBot.bot
const config = GlassBot.config

var isFormatted = false
var totalLinesOfCode = 0
var originalLines = []

var lines = []
var codeLines = []

// Create an event listener for messages to parse
bot.on('message', message => {
    if (message.author.bot){
        //console.log("This is a bot message :D")
        return
    }
    if(message.content.length > 1900){
        return
    }

    isFormatted = false
    totalLinesOfCode = 0;

    lines = message.content.split('\n')
    originalLines = message.content.split('\n')

    checkMessageForCode(lines)

    if(isBadCode() && !isFormatted){

        let firstLine = Math.min.apply(Math, codeLines)
        let lastLine  = Math.max.apply(Math, codeLines) + 2
        console.log("First Line is: " + firstLine)
        originalLines.splice(firstLine, 0, '```csharp\n')
        originalLines.splice(lastLine,  0, '\n```\n'    )

        let strmessage = ""

        for (let j = 0; j < originalLines.length; j++){
           strmessage += originalLines[j] + '\n'
        }

        // TODO: Check if channel name contains help, if so just paste the new code here
        // else paste it in programing_help
        let channel = message.guild.channels.find("name", "programing_help")

        if(channel != null && channel != message.channel){
            // TODO: Would like to add alink to #programming help for user friendliness :D
            // TODO: Would like to add some color to this message also
            // Maybe make it bold
            message.channel.send('__`Your unformatted code has been formatted and moved to`__ ' + '#'+ channel.name + '.\n`Which makes sense...`')
            channel.send('**`I have formated your code and placed it here. Good Luck!.`**')
            channel.send(strmessage);
        }
        else{
                message.channel.send('**`I see you forgot to format your code... Let me help you.`**')
                message.channel.send(strmessage)
            }
        return
    }
    return

});

// Loop through each line in message and check for
// code-like characters. If code formaatting is found
// return else keep checking.
function checkMessageForCode(inputLines){
    for(let i = 0; i < inputLines.length; i++){
        //let line = inputLines[i].replace(/\s"/,'')
        let line = inputLines[i]
        if(line.search("```") >= 0){
            isFormatted = true
            return
        }
        else{
            checkLastCharacter(i, line, ';')
            checkLastCharacter(i, line, '{')
            checkLastCharacter(i, line, '}')
            checkLastCharacter(i, line, ')')
        }
    }
    return
}

// Checks the last character in a string to see of it machess a code-like character (inChar)
function checkLastCharacter(index, inLine, inChar){
    if(inLine.charAt(inLine.length-1).valueOf() == inChar.valueOf()){
        codeLines.push(index)
        console.log(inLine)
        totalLinesOfCode += 1
        console.log("Total Lines of Code: " + totalLinesOfCode)
        return
    }
    return
}

// Checks the total number of code like elements in an unformatted
// code block. If greater than 5 than this is bad code lol, return true
function isBadCode(){
    if (totalLinesOfCode >= 5){
        //console.log("Bad code")
        return true
    }
    else{
        return false
    }
}<|endoftext|>