<commit_before>var util = require( 'util' );
var deasync = require( 'deasync' );
var BaseTemplate = require( 'umigrate-template-basedriver' );

util.inherits( DBMigrateMigrationBuilder, BaseTemplate );

function DBMigrateMigrationBuilder( primary )
{
    this.primary = primary;
    this.extra_values =
    {
        'ai': ', autoIncrement: true',
        'OUCT': '' //yet not supported by db_migrate
    };

    this.migrationTemplate = [
        [
            '\ndbm = dbm || require(\'db-migrate\');\nvar type = dbm.dataType;\nasync = async || require(\'async\');',
            '\n\nexports.up = function(db, callback) {\n'
        ].join( '\n' ),
        '\n};\n\nexports.down = function(db, callback) {\n',
        '\n};\n'
    ];
}

DBMigrateMigrationBuilder.prototype = {

    table: function ( table, columns, drop )
    {
        var createTable = util.format( 'db.createTable(\'%s\', {', table );
        var dropTable = util.format( 'db.dropTable(\'%s\', { ifExists: true }, callback);', table );

        createTable += this.Columns( '\n%s: { type: \'%s\'', columns, ' },' );

        createTable = createTable.substring( 0, createTable.length - 1 ) + '\n}, callback);';

        return this.createMigration( createTable, dropTable, drop );
    },

    //ToDo: callback for all columns
    columns: function ( table, columns, drop )
    {
        var addColumn = 'async.series([',
            dropColumn = 'async.series([';
        var aC = util.format( '\ndb.addColumn.bind( db, \'%s\', \'%%s\', { type: \'%%s\'', table );
        var dC = util.format( '\ndb.removeColumn.bind( db, \'%s\', \'%%s\')', table );

        for ( var i = 0; i < columns.length; ++i )
        {
            if ( i > 0 )
                dropColumn += ',';

            dropColumn += util.format( dC, columns[ i ][ 0 ] );
        }

        dropColumn += '], callback);';

        addColumn += this.Columns( aC, columns, ' } ),' );
        addColumn = addColumn.substring( 0, addColumn.length - 1 ) + '], callback);';

        return this.createMigration( addColumn, dropColumn, drop );
    },

    changeKeys: function ( table, keys, drop, index )
    {
        var addKey = 'async.series([',
            dropKey = 'async.series([',
            firstLine = true,
            index = ( drop !== undefined && index !== undefined ) ? index : 0,
            kI = 0, _kI = 0;

        var aK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\'),\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table, table );
        var dK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\'),\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table, table );
        var es = '\'%s\'';

        oKeys = Object.keys( keys );
        for( kI = 0; kI < oKeys.length; ++kI )
        {
            var addUnique = false,
                dropUnique = false,
                firstKey = true;

            if ( this.primary && oKeys[ kI ] === 'PRIMARY' )
                continue;

            if ( !firstLine )
            {
                dropKey += ',';
                addKey  += ',';
            }
            else
            {
                firstLine = false;
            }

            addKey += util.format( aK, oKeys[ kI ], oKeys[ kI ] );
            dropKey += util.format( dK, oKeys[ kI ], oKeys[ kI ] );

            _oKeys = Object.keys( keys[ oKeys[ kI ] ] );
            for( _kI = 0; _kI < _oKeys.length; ++_kI )
            {
                if ( firstKey )
                {
                    firstKey = false;
                    addKey  += util.format( es, _oKeys[ _kI ] );
                    dropKey += util.format( es, _oKeys[ _kI ] );
                }
                else
                {
                    addKey  += ', ' + util.format( es, _oKeys[ _kI ] );
                    dropKey += ', ' + util.format( es, _oKeys[ _kI ] );
                }

                if ( !addUnique )
                    addUnique = keys[ oKeys[ kI ] ][ _oKeys[ _kI ] ][ 0 ][ index ];

                if ( !dropUnique )
                    dropUnique = keys[ oKeys[ kI ] ][ _oKeys[ _kI ] ][ 1 ][ index ];
            }

            if ( addUnique )
                addKey += ' ], true )';
            else
                addKey += ' ] )';

            if ( dropUnique )
                dropKey += ' ], true )';
            else
                dropKey += ' ] )';
        }

        addKey  += '\n], callback);';
        dropKey += '\n], callback);';

        //removeIndex([tableName], indexName, callback);
        //addIndex(tableName, indexName, columns, [unique], callback);

        return this.createMigration( addKey, dropKey, drop );
    },

    keys: function ( table, keys, drop, index )
    {
        var addKey = 'async.series([',
            dropKey = 'async.series([',
            firstLine = true,
            index = ( drop !== undefined && index !== undefined ) ? index : 2;

        var aK = util.format( '\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table );
        var dK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\')', table );
        var es = '\'%s\'';

        if( !keys )
            return;

        var oKeys = Object.keys( keys );
        for( kI = 0; kI < oKeys.length; ++kI )
        {
            if ( this.primary && oKeys[ kI ] === 'PRIMARY' )
                continue;

            if ( !firstLine )
            {
                dropKey += ',';
                addKey += ',';
            }
            else
            {
                firstLine = false;
            }

            addKey += util.format( aK, oKeys[ kI ] );
            dropKey += util.format( dK, oKeys[ kI ] );

            addKey += util.format( es, keys[ oKeys[ kI ] ][ 0 ][ index ] );
            for ( var i = 1; i < keys[ oKeys[ kI ] ].length; ++i )
            {
                addKey += ', ' + util.format( es, keys[ oKeys[ kI ] ][ i ][ index ] );
            }

            if ( keys[ oKeys[ kI ] ][ 0 ][ 1 ] )
                addKey += ' ], true )';
            else
                addKey += ' ] )';

        }

        addKey  += '\n], callback);';
        dropKey += '\n], callback);';

        //removeIndex([tableName], indexName, callback);
        //addIndex(tableName, indexName, columns, [unique], callback);

        return this.createMigration( addKey, dropKey, drop );
    },

    engine: function ( table, engines, drop )
    {
        var sql = util.format( 'ALTER TABLE `%s` ENGINE = ?', table );

        engines[ 1 ] = engines[ 1 ] || engines[ 0 ];
        engines[ 0 ] = engines[ 0 ] || engines[ 1 ];

        var createEngine = 'db.runSql(\'' + sql + '\', \'' + engines[ 1 ] + '\', callback);';
        var dropEngine = '';

        if ( engines[ 0 ] !== engines[ 1 ] )
            dropEngine = 'db.runSql(\'' + sql + '\', \'' + engines[ 0 ] + '\', callback);';
        else
            dropEngine = 'callback(); //irreversable migration';

        return this.createMigration( createEngine, dropEngine, drop );
    },

    foreign: function( table, keys, drop )
    {
        //db.addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback)
        var addFK = 'async.series([',
            firstLine = true,
            dropFK = 'async.series([',
            fk = util.format( 'db.addForeignKey.bind(db, \'%s\', \'%%s\', \'%%s\', %%s, %%s)', table ),
            dk = util.format( 'db.removeForeignKey.bind(db, \'%s\', \'%%s\')', table ),
            oKeys = Object.keys( keys );

        for( kI = 0; kI < oKeys.length; ++kI )
        {
            var _firstLine = true,
                fieldMapping = '{ ',
                key = keys[ oKeys[ kI ] ],
                referencedTable = '',
                rules = util.format( '{ onDelete: \'%s\', onUpdate: \'%s\' }', key[ 0 ][ 5 ], key[ 0 ][ 6 ] );

            if( !firstLine )
            {
                addFK += ',';
                dropFK += ',';
            }
            else
            {
                firstLine = false;
            }

            for( var i = 0; i < key.length; ++i )
            {
                if( !_firstLine )
                {
                    fieldMapping += ',';
                }
                else
                {
                    _firstLine = false;
                }

                fieldMapping += util.format( '\'%s\': \'%s\'', key[ i ][ 0 ], key[ i ][ 3 ] );
            }

            fieldMapping += ' }';

            addFK += util.format( fk, key[ 0 ][ 2 ], oKeys[ kI ], fieldMapping, rules );
            dropFK += util.format( dk, oKeys[ kI ] );
        }

        addFK  += '\n], callback);';
        dropFK += '\n], callback);';

        return this.createMigration( addFK, dropFK, drop );
    },

    Columns: function ( begin, columns, end, br )
    {
        var create = '';

        for ( var i = 0; i < columns.length; ++i )
        {
            if ( br && i > 0 )
                create += '\n';

            create += util.format( begin, columns[ i ][ 0 ], columns[ i ][ 1 ][ 0 ] );
            if ( columns[ i ][ 1 ][ 2 ] )
                create += ', unsigned: true';

            if ( !columns[ i ][ 2 ] )
                create += ', notNull: true';

            if ( columns[ i ][ 3 ] )
                create += util.format( ', defaultValue: \'%s\'', columns[ i ][ 3 ] );

            //Some DBS may have no primary keys. But I like to have the primary oKeys[ kI ] information in the creation information,
            //instead of storing them separated like the other keys.
            if ( this.primary && columns[ i ][ 4 ] )
                create += ', primaryKey: true';

            if ( columns[ i ][ 5 ] )
                create += this.extra_values[ columns[ i ][ 5 ] ];

            if( typeof( columns[ i ][ 1 ][ 1 ] ) === 'string' && columns[ i ][ 1 ][ 1 ].indexOf( ',' ) !== -1 )
                columns[ i ][ 1 ][ 1 ] = columns[ i ][ 1 ][ 1 ].replace( ',', '.' );

            create += util.format( ', length: %d', columns[ i ][ 1 ][ 1 ] );

            create += end;
        }

        return create;
    },

    createMigration: function ( up, down, drop )
    {
        if ( drop )
            return this.migrationTemplate[ 0 ] + down + this.migrationTemplate[ 1 ] + up + this.migrationTemplate[ 2 ];
        else
            return this.migrationTemplate[ 0 ] + up + this.migrationTemplate[ 1 ] + down + this.migrationTemplate[ 2 ];
    }

};

exports.connect = function ( config, callback )
{
    callback( null, new DBMigrateMigrationBuilder( config.primary ) );
};<commit_msg>bugfix swap ondelete and onupdate elements fixes #10<commit_after>var util = require( 'util' );
var deasync = require( 'deasync' );
var BaseTemplate = require( 'umigrate-template-basedriver' );

util.inherits( DBMigrateMigrationBuilder, BaseTemplate );

function DBMigrateMigrationBuilder( primary )
{
    this.primary = primary;
    this.extra_values =
    {
        'ai': ', autoIncrement: true',
        'OUCT': '' //yet not supported by db_migrate
    };

    this.migrationTemplate = [
        [
            '\ndbm = dbm || require(\'db-migrate\');\nvar type = dbm.dataType;\nasync = async || require(\'async\');',
            '\n\nexports.up = function(db, callback) {\n'
        ].join( '\n' ),
        '\n};\n\nexports.down = function(db, callback) {\n',
        '\n};\n'
    ];
}

