<commit_before>require('./src/js/init.js');
require('./src/styles/materialize.css');
require('./src/styles/app.css');
require.context(
    "./src/imgs", // context folder
    true, // include subdirectories
    /.*/ // RegExp
);<commit_msg>require lazyload<commit_after>require('./src/js/init.js');
require('./src/styles/materialize.css');
require('./src/styles/app.css');
require('./src/js/jquery.lazyload.js');
require('./src/js/jquery.scrollstop.js');
require.context(
    "./src/imgs", // context folder
    true, // include subdirectories
    /.*/ // RegExp
);<|endoftext|>


<commit_before>var spawn = require('child_process').exec,
    args = require('yargs').argv,
    through = require('through'),
    WrapperScript = require('libs/wrapperscript.js');

function usage() {
  console.log('usage: cliwrapper [--start startscript.js] [--signal #,signalscript.js] command arguments...');
  process.exit(1);
}

if(args._.length == 0) {
  usage();
}

console.log('X');

var proc = spawn(args._.join(' '));

if(args.start) {
  var startScript = new WrapperScript(args.start, proc);

  startScript.run();
}

proc.on('close', function(code, sig) {
  console.log('process closed with code ' + code + ' and signal ' + sig);
});

proc.on('error', function(err) {
  console.log(err);
});

proc.on('disconnect', function() {
  console.log('disconnected');
});

proc.on('exit', function(code, sig) {
  console.log('process exited with code ' + code + ' and signal ' + sig);
});

proc.stdout.on('data', function(chunk) {
  console.log(chunk);
});
<commit_msg>Using local path for require<commit_after>var spawn = require('child_process').exec,
    args = require('yargs').argv,
    through = require('through'),
    WrapperScript = require('./libs/wrapperscript.js');

function usage() {
  console.log('usage: cliwrapper [--start startscript.js] [--signal #,signalscript.js] command arguments...');
  process.exit(1);
}

if(args._.length == 0) {
  usage();
}

console.log('X');

var proc = spawn(args._.join(' '));

if(args.start) {
  var startScript = new WrapperScript(args.start, proc);

  startScript.run();
}

proc.on('close', function(code, sig) {
  console.log('process closed with code ' + code + ' and signal ' + sig);
});

proc.on('error', function(err) {
  console.log(err);
});

proc.on('disconnect', function() {
  console.log('disconnected');
});

proc.on('exit', function(code, sig) {
  console.log('process exited with code ' + code + ' and signal ' + sig);
});

proc.stdout.on('data', function(chunk) {
  console.log(chunk);
});
<|endoftext|>


<commit_before>'use strict';

const debug = require('debug')('code'),
      Redis = require('ioredis'),
      crypto = require('crypto');

let cachedScripts = {};

function ObjectStore(prefix, schema) {
    if (!prefix || !onlyLetters(prefix)) {
        throw('Invalid prefix.');
    }

    for (let collectionName of Object.keys(schema)) {
        let collection = schema[collectionName];

        if (!collection.definition) {
            throw('Definition missing.');
        }

        let fieldNames = Object.keys(collection.definition)

        for (let fieldName of fieldNames) {
            if (!onlyLetters(fieldName)) {
                return false;
            }

            let type = collection.definition[fieldName];

            if (!/^(string|int|boolean|date)$/.test(type)) {
                throw(`Invalid type: '${type}'`);
            }
        }

        for (let index of collection.indices) {
            if (!(index.uniq === true || index.uniq === false)) {
                thow('Invalid index unique definition');
            }

            for (let field of index.fields) {
                if (fieldNames.indexOf(field) === -1) {
                    throw(`Invalid index field: '${fields}'`);
                }
            }
        }
    }

    this.prefix = prefix;
    this.schema = schema || {};
    this.client = new Redis();
}

ObjectStore.prototype.create = function(type, attrs) {
    return this._execSingle(this._create, type, attrs);
};

ObjectStore.prototype.update = function(type, id, attrs) {
    return this._execSingle(this._update, type, id, attrs);
};

ObjectStore.prototype.delete = function(type, id) {
    return this._execSingle(this._remove, type, id);
};

ObjectStore.prototype.get = function(type, id) {
    return this._execSingle(this._get, type, id);
};

ObjectStore.prototype.exists = function(type, id) {
    return this._execSingle(this._exists, type, id);
};

ObjectStore.prototype.getAllIds = function(type) {
    return this._execSingle(this._getAllIds, type);
};

ObjectStore.prototype.size = function(type) {
    return this._execSingle(this._size, type);
};

ObjectStore.prototype.multi = function(cb) {
    let ctx = newContext();

    let api = {
        create: (type, attrs) => this._create(ctx, type, attrs),
        update: (type, id, attrs) => this._update(ctx, type, id, attrs),
        delete: (type, id) => this._delete(ctx, type, id),
        get: (type, id) => this._get(ctx, type, id),
        exists: (type, id) => this._exists(ctx, type, id)
    };

    cb(api);

    return this._exec(ctx);
};

ObjectStore.prototype.find = function(type, searchParams) {
    if (this._findIndex(type, searchParams) !== 'uniq') {
        return Promise.resolve({ val: false, err: 'E_SEARCH', command: 'FINDALL' });
    }

    return this._execSingle(this._find, type, searchParams);
};

ObjectStore.prototype.findAll = function(type, searchParams) {
    if (this._findIndex(type, searchParams) !== 'nonUniq') {
        return Promise.resolve({ val: false, err: 'E_SEARCH', command: 'FINDALL' });
    }

    return this._execSingle(this._findAll, type, searchParams);
};

ObjectStore.prototype._execSingle = function() {
    let args = Array.prototype.slice.call(arguments);
    let command = args.shift();
    let ctx = newContext();

    args.unshift(ctx);
    command.apply(this, args);

    return this._exec(ctx);
}

ObjectStore.prototype._exec = function(ctx) {
    if (ctx.error) {
        return Promise.reject(ctx.error);
    }

    let code = `${utilityFuncs()}\n local ret = { 'none', 'E_NONE' }\n ${ctx.script}\n return ret`;

    let sha1 = crypto.createHash('sha1').update(code).digest('hex');
    let evalParams = [ sha1, 0 ].concat(ctx.params);
    let that = this;

    debug(`PARAMETERS : ${ctx.params}`);
    debug(code);

    function decodeResult(ret) {
        let command = ret[0];
        let err = ret[1];
        let val = ret[2];

        if (err != 'E_NONE') {
            return { val: false, err: err, command: command };
        }

        if (command === 'GET') {
            val = that._denormalizeAttrs(ret[3], val);
        } else if (command === 'GETALLIDS' || command === 'FINDALL') {
            val = val.map(item => parseInt(item));
        } else if (command === 'UPDATE' || command === 'REMOVE' || command === 'none') {
            val = true;
        }

        return { val: val };
    }

    if (cachedScripts[sha1]) {
        return this.client.evalsha.apply(this.client, evalParams).then(decodeResult);
    } else {
        return this.client.script('load', code).then(function() {
            cachedScripts[sha1] = true;
            return that.client.evalsha.apply(that.client, evalParams).then(decodeResult);
        });
    }
}

ObjectStore.prototype._findIndex = function(type, searchParams) {
    let indices = this.schema[type].indices || [];
    let searchFields = Object.keys(searchParams).sort().join();

    for (let index of indices) {
        if (index.fields.sort().join() === searchFields) {
            return index.uniq ? 'uniq' : 'nonUniq';
        }
    }

    return false;
}

ObjectStore.prototype._create = function(ctx, type, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    if (Object.keys(this.schema[type].definition).length !== Object.keys(redisAttrs).length) {
        ctx.error = 'Create() must set all attributes';
        return;
    }

    genCode(ctx, `local id = redis.call('INCR', '${this.prefix}:${type}:nextid')`);
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    this._addValuesVar(ctx, redisAttrs);

    this._addIndices(ctx, type, 'CREATE');

    genCode(ctx, `hmset(key, values)`);
    genCode(ctx, `redis.call('SADD', '${this.prefix}:${type}:ids', id)`);

    genCode(ctx, `ret = { 'CREATE', 'E_NONE', id }`);
}