DBMigrateMigrationBuilder.prototype = {

    table: function ( table, columns, drop )
    {
        var createTable = util.format( 'db.createTable(\'%s\', {', table );
        var dropTable = util.format( 'db.dropTable(\'%s\', { ifExists: true }, callback);', table );

        createTable += this.Columns( '\n%s: { type: \'%s\'', columns, ' },' );

        createTable = createTable.substring( 0, createTable.length - 1 ) + '\n}, callback);';

        return this.createMigration( createTable, dropTable, drop );
    },

    //ToDo: callback for all columns
    columns: function ( table, columns, drop )
    {
        var addColumn = 'async.series([',
            dropColumn = 'async.series([';
        var aC = util.format( '\ndb.addColumn.bind( db, \'%s\', \'%%s\', { type: \'%%s\'', table );
        var dC = util.format( '\ndb.removeColumn.bind( db, \'%s\', \'%%s\')', table );

        for ( var i = 0; i < columns.length; ++i )
        {
            if ( i > 0 )
                dropColumn += ',';

            dropColumn += util.format( dC, columns[ i ][ 0 ] );
        }

        dropColumn += '], callback);';

        addColumn += this.Columns( aC, columns, ' } ),' );
        addColumn = addColumn.substring( 0, addColumn.length - 1 ) + '], callback);';

        return this.createMigration( addColumn, dropColumn, drop );
    },

    changeKeys: function ( table, keys, drop, index )
    {
        var addKey = 'async.series([',
            dropKey = 'async.series([',
            firstLine = true,
            index = ( drop !== undefined && index !== undefined ) ? index : 0,
            kI = 0, _kI = 0;

        var aK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\'),\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table, table );
        var dK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\'),\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table, table );
        var es = '\'%s\'';

        oKeys = Object.keys( keys );
        for( kI = 0; kI < oKeys.length; ++kI )
        {
            var addUnique = false,
                dropUnique = false,
                firstKey = true;

            if ( this.primary && oKeys[ kI ] === 'PRIMARY' )
                continue;

            if ( !firstLine )
            {
                dropKey += ',';
                addKey  += ',';
            }
            else
            {
                firstLine = false;
            }

            addKey += util.format( aK, oKeys[ kI ], oKeys[ kI ] );
            dropKey += util.format( dK, oKeys[ kI ], oKeys[ kI ] );

            _oKeys = Object.keys( keys[ oKeys[ kI ] ] );
            for( _kI = 0; _kI < _oKeys.length; ++_kI )
            {
                if ( firstKey )
                {
                    firstKey = false;
                    addKey  += util.format( es, _oKeys[ _kI ] );
                    dropKey += util.format( es, _oKeys[ _kI ] );
                }
                else
                {
                    addKey  += ', ' + util.format( es, _oKeys[ _kI ] );
                    dropKey += ', ' + util.format( es, _oKeys[ _kI ] );
                }

                if ( !addUnique )
                    addUnique = keys[ oKeys[ kI ] ][ _oKeys[ _kI ] ][ 0 ][ index ];

                if ( !dropUnique )
                    dropUnique = keys[ oKeys[ kI ] ][ _oKeys[ _kI ] ][ 1 ][ index ];
            }

            if ( addUnique )
                addKey += ' ], true )';
            else
                addKey += ' ] )';

            if ( dropUnique )
                dropKey += ' ], true )';
            else
                dropKey += ' ] )';
        }

        addKey  += '\n], callback);';
        dropKey += '\n], callback);';

        //removeIndex([tableName], indexName, callback);
        //addIndex(tableName, indexName, columns, [unique], callback);

        return this.createMigration( addKey, dropKey, drop );
    },

    keys: function ( table, keys, drop, index )
    {
        var addKey = 'async.series([',
            dropKey = 'async.series([',
            firstLine = true,
            index = ( drop !== undefined && index !== undefined ) ? index : 2;

        var aK = util.format( '\ndb.addIndex.bind(db, \'%s\', \'%%s\', [ ', table );
        var dK = util.format( '\ndb.removeIndex.bind(db, \'%s\', \'%%s\')', table );
        var es = '\'%s\'';

        if( !keys )
            return;

        var oKeys = Object.keys( keys );
        for( kI = 0; kI < oKeys.length; ++kI )
        {
            if ( this.primary && oKeys[ kI ] === 'PRIMARY' )
                continue;

            if ( !firstLine )
            {
                dropKey += ',';
                addKey += ',';
            }
            else
            {
                firstLine = false;
            }

            addKey += util.format( aK, oKeys[ kI ] );
            dropKey += util.format( dK, oKeys[ kI ] );

            addKey += util.format( es, keys[ oKeys[ kI ] ][ 0 ][ index ] );
            for ( var i = 1; i < keys[ oKeys[ kI ] ].length; ++i )
            {
                addKey += ', ' + util.format( es, keys[ oKeys[ kI ] ][ i ][ index ] );
            }

            if ( keys[ oKeys[ kI ] ][ 0 ][ 1 ] )
                addKey += ' ], true )';
            else
                addKey += ' ] )';

        }

        addKey  += '\n], callback);';
        dropKey += '\n], callback);';

        //removeIndex([tableName], indexName, callback);
        //addIndex(tableName, indexName, columns, [unique], callback);

        return this.createMigration( addKey, dropKey, drop );
    },

    engine: function ( table, engines, drop )
    {
        var sql = util.format( 'ALTER TABLE `%s` ENGINE = ?', table );

        engines[ 1 ] = engines[ 1 ] || engines[ 0 ];
        engines[ 0 ] = engines[ 0 ] || engines[ 1 ];

        var createEngine = 'db.runSql(\'' + sql + '\', \'' + engines[ 1 ] + '\', callback);';
        var dropEngine = '';

        if ( engines[ 0 ] !== engines[ 1 ] )
            dropEngine = 'db.runSql(\'' + sql + '\', \'' + engines[ 0 ] + '\', callback);';
        else
            dropEngine = 'callback(); //irreversable migration';

        return this.createMigration( createEngine, dropEngine, drop );
    },

    foreign: function( table, keys, drop )
    {
        //db.addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback)
        var addFK = 'async.series([',
            firstLine = true,
            dropFK = 'async.series([',
            fk = util.format( 'db.addForeignKey.bind(db, \'%s\', \'%%s\', \'%%s\', %%s, %%s)', table ),
            dk = util.format( 'db.removeForeignKey.bind(db, \'%s\', \'%%s\')', table ),
            oKeys = Object.keys( keys );

        for( kI = 0; kI < oKeys.length; ++kI )
        {
            var _firstLine = true,
                fieldMapping = '{ ',
                key = keys[ oKeys[ kI ] ],
                referencedTable = '',
                rules = util.format( '{ onDelete: \'%s\', onUpdate: \'%s\' }', key[ 0 ][ 6 ], key[ 0 ][ 5 ] );

            if( !firstLine )
            {
                addFK += ',';
                dropFK += ',';
            }
            else
            {
                firstLine = false;
            }

            for( var i = 0; i < key.length; ++i )
            {
                if( !_firstLine )
                {
                    fieldMapping += ',';
                }
                else
                {
                    _firstLine = false;
                }

                fieldMapping += util.format( '\'%s\': \'%s\'', key[ i ][ 0 ], key[ i ][ 3 ] );
            }

            fieldMapping += ' }';

            addFK += util.format( fk, key[ 0 ][ 2 ], oKeys[ kI ], fieldMapping, rules );
            dropFK += util.format( dk, oKeys[ kI ] );
        }

        addFK  += '\n], callback);';
        dropFK += '\n], callback);';

        return this.createMigration( addFK, dropFK, drop );
    },

    Columns: function ( begin, columns, end, br )
    {
        var create = '';

        for ( var i = 0; i < columns.length; ++i )
        {
            if ( br && i > 0 )
                create += '\n';

            create += util.format( begin, columns[ i ][ 0 ], columns[ i ][ 1 ][ 0 ] );
            if ( columns[ i ][ 1 ][ 2 ] )
                create += ', unsigned: true';

            if ( !columns[ i ][ 2 ] )
                create += ', notNull: true';

            if ( columns[ i ][ 3 ] )
                create += util.format( ', defaultValue: \'%s\'', columns[ i ][ 3 ] );

            //Some DBS may have no primary keys. But I like to have the primary oKeys[ kI ] information in the creation information,
            //instead of storing them separated like the other keys.
            if ( this.primary && columns[ i ][ 4 ] )
                create += ', primaryKey: true';

            if ( columns[ i ][ 5 ] )
                create += this.extra_values[ columns[ i ][ 5 ] ];

            if( typeof( columns[ i ][ 1 ][ 1 ] ) === 'string' && columns[ i ][ 1 ][ 1 ].indexOf( ',' ) !== -1 )
                columns[ i ][ 1 ][ 1 ] = columns[ i ][ 1 ][ 1 ].replace( ',', '.' );

            create += util.format( ', length: %d', columns[ i ][ 1 ][ 1 ] );

            create += end;
        }

        return create;
    },

    createMigration: function ( up, down, drop )
    {
        if ( drop )
            return this.migrationTemplate[ 0 ] + down + this.migrationTemplate[ 1 ] + up + this.migrationTemplate[ 2 ];
        else
            return this.migrationTemplate[ 0 ] + up + this.migrationTemplate[ 1 ] + down + this.migrationTemplate[ 2 ];
    }

};

exports.connect = function ( config, callback )
{
    callback( null, new DBMigrateMigrationBuilder( config.primary ) );
};<|endoftext|>


<commit_before>var colors = ["blue", "red"];

function feld20er (num1, num2) {
  // started with paste from
  // http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/
  var canvas = document.createElement('canvas');
  canvas.id = 'ZahlenfelderPlot' + num1 + num2;
  canvas.width = 120 * 21;
  canvas.height = 120 * 2 ;
  document.querySelector('body').appendChild(canvas);
  // var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  for (var i = 0; i < 20; i ++) {
    var centerX =  50 + (i % 10) * 100;
    if ((i % 10) > 4) {
      centerX += 20
    }
    var centerY = 50;
    if (i > 9) {
      centerY += 110
    }
    var radius = 40;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    if (i < num1) {
      context.fillStyle = colors[0];
      context.fill();
    } else if (i < num1 + num2) {
      context.fillStyle = colors[1];
      context.fill();
    }
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
  }
}

feld20er(5, 0);
feld20er(9, 5);
feld20er(13, 4);
<commit_msg>korrigiere syntax<commit_after>var colors = ["blue", "red"];

function feld20er (num1, num2) {
  // started with paste from
  // http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/
  var canvas = document.createElement('canvas');
  canvas.id = 'ZahlenfelderPlot' + num1 + num2;
  canvas.width = 120 * 21;
  canvas.height = 120 * 2 ;
  document.querySelector('body').appendChild(canvas);
  // var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  for (var i = 0; i < 20; i ++) {
    var centerX =  50 + (i % 10) * 100;
    if ((i % 10) > 4) {
      centerX += 20;
    }
    var centerY = 50;
    if (i > 9) {
      centerY += 110;
    }
    var radius = 40;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    if (i < num1) {
      context.fillStyle = colors[0];
      context.fill();
    } else if (i < num1 + num2) {
      context.fillStyle = colors[1];
      context.fill();
    }
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
  }
}

feld20er(5, 0);
feld20er(9, 5);
feld20er(13, 4);
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient;
var errors = require('./lib/errors.json');
var errorHandler = require('zefti-error-handler');
errorHandler.addErrors(errors);

var mongoCommands = [
    'count'
  , 'find'
  , 'findOne'
  , 'findAndModify'
  , 'insert'
  , 'remove'
  , 'update'
];