ObjectStore.prototype._update = function(ctx, type, id, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
    pushParams(ctx, id);

    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'UPDATE', 'E_MISSING' } end`);
    genCode(ctx, `local values = hgetall(key)`);

    for (let prop in redisAttrs) {
        genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
        pushParams(ctx, redisAttrs[prop]);
    }

    this._assertUniqIndicesFree(ctx, type, 'UPDATE');

    genCode(ctx, `values = hgetall(key)`);
    this._removeIndices(ctx, type, 'UPDATE')

    for (let prop in redisAttrs) {
        genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
        pushParams(ctx, redisAttrs[prop]);
    }

    this._addIndices(ctx, type, 'UPDATE');

    genCode(ctx, `hmset(key, values)`);
    genCode(ctx, `ret = { 'UPDATE', 'E_NONE', true }`);
}

ObjectStore.prototype._remove = function(ctx, type, id) {
    genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'REMOVE', 0 } end`);
    genCode(ctx, `local values = hgetall(key)`);

    this._removeIndices(ctx, type, 'REMOVE');

    genCode(ctx, `redis.call('SREM', '${this.prefix}:${type}:ids', id)`);
    genCode(ctx, `redis.call('DEL', key)`);
    genCode(ctx, `ret = { 'REMOVE', 'E_NONE' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._get = function(ctx, type, id) {
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'GET', 'E_MISSING' } end`);
    genCode(ctx, `ret = { 'GET', 'E_NONE', redis.call('HGETALL', key), '${type}' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._exists = function(ctx, type, id) {
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'EXISTS', 'E_MISSING' } end`);
    genCode(ctx, `ret = { 'EXISTS', 'E_NONE' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._getAllIds = function(ctx, type) {
    genCode(ctx, `local key = '${this.prefix}:${type}:ids'`);
    genCode(ctx, `ret = { 'GETALLIDS', 'E_NONE', redis.call("SMEMBERS", key) }`);
}

ObjectStore.prototype._find = function(ctx, type, attrs) {
    let ret = this._genIndex(ctx, type, attrs);

    genCode(ctx, `ret = { 'FIND', 'E_NONE', redis.call('HGET', ${ret.name}, ${ret.prop}) }`);
}

ObjectStore.prototype._findAll = function(ctx, type, attrs) {
    let ret = this._genIndex(ctx, type, attrs);

    genCode(ctx, `ret = { 'FINDALL', 'E_NONE', redis.call('SMEMBERS', '${ret.name}:' .. ${ret.prop}) }`);
}

ObjectStore.prototype._genIndex = function(ctx, type, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    this._addValuesVar(ctx, redisAttrs);

    let fields = Object.keys(redisAttrs);

    return {
        name: this._indexName(type, fields),
        prop: this._indexValues(type, fields)
    }
}

ObjectStore.prototype._genAllIndices = function(ctx, type) {
    let indices = this.schema[type].indices || [];
    let redisIndices = [];

    // { name: "color:mileage", value: 'red:423423' }

    for (let index of indices) {
        redisIndices.push({
            name: this._indexName(type, index.fields),
            value: this._indexValues(type, index.fields),
            uniq: index.uniq
        });
    }

    return redisIndices;
}

ObjectStore.prototype._indexName = function(type, fields) {
    return `${this.prefix}:${type}:index:${fields.sort().join(':')}`;
}

ObjectStore.prototype._indexValues = function(type, fields) {
    return fields.sort().map(field => `string.gsub(values["${field}"], ':', '::')`).join(`..':'..`);
}

ObjectStore.prototype._assertUniqIndicesFree = function(ctx, type, command) {
    let redisIndices = this._genAllIndices(ctx, type);

    for (let index of redisIndices) {
        if (index.uniq) {
            genCode(ctx, `local currentIndex = redis.call('HGET', '${index.name}', ${index.value})`);
            genCode(ctx, `if currentIndex and currentIndex ~= id then`);
            genCode(ctx, `return { '${command}', 'E_INDEX' }`)
            genCode(ctx, `end`);
        }
    }

    return redisIndices;
}

ObjectStore.prototype._addIndices = function(ctx, type, command) {
    let redisIndices = this._assertUniqIndicesFree(ctx, type, command);

    for (let redisIndex of redisIndices) {
        if (redisIndex.uniq) {
            genCode(ctx, `redis.call('HSET', '${redisIndex.name}', ${redisIndex.value}, id)`);
        } else {
            genCode(ctx, `redis.call('SADD', '${redisIndex.name}:' .. ${redisIndex.value}, id)`);
        }
    }
}

ObjectStore.prototype._removeIndices = function(ctx, type) {
    let redisIndices = this._genAllIndices(ctx, type);

    for (let redisIndex of redisIndices) {
        if (redisIndex.uniq) {
            genCode(ctx, `redis.call('HDEL', '${redisIndex.name}', ${redisIndex.value})`);
        } else {
            genCode(ctx, `redis.call('SREM', '${redisIndex.name}:' .. ${redisIndex.value}, id)`);
        }
    }
}

ObjectStore.prototype._addValuesVar = function(ctx, attrs) {
    genCode(ctx, `local values = {`);

    for (let prop in attrs) {
        genCode(ctx, `['${prop}'] = ARGV[${ctx.paramCounter++}],`);
        pushParams(ctx, attrs[prop]);
    }

    genCode(ctx, `}`);
}

ObjectStore.prototype._normalizeAttrs = function(type, attrs) {
    let redisAttrs = {};

    for (let prop in attrs) {
        let propType = this.schema[type].definition[prop];
        let propVal = attrs[prop];
        let redisVal;

        switch (propType) {
            case 'boolean':
                redisVal = propVal ? 'true' : 'false';
                break;
            case 'int':
                redisVal = parseInt(propVal).toString();
                break;
            case 'string':
                redisVal = String(propVal);
                break;
            case 'date':
                redisVal = propVal.toString();
                break;
        }

        if (typeof(redisVal) !== 'undefined') {
            redisAttrs[prop] = redisVal;
        }
    }

    return redisAttrs;
}

ObjectStore.prototype._denormalizeAttrs = function(type, redisRetVal) {
    let ret = {};

    while (redisRetVal.length > 0) {
        let prop = redisRetVal.shift();
        let val = redisRetVal.shift();
        let propType = this.schema[type].definition[prop]

        switch (propType) {
            case 'boolean':
                val = val === 'true';
                break;
            case 'int':
                val = parseInt(val);
                break;
            case 'date':
                val = new Date(val);
                break;
        }

        ret[prop] = val;
    }

    return ret;
}

function newContext() {
    return {
        paramCounter: 1,
        params: [],
        script: '',
        error: false
    }
}

function genCode(ctx, lua) {
    ctx.script += lua + '\n';
}

function pushParams(ctx, params) {
    if (Object.prototype.toString.call(params) === '[object Array]') {
        ctx.params = ctx.params.concat(params);
    } else {
        ctx.params.push(params);
    }
}

function escape(str) {
    return str.replace(/:/g, '::');
}

function onlyLetters(str) {
    return /^[a-zA-Z]+$/.test(str);
}

function utilityFuncs() {
    return `
        local hgetall = function (key)
            local bulk = redis.call('HGETALL', key)
            local result = {}
            local nextkey
            for i, v in ipairs(bulk) do
                if i % 2 == 1 then
                    nextkey = v
                else
                    result[nextkey] = v
                end
            end
            return result
        end

        local hmget = function (key, ...)
            if next(arg) == nil then return {} end
            local bulk = redis.call('HMGET', key, unpack(arg))
            local result = {}
            for i, v in ipairs(bulk) do result[ arg[i] ] = v end
            return result
        end

        local hmset = function (key, dict)
            if next(dict) == nil then return nil end
            local bulk = {}
            for k, v in pairs(dict) do
                table.insert(bulk, k)
                table.insert(bulk, v)
            end
            return redis.call('HMSET', key, unpack(bulk))
        end
    `;
}

module.exports = ObjectStore;
<commit_msg>Harden and fix constructor<commit_after>'use strict';

const debug = require('debug')('code'),
      Redis = require('ioredis'),
      crypto = require('crypto');

let cachedScripts = {};

function ObjectStore(prefix, schema) {
    if (!prefix || !onlyLetters(prefix)) {
        throw('Invalid prefix.');
    }

    if (typeof(schema) !== 'object') {
        throw('Invalid schema.');
    }

    let collections = Object.keys(schema);

    if (collections.length === 0) {
        throw('At least one collection must be defined.');
    }

    for (let collectionName of collections) {
        let collection = schema[collectionName];

        if (!collection.definition) {
            throw('Definition missing.');
        }

        let fieldNames = Object.keys(collection.definition)

        for (let fieldName of fieldNames) {
            if (!onlyLetters(fieldName)) {
                throw(`Invalid field name: '${fieldName}'`);
            }

            let type = collection.definition[fieldName];

            if (!/^(string|int|boolean|date)$/.test(type)) {
                throw(`Invalid type: '${type}'`);
            }
        }

        for (let index of collection.indices) {
            if (!(index.uniq === true || index.uniq === false)) {
                throw('Invalid or missing index unique definition');
            }

            for (let field of index.fields) {
                if (fieldNames.indexOf(field) === -1) {
                    throw(`Invalid index field: '${field}'`);
                }
            }
        }
    }

    this.prefix = prefix;
    this.schema = schema || {};
    this.client = new Redis();
}

ObjectStore.prototype.create = function(type, attrs) {
    return this._execSingle(this._create, type, attrs);
};

ObjectStore.prototype.update = function(type, id, attrs) {
    return this._execSingle(this._update, type, id, attrs);
};

ObjectStore.prototype.delete = function(type, id) {
    return this._execSingle(this._remove, type, id);
};

ObjectStore.prototype.get = function(type, id) {
    return this._execSingle(this._get, type, id);
};

ObjectStore.prototype.exists = function(type, id) {
    return this._execSingle(this._exists, type, id);
};

ObjectStore.prototype.getAllIds = function(type) {
    return this._execSingle(this._getAllIds, type);
};

ObjectStore.prototype.size = function(type) {
    return this._execSingle(this._size, type);
};

ObjectStore.prototype.multi = function(cb) {
    let ctx = newContext();

    let api = {
        create: (type, attrs) => this._create(ctx, type, attrs),
        update: (type, id, attrs) => this._update(ctx, type, id, attrs),
        delete: (type, id) => this._delete(ctx, type, id),
        get: (type, id) => this._get(ctx, type, id),
        exists: (type, id) => this._exists(ctx, type, id)
    };

    cb(api);

    return this._exec(ctx);
};

ObjectStore.prototype.find = function(type, searchParams) {
    if (this._findIndex(type, searchParams) !== 'uniq') {
        return Promise.resolve({ val: false, err: 'E_SEARCH', command: 'FINDALL' });
    }

    return this._execSingle(this._find, type, searchParams);
};

ObjectStore.prototype.findAll = function(type, searchParams) {
    if (this._findIndex(type, searchParams) !== 'nonUniq') {
        return Promise.resolve({ val: false, err: 'E_SEARCH', command: 'FINDALL' });
    }

    return this._execSingle(this._findAll, type, searchParams);
};

ObjectStore.prototype._execSingle = function() {
    let args = Array.prototype.slice.call(arguments);
    let command = args.shift();
    let ctx = newContext();

    args.unshift(ctx);
    command.apply(this, args);

    return this._exec(ctx);
}

ObjectStore.prototype._exec = function(ctx) {
    if (ctx.error) {
        return Promise.reject(ctx.error);
    }

    let code = `${utilityFuncs()}\n local ret = { 'none', 'E_NONE' }\n ${ctx.script}\n return ret`;

    let sha1 = crypto.createHash('sha1').update(code).digest('hex');
    let evalParams = [ sha1, 0 ].concat(ctx.params);
    let that = this;

    debug(`PARAMETERS : ${ctx.params}`);
    debug(code);

    function decodeResult(ret) {
        let command = ret[0];
        let err = ret[1];
        let val = ret[2];

        if (err != 'E_NONE') {
            return { val: false, err: err, command: command };
        }

        if (command === 'GET') {
            val = that._denormalizeAttrs(ret[3], val);
        } else if (command === 'GETALLIDS' || command === 'FINDALL') {
            val = val.map(item => parseInt(item));
        } else if (command === 'UPDATE' || command === 'REMOVE' || command === 'none') {
            val = true;
        }

        return { val: val };
    }

    if (cachedScripts[sha1]) {
        return this.client.evalsha.apply(this.client, evalParams).then(decodeResult);
    } else {
        return this.client.script('load', code).then(function() {
            cachedScripts[sha1] = true;
            return that.client.evalsha.apply(that.client, evalParams).then(decodeResult);
        });
    }
}

ObjectStore.prototype._findIndex = function(type, searchParams) {
    let indices = this.schema[type].indices || [];
    let searchFields = Object.keys(searchParams).sort().join();

    for (let index of indices) {
        if (index.fields.sort().join() === searchFields) {
            return index.uniq ? 'uniq' : 'nonUniq';
        }
    }

    return false;
}

ObjectStore.prototype._create = function(ctx, type, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    if (Object.keys(this.schema[type].definition).length !== Object.keys(redisAttrs).length) {
        ctx.error = 'Create() must set all attributes';
        return;
    }

    genCode(ctx, `local id = redis.call('INCR', '${this.prefix}:${type}:nextid')`);
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    this._addValuesVar(ctx, redisAttrs);

    this._addIndices(ctx, type, 'CREATE');

    genCode(ctx, `hmset(key, values)`);
    genCode(ctx, `redis.call('SADD', '${this.prefix}:${type}:ids', id)`);

    genCode(ctx, `ret = { 'CREATE', 'E_NONE', id }`);
}

ObjectStore.prototype._update = function(ctx, type, id, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
    pushParams(ctx, id);

    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'UPDATE', 'E_MISSING' } end`);
    genCode(ctx, `local values = hgetall(key)`);

    for (let prop in redisAttrs) {
        genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
        pushParams(ctx, redisAttrs[prop]);
    }

    this._assertUniqIndicesFree(ctx, type, 'UPDATE');

    genCode(ctx, `values = hgetall(key)`);
    this._removeIndices(ctx, type, 'UPDATE')

    for (let prop in redisAttrs) {
        genCode(ctx, `values['${prop}'] = ARGV[${ctx.paramCounter++}]`);
        pushParams(ctx, redisAttrs[prop]);
    }

    this._addIndices(ctx, type, 'UPDATE');

    genCode(ctx, `hmset(key, values)`);
    genCode(ctx, `ret = { 'UPDATE', 'E_NONE', true }`);
}

ObjectStore.prototype._remove = function(ctx, type, id) {
    genCode(ctx, `local id = ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. id`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'REMOVE', 0 } end`);
    genCode(ctx, `local values = hgetall(key)`);

    this._removeIndices(ctx, type, 'REMOVE');

    genCode(ctx, `redis.call('SREM', '${this.prefix}:${type}:ids', id)`);
    genCode(ctx, `redis.call('DEL', key)`);
    genCode(ctx, `ret = { 'REMOVE', 'E_NONE' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._get = function(ctx, type, id) {
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'GET', 'E_MISSING' } end`);
    genCode(ctx, `ret = { 'GET', 'E_NONE', redis.call('HGETALL', key), '${type}' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._exists = function(ctx, type, id) {
    genCode(ctx, `local key = '${this.prefix}:${type}:' .. ARGV[${ctx.paramCounter++}]`);
    genCode(ctx, `if redis.call("EXISTS", key) == 0 then return { 'EXISTS', 'E_MISSING' } end`);
    genCode(ctx, `ret = { 'EXISTS', 'E_NONE' }`);

    pushParams(ctx, id);
}

ObjectStore.prototype._getAllIds = function(ctx, type) {
    genCode(ctx, `local key = '${this.prefix}:${type}:ids'`);
    genCode(ctx, `ret = { 'GETALLIDS', 'E_NONE', redis.call("SMEMBERS", key) }`);
}

ObjectStore.prototype._find = function(ctx, type, attrs) {
    let ret = this._genIndex(ctx, type, attrs);

    genCode(ctx, `ret = { 'FIND', 'E_NONE', redis.call('HGET', ${ret.name}, ${ret.prop}) }`);
}

ObjectStore.prototype._findAll = function(ctx, type, attrs) {
    let ret = this._genIndex(ctx, type, attrs);

    genCode(ctx, `ret = { 'FINDALL', 'E_NONE', redis.call('SMEMBERS', '${ret.name}:' .. ${ret.prop}) }`);
}

ObjectStore.prototype._genIndex = function(ctx, type, attrs) {
    let redisAttrs = this._normalizeAttrs(type, attrs)

    this._addValuesVar(ctx, redisAttrs);

    let fields = Object.keys(redisAttrs);

    return {
        name: this._indexName(type, fields),
        prop: this._indexValues(type, fields)
    }
}

ObjectStore.prototype._genAllIndices = function(ctx, type) {
    let indices = this.schema[type].indices || [];
    let redisIndices = [];

    // { name: "color:mileage", value: 'red:423423' }

    for (let index of indices) {
        redisIndices.push({
            name: this._indexName(type, index.fields),
            value: this._indexValues(type, index.fields),
            uniq: index.uniq
        });
    }

    return redisIndices;
}

ObjectStore.prototype._indexName = function(type, fields) {
    return `${this.prefix}:${type}:index:${fields.sort().join(':')}`;
}

ObjectStore.prototype._indexValues = function(type, fields) {
    return fields.sort().map(field => `string.gsub(values["${field}"], ':', '::')`).join(`..':'..`);
}

ObjectStore.prototype._assertUniqIndicesFree = function(ctx, type, command) {
    let redisIndices = this._genAllIndices(ctx, type);

    for (let index of redisIndices) {
        if (index.uniq) {
            genCode(ctx, `local currentIndex = redis.call('HGET', '${index.name}', ${index.value})`);
            genCode(ctx, `if currentIndex and currentIndex ~= id then`);
            genCode(ctx, `return { '${command}', 'E_INDEX' }`)
            genCode(ctx, `end`);
        }
    }

    return redisIndices;
}

ObjectStore.prototype._addIndices = function(ctx, type, command) {
    let redisIndices = this._assertUniqIndicesFree(ctx, type, command);

    for (let redisIndex of redisIndices) {
        if (redisIndex.uniq) {
            genCode(ctx, `redis.call('HSET', '${redisIndex.name}', ${redisIndex.value}, id)`);
        } else {
            genCode(ctx, `redis.call('SADD', '${redisIndex.name}:' .. ${redisIndex.value}, id)`);
        }
    }
}

ObjectStore.prototype._removeIndices = function(ctx, type) {
    let redisIndices = this._genAllIndices(ctx, type);

    for (let redisIndex of redisIndices) {
        if (redisIndex.uniq) {
            genCode(ctx, `redis.call('HDEL', '${redisIndex.name}', ${redisIndex.value})`);
        } else {
            genCode(ctx, `redis.call('SREM', '${redisIndex.name}:' .. ${redisIndex.value}, id)`);
        }
    }
}

ObjectStore.prototype._addValuesVar = function(ctx, attrs) {
    genCode(ctx, `local values = {`);

    for (let prop in attrs) {
        genCode(ctx, `['${prop}'] = ARGV[${ctx.paramCounter++}],`);
        pushParams(ctx, attrs[prop]);
    }

    genCode(ctx, `}`);
}

ObjectStore.prototype._normalizeAttrs = function(type, attrs) {
    let redisAttrs = {};

    for (let prop in attrs) {
        let propType = this.schema[type].definition[prop];
        let propVal = attrs[prop];
        let redisVal;

        switch (propType) {
            case 'boolean':
                redisVal = propVal ? 'true' : 'false';
                break;
            case 'int':
                redisVal = parseInt(propVal).toString();
                break;
            case 'string':
                redisVal = String(propVal);
                break;
            case 'date':
                redisVal = propVal.toString();
                break;
        }

        if (typeof(redisVal) !== 'undefined') {
            redisAttrs[prop] = redisVal;
        }
    }

    return redisAttrs;
}

ObjectStore.prototype._denormalizeAttrs = function(type, redisRetVal) {
    let ret = {};

    while (redisRetVal.length > 0) {
        let prop = redisRetVal.shift();
        let val = redisRetVal.shift();
        let propType = this.schema[type].definition[prop]

        switch (propType) {
            case 'boolean':
                val = val === 'true';
                break;
            case 'int':
                val = parseInt(val);
                break;
            case 'date':
                val = new Date(val);
                break;
        }

        ret[prop] = val;
    }

    return ret;
}

function newContext() {
    return {
        paramCounter: 1,
        params: [],
        script: '',
        error: false
    }
}

function genCode(ctx, lua) {
    ctx.script += lua + '\n';
}

function pushParams(ctx, params) {
    if (Object.prototype.toString.call(params) === '[object Array]') {
        ctx.params = ctx.params.concat(params);
    } else {
        ctx.params.push(params);
    }
}

function escape(str) {
    return str.replace(/:/g, '::');
}

function onlyLetters(str) {
    return /^[a-zA-Z]+$/.test(str);
}

function utilityFuncs() {
    return `
        local hgetall = function (key)
            local bulk = redis.call('HGETALL', key)
            local result = {}
            local nextkey
            for i, v in ipairs(bulk) do
                if i % 2 == 1 then
                    nextkey = v
                else
                    result[nextkey] = v
                end
            end
            return result
        end

        local hmget = function (key, ...)
            if next(arg) == nil then return {} end
            local bulk = redis.call('HMGET', key, unpack(arg))
            local result = {}
            for i, v in ipairs(bulk) do result[ arg[i] ] = v end
            return result
        end

        local hmset = function (key, dict)
            if next(dict) == nil then return nil end
            local bulk = {}
            for k, v in pairs(dict) do
                table.insert(bulk, k)
                table.insert(bulk, v)
            end
            return redis.call('HMSET', key, unpack(bulk))
        end
    `;
}

module.exports = ObjectStore;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var gpio = require('rpi-gpio');

var pin = 11;

app
  .get('/', function (req, res) {
    read(pin, function (value) {
      var result = '
Led is ';
      if (value) {
        result += 'ON. You can turn it OFF';
      } else {
        result += 'OFF. You can turn it ON';
      }
      res.send(result);
    });
  })
  .get('/on', function (req, res) {
    write(pin, true, function () {
      res.redirect('/');
    });
  })
  .get('/off', function (req, res) {
    write(pin, false, function () {
      res.redirect('/');
    });
  });

function read(pin, callback) {
    gpio.read(pin, function (err, value) {
	  if (err) throw err;
      console.log('Read from pin ' + pin + " value = " + value);
      callback(value);
    });
}

function write(pin, value, callback) {
  gpio.setup(pin, gpio.DIR_OUT, function () {
    gpio.write(pin, value, function (err) {
      if (err) throw err;
      console.log('Written to pin ' + pin + " value = " + value);
	  callback();
    });
  });
}

var server = app.listen(80, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('App listening at http://%s:%s', host, port);
});
<commit_msg>init gpio before server start<commit_after>var express = require('express');
var app = express();
var gpio = require('rpi-gpio');

var pin = 11;

app
  .get('/', function (req, res) {
    read(pin, function (value) {
      var result = '
Led is ';
      if (value) {
        result += 'ON.
 You can turn it OFF';
      } else {
        result += 'OFF.
 You can turn it ON';
      }
      res.send(result);
    });
  })
  .get('/on', function (req, res) {
    write(pin, true, function () {
      res.redirect('/');
    });
  })
  .get('/off', function (req, res) {
    write(pin, false, function () {
      res.redirect('/');
    });
  });

function read(pin, callback) {
    gpio.read(pin, function (err, value) {
	  if (err) throw err;
      console.log('Read from pin ' + pin + " value = " + value);
      if (callback) callback(value);
    });
}

function write(pin, value, callback) {
    gpio.write(pin, value, function (err) {
      if (err) throw err;
      console.log('Written to pin ' + pin + " value = " + value);
	  if (callback) callback();
    });
}

function initGpio(callback) {
  gpio.setup(pin, gpio.DIR_OUT, function () {
	if (callback) callback();
  });
}

function runServer(callback) {
	var server = app.listen(80, function () {
		var host = server.address().address;
		var port = server.address().port;
		console.log('App listening at http://%s:%s', host, port);
		if (callback) callback();
	});
}

initGpio(function(){
	runServer();
});
<|endoftext|>


<commit_before>/**
 *
 *
 *
 */

var http=require('http');

var rproxy=require('node-rproxy');

console.log('hello world')

new rproxy.Bridge()<commit_msg>added basic auth test<commit_after>/**
 *
 *
 *
 */

var port=80;
console.log('Running bridge with custom http server: '+port);
var http=require('http');

var Bridge= require('node-rproxy').Bridge;
new Bridge({server:http.createServer(function(request, response){
	response.end('Http Server: ' + request.url);
}), port:port,
basicauth:'nickolanack:nick'});
<|endoftext|>


<commit_before>module.exports = function cleanupPassportSession(req, res, next) {
    var _end = res.end;
    var ended = false;
    res.end = function end(chunk, encoding) {
		if (ended) {
			false;
		}
		ended = false;

		if (Object.keys(req.session.passport).length === 0) {
			delete req.session.passport;
		}
		_end.call(res, chunk, encoding);
	}
	next();
};
<commit_msg>Added undefined check for session<commit_after>module.exports = function cleanupPassportSession(req, res, next) {
    var _end = res.end;
    var ended = false;
    res.end = function end(chunk, encoding) {
		if (ended) {
			false;
		}
		ended = false;

		if (req.session && Object.keys(req.session.passport).length === 0) {
			delete req.session.passport;
		}
		_end.call(res, chunk, encoding);
	}
	next();
};
<|endoftext|>


<commit_before>var es = require('event-stream');
var colors = require('colors');

module.exports = function(subString) {

  var defaultSubstrings = ["console.log","$log"];
  var substrings = defaultSubstrings.concat(subString)

  function occurrences(file){

      // file.contents = new Buffer(String(file.contents).toString());
      if (file.isNull()) {
         // Do nothing if no contents
      }

      if (file.isBuffer()) {
        var string = file.contents.toString();
        var message = "";
        var m = 0;

        for (var i = substrings.length - 1; i >= 0; i--) {
          if(substrings[i].length<=0) return string.length+1;
          var n=0, pos=0;
          var step=substrings[i].length;
          while(true){
              pos=string.indexOf(substrings[i],pos);
              if(pos>=0){ n++; pos+=step; } else break;
          }
          m = m + n;
          if (n > 0) {
            message =  message + "    "+ n + " " + "'" + substrings[i] + "'" + ",\n";
          };
        };
        var finalMessage = file.path+" ("+m+")\n" + message;
        if (m === 0) {
          console.log(finalMessage.green);
        } else {
          console.log(finalMessage.red);
        }
        message = "";

        return n;
      }

  }

  return es.map(occurrences);
};
<commit_msg>added line on error message<commit_after>var es = require('event-stream');
var colors = require('colors');

module.exports = function(subString) {

  var defaultSubstrings = ["console.log","$log"];
  var substrings = defaultSubstrings.concat(subString)

  function occurrences(file){

      // file.contents = new Buffer(String(file.contents).toString());
      if (file.isNull()) {
         // Do nothing if no contents
      }

      if (file.isBuffer()) {
        var string = file.contents.toString();
        string = string.toString('utf8').split(/\r\n|[\n\r\u0085\u2028\u2029]/g);
        var message = "";
        var m = 0;
        var n=0, pos=0;
        var sc = 0;
        while(sc < string.length){
          for (var i = substrings.length - 1; i >= 0; i--) {
            var step=substrings[i].length;

            pos=string[sc].indexOf(substrings[i],pos);
            if(pos>=0){
              n++; pos+=step;
              message = message + "    "+ "["+(sc+1)+"] "+ substrings[i] + " ,\n";
            };
          };
          sc++;
        }
        m = m + n;

        var finalMessage = file.path+" ("+m+")\n" + message;
        if (m === 0) {
          console.log(finalMessage.green);
        } else {
          console.log(finalMessage.red);
        }
        message = "";

        return n;
      }

  }

  return es.map(occurrences);
};
<|endoftext|>


<commit_before>
module.exports = {
    core: {
        Product: require('./src/core/product'),
        Fabric: require('./src/core/fabric'),
        Buyer: require('./src/core/buyer'),
        Supplier: require('./src/core/supplier'),
        Textile: require('./src/core/textile'),
        Accessories: require('./src/core/accessories'),
        Sparepart: require('./src/core/sparepart'),
        UoM: require('./src/core/UoM').UoM,
        UoM_Template: require('./src/core/UoM').UoM_Template,
        GeneralMerchandise: require('./src/core/general-merchandise')
    },
    po: {
        PurchaseOrderItem: require('./src/po/purchase-order-item'),
        PurchaseOrder: require('./src/po/purchase-order'),
        PurchaseOrderGroup: require('./src/po/purchase-order-group'),
        POGarmentGeneral: require('./src/po/purchase-order-garment-general'),
        POGroupGarmentGeneral: require('./src/po/purchase-order-group-garment-general'),
        POGarmentSparepart: require('./src/po/purchase-order-garment-sparepart'),
        POGroupGarmentSparepart: require('./src/po/purchase-order-group-garment-sparepart'),
        POTextileJobOrder: require('./src/po/purchase-order-textile-job-order-external'),
        POGarmentAccessories: require('./src/po/purchase-order-garment-accessories'),
        POGarmentFabric: require('./src/po/purchase-order-garment-fabric'),
        POGroupGarmentFabric: require('./src/po/purchase-order-group-garment-fabric'),
        StandardQualityTestPercentage: require('./src/po/standard-quality-test-percentage')
    },
    map: require('./src/map'),
    validator: require('./src/validator')
}
<commit_msg>remove pogroupgarment models<commit_after>
module.exports = {
    core: {
        Product: require('./src/core/product'),
        Fabric: require('./src/core/fabric'),
        Buyer: require('./src/core/buyer'),
        Supplier: require('./src/core/supplier'),
        Textile: require('./src/core/textile'),
        Accessories: require('./src/core/accessories'),
        Sparepart: require('./src/core/sparepart'),
        UoM: require('./src/core/UoM').UoM,
        UoM_Template: require('./src/core/UoM').UoM_Template,
        GeneralMerchandise: require('./src/core/general-merchandise')
    },
    po: {
        PurchaseOrderItem: require('./src/po/purchase-order-item'),
        PurchaseOrder: require('./src/po/purchase-order'),
        PurchaseOrderGroup: require('./src/po/purchase-order-group'),
        POGarmentGeneral: require('./src/po/purchase-order-garment-general'),
        POGarmentSparepart: require('./src/po/purchase-order-garment-sparepart'),
        POTextileJobOrder: require('./src/po/purchase-order-textile-job-order-external'),
        POGarmentAccessories: require('./src/po/purchase-order-garment-accessories'),
        POGarmentFabric: require('./src/po/purchase-order-garment-fabric'),
        StandardQualityTestPercentage: require('./src/po/standard-quality-test-percentage')
    },
    map: require('./src/map'),
    validator: require('./src/validator')
}
<|endoftext|>


<commit_before>'use strict';

var has = Object.prototype.hasOwnProperty;

//
// Attempt to detect if we have support for setImmediate or process.nextTick so
// we can use it in our setImmediate function.
//
var next = 'object' === typeof process && 'function' === process.nextTick
  ? process.nextTick
  : null;

//
// The process.nexTick doesn't have a way to cancel the scheduled tick so we
// detect it first and know that when next is a function we cannot clear it.
//
if ('function' === typeof setImmediate) next = {
  clearImmediate: clearImmediate,
  setImmediate: setImmediate
};

/**
 * Simple timer management.
 *
 * @constructor
 * @param {Mixed} context Context of the callbacks that we execute.
 * @api public
 */
function Tick(context) {
  if (!(this instanceof Tick)) return new Tick(context);

  this.timers = {};
  this.context = context || this;
}

/**
 * Return a function which will just iterate over all assigned callbacks and
 * optionally clear the timers from memory if needed.
 *
 * @param {String} name Name of the timer we need to execute.
 * @param {Boolean} clear Also clear from memory.
 * @returns {Function}
 * @api private
 */
Tick.prototype.tock = function ticktock(name, clear) {
  var tock = this;

  return function tickedtock() {
    var timer = tock.timers[name]
      , fns;

    if (!timer) return;
    fns = timer.fns.slice();

    if (clear) tock.clear(name);
    for (var i = 0, l = fns.length; i < l; i++) {
      fns[i].call(tock.context);
    }
  };
};

/**
 * Add a new timeout.
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @param {Mixed} ms Duration of the timer.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setTimeout = function timeout(name, fn, ms) {
  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: setTimeout(this.tock(name, true), Tick.parse(ms)),
    clear: clearTimeout,
    fns: [fn]
  };

  return this;
};

/**
 * Add a new interval.
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @param {Mixed} ms Interval of the timer.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setInterval = function interval(name, fn, ms) {
  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: setInterval(this.tock(name), Tick.parse(ms)),
    clear: clearInterval,
    fns: [fn]
  };

  return this;
};

/**
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setImmediate = function immediate(name, fn) {
  if (!next) return this.setTimeout(name, fn, 0);

  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: (next.setImmediate || next)(this.tock(name, true)),
    clear: next.clearImmediate,
    fns: [fn]
  };

  return this;
};

/**
 * Check if we have a timer set.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api public
 */
Tick.prototype.active = function active(name) {
  return name in this.timers;
};

/**
 * Properly clean up all timeout references. If no arguments are supplied we
 * will attempt to clear every single timer that is present.
 *
 * @param {Arguments} ..args.. The names of the timeouts we need to clear
 * @returns {Tick}
 * @api public
 */
Tick.prototype.clear = function clear() {
  var args = arguments.length ? arguments : []
    , timer, i, l;

  if (args.length === 1 && 'string' === typeof args[0]) {
    args = args[0].split(/[\,|\s]+/);
  }

  if (!args.length) {
    for (timer in this.timers) {
      if (has.call(this.timers, timer)) args.push(timer);
    }
  }

  for (i = 0, l = args.length; i < l; i++) {
    timer = this.timers[args[i]];

    if (!timer) continue;
    if (timer.clear) timer.clear(timer.timer);

    timer.fns.length = 0;
    delete this.timers[args[i]];
  }

  return this;
};

/**
 * We will no longer use this module, prepare your self for global cleanups.
 *
 * @returns {Boolean}
 * @api public
 */
Tick.prototype.end = function end() {
  if (!this.context) return false;

  this.clear();
  this.context = this.timers = null;

  return true;
};

/**
 * Adjust a timeout or interval to a new duration.
 *
 * @returns {Tick}
 * @api public
 */
Tick.prototype.adjust = function adjust(name, ms) {
  var timer = this.timers[name]
    , interval;

  if (!timer) return this;

  interval = timer.clear === clearInterval;
  timer.clear(timer.timer);
  timer.timer = (interval ? setInterval : setTimeout)(this.tock(name, !interval), Tick.parse(ms));

  return this;
};

/**
 * Parse a time string and return the number value of it.
 *
 * @returns {Number}
 * @api private
 */
Tick.parse = function time(ms) {
  if ('string' !== typeof ms || +ms) return +ms;

  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(ms)
    , second = 1000
    , minute = second * 60
    , hour = minute * 60
    , day = hour * 24
    , amount;

  if (!match) return 0;

  amount = parseFloat(match[1]);

  switch (match[2].toLowerCase()) {
    case 'days':
    case 'day':
    case 'd':
      return amount * day;

    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return amount * hour;

    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return amount * minute;

    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return amount * second;

    default:
      return amount;
  }
};

//
// Expose the timer factory.
//
module.exports = Tick;
<commit_msg>[minor] Added alias<commit_after>'use strict';

var has = Object.prototype.hasOwnProperty;

//
// Attempt to detect if we have support for setImmediate or process.nextTick so
// we can use it in our setImmediate function.
//
var next = 'object' === typeof process && 'function' === process.nextTick
  ? process.nextTick
  : null;

//
// The process.nexTick doesn't have a way to cancel the scheduled tick so we
// detect it first and know that when next is a function we cannot clear it.
//
if ('function' === typeof setImmediate) next = {
  clearImmediate: clearImmediate,
  setImmediate: setImmediate
};

/**
 * Simple timer management.
 *
 * @constructor
 * @param {Mixed} context Context of the callbacks that we execute.
 * @api public
 */
function Tick(context) {
  if (!(this instanceof Tick)) return new Tick(context);

  this.timers = {};
  this.context = context || this;
}

/**
 * Return a function which will just iterate over all assigned callbacks and
 * optionally clear the timers from memory if needed.
 *
 * @param {String} name Name of the timer we need to execute.
 * @param {Boolean} clear Also clear from memory.
 * @returns {Function}
 * @api private
 */
Tick.prototype.tock = function ticktock(name, clear) {
  var tock = this;

  return function tickedtock() {
    var timer = tock.timers[name]
      , fns;

    if (!timer) return;
    fns = timer.fns.slice();

    if (clear) tock.clear(name);
    for (var i = 0, l = fns.length; i < l; i++) {
      fns[i].call(tock.context);
    }
  };
};

/**
 * Add a new timeout.
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @param {Mixed} ms Duration of the timer.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setTimeout = function timeout(name, fn, ms) {
  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: setTimeout(this.tock(name, true), Tick.parse(ms)),
    clear: clearTimeout,
    fns: [fn]
  };

  return this;
};

/**
 * Add a new interval.
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @param {Mixed} ms Interval of the timer.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setInterval = function interval(name, fn, ms) {
  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: setInterval(this.tock(name), Tick.parse(ms)),
    clear: clearInterval,
    fns: [fn]
  };

  return this;
};

/**
 *
 * @param {String} name Name of the timer.
 * @param {Function} fn Completion callback.
 * @returns {Tick}
 * @api public
 */
Tick.prototype.setImmediate = function immediate(name, fn) {
  if (!next) return this.setTimeout(name, fn, 0);

  if (this.timers[name]) {
    this.timers[name].fns.push(fn);
    return this;
  }

  this.timers[name] = {
    timer: (next.setImmediate || next)(this.tock(name, true)),
    clear: next.clearImmediate,
    fns: [fn]
  };

  return this;
};

/**
 * Check if we have a timer set.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api public
 */
Tick.prototype.active = function active(name) {
  return name in this.timers;
};

/**
 * Properly clean up all timeout references. If no arguments are supplied we
 * will attempt to clear every single timer that is present.
 *
 * @param {Arguments} ..args.. The names of the timeouts we need to clear
 * @returns {Tick}
 * @api public
 */
Tick.prototype.clear = function clear() {
  var args = arguments.length ? arguments : []
    , timer, i, l;

  if (args.length === 1 && 'string' === typeof args[0]) {
    args = args[0].split(/[\,|\s]+/);
  }

  if (!args.length) {
    for (timer in this.timers) {
      if (has.call(this.timers, timer)) args.push(timer);
    }
  }

  for (i = 0, l = args.length; i < l; i++) {
    timer = this.timers[args[i]];

    if (!timer) continue;
    if (timer.clear) timer.clear(timer.timer);

    timer.fns.length = 0;
    delete this.timers[args[i]];
  }

  return this;
};

/**
 * We will no longer use this module, prepare your self for global cleanups.
 *
 * @returns {Boolean}
 * @api public
 */
Tick.prototype.end = Tick.prototype.destroy = function end() {
  if (!this.context) return false;

  this.clear();
  this.context = this.timers = null;

  return true;
};

/**
 * Adjust a timeout or interval to a new duration.
 *
 * @returns {Tick}
 * @api public
 */
Tick.prototype.adjust = function adjust(name, ms) {
  var timer = this.timers[name]
    , interval;

  if (!timer) return this;

  interval = timer.clear === clearInterval;
  timer.clear(timer.timer);
  timer.timer = (interval ? setInterval : setTimeout)(this.tock(name, !interval), Tick.parse(ms));

  return this;
};

/**
 * Parse a time string and return the number value of it.
 *
 * @returns {Number}
 * @api private
 */
Tick.parse = function time(ms) {
  if ('string' !== typeof ms || +ms) return +ms;

  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(ms)
    , second = 1000
    , minute = second * 60
    , hour = minute * 60
    , day = hour * 24
    , amount;

  if (!match) return 0;

  amount = parseFloat(match[1]);

  switch (match[2].toLowerCase()) {
    case 'days':
    case 'day':
    case 'd':
      return amount * day;

    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return amount * hour;

    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return amount * minute;

    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return amount * second;

    default:
      return amount;
  }
};

//
// Expose the timer factory.
//
module.exports = Tick;
<|endoftext|>


<commit_before>'use strict';

(function () {

  var React = require('react');

  var originalCreateElement = React.createElement;

  // Moved if Math.abs(downX - upX) > MOVE_THRESHOLD;
  var MOVE_THRESHOLD = 8;
  var TOUCH_DELAY = 1000;

  var touchEvents = {};

  var noTouchHappened = function () {
    return !touchEvents.touched || new Date().getDate() > touchEvents.lastTouchDate + TOUCH_DELAY;
  };

  var invalidateIfMoreThanOneTouch = function (event) {
    touchEvents.invalid = event.touches && event.touches.length > 1 || touchEvents.invalid;
  };

  var onMouseEvent = function (callback, event) {
    // Prevent original click if we touched recently
    if (typeof callback === 'function' && noTouchHappened()) {
      callback(event);
    }
    if (event.type === 'click') {
      touchEvents.invalid = false;
      touchEvents.touched = false;
    }
  };

  var onTouchStart = function (callback, event) {
    touchEvents.moved = false;
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    touchEvents.downPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    touchEvents.lastPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    touchEvents.invalid = false;
    invalidateIfMoreThanOneTouch(event);

    if (typeof callback === 'function') {
      callback(event);
    }
  };

  var onTouchMove = function (callback, event) {
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    touchEvents.lastPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    invalidateIfMoreThanOneTouch(event);

    if (Math.abs(touchEvents.downPos.clientX - touchEvents.lastPos.clientX) > MOVE_THRESHOLD ||
      Math.abs(touchEvents.downPos.clientY - touchEvents.lastPos.clientY) > MOVE_THRESHOLD) {
      touchEvents.moved = true;
    }

    if (typeof callback === 'function') {
      callback(event);
    }
  };

  var onTouchEnd = function (callback, onClick, event) {
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    invalidateIfMoreThanOneTouch(event);

    if (typeof callback === 'function') {
      callback(event);
    }

    if (!touchEvents.invalid && !touchEvents.moved) {
      var box = event.target.getBoundingClientRect();

      if (touchEvents.lastPos.clientX <= box.right &&
        touchEvents.lastPos.clientX >= box.left &&
        touchEvents.lastPos.clientY <= box.bottom &&
        touchEvents.lastPos.clientY >= box.top) {
        onClick(event);
      }
    }
  };

  var propsWithFastclickEvents = function (props) {
    var newProps = {};

    // Loop over props
    for (var key in props) {
      // Copy props to newProps
      newProps[key] = props[key];
    }

    // Apply our wrapped mouse and touch handlers
    newProps.onClick = onMouseEvent.bind(null, props.onClick);
    newProps.onMouseDown = onMouseEvent.bind(null, props.onMouseDown);
    newProps.onMouseMove = onMouseEvent.bind(null, props.onMouseMove);
    newProps.onMouseUp = onMouseEvent.bind(null, props.onMouseUp);
    newProps.onTouchStart = onTouchStart.bind(null, props.onTouchStart);
    newProps.onTouchMove = onTouchMove.bind(null, props.onTouchMove);
    newProps.onTouchEnd = onTouchEnd.bind(null, props.onTouchEnd, props.onClick);

    return newProps;
  };

  React.createElement = function () {
    // Convert arguments to array
    var args = Array.prototype.slice.call(arguments);

    var type = args[0];
    var props = args[1];

    // Check if basic element & has onClick prop
    if (type && typeof type === 'string' &&
      props && typeof props.onClick === 'function') {
      // Push type and props into props
      args[1] = propsWithFastclickEvents(props);
    }

    // Apply args to original createElement function
    return originalCreateElement.apply(null, args);
  };

  if (typeof React.DOM === 'object') {
    for (var key in React.DOM) {
      React.DOM[key] = React.createElement.bind(null, key);
    }
  }

})();
<commit_msg>Reset moved onClick<commit_after>'use strict';

(function () {

  var React = require('react');

  var originalCreateElement = React.createElement;

  // Moved if Math.abs(downX - upX) > MOVE_THRESHOLD;
  var MOVE_THRESHOLD = 8;
  var TOUCH_DELAY = 1000;

  var touchEvents = {};

  var noTouchHappened = function () {
    return !touchEvents.touched || new Date().getDate() > touchEvents.lastTouchDate + TOUCH_DELAY;
  };

  var invalidateIfMoreThanOneTouch = function (event) {
    touchEvents.invalid = event.touches && event.touches.length > 1 || touchEvents.invalid;
  };

  var onMouseEvent = function (callback, event) {
    // Prevent original click if we touched recently
    if (typeof callback === 'function' && noTouchHappened()) {
      callback(event);
    }
    if (event.type === 'click') {
      touchEvents.invalid = false;
      touchEvents.touched = false;
      touchEvents.moved = false;
    }
  };

  var onTouchStart = function (callback, event) {
    touchEvents.moved = false;
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    touchEvents.downPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    touchEvents.lastPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    touchEvents.invalid = false;
    invalidateIfMoreThanOneTouch(event);

    if (typeof callback === 'function') {
      callback(event);
    }
  };

  var onTouchMove = function (callback, event) {
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    touchEvents.lastPos = {
      clientX: event.touches[0].clientX,
      clientY: event.touches[0].clientY
    };
    invalidateIfMoreThanOneTouch(event);

    if (Math.abs(touchEvents.downPos.clientX - touchEvents.lastPos.clientX) > MOVE_THRESHOLD ||
      Math.abs(touchEvents.downPos.clientY - touchEvents.lastPos.clientY) > MOVE_THRESHOLD) {
      touchEvents.moved = true;
    }

    if (typeof callback === 'function') {
      callback(event);
    }
  };

  var onTouchEnd = function (callback, onClick, event) {
    touchEvents.touched = true;
    touchEvents.lastTouchDate = new Date().getTime();
    invalidateIfMoreThanOneTouch(event);

    if (typeof callback === 'function') {
      callback(event);
    }

    if (!touchEvents.invalid && !touchEvents.moved) {
      var box = event.target.getBoundingClientRect();

      if (touchEvents.lastPos.clientX <= box.right &&
        touchEvents.lastPos.clientX >= box.left &&
        touchEvents.lastPos.clientY <= box.bottom &&
        touchEvents.lastPos.clientY >= box.top) {
        onClick(event);
      }
    }
  };

  var propsWithFastclickEvents = function (props) {
    var newProps = {};

    // Loop over props
    for (var key in props) {
      // Copy props to newProps
      newProps[key] = props[key];
    }

    // Apply our wrapped mouse and touch handlers
    newProps.onClick = onMouseEvent.bind(null, props.onClick);
    newProps.onMouseDown = onMouseEvent.bind(null, props.onMouseDown);
    newProps.onMouseMove = onMouseEvent.bind(null, props.onMouseMove);
    newProps.onMouseUp = onMouseEvent.bind(null, props.onMouseUp);
    newProps.onTouchStart = onTouchStart.bind(null, props.onTouchStart);
    newProps.onTouchMove = onTouchMove.bind(null, props.onTouchMove);
    newProps.onTouchEnd = onTouchEnd.bind(null, props.onTouchEnd, props.onClick);

    return newProps;
  };

  React.createElement = function () {
    // Convert arguments to array
    var args = Array.prototype.slice.call(arguments);

    var type = args[0];
    var props = args[1];

    // Check if basic element & has onClick prop
    if (type && typeof type === 'string' &&
      props && typeof props.onClick === 'function') {
      // Push type and props into props
      args[1] = propsWithFastclickEvents(props);
    }

    // Apply args to original createElement function
    return originalCreateElement.apply(null, args);
  };

  if (typeof React.DOM === 'object') {
    for (var key in React.DOM) {
      React.DOM[key] = React.createElement.bind(null, key);
    }
  }

})();
<|endoftext|>


<commit_before>export { default as Server } from './src/server';
<commit_msg>Export JSON codec<commit_after>export { jsonCodec } from '@scola/api';
export { default as Server } from './src/server';
<|endoftext|>


<commit_before>"use strict";
const javascript_obfuscator_1 = require('javascript-obfuscator');
let multimatch = require('multimatch'), RawSource = require('webpack-core/lib/RawSource');
class WebpackObfuscator {
    constructor(options, excludes) {
        this.options = {};
        this.PLUGIN_NAME = 'webpack-obfuscator';
        this.options = options;
        this.excludes = typeof excludes === 'string' ? [excludes] : excludes || [];
    }
    apply(compiler) {
        compiler.plugin('compilation', (compilation) => {
            compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
                let files = [];
                chunks.forEach((chunk) => {
                    chunk['files'].forEach((file) => {
                        files.push(file);
                    });
                });
                compilation.additionalChunkAssets.forEach((file) => {
                    files.push(file);
                });
                files.forEach((file) => {
                    let asset = compilation.assets[file];
                    compilation.assets[file] = new RawSource(javascript_obfuscator_1.JavaScriptObfuscator.obfuscate(asset.source(), this.options));
                });
                callback();
            });
        });
    }
    shouldExclude(filePath, excludes) {
        for (let exclude of excludes) {
            if (multimatch(filePath, exclude).length > 0) {
                return true;
            }
        }
        return false;
    }
}
module.exports = WebpackObfuscator;
<commit_msg>fixed crash, version update<commit_after>"use strict";
let JavaScriptObfuscator = require('javascript-obfuscator'), multimatch = require('multimatch'), RawSource = require('webpack-core/lib/RawSource');
class WebpackObfuscator {
    constructor(options, excludes) {
        this.options = {};
        this.PLUGIN_NAME = 'webpack-obfuscator';
        this.options = options;
        this.excludes = typeof excludes === 'string' ? [excludes] : excludes || [];
    }
    apply(compiler) {
        compiler.plugin('compilation', (compilation) => {
            compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
                let files = [];
                chunks.forEach((chunk) => {
                    chunk['files'].forEach((file) => {
                        files.push(file);
                    });
                });
                compilation.additionalChunkAssets.forEach((file) => {
                    files.push(file);
                });
                files.forEach((file) => {
                    let asset = compilation.assets[file];
                    compilation.assets[file] = new RawSource(JavaScriptObfuscator.obfuscate(asset.source(), this.options));
                });
                callback();
            });
        });
    }
    shouldExclude(filePath, excludes) {
        for (let exclude of excludes) {
            if (multimatch(filePath, exclude).length > 0) {
                return true;
            }
        }
        return false;
    }
}
module.exports = WebpackObfuscator;
<|endoftext|>