var init = function(options){
  var dataSource = options.dataSource;
  var connectString = (dataSource.username && dataSource.password) ?
    'mongodb://' + dataSource.username + ':' + dataSource.password + '@' + dataSource.replicaSet :
    'mongodb://' + dataSource.replicaSet;
  if (dataSource.database) {
    connectString = connectString + '/' + dataSource.database;
  }
  if (options.errorHandler) errorHandler.addErrors(errors);
  return mongoCommand(connectString, {}, dataSource.collection);
};

function mongoCommand(connectString, config, collection){
  var db = null;
  var status = null;
  var mongoVirtualClient = {};
  var pendingCommands = [];
  mongoCommands.forEach(function(command){

    mongoVirtualClient[command] = function(){
      var args = [].slice.call(arguments);
      //TODO: fix the below
      var outerCb = args.splice(args.length-1, 1)[0];
      function errHandler(err, result){
        if (err) return outerCb(({errCode:'56b66547b19d2b3236345648', err:err}));
        return outerCb(null, result);
      }
      args.push(errHandler);
      if (db) {
        db[command].apply(db, args);
      } else if (!db && !status) {
        status = 'connecting';
        pendingCommands.push({cmd:command, args:args});
        MongoClient.connect(connectString, config, function(err, returnedDb) {
          if (err) throw new Error('err connecting to mongo: ' + err);
          db = returnedDb.collection(collection);
          status = 'ready';
          pendingCommands.forEach(function(request){
            db[request.cmd].apply(db, request.args)
          });
        });
      } else {
        //console.log('status is not ready - pushing')
        pendingCommands.push({cmd:command, args:args})
      }
    }
  });
  return mongoVirtualClient;
}

module.exports = init;<commit_msg>stuff<commit_after>var MongoClient = require('mongodb').MongoClient;
var errors = require('./lib/errors.json');
var errorHandler = require('zefti-error-handler');
errorHandler.addErrors(errors);

var mongoCommands = [
    'count'
  , 'find'
  , 'findOne'
  , 'findAndModify'
  , 'insert'
  , 'remove'
  , 'stats'
  , 'update'
];

var init = function(options){
  var dataSource = options.dataSource;
  var connectString = (dataSource.username && dataSource.password) ?
    'mongodb://' + dataSource.username + ':' + dataSource.password + '@' + dataSource.replicaSet :
    'mongodb://' + dataSource.replicaSet;
  if (dataSource.database) {
    connectString = connectString + '/' + dataSource.database;
  }
  if (options.errorHandler) errorHandler.addErrors(errors);
  return mongoCommand(connectString, {}, dataSource.collection);
};

function mongoCommand(connectString, config, collection){
  var db = null;
  var status = null;
  var mongoVirtualClient = {};
  var pendingCommands = [];
  mongoCommands.forEach(function(command){

    mongoVirtualClient[command] = function(){
      var args = [].slice.call(arguments);
      //TODO: fix the below
      var outerCb = args.splice(args.length-1, 1)[0];
      function errHandler(err, result){
        if (err) return outerCb(({errCode:'56b66547b19d2b3236345648', err:err}));
        return outerCb(null, result);
      }
      args.push(errHandler);
      if (db) {
        db[command].apply(db, args);
      } else if (!db && !status) {
        status = 'connecting';
        pendingCommands.push({cmd:command, args:args});
        MongoClient.connect(connectString, config, function(err, returnedDb) {
          if (err) throw new Error('err connecting to mongo: ' + err);
          db = returnedDb.collection(collection);
          status = 'ready';
          pendingCommands.forEach(function(request){
            db[request.cmd].apply(db, request.args)
          });
        });
      } else {
        //console.log('status is not ready - pushing')
        pendingCommands.push({cmd:command, args:args})
      }
    }
  });
  return mongoVirtualClient;
}

module.exports = init;<|endoftext|>


<commit_before>var mapper = require('parcel-map');
var fs = require('fs');
var path = require('path');
var parcelMap = require('parcel-map');
var packageWriter = require('package-writer');
var match = require('minimatch');
var shasum = require('shasum');
var EventEmitter = require('events').EventEmitter;
var mkdirp = require('mkdirp');
var through2 = require('through2');
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');
var concat = require('concat-stream');

module.exports = function (b, opts) {
    mkdirp(opts.dst, function () {
        parcelMap(b, opts, function (err, map) {
            if (err) return output.emit('error', err);
            withMap(map);
        });
        var ostream = b.bundle().pipe(through2());
        ostream.pause();

        outer.on('package', function (pkg) {
            var outdir = path.join(opts.dst, pkg.hash);
            var tmpfile = path.join(outdir, '.bundle_' + pkg.hash + '.js');
            var pending = 2, hash;

            mkdirp(outdir, function (err) {
                if (err) return outer.emit('error', err);

                var p = pkg.package;
                p.path = pkg.path;
                if (!p.cartero) p.cartero = {};
                console.log(pkg.files);

                var streams = packageWriter(p, pkg.files, outdir);
                console.log(streams);

                var h = crypto.createHash('sha1');
                ostream.pipe(h).pipe(concat(function (buf) {
                    hash = buf.toString('hex');
                    done();
                }));
                ostream.pipe(h);
                ostream.pipe(fs.createWriteStream(tmpfile))
                    .on('close', done)
                ;
                ostream.resume();
            });

            function done () {
                if (--pending === 0) return;
                var dstfile = path.join(outdir, 'bundle_' + hash + '.js');
                fs.rename(tmpfile, dstfile, function (err) {
                    if (err) outer.emit('error', err)
                    else outer.emit('bundle.js', dstfile)
                });
            }
        });
    });

    function withMap (map) {
        outer.emit('map', map);

        var packages = {};
        Object.keys(map.packages).forEach(function (key) {
            packages[key] = {
                package: map.packages[key],
                assets: []
            };
        });
        Object.keys(map.assets).forEach(function (key) {
            var pkg = map.assets[key];
            packages[pkg].assets.push(key);
        });

        Object.keys(packages).forEach(function (key) {
            var pkg = packages[key];
            var dir = pkg.package.__dirname || opts.basedir || process.cwd();
            var props = opts.keys || [];
            pkg.files = {};
            pkg.path = dir;
            pkg.dependencies = map.dependencies[key] || [];
            pkg.hash = shasum(dir + '!' + pkg.dependencies.join(','));

            pkg.assets.forEach(function (file) {
                props.forEach(function (prop) {
                    pkg.files[prop] = [];

                    var pattern = pkg.package[prop];
                    var rel = path.relative(dir, file);
                    if (match(rel, pattern)) pkg.files[prop].push(file);
                });
            });

            outer.emit('package', pkg);
        });
    }

    var outer = new EventEmitter;
    return outer;
};
<commit_msg>generate css bundles<commit_after>var mapper = require('parcel-map');
var fs = require('fs');
var path = require('path');
var parcelMap = require('parcel-map');
var packageWriter = require('package-writer');
var match = require('minimatch');
var shasum = require('shasum');
var EventEmitter = require('events').EventEmitter;
var mkdirp = require('mkdirp');
var through2 = require('through2');
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');
var concat = require('concat-stream');

module.exports = function (b, opts) {
    mkdirp(opts.dst, function () {
        parcelMap(b, opts, function (err, map) {
            if (err) return output.emit('error', err);
            withMap(map);
        });
        var ostream = b.bundle().pipe(through2());
        ostream.pause();

        outer.on('package', function (pkg) {
            var outdir = path.join(opts.dst, pkg.hash);
            var tmpjs = path.join(outdir, '.bundle_' + pkg.hash + '.js');
            var tmpcss = path.join(outdir, '.bundle_' + pkg.hash + '.css');

            var pending = 4, hashjs, hashcss;
            var fileTypes = Object.keys(pkg.files).reduce(function (acc, key) {
                pkg.files[key].forEach(function (file) {
                    acc[file] = key;
                });
                return acc;
            }, {});

            mkdirp(outdir, function (err) {
                if (err) return outer.emit('error', err);

                var p = pkg.package;
                p.path = pkg.path;
                if (!p.cartero) p.cartero = {};

                var streams = packageWriter(p, pkg.files, outdir);
                var types = {};
                Object.keys(streams).forEach(function (key) {
                    var t = fileTypes[key];
                    if (!types[t]) types[t] = {};
                    types[t][key] = streams[key];
                });

                var cssBundle = through2();
                var cssPending = 0;

                Object.keys(types.style || {}).forEach(function (key) {
                    cssPending ++;
                    var stream = types.style[key];
                    stream.on('end', function () {
                        if (-- cssPending === 0) cssBundle.push(null);
                    });
                    stream.pipe(cssBundle, { end: false });
                });

                var hjs = crypto.createHash('sha1');
                ostream.pipe(hjs).pipe(concat(function (buf) {
                    hashjs = buf.toString('hex');
                    done();
                }));
                ostream.pipe(hjs);
                ostream.pipe(fs.createWriteStream(tmpjs)).on('close', done);

                var hcss = crypto.createHash('sha1');
                cssBundle.pipe(hcss).pipe(concat(function (buf) {
                    hashcss = buf.toString('hex');
                    done();
                }));
                cssBundle.pipe(fs.createWriteStream(tmpcss)).on('close', done);

                ostream.resume();
            });

            function done () {
                if (--pending !== 0) return;
                var dstjs = path.join(outdir, 'bundle_' + hashjs + '.js');
                var dstcss = path.join(outdir, 'bundle_' + hashcss + '.css');

                fs.rename(tmpjs, dstjs, function (err) {
                    if (err) outer.emit('error', err)
                    else outer.emit('bundle.js', dstjs)
                });
                fs.rename(tmpcss, dstcss, function (err) {
                    if (err) outer.emit('error', err)
                    else outer.emit('bundle.css', dstcss)
                });
            }
        });
    });

    function withMap (map) {
        outer.emit('map', map);

        var packages = {};
        Object.keys(map.packages).forEach(function (key) {
            packages[key] = {
                package: map.packages[key],
                assets: []
            };
        });
        Object.keys(map.assets).forEach(function (key) {
            var pkg = map.assets[key];
            packages[pkg].assets.push(key);
        });

        Object.keys(packages).forEach(function (key) {
            var pkg = packages[key];
            var dir = pkg.package.__dirname || opts.basedir || process.cwd();
            var props = opts.keys || [];
            pkg.files = {};
            pkg.path = dir;
            pkg.dependencies = map.dependencies[key] || [];
            pkg.hash = shasum(dir + '!' + pkg.dependencies.join(','));

            pkg.assets.forEach(function (file) {
                props.forEach(function (prop) {
                    pkg.files[prop] = [];

                    var pattern = pkg.package[prop];
                    var rel = path.relative(dir, file);
                    if (match(rel, pattern)) pkg.files[prop].push(file);
                });
            });

            outer.emit('package', pkg);
        });
    }

    var outer = new EventEmitter;
    return outer;
};
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose');
var Promise = require('bluebird');
var _ = require('lodash');

Promise.promisifyAll(mongoose);
var DefaultObjectId = mongoose.Schema.Types.ObjectId;