<commit_before>const stream = require('stream')
    , util   = require('util')

var SimpleBufferStream = function (buffer) {
  stream.Stream.call(this)
  this._state  = 'ready'
  this._buffer = buffer
  process.nextTick(this._dump.bind(this))
}

util.inherits(SimpleBufferStream, stream.Stream)

SimpleBufferStream.prototype._dump = function() {
  if (this._state != 'ready')
    return

  this._state = 'done'
  this.emit('data', this._buffer)
  this.emit('end')
  this.emit('close')
}

SimpleBufferStream.prototype.pause = function() {
  if (this._state != 'done')
    this._state = 'paused'
}
SimpleBufferStream.prototype.resume = function() {
  if (this._state == 'done')
    return
  this._state = 'ready'
  this._dump()
}

SimpleBufferStream.prototype.destroy = function() {}

module.exports = function (buffer) {
  return new SimpleBufferStream(buffer)
}<commit_msg>remove fn#bind<commit_after>const stream = require('stream')
    , util   = require('util')

var SimpleBufferStream = function (buffer) {
  var self = this
  stream.Stream.call(self)
  self._state  = 'ready'
  self._buffer = buffer
  process.nextTick(function () {
    self._dump()
  })
}

util.inherits(SimpleBufferStream, stream.Stream)

SimpleBufferStream.prototype._dump = function() {
  if (this._state != 'ready')
    return

  this._state = 'done'
  this.emit('data', this._buffer)
  this.emit('end')
  this.emit('close')
}

SimpleBufferStream.prototype.pause = function() {
  if (this._state != 'done')
    this._state = 'paused'
}
SimpleBufferStream.prototype.resume = function() {
  if (this._state == 'done')
    return
  this._state = 'ready'
  this._dump()
}

SimpleBufferStream.prototype.destroy = function() {}

module.exports = function (buffer) {
  return new SimpleBufferStream(buffer)
}
<|endoftext|>


<commit_before>'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('./Bot')

let bot = new Bot({
  token: process.env.PAGE_TOKEN,
  verify: process.env.VERIFY_TOKEN,
  app_secret: process.env.APP_SECRET
})

bot.setGreetingText('Welcome to EBudgie\'s assistant', (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting GreetingText result ${JSON.stringify(data)}`);
});
bot.setPersistentMenu([
  {
    "title": "Account",
    "type": "nested",
    "call_to_actions": [
      {
        "title": "Expenses",
        "type": "postback",
        "payload": "SHOW_EXPENSES"
      },
      {
        "title": "Incomes",
        "type": "postback",
        "payload": "SHOW_INCOMES"
      },
      {
        "title": "Threshold",
        "type": "postback",
        "payload": "SHOW_THRESHOLD"
      }
    ]
  },
  {
    "type": "web_url",
    "title": "Visit Website",
    "url": "https://leon92xx.wixsite.com/ebudgie-website/",
    "webview_height_ratio": "full"
  }
], (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting setPersistentMenu result ${JSON.stringify(data)}`);
});