// TODO: Promise or callback
var setupOptions = function(options) {
  options = options || {};

  var defaults = {
    name: 'view',
    numToKeep: 10,
    idType: DefaultObjectId,
    dateFieldName: 'date',
    duplicatesAllowed: false
  };

  _.extend(options, defaults);

  if (!options.compareFunc) {
    options.compareFunc = function(o1, o2) {
      return o1[options.name] === o2[options.name];
    };
  }

  return options;
};

var generateAddFunction = function(collectionPath, options) {
  return function(objectOrId, cb) {
    // TODO: Doesn't work in static case - need to do a find and update instead.
    var collection = this[collectionPath];

    var foundIdx = _.findIndex(collection, options.compareFunc);
    if (options.duplicatesAllowed || foundIdx === -1) {
      var newObject = {};
      newObject[options.name] = objectOrId;
      collection.push(newObject);
    } else {
      var entry = collection[foundIdx];
      entry[options.dateFieldName] = Date.now();
    }

    this[collectionPath] = _(collection).sortBy('date').reverse().slice(0, options.numToKeep).value();

    if (cb) {
      this.save(cb);
    } else {
      return this.saveAsync();
    }
  };
};

var plugin = function(schema, options) {
  options = setupOptions(options);

  var upperCasedName = options.name.charAt(0).toUpperCase() + options.name.slice(1);
  var collectionPath = options.collectionPath || 'recent' + upperCasedName + 's';
  var addFuncName = options.addFunctionName || 'addRecent' + upperCasedName;

  var fields = {};
  var docSchema = {};
  docSchema[options.dateName] = { type: Date, 'default': Date.now };

  if (options.object) {
    docSchema[options.name] = options.object;
  } else {
    docSchema[options.name] = options.idType;
  }

  fields[collectionPath] = [docSchema];

  if (!schema.paths[collectionPath]) {
    schema.add(fields);
  }

  schema.statics[addFuncName] = generateAddFunction(collectionPath, options);
  schema.methods[addFuncName] = function(objectOrId, cb) {
    return this.constructor[addFuncName].call(this.constructor, this._id, objectOrId, cb);
  };
};

module.exports = exports = plugin;
<commit_msg>Only add method for now.<commit_after>'use strict';

var mongoose = require('mongoose');
var Promise = require('bluebird');
var _ = require('lodash');

Promise.promisifyAll(mongoose);
var DefaultObjectId = mongoose.Schema.Types.ObjectId;

// TODO: Promise or callback
var setupOptions = function(options) {
  options = options || {};

  var defaults = {
    name: 'view',
    numToKeep: 10,
    idType: DefaultObjectId,
    dateFieldName: 'date',
    duplicatesAllowed: false
  };

  _.extend(options, defaults);

  if (!options.compareFunc) {
    options.compareFunc = function(o1, o2) {
      return o1[options.name] === o2[options.name];
    };
  }

  return options;
};

var generateAddFunction = function(collectionPath, options) {
  return function(objectOrId, cb) {
    // TODO: Doesn't work in static case - need to do a find and update instead.
    var collection = this[collectionPath];

    var foundIdx = _.findIndex(collection, options.compareFunc);
    if (options.duplicatesAllowed || foundIdx === -1) {
      var newObject = {};
      newObject[options.name] = objectOrId;
      collection.push(newObject);
    } else {
      var entry = collection[foundIdx];
      entry[options.dateFieldName] = Date.now();
    }

    this[collectionPath] = _(collection).sortBy('date').reverse().slice(0, options.numToKeep).value();

    if (cb) {
      this.save(cb);
    } else {
      return this.saveAsync();
    }
  };
};

var plugin = function(schema, options) {
  options = setupOptions(options);

  var upperCasedName = options.name.charAt(0).toUpperCase() + options.name.slice(1);
  var collectionPath = options.collectionPath || 'recent' + upperCasedName + 's';
  var addFuncName = options.addFunctionName || 'addRecent' + upperCasedName;

  var fields = {};
  var docSchema = {};
  docSchema[options.dateName] = { type: Date, 'default': Date.now };

  if (options.object) {
    docSchema[options.name] = options.object;
  } else {
    docSchema[options.name] = options.idType;
  }

  fields[collectionPath] = [docSchema];

  if (!schema.paths[collectionPath]) {
    schema.add(fields);
  }

  // TODO: Also add static
  schema.methods[addFuncName] = generateAddFunction(collectionPath, options);
};

module.exports = exports = plugin;
<|endoftext|>


<commit_before>panel.plugin('flokosiol/translations', {
  sections: {
    translations: {
      data: function () {
        return {
          deletable: null,
          revertable: null,
          translations: null
        }
      },
      computed: {
        defaultLanguage() {
          return this.$store.state.languages.default;
        },
        language() {
          return this.$store.state.languages.current;
        },
        languages() {
          // return this.$store.state.languages.all.filter(language => language.default === false);
          return this.$store.state.languages.all;
        }
      },
      created: function() {
        this.load().then(response => {
          this.deletable    = response.deletable;
          this.revertable   = response.revertable;
          this.translations = response.translations;

          // loop through all panel languages
          let languages = this.languages;
          for (let i = 0; i < languages.length; i++) {
            let languageCode = languages[i].code;

            // check if page is translated for this language
            if (this.translations.indexOf(languageCode) >= 0) {
              this.languages[i].icon = 'check';
              this.languages[i].theme = 'positive';
            }
            else {
              this.languages[i].icon = 'add';
              this.languages[i].theme = 'negative';
            }
          }
        });
      },
      methods: {
        change(language) {
          this.$store.dispatch("languages/current", language);
          this.$emit("change", language);
        }
      },
      template: `

            <k-button-group>
              <k-button v-for="language in languages" :icon="language.icon" :theme="language.theme" :key="language.code" @click="change(language)">
                {{ language.name }}
              </k-button>
            </k-button-group>

            {{deletable}}

            {{revertable}}

      `
    }
  }
});<commit_msg>keeps the default language always at the beginning<commit_after>panel.plugin('flokosiol/translations', {
  sections: {
    translations: {
      data: function () {
        return {
          deletable: null,
          revertable: null,
          translations: null
        }
      },
      computed: {
        defaultLanguage() {
          return this.$store.state.languages.default;
        },
        language() {
          return this.$store.state.languages.current;
        },
        languages() {
          return this.$store.state.languages.all.filter(language => language.default === false);
        }
      },
      created: function() {
        this.load().then(response => {
          this.deletable    = response.deletable;
          this.revertable   = response.revertable;
          this.translations = response.translations;

          // loop through all panel languages
          let languages = this.languages;
          for (let i = 0; i < languages.length; i++) {
            let languageCode = languages[i].code;

            // check if page is translated for this language
            if (this.translations.indexOf(languageCode) >= 0) {
              this.languages[i].icon = 'check';
              this.languages[i].theme = 'positive';
            }
            else {
              this.languages[i].icon = 'add';
              this.languages[i].theme = 'negative';
            }
          }
        });
      },
      methods: {
        change(language) {
          this.$store.dispatch("languages/current", language);
          this.$emit("change", language);
        }
      },
      template: `

            <k-button-group>
              <k-button icon="check" theme="positive" :key="defaultLanguage.code" @click="change(defaultLanguage)">
                  {{ defaultLanguage.name }}
              </k-button>
              <k-button v-for="language in languages" :icon="language.icon" :theme="language.theme" :key="language.code" @click="change(language)">
                {{ language.name }}
              </k-button>
            </k-button-group>

            {{deletable}}

            {{revertable}}

      `
    }
  }
});<|endoftext|>


<commit_before>'use strict'
const app = require('app')
const BrowserWindow = require('browser-window')
const path = require('path')
const fs = require('fs')
const ipc = require('ipc')

// report crashes to the Electron project
require('crash-reporter').start()

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()

// WHITELABELING OPTIONS
var options = {
	page_title: 'Aufbau' // What do you want to display in the menu bar?
}

// Return requested path location
function sendPath (mode) {
	return function (event, arg) {
		var path = app.getPath(arg)
		if (mode == 'async') {
		  event.sender.send('asynchronous-reply', path)
		} else if (mode == 'sync') {
			event.returnValue = path
		}
	}
}

function createMainWindow () {
	const win = new BrowserWindow({
		width: 1280,
		height: 768,
		resizable: true,
		title: options.page_title
	})

	// Set the download directory to being off of the user's home folder
	var tilde_downloads = path.join(app.getHomeDir(), 'Downloads')
	win.webContents.session.setDownloadPath(tilde_downloads)

	// Allow for messages to be sent from client
	ipc.on('asynchronous-message', sendPath('async'))
	ipc.on('synchronous-message', sendPath('sync'))

	win.webContents.on('did-finish-load', function (webContents) {
		var page_title = webContents.sender.getTitle()
		var index_path
		var home_btn_css
		var home_btn_js
		if (page_title != 'Aufbau home') {
			// Add css
			home_btn_css = fs.readFileSync(path.join(__dirname, 'home-btn.css'), 'utf-8')
			webContents.sender.insertCSS(home_btn_css)

			// Add home button
			index_path = path.join(__dirname, 'www', 'index.html')
			home_btn_js = fs.readFileSync(path.join(__dirname, 'home-btn.jst'), 'utf-8').replace('{{index_path}}', index_path)
			webContents.sender.executeJavaScript(home_btn_js)

		}
	})

	win.loadUrl(`file://${__dirname}/www/index.html`)
	win.on('closed', onClosed)

	return win
}

function onClosed() {
	// deref the window
	// for multiple windows store them in an array
	mainWindow = null
}

// prevent window being GC'd
let mainWindow

app.on('window-all-closed', function () {
	app.quit();
})

app.on('activate-with-no-open-windows', function () {
	if (!mainWindow) {
		mainWindow = createMainWindow()
	}
})

app.on('ready', function () {
	var Menu = require('menu')
	var menu_template = require('./menus.js')(BrowserWindow)
	var menu = Menu.buildFromTemplate(menu_template)
	Menu.setApplicationMenu(menu)

	mainWindow = createMainWindow()
})
<commit_msg>remove whitespace<commit_after>'use strict'
const app = require('app')
const BrowserWindow = require('browser-window')
const path = require('path')
const fs = require('fs')
const ipc = require('ipc')

// report crashes to the Electron project
require('crash-reporter').start()

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()

// WHITELABELING OPTIONS
var options = {
	page_title: 'Aufbau' // What do you want to display in the menu bar?
}

// Return requested path location
function sendPath (mode) {
	return function (event, arg) {
		var path = app.getPath(arg)
		if (mode == 'async') {
		  event.sender.send('asynchronous-reply', path)
		} else if (mode == 'sync') {
			event.returnValue = path
		}
	}
}

function createMainWindow () {
	const win = new BrowserWindow({
		width: 1280,
		height: 768,
		resizable: true,
		title: options.page_title
	})

	// Set the download directory to being off of the user's home folder
	var tilde_downloads = path.join(app.getHomeDir(), 'Downloads')
	win.webContents.session.setDownloadPath(tilde_downloads)

	// Allow for messages to be sent from client
	ipc.on('asynchronous-message', sendPath('async'))
	ipc.on('synchronous-message', sendPath('sync'))

	win.webContents.on('did-finish-load', function (webContents) {
		var page_title = webContents.sender.getTitle()
		var index_path
		var home_btn_css
		var home_btn_js
		if (page_title != 'Aufbau home') {
			// Add css
			home_btn_css = fs.readFileSync(path.join(__dirname, 'home-btn.css'), 'utf-8')
			webContents.sender.insertCSS(home_btn_css)

			// Add home button
			index_path = path.join(__dirname, 'www', 'index.html')
			home_btn_js = fs.readFileSync(path.join(__dirname, 'home-btn.jst'), 'utf-8').replace('{{index_path}}', index_path)
			webContents.sender.executeJavaScript(home_btn_js)

		}
	})

	win.loadUrl(`file://${__dirname}/www/index.html`)
	win.on('closed', onClosed)

	return win
}

function onClosed() {
	// deref the window
	// for multiple windows store them in an array
	mainWindow = null
}

// prevent window being GC'd
let mainWindow

app.on('window-all-closed', function () {
	app.quit();
})

app.on('activate-with-no-open-windows', function () {
	if (!mainWindow) {
		mainWindow = createMainWindow()
	}
})

app.on('ready', function () {
	var Menu = require('menu')
	var menu_template = require('./menus.js')(BrowserWindow)
	var menu = Menu.buildFromTemplate(menu_template)
	Menu.setApplicationMenu(menu)

	mainWindow = createMainWindow()
})
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'

// Force CSS to load.  This should use extract text in production.
import styles from './sass/App.sass'

const API_BASE = "http://localhost:3000"

//var get = new Promise(function(resolve, reject) {
//  var xhr = new XMLHttpRequest();
//  xhr.open('get', `${API_BASE}/collections`);
//  xhr.send();
//  xhr.onload = () => (this.status >= 200 && this.status < 300) ?
//    resolve(this.response) : reject(this.statusText)
//  xhr.onerror = () => reject(this.statusText)
//});

render(<Router routes={routes} history={browserHistory}/>, document.body.children[0])

<commit_msg>Target injection point by id.<commit_after>import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'

// Force CSS to load.  This should use extract text in production.
import styles from './sass/App.sass'

const API_BASE = "http://localhost:3000"

//var get = new Promise(function(resolve, reject) {
//  var xhr = new XMLHttpRequest();
//  xhr.open('get', `${API_BASE}/collections`);
//  xhr.send();
//  xhr.onload = () => (this.status >= 200 && this.status < 300) ?
//    resolve(this.response) : reject(this.statusText)
//  xhr.onerror = () => reject(this.statusText)
//});

render(<Router routes={routes} history={browserHistory}/>, document.querySelector("#app"))

<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHarvester = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if(creep.memory.transporting && creep.carry.energy == 0) {
            creep.memory.transporting = false;
            creep.say("Harvesting");
        }
        if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.say("Xporting");
        }

        if(!creep.memory.transporting) {

            //var sources = creep.room.find(FIND_SOURCES);
            var target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE); /*, {
                filter: (source) => { source.energy > 0 }
            })*/
            //creep.say("H-"+target);
            //creep.say("H - " + target.energy);
            if(creep.harvest(target) == ERR_NOT_IN_RANGE) {
                creep.moveTo(target);
                //if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                //    creep.moveTo(sources[0]);
            }

        } else {
            var targets = creep.room.find(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                        }
            })

            if(targets.length > 0) {
                var target = creep.pos.findClosestByPath(targets);
                if(creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(target);
                }

            } else {
                var roadsToRepair = creep.room.find(FIND_STRUCTURES, {
                    filter: function(object){
                        return (object.structureType == STRUCTURE_ROAD ||
                        object.structureType == STRUCTURE_CONTAINER ) && (object.hits < object.hitsMax);
                    }
                });

                if (roadsToRepair){
                    //creep.say("Mvg to Rpr");
                    var targetRoad = creep.pos.findClosestByPath(roadsToRepair);
                    if (creep.repair(targetRoad) === ERR_NOT_IN_RANGE) {
                        creep.moveTo(targetRoad);
                        creep.say("Mvg to Repair");
                    }

                    // perhaps check the results again?

                } else {
                    // nothing to repair
                    creep.moveTo(Game.flags.Flag1);
                }
            }
        }
    }
};

module.exports = roleHarvester;<commit_msg>Fixing harvesters ability to use containers and cleaning up<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHarvester = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if(creep.memory.transporting && creep.carry.energy == 0) {
            creep.memory.transporting = false;
            creep.say("Harvesting");
        }
        if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.say("Xporting");
        }

        if(!creep.memory.transporting) {

            //var sources = creep.room.find(FIND_SOURCES);
            var activeSource = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE); /*, {
                filter: (source) => { source.energy > 0 }
            })*/
            //creep.say("H-"+target);
            //creep.say("H - " + target.energy);
            if(creep.harvest(activeSource) == ERR_NOT_IN_RANGE) {
                creep.moveTo(activeSource);
                //if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
                //    creep.moveTo(sources[0]);
            }

        } else {
            var energyStorageStructures = creep.room.find(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_CONTAINER ||
                            structure.structureType == STRUCTURE_SPAWN ||
                            structure.structureType == STRUCTURE_TOWER) &&
                            (structure.energy < structure.energyCapacity || _sum(structure.store) < structure.storeCapacity);
                        }
            })

            if(energyStorageStructures.length > 0) {
                var energyStorageStructure = creep.pos.findClosestByPath(energyStorageStructures);
                if(creep.transfer(energyStorageStructure, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(energyStorageStructure);
                }

            } else {
                var structuresToRepair = creep.room.find(FIND_STRUCTURES, {
                    filter: function(object){
                        return (object.structureType == STRUCTURE_ROAD ||
                        object.structureType == STRUCTURE_CONTAINER ) && (object.hits < object.hitsMax);
                    }
                });

                if (structuresToRepair !== []){
                    //creep.say("Mvg to Rpr");
                    var structureToRepair = creep.pos.findClosestByPath(structuresToRepair);
                    if (creep.repair(structureToRepair) === ERR_NOT_IN_RANGE) {
                        creep.moveTo(structureToRepair);
                        creep.say("Mvg to Repair");
                    }

                    // perhaps check the results again?

                } else {
                    // nothing to repair
                    creep.moveTo(Game.flags.Flag1);
                }
            }
        }
    }
};

module.exports = roleHarvester;<|endoftext|>


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

    angular.module(appName)
        .factory('statsModel', [
			'raceModel',
            'helpers',

			function (raceModel, helpers) {
			    function getModifier(rawStatValue, racialBonus) {
			        return Math.floor(((parseInt(rawStatValue) || 0) + racialBonus - 10) / 2);
			    }

			    var self = this;

			    self.init = function () {
			        self.strength = '';
			        self.dexterity = '';
			        self.constitution = '';
			        self.intelligence = '';
			        self.wisdom = '';
			        self.charisma = '';

			        self.customRacialStrBonus = '';
			        self.customRacialDexBonus = '';
			        self.customRacialConBonus = '';
			        self.customRacialIntBonus = '';
			        self.customRacialWisBonus = '';
			        self.customRacialChaBonus = '';

			        self.strBonus = '';
			        self.dexBonus = '';
			        self.conBonus = '';
			        self.intBonus = '';
			        self.wisBonus = '';
			        self.chaBonus = '';
			    }

			    self.init();

			    // Calculable fields
			    self.racialStrBonus = function () {
			        if (helpers.isInteger(self.customRacialStrBonus))
			            return self.customRacialStrBonus;

			        return raceModel.race
						? (raceModel.race.strBonus || 0)
						: 0;
			    };

			    self.racialDexBonus = function () {
			        if (helpers.isInteger(self.customRacialDexBonus))
			            return self.customRacialDexBonus;

			        return raceModel.race
						? (raceModel.race.dexBonus || 0)
						: 0;
			    };

			    self.racialConBonus = function () {
			        if (helpers.isInteger(self.customRacialConBonus))
			            return self.customRacialConBonus;

			        return raceModel.race
						? (raceModel.race.conBonus || 0)
						: 0;
			    };

			    self.racialIntBonus = function () {
			        if (helpers.isInteger(self.customRacialIntBonus))
			            return self.customRacialIntBonus;

			        return raceModel.race
						? (raceModel.race.intBonus || 0)
						: 0;
			    };

			    self.racialWisBonus = function () {
			        if (helpers.isInteger(self.customRacialWisBonus))
			            return self.customRacialWisBonus;

			        return raceModel.race
						? (raceModel.race.wisBonus || 0)
						: 0;
			    };

			    self.racialChaBonus = function () {
			        if (helpers.isInteger(self.customRacialChaBonus))
			            return self.customRacialChaBonus;

			        return raceModel.race
			            ? (raceModel.race.chaBonus || 0)
			            : 0;
			    };

			    self.strModifier = function () {
			        return getModifier(self.strength, self.racialStrBonus()) + (parseInt(self.strBonus) || 0);
			    };

			    self.dexModifier = function () {
			        return getModifier(self.dexterity, self.racialDexBonus()) + (parseInt(self.dexBonus) || 0);
			    };

			    self.conModifier = function () {
			        return getModifier(self.constitution, self.racialConBonus()) + (parseInt(self.conBonus) || 0);
			    };

			    self.intModifier = function () {
			        return getModifier(self.intelligence, self.racialIntBonus()) + (parseInt(self.intBonus) || 0);
			    };

			    self.wisModifier = function () {
			        return getModifier(self.wisdom, self.racialWisBonus()) + (parseInt(self.wisBonus) || 0);
			    };

			    self.chaModifier = function () {
			        return getModifier(self.charisma, self.racialChaBonus()) + (parseInt(self.chaBonus) || 0);
			    };

			    // Methods
			    self.exportData = function () {
			        return {
			            strength: self.strength,
			            dexterity: self.dexterity,
			            constitution: self.constitution,
			            intelligence: self.intelligence,
			            wisdom: self.wisdom,
			            charisma: self.charisma,

			            strBonus: self.strBonus,
			            dexBonus: self.dexBonus,
			            conBonus: self.conBonus,
			            intBonus: self.intBonus,
			            wisBonus: self.wisBonus,
			            chaBonus: self.chaBonus
			        }
			    }

			    self.importData = function (data) {
			        self.strength = data.strength;
			        self.dexterity = data.dexterity;
			        self.constitution = data.constitution;
			        self.intelligence = data.intelligence;
			        self.wisdom = data.wisdom;
			        self.charisma = data.charisma;

			        self.strBonus = data.strBonus;
			        self.dexBonus = data.dexBonus;
			        self.conBonus = data.conBonus;
			        self.intBonus = data.intBonus;
			        self.wisBonus = data.wisBonus;
			        self.chaBonus = data.chaBonus;
			    }

			    return self;
			}]);
})();<commit_msg>Fixed bug in stats block - custom racial bonus now can be saved<commit_after>(function () {
    'use strict';

    angular.module(appName)
        .factory('statsModel', [
			'raceModel',
            'helpers',

			function (raceModel, helpers) {
			    function getModifier(rawStatValue, racialBonus) {
			        return Math.floor(((parseInt(rawStatValue) || 0) + racialBonus - 10) / 2);
			    }

			    var self = this;

			    self.init = function () {
			        self.strength = '';
			        self.dexterity = '';
			        self.constitution = '';
			        self.intelligence = '';
			        self.wisdom = '';
			        self.charisma = '';

			        self.customRacialStrBonus = '';
			        self.customRacialDexBonus = '';
			        self.customRacialConBonus = '';
			        self.customRacialIntBonus = '';
			        self.customRacialWisBonus = '';
			        self.customRacialChaBonus = '';

			        self.strBonus = '';
			        self.dexBonus = '';
			        self.conBonus = '';
			        self.intBonus = '';
			        self.wisBonus = '';
			        self.chaBonus = '';
			    }

			    self.init();

			    // Calculable fields
			    self.racialStrBonus = function () {
			        if (helpers.isInteger(self.customRacialStrBonus))
			            return self.customRacialStrBonus;

			        return raceModel.race
						? (raceModel.race.strBonus || 0)
						: 0;
			    };

			    self.racialDexBonus = function () {
			        if (helpers.isInteger(self.customRacialDexBonus))
			            return self.customRacialDexBonus;

			        return raceModel.race
						? (raceModel.race.dexBonus || 0)
						: 0;
			    };

			    self.racialConBonus = function () {
			        if (helpers.isInteger(self.customRacialConBonus))
			            return self.customRacialConBonus;

			        return raceModel.race
						? (raceModel.race.conBonus || 0)
						: 0;
			    };

			    self.racialIntBonus = function () {
			        if (helpers.isInteger(self.customRacialIntBonus))
			            return self.customRacialIntBonus;

			        return raceModel.race
						? (raceModel.race.intBonus || 0)
						: 0;
			    };

			    self.racialWisBonus = function () {
			        if (helpers.isInteger(self.customRacialWisBonus))
			            return self.customRacialWisBonus;

			        return raceModel.race
						? (raceModel.race.wisBonus || 0)
						: 0;
			    };

			    self.racialChaBonus = function () {
			        if (helpers.isInteger(self.customRacialChaBonus))
			            return self.customRacialChaBonus;

			        return raceModel.race
			            ? (raceModel.race.chaBonus || 0)
			            : 0;
			    };

			    self.strModifier = function () {
			        return getModifier(self.strength, self.racialStrBonus()) + (parseInt(self.strBonus) || 0);
			    };

			    self.dexModifier = function () {
			        return getModifier(self.dexterity, self.racialDexBonus()) + (parseInt(self.dexBonus) || 0);
			    };

			    self.conModifier = function () {
			        return getModifier(self.constitution, self.racialConBonus()) + (parseInt(self.conBonus) || 0);
			    };

			    self.intModifier = function () {
			        return getModifier(self.intelligence, self.racialIntBonus()) + (parseInt(self.intBonus) || 0);
			    };

			    self.wisModifier = function () {
			        return getModifier(self.wisdom, self.racialWisBonus()) + (parseInt(self.wisBonus) || 0);
			    };

			    self.chaModifier = function () {
			        return getModifier(self.charisma, self.racialChaBonus()) + (parseInt(self.chaBonus) || 0);
			    };

			    // Methods
			    self.exportData = function () {
			        return {
			            strength: self.strength,
			            dexterity: self.dexterity,
			            constitution: self.constitution,
			            intelligence: self.intelligence,
			            wisdom: self.wisdom,
			            charisma: self.charisma,

			            customRacialStrBonus: self.customRacialStrBonus,
			            customRacialDexBonus: self.customRacialDexBonus,
			            customRacialConBonus: self.customRacialConBonus,
			            customRacialIntBonus: self.customRacialIntBonus,
			            customRacialWisBonus: self.customRacialWisBonus,
			            customRacialChaBonus: self.customRacialChaBonus,

			            strBonus: self.strBonus,
			            dexBonus: self.dexBonus,
			            conBonus: self.conBonus,
			            intBonus: self.intBonus,
			            wisBonus: self.wisBonus,
			            chaBonus: self.chaBonus
			        }
			    }

			    self.importData = function (data) {
			        self.strength = data.strength;
			        self.dexterity = data.dexterity;
			        self.constitution = data.constitution;
			        self.intelligence = data.intelligence;
			        self.wisdom = data.wisdom;
			        self.charisma = data.charisma;

			        self.customRacialStrBonus = data.customRacialStrBonus;
			        self.customRacialDexBonus = data.customRacialDexBonus;
			        self.customRacialConBonus = data.customRacialConBonus;
			        self.customRacialIntBonus = data.customRacialIntBonus;
			        self.customRacialWisBonus = data.customRacialWisBonus;
			        self.customRacialChaBonus = data.customRacialChaBonus;

			        self.strBonus = data.strBonus;
			        self.dexBonus = data.dexBonus;
			        self.conBonus = data.conBonus;
			        self.intBonus = data.intBonus;
			        self.wisBonus = data.wisBonus;
			        self.chaBonus = data.chaBonus;
			    }

			    return self;
			}]);
})();<|endoftext|>