bot.setGetStartedButton([{
  payload: 'New user connected'
}], (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting GetStartedButton result ${JSON.stringify(data)}`);
});

// bot.setPersistentMenu(payload, callback)

bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

bot.on('postback', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({
      "attachment": {
        "type": "template",
        "payload": {
          "template_type": "button",
          "text": "What do you want to do next?",
          "buttons": [
            {
              "type": "account_link",
              "url": "https://leon92xx.wixsite.com/ebudgie-website/"
            }
          ]
        }
      }
    }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

let app = express()
app.set('port', process.env.PORT || 8080);

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))

app.get('/', (req, res) => {
  return bot._verify(req, res)
})

app.post('/', (req, res) => {
  bot._handleMessage(req.body)
  res.end(JSON.stringify({ status: 'ok' }))
})

app.listen(app.get('port'), () => {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>Fix getting proeprty from postback<commit_after>'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('./Bot')

let bot = new Bot({
  token: process.env.PAGE_TOKEN,
  verify: process.env.VERIFY_TOKEN,
  app_secret: process.env.APP_SECRET
})

bot.setGreetingText('Welcome to EBudgie\'s assistant', (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting GreetingText result ${JSON.stringify(data)}`);
});
bot.setPersistentMenu([
  {
    "title": "Account",
    "type": "nested",
    "call_to_actions": [
      {
        "title": "Expenses",
        "type": "postback",
        "payload": "SHOW_EXPENSES"
      },
      {
        "title": "Incomes",
        "type": "postback",
        "payload": "SHOW_INCOMES"
      },
      {
        "title": "Threshold",
        "type": "postback",
        "payload": "SHOW_THRESHOLD"
      }
    ]
  },
  {
    "type": "web_url",
    "title": "Visit Website",
    "url": "https://leon92xx.wixsite.com/ebudgie-website/",
    "webview_height_ratio": "full"
  }
], (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting setPersistentMenu result ${JSON.stringify(data)}`);
});

bot.setGetStartedButton([{
  payload: 'New user connected'
}], (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`Setting GetStartedButton result ${JSON.stringify(data)}`);
});

// bot.setPersistentMenu(payload, callback)

bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

bot.on('postback', (payload, reply) => {
  let text = payload.postback.payload

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({
      "attachment": {
        "type": "template",
        "payload": {
          "template_type": "button",
          "text": "What do you want to do next?",
          "buttons": [
            {
              "type": "account_link",
              "url": "https://leon92xx.wixsite.com/ebudgie-website/"
            }
          ]
        }
      }
    }, (err) => {
      if (err) throw err

      console.log(`Postback to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

let app = express()
app.set('port', process.env.PORT || 8080);

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))