<commit_before>'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var clonedeep = require('lodash.clonedeep');
var path = require('path');
var applySourceMap = require('vinyl-sourcemaps-apply');

var PLUGIN_NAME = 'gulp-sass';

//////////////////////////////
// Main Gulp Sass function
//////////////////////////////
var gulpSass = function gulpSass(options, sync) {
  return through.obj(function(file, enc, cb) {
    var opts,
        filePush,
        errorM,
        callback,
        result;

    if (file.isNull()) {
      return cb(null, file);
    }
    if (file.isStream()) {
      return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }
    if (path.basename(file.path).indexOf('_') === 0) {
      return cb();
    }
    if (!file.contents.length) {
      file.path = gutil.replaceExtension(file.path, '.css');
      return cb(null, file);
    }

    opts = clonedeep(options || {});
    opts.data = file.contents.toString();

    // we set the file path here so that libsass can correctly resolve import paths
    opts.file = file.path;

    // Ensure `indentedSyntax` is true if a `.sass` file
    if (path.extname(file.path) === '.sass') {
      opts.indentedSyntax = true;
    }

    // Ensure file's parent directory in the include path
    if (opts.includePaths) {
      if (typeof opts.includePaths === 'string') {
        opts.includePaths = [opts.includePaths];
      }
    }
    else {
      opts.includePaths = [];
    }

    opts.includePaths.unshift(path.dirname(file.path));

    // Generate Source Maps if plugin source-map present
    if (file.sourceMap) {
      opts.sourceMap = file.path;
      opts.omitSourceMapUrl = true;
      opts.sourceMapContents = true;
    }

    //////////////////////////////
    // Handles returning the file to the stream
    //////////////////////////////
    filePush = function filePush(sassObj) {
      var sassMap,
          sassMapFile,
          sassFileSrc,
          sassFileSrcPath,
          sourceFileIndex;

      // Build Source Maps!
      if (sassObj.map) {
        // Transform map into JSON
        sassMap = JSON.parse(sassObj.map.toString());
        // Grab the stdout and transform it into stdin
        sassMapFile = sassMap.file.replace(/^stdout$/, 'stdin');
        // Grab the base file name that's being worked on
        sassFileSrc = file.relative;
        // Grab the path portion of the file that's being worked on
        sassFileSrcPath = path.dirname(sassFileSrc);
        if (sassFileSrcPath) {
          //Prepend the path to all files in the sources array except the file that's being worked on
          sourceFileIndex = sassMap.sources.indexOf(sassMapFile);
          sassMap.sources = sassMap.sources.map(function(source, index) {
            return (index === sourceFileIndex) ? source : path.join(sassFileSrcPath, source);
          });
        }

        // Remove 'stdin' from souces and replace with filenames!
        sassMap.sources = sassMap.sources.filter(function(src) {
          if (src !== 'stdin') {
            return src;
          }
        });

        // Replace the map file with the original file name (but new extension)
        sassMap.file = gutil.replaceExtension(sassFileSrc, '.css');
        // Apply the map
        applySourceMap(file, sassMap);
      }

      file.contents = sassObj.css;
      file.path = gutil.replaceExtension(file.path, '.css');

      cb(null, file);
    };

    //////////////////////////////
    // Handles error message
    //////////////////////////////
    errorM = function errorM(error) {
      var relativePath = '',
          filePath = error.file === 'stdin' ? file.path : error.file,
          message = '';

      filePath = filePath ? filePath : file.path;
      relativePath = path.relative(process.cwd(), filePath);

      message += gutil.colors.underline(relativePath) + '\n';
      message += error.formatted;

      error.messageFormatted = message;
      error.messageOriginal = error.message;
      error.message = gutil.colors.stripColor(message);

      error.relativePath = relativePath;

      return cb(new gutil.PluginError(
          PLUGIN_NAME, error
        ));
    };

    if (sync !== true) {
      //////////////////////////////
      // Async Sass render
      //////////////////////////////
      callback = function(error, obj) {
        if (error) {
          return errorM(error);
        }
        filePush(obj);
      };

      gulpSass.compiler.render(opts, callback);
    }
    else {
      //////////////////////////////
      // Sync Sass render
      //////////////////////////////
      try {
        result = gulpSass.compiler.renderSync(opts);

        filePush(result);
      }
      catch (error) {
        return errorM(error);
      }
    }
  });
};

//////////////////////////////
// Sync Sass render
//////////////////////////////
gulpSass.sync = function sync(options) {
  return gulpSass(options, true);
};

//////////////////////////////
// Log errors nicely
//////////////////////////////
gulpSass.logError = function logError(error) {
  var message = new gutil.PluginError('sass', error.messageFormatted).toString();
  process.stderr.write(message + '\n');
  this.emit('end');
};

//////////////////////////////
// Store compiler in a prop
//////////////////////////////
gulpSass.compiler = require('node-sass');

module.exports = gulpSass;
<commit_msg>Add whitespace<commit_after>'use strict';

var gutil = require('gulp-util');
var through = require('through2');
var clonedeep = require('lodash.clonedeep');
var path = require('path');
var applySourceMap = require('vinyl-sourcemaps-apply');

var PLUGIN_NAME = 'gulp-sass';

//////////////////////////////
// Main Gulp Sass function
//////////////////////////////
var gulpSass = function gulpSass(options, sync) {
  return through.obj(function(file, enc, cb) {
    var opts,
        filePush,
        errorM,
        callback,
        result;

    if (file.isNull()) {
      return cb(null, file);
    }
    if (file.isStream()) {
      return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }
    if (path.basename(file.path).indexOf('_') === 0) {
      return cb();
    }
    if (!file.contents.length) {
      file.path = gutil.replaceExtension(file.path, '.css');
      return cb(null, file);
    }

    opts = clonedeep(options || {});
    opts.data = file.contents.toString();

    // we set the file path here so that libsass can correctly resolve import paths
    opts.file = file.path;

    // Ensure `indentedSyntax` is true if a `.sass` file
    if (path.extname(file.path) === '.sass') {
      opts.indentedSyntax = true;
    }

    // Ensure file's parent directory in the include path
    if (opts.includePaths) {
      if (typeof opts.includePaths === 'string') {
        opts.includePaths = [opts.includePaths];
      }
    }
    else {
      opts.includePaths = [];
    }

    opts.includePaths.unshift(path.dirname(file.path));

    // Generate Source Maps if plugin source-map present
    if (file.sourceMap) {
      opts.sourceMap = file.path;
      opts.omitSourceMapUrl = true;
      opts.sourceMapContents = true;
    }

    //////////////////////////////
    // Handles returning the file to the stream
    //////////////////////////////
    filePush = function filePush(sassObj) {
      var sassMap,
          sassMapFile,
          sassFileSrc,
          sassFileSrcPath,
          sourceFileIndex;

      // Build Source Maps!
      if (sassObj.map) {
        // Transform map into JSON
        sassMap = JSON.parse(sassObj.map.toString());
        // Grab the stdout and transform it into stdin
        sassMapFile = sassMap.file.replace(/^stdout$/, 'stdin');
        // Grab the base file name that's being worked on
        sassFileSrc = file.relative;
        // Grab the path portion of the file that's being worked on
        sassFileSrcPath = path.dirname(sassFileSrc);
        if (sassFileSrcPath) {
          // Prepend the path to all files in the sources array except the file that's being worked on
          sourceFileIndex = sassMap.sources.indexOf(sassMapFile);
          sassMap.sources = sassMap.sources.map(function(source, index) {
            return (index === sourceFileIndex) ? source : path.join(sassFileSrcPath, source);
          });
        }

        // Remove 'stdin' from souces and replace with filenames!
        sassMap.sources = sassMap.sources.filter(function(src) {
          if (src !== 'stdin') {
            return src;
          }
        });

        // Replace the map file with the original file name (but new extension)
        sassMap.file = gutil.replaceExtension(sassFileSrc, '.css');
        // Apply the map
        applySourceMap(file, sassMap);
      }

      file.contents = sassObj.css;
      file.path = gutil.replaceExtension(file.path, '.css');

      cb(null, file);
    };

    //////////////////////////////
    // Handles error message
    //////////////////////////////
    errorM = function errorM(error) {
      var relativePath = '',
          filePath = error.file === 'stdin' ? file.path : error.file,
          message = '';

      filePath = filePath ? filePath : file.path;
      relativePath = path.relative(process.cwd(), filePath);

      message += gutil.colors.underline(relativePath) + '\n';
      message += error.formatted;

      error.messageFormatted = message;
      error.messageOriginal = error.message;
      error.message = gutil.colors.stripColor(message);

      error.relativePath = relativePath;

      return cb(new gutil.PluginError(
          PLUGIN_NAME, error
        ));
    };

    if (sync !== true) {
      //////////////////////////////
      // Async Sass render
      //////////////////////////////
      callback = function(error, obj) {
        if (error) {
          return errorM(error);
        }
        filePush(obj);
      };

      gulpSass.compiler.render(opts, callback);
    }
    else {
      //////////////////////////////
      // Sync Sass render
      //////////////////////////////
      try {
        result = gulpSass.compiler.renderSync(opts);

        filePush(result);
      }
      catch (error) {
        return errorM(error);
      }
    }
  });
};

//////////////////////////////
// Sync Sass render
//////////////////////////////
gulpSass.sync = function sync(options) {
  return gulpSass(options, true);
};

//////////////////////////////
// Log errors nicely
//////////////////////////////
gulpSass.logError = function logError(error) {
  var message = new gutil.PluginError('sass', error.messageFormatted).toString();
  process.stderr.write(message + '\n');
  this.emit('end');
};

//////////////////////////////
// Store compiler in a prop
//////////////////////////////
gulpSass.compiler = require('node-sass');

module.exports = gulpSass;
<|endoftext|>


<commit_before>'use strict';

var glob = require('glob-all');
var path = require('path');
var _ = require('lodash');
var gulp = require('gulp-help')(require('gulp'), {
  hideEmpty: true
});

var conf = {};

module.exports = {
  /**
   *
   * @param cfg
   */
  config: function (cfg) {
    config.call(this, cfg);

    return this;
  },

  /**
   *
   * @param paths
   */
  loadTasks: function (paths) {
    loadTasks.call(this, paths);

    return this;
  }
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function config(cfg) {
  conf = _.merge({}, conf, cfg);
}

function loadTasks(paths) {
  if (!_.isArray(paths))
    paths = [paths];

  var files = glob.sync(paths).sort();
  var base = _.reduce(files, findBase);

  if (files.length === 1) base = path.dirname(base);

  files.forEach(loadTask(base));
}

function findBase(a, b) {
  return (function f(a, b, l) {
    if (a === b) return a;

    l = l ? l - 1 : (a.length > b.length ? b.length : a.length);

    return f(a.substr(0, l), b.substr(0, l), l);
  })(a, b);
}

function loadTask(base) {
  return function (file) {
    var r = path.relative(base, file);
    var f = path.join(process.cwd(), file);
    var b = path.basename(r);
    var d = path.dirname(r);
    var e = path.extname(b);
    var x = require(f);
    var t = {};
    var c = {};

    if (x['config'])
      if (_.isFunction(x['config']))
        c = x['config'](_.cloneDeep(conf));
      else
        c = _.merge({}, conf, x['config']);
    else
      c = _.merge({}, conf);

    if (x['name'])
      if (_.isFunction(x['name']))
        t['name'] = (function (fn) {
          var r;
          this.config = c;
          r = fn.call(this);
          c = this.config;

          return r;
        })(x['name']);
      else
        t['name'] = x['name'];
    else
      t['name'] = (d === '.' ? '' : d.replace(path.sep, ':') + ':') + path.basename(b, e);

    t = getProperty.call(this, 'dependencies', x, t, c);
    t = getProperty.call(this, 'help', x, t, c);
    t = getProperty.call(this, 'aliases', x, t, c);
    t = getProperty.call(this, 'options', x, t, c);

    if (t['dependencies'] && !_.isArray(t['dependencies']))
      t['dependencies'] = [t['dependencies']];

    if (_.isFunction(x['task']))
      t['task'] = (function (fn) {
        var f = function (next) {
          var r;
          this.config = c;
          r = fn.apply(this, arguments);
          c = this.config;

          return r;
        };

        if (fn.length === 1) return function (a) {
          return f.apply(this, arguments);
        };
        else return function () {
          return f.apply(this, arguments);
        };
      })(x['task']);
    else if (_.isFunction(x))
      t['task'] = (function (fn) {
        var f = function (next) {
          var r;
          this.config = c;
          r = fn.apply(this, arguments);
          c = this.config;

          return r;
        };

        if (fn.length === 1) return function (a) {
          return f.apply(this, arguments);
        };
        else return function () {
          return f.apply(this, arguments);
        };
      })(x);

    createTask(t);
  };
}

function getProperty(prop, x, t, c) {
  if (x[prop])
    if (_.isFunction(x[prop]))
      t[prop] = (function (fn) {
        this.config = c;

        return fn.call(this);
      })(x[prop]);
    else
      t[prop] = x[prop];

  return t;
}

function createTask(task) {
  if (!task['dependencies'] && !task['task'])
    throw new Error('Tasks must either have dependencies or a task function!');

  var opts = {};

  if (task['aliases']) opts['aliases'] = task['aliases'];
  if (task['options']) opts['options'] = task['options'];

  var args = _.flatten([
    task['name'],
    task['help'],
    task['deps'],
    task['task'],
    opts
  ]);

  gulp.task.apply(gulp, args);
}
<commit_msg>Added gulp-help<commit_after>'use strict';

var glob = require('glob-all');
var path = require('path');
var _ = require('lodash');
var gulp = require('gulp-help')(require('gulp'), {
  hideEmpty: true
});

var conf = {};

module.exports = {
  /**
   *
   * @param cfg
   */
  config: function (cfg) {
    config.call(this, cfg);

    return this;
  },

  /**
   *
   * @param paths
   */
  loadTasks: function (paths) {
    loadTasks.call(this, paths);

    return this;
  }
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function config(cfg) {
  conf = _.merge({}, conf, cfg);
}

function loadTasks(paths) {
  if (!_.isArray(paths))
    paths = [paths];

  var files = glob.sync(paths).sort();
  var base = _.reduce(files, findBase);

  if (files.length === 1) base = path.dirname(base);

  files.forEach(loadTask(base));
}

function findBase(a, b) {
  return (function f(a, b, l) {
    if (a === b) return a;

    l = l ? l - 1 : (a.length > b.length ? b.length : a.length);

    return f(a.substr(0, l), b.substr(0, l), l);
  })(a, b);
}

function loadTask(base) {
  return function (file) {
    var r = path.relative(base, file);
    var f = path.join(process.cwd(), file);
    var b = path.basename(r);
    var d = path.dirname(r);
    var e = path.extname(b);
    var x = require(f);
    var t = {};
    var c = {};

    if (x['config'])
      if (_.isFunction(x['config']))
        c = x['config'](_.cloneDeep(conf));
      else
        c = _.merge({}, conf, x['config']);
    else
      c = _.merge({}, conf);

    if (x['name'])
      if (_.isFunction(x['name']))
        t['name'] = (function (fn) {
          var r;
          this.config = c;
          r = fn.call(this);
          c = this.config;

          return r;
        })(x['name']);
      else
        t['name'] = x['name'];
    else
      t['name'] = (d === '.' ? '' : d.replace(path.sep, ':') + ':') + path.basename(b, e);

    t = getProperty('dependencies', x, t, c);
    t = getProperty('help', x, t, c);
    t = getProperty('aliases', x, t, c);
    t = getProperty('options', x, t, c);

    if (t['dependencies'] && !_.isArray(t['dependencies']))
      t['dependencies'] = [t['dependencies']];

    if (_.isFunction(x['task']))
      t['task'] = (function (fn) {
        var f = function (next) {
          this.config = c;
          return fn.apply(this, arguments);
        };

        if (fn.length === 1) return function (a) {
          return f.apply(this, arguments);
        };
        else return function () {
          return f.apply(this, arguments);
        };
      })(x['task']);
    else if (_.isFunction(x))
      t['task'] = (function (fn) {
        var f = function (next) {
          this.config = c;
          return fn.apply(this, arguments);
        };

        if (fn.length === 1) return function (a) {
          return f.apply(this, arguments);
        };
        else return function () {
          return f.apply(this, arguments);
        };
      })(x);

    createTask(t);
  };
}

function getProperty(prop, x, t, c) {
  if (x[prop])
    if (_.isFunction(x[prop]))
      t[prop] = x[prop].call({config: c});
    else
      t[prop] = x[prop];

  return t;
}

function createTask(task) {
  if (!task['dependencies'] && !task['task'])
    throw new Error('Tasks must either have dependencies or a task function!');

  var opts = {};

  if (task['aliases']) opts['aliases'] = task['aliases'];
  if (task['options']) opts['options'] = task['options'];

  var args = _.flatten([
    task['name'],
    task['help'],
    task['deps'],
    task['task'],
    opts
  ]);

  gulp.task.apply(gulp, args);
}
<|endoftext|>


<commit_before>console.log('george');
<commit_msg>update<commit_after>console.log('123');
console.log('george');
<|endoftext|>


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

var stdBackend = require('./stdBackend');

/**
 * returns a a function that is used to create debug messages
 * the logging of the messages happens in the context of the initializing factory method
 * @param pDebug flag that indicates if debugging should be activated
 * @param pName context name for debugging messages
 * @param pOptions options hash
 * @return {Function}
 */

module.exports = function(pDebug, pName, pOptions) {
    var debug, name, options, backend;

    if(typeof pDebug === 'object') {
        debug = !!pDebug.debug;
        name = pDebug.name || '';
        backend = pDebug.backend || stdBackend;
    } else {
        debug = !!pDebug;
        name = pName || '';
        backend = stdBackend;
    }

    var prefix = name ? util.format('[%s] ', name) : '';

    return function() {
        if(!debug) {
            return;
        }

        var args = [].splice.call(arguments, 0);
        var message = util.format.apply(null, args);

        message = prefix + message;

        backend.write(message);
    }
};<commit_msg>switched to array.prototype<commit_after>var util = require('util');

var stdBackend = require('./stdBackend');

/**
 * returns a a function that is used to create debug messages
 * the logging of the messages happens in the context of the initializing factory method
 * @param pDebug flag that indicates if debugging should be activated
 * @param pName context name for debugging messages
 * @param pOptions options hash
 * @return {Function}
 */

module.exports = function(pDebug, pName, pOptions) {
    var debug, name, options, backend;

    if(typeof pDebug === 'object') {
        debug = !!pDebug.debug;
        name = pDebug.name || '';
        backend = pDebug.backend || stdBackend;
    } else {
        debug = !!pDebug;
        name = pName || '';
        backend = stdBackend;
    }

    var prefix = name ? util.format('[%s] ', name) : '';

    return function() {
        if(!debug) {
            return;
        }

        var args = Array.prototype.splice.call(arguments, 0);
        var message = util.format.apply(null, args);

        message = prefix + message;

        backend.write(message);
    }
};<|endoftext|>


<commit_before>var env = process.env.RACK_ENV;

var express = require('express')
  , compression = require('compression')
  , Twitter = require('twitter')
  , fs = require('fs')
  , _ = require('lodash')
  , Q = require('q')
  , ig = require('instagram-node').instagram()
  , app = express();

var apicache = require('apicache').options({ debug: true }).middleware;

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

ig.use({ client_id: process.env.INSTAGRAM_ID,
         client_secret: process.env.INSTAGRAM_SECRET });

app.use(compression()); //gzip!

app.use(function(req, res, next){
  var whitelist = ['localhost:4000', 'localhost:8080', 'slowsbarbq.com']
  var host = req.get('host');

  whitelist.forEach(function(val, key){
    if (host.indexOf(val) > -1){
      res.setHeader('Access-Control-Allow-Origin', host);
    }
  })

  //res.setHeader('Access-Control-Allow-Origin', '*');

  next();
});

app.get("/photos/:user", apicache('30 minutes'), function(req, res, next){
  ig.user_media_recent(req.params.user, {count: 10}, function(err, medias, pagination, remaining, limit) {
    if(err){
      console.log('error: ', err);
      res.status(500).send({'error ': err});
    }

    output = _.map(medias, function(val, i){
      var caption = '';
      if (val.caption){
        caption = val.caption.text;
      }

      return {
        type: val.type || 'image',
        images: val.images || false,
        location: val.location || false,
        posted: val.created_time,
        caption: caption
      }
    })

    console.log('media: ', medias);

    res.send(output);
  });

})

app.get("/media/:handle", apicache('30 minutes'), function(req, res, next){
  console.time('getMedia'); // Track how long this takes!
  var startTime = Date.now();

  console.log(req.params.handle)
  media_timeline(req.params.handle)
    .then(function(data){
      console.timeEnd('getMedia'); // How long did it take?
      var endTime = Date.now()

      res.send({
        'created_at': endTime,
        'generation_time': (endTime - startTime) + 'ms',
        'cached_until': endTime + (20 * 60 * 1000),
        'tweets': data
      })
    }, function(error){
      res.status(500).send({'error': data})
    })

});

app.get("/cards/:handle", apicache('20 minutes'), function(req, res, next){

  console.time('getEmbends'); // Track how long this takes!
  var startTime = Date.now();

  timeline(req.params.handle)
    .then(function(data){
      console.timeEnd('getEmbends'); // How long did it take?
      var endTime = Date.now()

      res.send({
        'created_at': endTime,
        'generation_time': (endTime - startTime) + 'ms',
        'cached_until': endTime + (20 * 60 * 1000),
        'cards': data
      })
    }, function(error){
      res.status(500).send({'error': data})
    })

})

app.use(function(req, res, next){ res.sendfile('./public/index.html'); })

var port = process.env.PORT || 8080;
app.listen(port);

console.log("listening on port " + port);

////////
/// helpers ============================

function settled(results) {
  var embeds = [];
  results.forEach(function (result) {
    if (result.state === "fulfilled") {
      console.log('got embed code for ', result.value.url);
      embeds.push({
        url: result.value.url,
        html: result.value.html
      });
    } else {
      console.log('error: ', result.reason);
    }
  });
  return embeds;
}

function withMedia(tweets) {
  return _.filter(tweets, function(t) {
    if(t.entities.media) {
      return t;
    }
  });
}

function embed(tweet){
  var defer = Q.defer();

  var params = {
    id: tweet.id_str,
    omit_script: true,
    hide_thread: true,
    maxwidth: 350
  }
  //console.log(params)
  client.get('statuses/oembed', params, function(error, tweets, response){
    if (error) {
      console.log('cannot get embed code for ', tweet.id_str)
      defer.reject(error);
    } else {
      defer.resolve(tweets);
    }
  });
  return defer.promise;
}

function timeline(handle){
  var defer = Q.defer();
  var maxCards = 10;
  var params = {
    screen_name: handle,
    trim_user: true,
    count: 100,
    include_rts: true,
    include_entities: true
  };

  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      var _embeds = [];

      withMedia(tweets).forEach(function(tweet){
        if(_embeds.length < maxCards) {
          _embeds.push(embed(tweet));
        }
      })

      Q.allSettled(_embeds)
      .then(settled)
      .done(function(embeds){
        console.log('all done')
        defer.resolve(embeds)
      });

    } else {
      defer.reject(error);
    }
  });

  return defer.promise;
}