app.get('/', (req, res) => {
  return bot._verify(req, res)
})

app.post('/', (req, res) => {
  bot._handleMessage(req.body)
  res.end(JSON.stringify({ status: 'ok' }))
})

app.listen(app.get('port'), () => {
  console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>


<commit_before>var Ractive = require('ractive');

var templateTable = "
" +
  "
" +
  "
{{#.headers:i}}{{.}}	{{/}}
" +
  "
" +
  "
" +
  "    {{#.rendered}}" +
  "      {{#.itemsView:i}}" +
  "
{{>tableRow}}
" +
  "      {{/}}" +
  "    {{/}}" +
  "
" +
  "
";

var templateDiv = "
" +
  "
{{#.headers:i}}
{{.}}
{{/}}
" +
  "
" +
  "    {{#.rendered}}" +
  "      {{#.itemsView:i}}" +
  "
{{>divRow}}
" +
  "      {{/}}" +
  "    {{/}}" +
  "
" +
  "
";

(function() {
  var getProp = function getProp(obj, path) {
    var parts = path.split('.');
    for (var i = 0; i < parts.length; i++) {
      if (!!!obj) return obj;
      var p = parts[i];
      obj = obj[p];
    }
    return obj;
  };

  var Grid;
  Grid = Ractive.extend({
    template: '{{#.table}}{{>table}}{{/}}{{^.table}}{{>div}}{{/}}',
    beforeInit: function(opts) {
      var transfer = ['class', 'style', 'id'];
      var str = '';
      for (var k in opts.data) if (transfer.indexOf(k) >= 0) str += ' ' + k + '="' + opts.data[k] + '"';
      opts.partials.table = templateTable.replace(/\|/, str);
      opts.partials.div = templateDiv.replace(/\|/, str);
    },
    init: function() {
      var grid = this;
      grid.on('rowDoubleClicked', function(e, i) {
        grid.fire('rowSelected', grid.get('itemsView.' + i), i, e);
      });
      grid.on('rowClicked', function(e, i) {
        grid.set('currentIndex', i);
      });
      grid.on('selection', function(e) {
        var current = grid.get('currentIndex');
        if (typeof current !== 'number') return;
        var items = grid.get('itemsView');
        if (e.original.keyCode === 38 && current > 0) current--;
        else if (e.original.keyCode === 40) current++;
        else if (e.original.keyCode === 13) {
          grid.fire('rowSelected', grid.get('current'), current, e);
          e.original.preventDefault();
          return;
        }
        else return;
        e.original.preventDefault();
        grid.current(current);
      });
      grid.on('colDoubleClicked', function(e, arr) {
        grid.fire('colSelected', e, grid.get('itemsView.' + arr[0]), arr[1], arr[0]);
      });
      grid.on('headerClicked', function(e, i) {
        var sorts = grid.get('sorts');
        var state = sorts[i];
        var nstate;
        if (e.original.ctrlKey && grid.get('multisortable')) {
          nstate = 3;
          if (!!!state || state > 2) nstate = 1;
          else if (state === 1) nstate = 2;
          if (nstate > 0 && nstate < 3) {
            if (sorts.order.indexOf(i) < 0) sorts.order.push(i);
          }
          grid.set('sorts.' + i, nstate);
        } else if (grid.get('sortable')) {
          for (var s in sorts) {
            if (s !== 'order') grid.set('sorts.' + s, 3);
          }
          nstate = 3;
          if (!!!state || state > 2) nstate = 1;
          else if (state === 1) nstate = 2;
          else {
            grid.set('sorts.order', []);
          }
          if (nstate > 0 && nstate < 3) grid.set('sorts.order', [i]);
          grid.set('sorts.' + i, nstate);
        }
      });
    },
    data: {
      rendered: false,
      editingRow: function(idx) {
        return (this.get('editingRows') || []).indexOf(idx) >= 0;
      },
      sortDir: function(idx) {
        return this.get('sorts')[idx];
      },
      columnClass: function(idx) {
        return ((this.get('_columns') || [])[idx] || {}).class;
      },
      isCurrentRow: function(idx) {
        return this.get('currentIndex') === idx;
      },
      editingRows: [],
      sorts: { order: [] },
      sortable: true,
      multisortable: true,
      table: true
    },
    computed: {
      itemsView: function() {
        var grd = this;
        this.get('sorts');
        var filter = this.get('_filter');
        var sorts = this.get('sorting') || [];
        var items = (this.get('items') || []).slice(0);
        var columns = this.get('_columns' + '') || [];
        var flted, i;
        if (typeof filter === 'function') {
          flted = [];
          for (i = 0; i < items.length; i++) {
            if (filter(items[i])) flted.push(items[i]);
          }
          items = flted;
        }
        if (this.get('currentIndex' + '') >= items.length) this.set('currentIndex', items.length - 1);
        items.sort(function(a, b) {
          for (var i in sorts) {
            var s = sorts[i];
            var dir = 1;
            var ai = getProp(a, columns[s.field].path);
            var bi = getProp(b, columns[s.field].path);

            if (s.dir === 2) dir = -1;
            else if (s.dir > 2) continue;

            if (ai < bi) return -1 * dir;
            else if (ai > bi) return 1 * dir;
            else continue;
          }
          return 0;
        });
        return items;
      },
      current: function() {
        var items = this.get('itemsView');
        var idx = this.get('currentIndex');
        if (typeof idx !== 'number') return null;
        return (items || [])[idx];
      },
      sorting: function() {
        var res = [];
        var sorts = this.get('sorts');
        var orders = sorts.order || [];
        for (var i in orders) {
          res.push({ field: orders[i], dir: sorts[orders[i]] });
        }
        return res;
      },
      headers: function() {
        var cols = this.get('columns');
        var res = [];
        for (var i in cols) {
          var c = cols[i];
          if (!!c.label) res.push(c.label);
          else if (!!!c.compute) {
            var nm = c.path || 'Column ' + i;
            res.push(nm.substring(nm.lastIndexOf('.') + 1));
          } else res.push('Column ' + i);
        }
        return res;
      },
      columns: function() {
        var cols = this.get('_columns');
        if (cols === undefined) cols = this.columns();
        cols = cols.slice(0);
        cols.sort(function(a, b) {
          var ai = a.order || 0;
          var bi = b.order || 0;
          if (ai < bi) return -1;
          else if (ai > bi) return 1;
          else return 0;
        });
        return cols;
      }
    },
    partials: {
      tableRow: '',
      divRow: '',
      table: '',
      div: ''
    },
    columns: function(arr) {
      var i;
      if (!!!arr) { // init columns from items
        var item = this.get('items').slice(0).pop();
        var res = [];
        if (!!item) {
          var okTypes = ['String', 'Number', 'Boolean', 'Date'];
          for (i in item) {
            if (item.hasOwnProperty(i) && !!item[i]) {
              var t = item[i].constructor.name;
              if (okTypes.indexOf(t) >= 0) res.push({ label: i, path: i });
            }
          }
        }
        return this.columns(res);
      } else {
        for (i = 0; i < arr.length; i++) if (!arr[i].hasOwnProperty('order')) arr[i].order = i;
        arr.sort(function(a, b) {
          var ai = a.order;
          var bi = b.order;
          if (ai < bi) return -1;
          else if (ai > bi) return 1;
          else return 0;
        });
        this.set('_columns', arr);
        var tstr = '', dstr = '';
        for (var c = 0; c < arr.length; c++) {
          tstr += '{{.' + arr[c].path + '}}	';
          dstr += '
{{.' + arr[c].path + '}}
';
        }
        this.partials.tableRow = tstr;
        this.partials.divRow = dstr;
        this.set('rendered', false);
        this.set('rendered', true);
        return arr;
      }
    },
    current: function(idx) {
      if (arguments.length === 0) return this.get('current')();
      var items = this.get('itemsView');
      if (idx < 0 || idx >= items.length) return;
      this.set('currentIndex', idx);
      var tbl = this.get('table');

      var n, p;
      if (tbl) {
        n = this.el.querySelector('tbody').children[idx];
        p = this.el;
      } else {
        n = this.el.querySelector('.rg-body').children[idx];
        if (n.style.overflow !== '') p = n;
        else p = this.el;
      }

      if (n.offsetTop
 p.scrollTop + p.clientHeight) p.scrollTop = (n.offsetTop - p.clientHeight / 2);
    },
    filter: function(fn) {
      this.set('_filter', fn);
      this.update('itemsView');
    }
  });

  module.exports = Grid;
})();
<commit_msg>Addresses more leaky context bugs by making sure referenced keypaths are present before the template is installed.<commit_after>var Ractive = require('ractive');

var templateTable = "
" +
  "
" +
  "
{{#.headers:i}}{{.}}	{{/}}
" +
  "
" +
  "
" +
  "    {{#.rendered}}" +
  "      {{#.itemsView:i}}" +
  "
{{>tableRow}}
" +
  "      {{/}}" +
  "    {{/}}" +
  "
" +
  "
";

var templateDiv = "
" +
  "
{{#.headers:i}}
{{.}}
{{/}}
" +
  "
" +
  "    {{#.rendered}}" +
  "      {{#.itemsView:i}}" +
  "
{{>divRow}}
" +
  "      {{/}}" +
  "    {{/}}" +
  "
" +
  "
";

(function() {
  var getProp = function getProp(obj, path) {
    var parts = path.split('.');
    for (var i = 0; i < parts.length; i++) {
      if (!!!obj) return obj;
      var p = parts[i];
      obj = obj[p];
    }
    return obj;
  };

  var Grid;
  Grid = Ractive.extend({
    template: '{{#.table}}{{>table}}{{/}}{{^.table}}{{>div}}{{/}}',
    beforeInit: function(opts) {
      var transfer = ['class', 'style', 'id'];
      var str = '';
      for (var k in opts.data) if (transfer.indexOf(k) >= 0) str += ' ' + k + '="' + opts.data[k] + '"';
      opts.partials.table = templateTable.replace(/\|/, str);
      opts.partials.div = templateDiv.replace(/\|/, str);
    },
    init: function() {
      var grid = this;
      grid.on('rowDoubleClicked', function(e, i) {
        grid.fire('rowSelected', grid.get('itemsView.' + i), i, e);
      });
      grid.on('rowClicked', function(e, i) {
        grid.set('currentIndex', i);
      });
      grid.on('selection', function(e) {
        var current = grid.get('currentIndex');
        if (typeof current !== 'number') return;
        var items = grid.get('itemsView');
        if (e.original.keyCode === 38 && current > 0) current--;
        else if (e.original.keyCode === 40) current++;
        else if (e.original.keyCode === 13) {
          grid.fire('rowSelected', grid.get('current'), current, e);
          e.original.preventDefault();
          return;
        }
        else return;
        e.original.preventDefault();
        grid.current(current);
      });
      grid.on('colDoubleClicked', function(e, arr) {
        grid.fire('colSelected', e, grid.get('itemsView.' + arr[0]), arr[1], arr[0]);
      });
      grid.on('headerClicked', function(e, i) {
        var sorts = grid.get('sorts');
        var state = sorts[i];
        var nstate;
        if (e.original.ctrlKey && grid.get('multisortable')) {
          nstate = 3;
          if (!!!state || state > 2) nstate = 1;
          else if (state === 1) nstate = 2;
          if (nstate > 0 && nstate < 3) {
            if (sorts.order.indexOf(i) < 0) sorts.order.push(i);
          }
          grid.set('sorts.' + i, nstate);
        } else if (grid.get('sortable')) {
          for (var s in sorts) {
            if (s !== 'order') grid.set('sorts.' + s, 3);
          }
          nstate = 3;
          if (!!!state || state > 2) nstate = 1;
          else if (state === 1) nstate = 2;
          else {
            grid.set('sorts.order', []);
          }
          if (nstate > 0 && nstate < 3) grid.set('sorts.order', [i]);
          grid.set('sorts.' + i, nstate);
        }
      });
    },
    data: {
      rendered: false,
      editingRow: function(idx) {
        return (this.get('editingRows') || []).indexOf(idx) >= 0;
      },
      sortDir: function(idx) {
        return this.get('sorts')[idx];
      },
      columnClass: function(idx) {
        return ((this.get('_columns') || [])[idx] || {}).class;
      },
      isCurrentRow: function(idx) {
        return this.get('currentIndex') === idx;
      },
      editingRows: [],
      _columns: undefined,
      _filter: undefined,
      items: undefined,
      currentIndex: undefined,
      sorts: { order: [] },
      sortable: true,
      multisortable: true,
      table: true
    },
    computed: {
      itemsView: function() {
        var grd = this;
        this.get('sorts');
        var filter = this.get('_filter');
        var sorts = this.get('sorting') || [];
        var items = (this.get('items') || []).slice(0);
        var columns = this.get('_columns' + '') || [];
        var flted, i;
        if (typeof filter === 'function') {
          flted = [];
          for (i = 0; i < items.length; i++) {
            if (filter(items[i])) flted.push(items[i]);
          }
          items = flted;
        }
        if (this.get('currentIndex' + '') >= items.length) this.set('currentIndex', items.length - 1);
        items.sort(function(a, b) {
          for (var i in sorts) {
            var s = sorts[i];
            var dir = 1;
            var ai = getProp(a, columns[s.field].path);
            var bi = getProp(b, columns[s.field].path);

            if (s.dir === 2) dir = -1;
            else if (s.dir > 2) continue;

            if (ai < bi) return -1 * dir;
            else if (ai > bi) return 1 * dir;
            else continue;
          }
          return 0;
        });
        return items;
      },
      current: function() {
        var items = this.get('itemsView');
        var idx = this.get('currentIndex');
        if (typeof idx !== 'number') return null;
        return (items || [])[idx];
      },
      sorting: function() {
        var res = [];
        var sorts = this.get('sorts');
        var orders = sorts.order || [];
        for (var i in orders) {
          res.push({ field: orders[i], dir: sorts[orders[i]] });
        }
        return res;
      },
      headers: function() {
        var cols = this.get('columns');
        var res = [];
        for (var i in cols) {
          var c = cols[i];
          if (!!c.label) res.push(c.label);
          else if (!!!c.compute) {
            var nm = c.path || 'Column ' + i;
            res.push(nm.substring(nm.lastIndexOf('.') + 1));
          } else res.push('Column ' + i);
        }
        return res;
      },
      columns: function() {
        var cols = this.get('_columns');
        if (cols === undefined) cols = this.columns();
        cols = cols.slice(0);
        cols.sort(function(a, b) {
          var ai = a.order || 0;
          var bi = b.order || 0;
          if (ai < bi) return -1;
          else if (ai > bi) return 1;
          else return 0;
        });
        return cols;
      }
    },
    partials: {
      tableRow: '',
      divRow: '',
      table: '',
      div: ''
    },
    columns: function(arr) {
      var i;
      if (!!!arr) { // init columns from items
        var item = this.get('items').slice(0).pop();
        var res = [];
        if (!!item) {
          var okTypes = ['String', 'Number', 'Boolean', 'Date'];
          for (i in item) {
            if (item.hasOwnProperty(i) && !!item[i]) {
              var t = item[i].constructor.name;
              if (okTypes.indexOf(t) >= 0) res.push({ label: i, path: i });
            }
          }
        }
        return this.columns(res);
      } else {
        for (i = 0; i < arr.length; i++) if (!arr[i].hasOwnProperty('order')) arr[i].order = i;
        arr.sort(function(a, b) {
          var ai = a.order;
          var bi = b.order;
          if (ai < bi) return -1;
          else if (ai > bi) return 1;
          else return 0;
        });
        this.set('_columns', arr);
        var tstr = '', dstr = '';
        for (var c = 0; c < arr.length; c++) {
          tstr += '{{.' + arr[c].path + '}}	';
          dstr += '
{{.' + arr[c].path + '}}
';
        }
        this.partials.tableRow = tstr;
        this.partials.divRow = dstr;
        this.set('rendered', false);
        this.set('rendered', true);
        return arr;
      }
    },
    current: function(idx) {
      if (arguments.length === 0) return this.get('current')();
      var items = this.get('itemsView');
      if (idx < 0 || idx >= items.length) return;
      this.set('currentIndex', idx);
      var tbl = this.get('table');

      var n, p;
      if (tbl) {
        n = this.el.querySelector('tbody').children[idx];
        p = this.el;
      } else {
        n = this.el.querySelector('.rg-body').children[idx];
        if (n.style.overflow !== '') p = n;
        else p = this.el;
      }

      if (n.offsetTop
 p.scrollTop + p.clientHeight) p.scrollTop = (n.offsetTop - p.clientHeight / 2);
    },
    filter: function(fn) {
      this.set('_filter', fn);
      this.update('itemsView');
    }
  });

  module.exports = Grid;
})();
<|endoftext|>


<commit_before>var delim = "---\n";
var assign = require('object-assign');

module.exports = function(converter) {

    return function (pages, done) {

        try {

            pages.forEach(function(page){

                var content = page.content;

                var frontmatter;

                content = content.split(delim);

                if(content.length > 1) {

                    frontmatter = converter(content[1]);

                    page = assign(page, frontmatter);

                    content = content.slice(2);
                }

                page.content = content.join(delim);
            });

            done(null, pages);
        }
        catch(e) {

            done(e);
        }
    };
};
<commit_msg>Add delim support and trim<commit_after>var assign = require('object-assign');

module.exports = function(converter, delim) {

    delim = delim || '---';

    return function (pages, done) {

        try {

            pages.forEach(function(page){

                var content = page.content;

                var frontmatter;

                content = content.split(delim).map(function(v){

                    return v.trim();
                });

                if(content.length > 1) {

                    frontmatter = converter(content[1]);

                    page = assign(page, frontmatter);

                    content = content.slice(2);
                }

                page.content = content.join(delim);
            });

            done(null, pages);
        }
        catch(e) {

            done(e);
        }
    };
};
<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var beautifyHTML = require('js-beautify').html;
var assign = require('object-assign');
var path = require('path');

var DEFAULT_OPTIONS = {
  doctype: '<!DOCTYPE html>',
  beautify: false
};

module.exports = function createEngine(engineOptions) {
  var registered = false;
  var moduleDetectRegEx;
  engineOptions = assign({}, DEFAULT_OPTIONS, engineOptions || {});

  function compile(template, options) {
    // Defer babel registration until the first request so we can grab the view path.
    if (!registered) {
      moduleDetectRegEx = new RegExp('^' + path.dirname(options.filename));
      require('babel/register')({ only: moduleDetectRegEx });
      registered = true;
    }

    var component;

    try {
      component = require(options.filename);
      // Transpiled ES6 may export components as { default: Component }
      component = component.default || component;
    } catch (e) {
      return function() {
        throw e;
      };
    }

    return function _compile(context) {
      var markup = engineOptions.doctype;

      try {
        markup += React.renderToStaticMarkup(React.createElement(component, context));
      } catch (e) {
        throw e;
      }

      if (engineOptions.beautify) {
        // NOTE: This will screw up some things where whitespace is important, and be
        // subtly different than prod.
        markup = beautifyHTML(markup);
      }

      if (options.env === 'development') {
        // Remove all files from the module cache that are in the view folder.
        Object.keys(require.cache).forEach(function(module) {
          if (moduleDetectRegEx.test(require.cache[module].filename)) {
            delete require.cache[module];
          }
        });
      }

      return markup;
    };
  }

  return {
    compile: compile
  };
};
<commit_msg>use exact view path<commit_after>'use strict';

var React = require('react');
var beautifyHTML = require('js-beautify').html;
var assign = require('object-assign');
var path = require('path');

var DEFAULT_OPTIONS = {
  doctype: '<!DOCTYPE html>',
  beautify: false
};

module.exports = function createEngine(engineOptions) {
  var registered = false;
  var moduleDetectRegEx;
  engineOptions = assign({}, DEFAULT_OPTIONS, engineOptions || {});

  function compile(template, options) {
    // Defer babel registration until the first request so we can grab the view path.
    if (!registered) {
      moduleDetectRegEx = new RegExp('^' + path.dirname(options.filename));

      // Passing a RegExp to Babel results in an issue on Windows so we'll just
      // pass the view path.
      require('babel/register')({ only: options.settings.views });
      registered = true;
    }

    var component;

    try {
      component = require(options.filename);
      // Transpiled ES6 may export components as { default: Component }
      component = component.default || component;
    } catch (e) {
      return function() {
        throw e;
      };
    }

    return function _compile(context) {
      var markup = engineOptions.doctype;

      try {
        markup += React.renderToStaticMarkup(React.createElement(component, context));
      } catch (e) {
        throw e;
      }

      if (engineOptions.beautify) {
        // NOTE: This will screw up some things where whitespace is important, and be
        // subtly different than prod.
        markup = beautifyHTML(markup);
      }

      if (options.env === 'development') {
        // Remove all files from the module cache that are in the view folder.
        Object.keys(require.cache).forEach(function(module) {
          if (moduleDetectRegEx.test(require.cache[module].filename)) {
            delete require.cache[module];
          }
        });
      }

      return markup;
    };
  }

  return {
    compile: compile
  };
};
<|endoftext|>