function media_timeline(handle){
  var defer = Q.defer();
  var maxCards = 10;
  var params = {
    screen_name: handle,
    trim_user: true,
    count: 100,
    include_rts: true,
    include_entities: true
  };

  client.get('statuses/user_timeline', params, function(error, tweets, response){

    if (!error) {
      var _tweets = [];

      withMedia(tweets).forEach(function(tweet){
        if(_tweets.length < maxCards) {
          _tweets.push(tweet);
        }
      })

      defer.resolve(_tweets)

    } else {
      defer.reject(error);
    }
  });

  return defer.promise;
}
<commit_msg>proper access headers<commit_after>var env = process.env.RACK_ENV;

var express = require('express')
  , compression = require('compression')
  , Twitter = require('twitter')
  , fs = require('fs')
  , _ = require('lodash')
  , Q = require('q')
  , ig = require('instagram-node').instagram()
  , app = express();

var apicache = require('apicache').options({ debug: true }).middleware;

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

ig.use({ client_id: process.env.INSTAGRAM_ID,
         client_secret: process.env.INSTAGRAM_SECRET });

app.use(compression()); //gzip!

app.use(function(req, res, next){
  var whitelist = ['localhost:4000', 'localhost:8080', 'slowsbarbq.com', 'moss-willow.cloudvent.net']
  var host = req.get('origin');

  console.log(host)
  whitelist.forEach(function(val, key){
    if (host.indexOf(val) > -1){
      res.setHeader('Access-Control-Allow-Origin', host);
    }
  })

  //res.setHeader('Access-Control-Allow-Origin', '*');

  next();
});

app.get("/photos/:user", apicache('30 minutes'), function(req, res, next){
  ig.user_media_recent(req.params.user, {count: 10}, function(err, medias, pagination, remaining, limit) {
    if(err){
      console.log('error: ', err);
      res.status(500).send({'error ': err});
    }

    output = _.map(medias, function(val, i){
      var caption = '';
      if (val.caption){
        caption = val.caption.text;
      }

      return {
        type: val.type || 'image',
        images: val.images || false,
        location: val.location || false,
        posted: val.created_time,
        caption: caption
      }
    })

    //console.log('media: ', medias);

    res.send(output);
  });

})

app.get("/media/:handle", apicache('30 minutes'), function(req, res, next){
  console.time('getMedia'); // Track how long this takes!
  var startTime = Date.now();

  console.log(req.params.handle)
  media_timeline(req.params.handle)
    .then(function(data){
      console.timeEnd('getMedia'); // How long did it take?
      var endTime = Date.now()

      res.send({
        'created_at': endTime,
        'generation_time': (endTime - startTime) + 'ms',
        'cached_until': endTime + (20 * 60 * 1000),
        'tweets': data
      })
    }, function(error){
      res.status(500).send({'error': data})
    })

});

app.get("/cards/:handle", apicache('20 minutes'), function(req, res, next){

  console.time('getEmbends'); // Track how long this takes!
  var startTime = Date.now();

  timeline(req.params.handle)
    .then(function(data){
      console.timeEnd('getEmbends'); // How long did it take?
      var endTime = Date.now()

      res.send({
        'created_at': endTime,
        'generation_time': (endTime - startTime) + 'ms',
        'cached_until': endTime + (20 * 60 * 1000),
        'cards': data
      })
    }, function(error){
      res.status(500).send({'error': data})
    })

})

app.use(function(req, res, next){ res.sendfile('./public/index.html'); })

var port = process.env.PORT || 3000;
app.listen(port);

console.log("listening on port " + port);

////////
/// helpers ============================

function settled(results) {
  var embeds = [];
  results.forEach(function (result) {
    if (result.state === "fulfilled") {
      console.log('got embed code for ', result.value.url);
      embeds.push({
        url: result.value.url,
        html: result.value.html
      });
    } else {
      console.log('error: ', result.reason);
    }
  });
  return embeds;
}

function withMedia(tweets) {
  return _.filter(tweets, function(t) {
    if(t.entities.media) {
      return t;
    }
  });
}

function embed(tweet){
  var defer = Q.defer();

  var params = {
    id: tweet.id_str,
    omit_script: true,
    hide_thread: true,
    maxwidth: 350
  }
  //console.log(params)
  client.get('statuses/oembed', params, function(error, tweets, response){
    if (error) {
      console.log('cannot get embed code for ', tweet.id_str)
      defer.reject(error);
    } else {
      defer.resolve(tweets);
    }
  });
  return defer.promise;
}

function timeline(handle){
  var defer = Q.defer();
  var maxCards = 10;
  var params = {
    screen_name: handle,
    trim_user: true,
    count: 100,
    include_rts: true,
    include_entities: true
  };

  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      var _embeds = [];

      withMedia(tweets).forEach(function(tweet){
        if(_embeds.length < maxCards) {
          _embeds.push(embed(tweet));
        }
      })

      Q.allSettled(_embeds)
      .then(settled)
      .done(function(embeds){
        console.log('all done')
        defer.resolve(embeds)
      });

    } else {
      defer.reject(error);
    }
  });

  return defer.promise;
}

function media_timeline(handle){
  var defer = Q.defer();
  var maxCards = 10;
  var params = {
    screen_name: handle,
    trim_user: true,
    count: 100,
    include_rts: true,
    include_entities: true
  };

  client.get('statuses/user_timeline', params, function(error, tweets, response){

    if (!error) {
      var _tweets = [];

      withMedia(tweets).forEach(function(tweet){
        if(_tweets.length < maxCards) {
          _tweets.push(tweet);
        }
      })

      defer.resolve(_tweets)

    } else {
      defer.reject(error);
    }
  });

  return defer.promise;
}
<|endoftext|>