<commit_before>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

if (typeof define !== 'function') { var define = require(VVVVContext.Root+'/node_modules/amdefine')(module, VVVVContext.getRelativeRequire(require)) }
define(function(require,exports) {

var Node = require('core/vvvv.core.node');
var VVVV = require('core/vvvv.core.defines');

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Database (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.DatabaseSQLite = function(id, graph) {
  this.constructor(id, "Database (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connStringIn = this.addInputPin('Connection String', [0], VVVV.PinTypes.String);
  var connectIn = this.addInputPin('Connect', [0], VVVV.PinTypes.Value);

  // output pins
  var dbOut = this.addOutputPin('Connection', [''], VVVV.PinTypes.Node);
  var statusOut = this.addOutputPin('Status', ['Disconnected'], VVVV.PinTypes.String);
  var connectedOut = this.addOutputPin('Connected', [0], VVVV.PinTypes.Value);

  var sqlite3 = undefined;
  var fs = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  this.evaluate = function() {
    if (db===undefined && connectIn.getValue(0)>=0.5) {
      try {
        var file = VVVV.Helpers.prepareFilePath(connStringIn.getValue(0), this.parentPatch);
        if (!fs.existsSync(file))
          throw "Database "+connStringIn.getValue(0)+" not found";
        db = new sqlite3.Database(file);
        if (db) {
          dbOut.setValue(0, db);
          connectedOut.setValue(0, 1);
          statusOut.setValue(0, 'Connected');
        }
      }
      catch (err) {
        console.log(err);
        dbOut.setValue(0, undefined);
        connectedOut.setValue(0, 0);
        statusOut.setValue(0, err);
      }
    }

    if (db!==undefined && connectIn.getValue(0)<0.5) {
      db.close();
      db = undefined;
      dbOut.setValue(0, undefined);
      connectedOut.setValue(0, 0);
      statusOut.setValue(0, 'Disconnected');
    }

  }

}
VVVV.Nodes.DatabaseSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: SELECT (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.SelectSQLite = function(id, graph) {
  this.constructor(id, "Select (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var fieldsIn = this.addInputPin('Fields', ['*'], VVVV.PinTypes.String);
  var tablesIn = this.addInputPin('Tables', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', [''], VVVV.PinTypes.String);
  var groupByIn = this.addInputPin('Group By', [''], VVVV.PinTypes.String);
  var havingIn = this.addInputPin('Having', [''], VVVV.PinTypes.String);
  var orderByIn = this.addInputPin('Order By', [''], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  var fieldsCfgIn = this.addInvisiblePin('Field Names', [''], VVVV.PinTypes.String);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var onDataOut = this.addOutputPin('OnData', [0], VVVV.PinTypes.Value);
  onDataOut.auto_reset = true;
  var outputPins = {};

  function createResultFieldPins(fieldString) {
    var fieldNames = fieldString.split(',').map(function(f) { return f.trim(); });
    for (var i=0; i<fieldNames.length; i++) {
      if (fieldNames[i]=='')
        continue;
      if (outputPins[fieldNames[i]]===undefined)
        outputPins[fieldNames[i]] = this.addOutputPin(fieldNames[i], [], VVVV.PinTypes.String)
    }
    for (var pinname in outputPins) {
      if (fieldNames.indexOf(pinname)<0)
        this.removeOutputPin(pinname);
    }
  }

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');

    createResultFieldPins.call(this, fieldsCfgIn.getValue(0));
  }

  var query = "";

  this.evaluate = function() {

    if (fieldsCfgIn.pinIsChanged())
      createResultFieldPins.call(this, fieldsCfgIn.getValue(0));

    var q = ["SELECT", fieldsIn.getValue(0), "FROM ", tablesIn.getValue(0)];
    if (whereIn.getValue(0).trim()!="")
      q.push("WHERE "+whereIn.getValue(0));
    if (groupByIn.getValue(0).trim()!="")
      q.push("GROUP BY "+groupByIn.getValue(0));
    if (havingIn.getValue(0).trim()!="")
      q.push("HAVING "+havingIn.getValue(0));
    if (orderByIn.getValue(0).trim()!="")
      q.push("ORDER BY "+orderByIn.getValue(0));

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.all(query, function(err, rows) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          onDataOut.setValue(0, 1);
          for (var i=0; i<rows.length; i++) {
            for (var fieldName in rows[i]) {
              if (outputPins[fieldName])
                outputPins[fieldName].setValue(i, rows[i][fieldName]);
            }
          }
          for (var pinname in outputPins) {
            outputPins[pinname].setSliceCount(rows.length);
          }
        }
        else {
          statusOut.setValue(0, err.message);
          for (var pinname in outputPins) {
            outputPins[pinname].setSliceCount(0);
          }
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.SelectSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Insert (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.InsertSQLite = function(id, graph) {
  this.constructor(id, "Insert (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var fieldsIn = this.addInputPin('Fields', [''], VVVV.PinTypes.String);
  var valuesIn = this.addInputPin('Values', [''], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var insertedOut = this.addOutputPin('Inserted', [0], VVVV.PinTypes.Value);
  insertedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["INSERT INTO", "", "", "VALUES ", ""];

  this.evaluate = function() {

    q[1] = tableIn.getValue(0);
    q[2] = "("+fieldsIn.getValue(0)+")";
    q[4] = "("+valuesIn.getValue(0)+")";

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          insertedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.InsertSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Update (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.UpdateSQLite = function(id, graph) {
  this.constructor(id, "Update (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var setIn = this.addInputPin('Set', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', ['1=0'], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var updatedOut = this.addOutputPin('Updated', [0], VVVV.PinTypes.Value);
  updatedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["UPDATE", "", "SET", "", "WHERE", ""];

  this.evaluate = function() {
    q[1] = tableIn.getValue(0);
    q[3] = setIn.getValue(0);
    q[5] = whereIn.getValue(0);

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          updatedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.UpdateSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Delete (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.DeleteSQLite = function(id, graph) {
  this.constructor(id, "Delete (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', ['1=0'], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var deletedOut = this.addOutputPin('Deleted', [0], VVVV.PinTypes.Value);
  deletedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["DELETE FROM ", "", "WHERE", ""];

  this.evaluate = function() {
    q[1] = tableIn.getValue(0);
    q[3] = whereIn.getValue(0);

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          deletedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.DeleteSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Escape (SQLite String)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): ''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.EscapeSQLite = function(id, graph) {
  this.constructor(id, "Escape (SQLite String)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;

  // input pins
  var inputIn = this.addInputPin('Input', [''], VVVV.PinTypes.String);

  // output pins
  var outputOut = this.addOutputPin('Output', [''], VVVV.PinTypes.String);

  this.evaluate = function() {

  }

  this.getCode = function() {
    return "{Input}.replace(/'/g, \"''\")";
  }

}
VVVV.Nodes.EscapeSQLite.prototype = new Node();

});
<commit_msg>adapts Select (SQLite) to use Node#configure; fixes Escape (SQLite) to compensate non-string input<commit_after>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

if (typeof define !== 'function') { var define = require(VVVVContext.Root+'/node_modules/amdefine')(module, VVVVContext.getRelativeRequire(require)) }
define(function(require,exports) {

var Node = require('core/vvvv.core.node');
var VVVV = require('core/vvvv.core.defines');

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Database (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.DatabaseSQLite = function(id, graph) {
  this.constructor(id, "Database (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connStringIn = this.addInputPin('Connection String', [0], VVVV.PinTypes.String);
  var connectIn = this.addInputPin('Connect', [0], VVVV.PinTypes.Value);

  // output pins
  var dbOut = this.addOutputPin('Connection', [''], VVVV.PinTypes.Node);
  var statusOut = this.addOutputPin('Status', ['Disconnected'], VVVV.PinTypes.String);
  var connectedOut = this.addOutputPin('Connected', [0], VVVV.PinTypes.Value);

  var sqlite3 = undefined;
  var fs = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  this.evaluate = function() {
    if (db===undefined && connectIn.getValue(0)>=0.5) {
      try {
        var file = VVVV.Helpers.prepareFilePath(connStringIn.getValue(0), this.parentPatch);
        if (!fs.existsSync(file))
          throw "Database "+connStringIn.getValue(0)+" not found";
        db = new sqlite3.Database(file);
        if (db) {
          dbOut.setValue(0, db);
          connectedOut.setValue(0, 1);
          statusOut.setValue(0, 'Connected');
        }
      }
      catch (err) {
        console.log(err);
        dbOut.setValue(0, undefined);
        connectedOut.setValue(0, 0);
        statusOut.setValue(0, err);
      }
    }

    if (db!==undefined && connectIn.getValue(0)<0.5) {
      db.close();
      db = undefined;
      dbOut.setValue(0, undefined);
      connectedOut.setValue(0, 0);
      statusOut.setValue(0, 'Disconnected');
    }

  }

}
VVVV.Nodes.DatabaseSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: SELECT (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.SelectSQLite = function(id, graph) {
  this.constructor(id, "Select (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var fieldsIn = this.addInputPin('Fields', ['*'], VVVV.PinTypes.String);
  var tablesIn = this.addInputPin('Tables', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', [''], VVVV.PinTypes.String);
  var groupByIn = this.addInputPin('Group By', [''], VVVV.PinTypes.String);
  var havingIn = this.addInputPin('Having', [''], VVVV.PinTypes.String);
  var orderByIn = this.addInputPin('Order By', [''], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  var fieldsCfgIn = this.addInvisiblePin('Field Names', [''], VVVV.PinTypes.String);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var onDataOut = this.addOutputPin('OnData', [0], VVVV.PinTypes.Value);
  onDataOut.auto_reset = true;
  var outputPins = {};

  function createResultFieldPins(fieldString) {
    var fieldNames = fieldString.split(',').map(function(f) { return f.trim(); });
    for (var i=0; i<fieldNames.length; i++) {
      if (fieldNames[i]=='')
        continue;
      if (outputPins[fieldNames[i]]===undefined)
        outputPins[fieldNames[i]] = this.addOutputPin(fieldNames[i], [], VVVV.PinTypes.String)
    }
    for (var pinname in outputPins) {
      if (fieldNames.indexOf(pinname)<0)
        this.removeOutputPin(pinname);
    }
  }

  this.configure = function() {
    createResultFieldPins.call(this, fieldsCfgIn.getValue(0));
  }

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";

  this.evaluate = function() {

    if (fieldsCfgIn.pinIsChanged())
      createResultFieldPins.call(this, fieldsCfgIn.getValue(0));

    var q = ["SELECT", fieldsIn.getValue(0), "FROM ", tablesIn.getValue(0)];
    if (whereIn.getValue(0).trim()!="")
      q.push("WHERE "+whereIn.getValue(0));
    if (groupByIn.getValue(0).trim()!="")
      q.push("GROUP BY "+groupByIn.getValue(0));
    if (havingIn.getValue(0).trim()!="")
      q.push("HAVING "+havingIn.getValue(0));
    if (orderByIn.getValue(0).trim()!="")
      q.push("ORDER BY "+orderByIn.getValue(0));

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.all(query, function(err, rows) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          onDataOut.setValue(0, 1);
          for (var i=0; i<rows.length; i++) {
            for (var fieldName in rows[i]) {
              if (outputPins[fieldName])
                outputPins[fieldName].setValue(i, rows[i][fieldName]);
            }
          }
          for (var pinname in outputPins) {
            outputPins[pinname].setSliceCount(rows.length);
          }
        }
        else {
          statusOut.setValue(0, err.message);
          for (var pinname in outputPins) {
            outputPins[pinname].setSliceCount(0);
          }
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.SelectSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Insert (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.InsertSQLite = function(id, graph) {
  this.constructor(id, "Insert (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var fieldsIn = this.addInputPin('Fields', [''], VVVV.PinTypes.String);
  var valuesIn = this.addInputPin('Values', [''], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var insertedOut = this.addOutputPin('Inserted', [0], VVVV.PinTypes.Value);
  insertedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["INSERT INTO", "", "", "VALUES ", ""];

  this.evaluate = function() {

    q[1] = tableIn.getValue(0);
    q[2] = "("+fieldsIn.getValue(0)+")";
    q[4] = "("+valuesIn.getValue(0)+")";

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          insertedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.InsertSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Update (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.UpdateSQLite = function(id, graph) {
  this.constructor(id, "Update (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var setIn = this.addInputPin('Set', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', ['1=0'], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var updatedOut = this.addOutputPin('Updated', [0], VVVV.PinTypes.Value);
  updatedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["UPDATE", "", "SET", "", "WHERE", ""];

  this.evaluate = function() {
    q[1] = tableIn.getValue(0);
    q[3] = setIn.getValue(0);
    q[5] = whereIn.getValue(0);

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          updatedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.UpdateSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Delete (SQLite Network)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'vux'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.DeleteSQLite = function(id, graph) {
  this.constructor(id, "Delete (SQLite Network)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;
  this.environments = ['nodejs'];

  // input pins
  var connectionIn = this.addInputPin('Connection', [], VVVV.PinTypes.Node);
  var tableIn = this.addInputPin('Table', [''], VVVV.PinTypes.String);
  var whereIn = this.addInputPin('Where', ['1=0'], VVVV.PinTypes.String);
  var sendQueryIn = this.addInputPin('SendQuery', [0], VVVV.PinTypes.Value);

  // output pins
  var statementOut = this.addOutputPin('Statement', [''], VVVV.PinTypes.String);
  var statusOut = this.addOutputPin('Status', [''], VVVV.PinTypes.String);
  var deletedOut = this.addOutputPin('Deleted', [0], VVVV.PinTypes.Value);
  deletedOut.auto_reset = true;

  var sqlite3 = undefined;
  var db = undefined;
  this.initialize = function() {
    sqlite3 = window.server_req('sqlite3');
    if (sqlite3)
      sqlite3 = sqlite3.verbose();
    fs = window.server_req('fs');
  }

  var query = "";
  var q = ["DELETE FROM ", "", "WHERE", ""];

  this.evaluate = function() {
    q[1] = tableIn.getValue(0);
    q[3] = whereIn.getValue(0);

    query = q.join(' ');
    statementOut.setValue(0, query);

    if (sendQueryIn.getValue(0)>=0.5) {
      var db = connectionIn.getValue(0);
      var that = this;
      db.exec(query, function(err) {
        if (!err) {
          statusOut.setValue(0, 'OK');
          deletedOut.setValue(0, 1);
        }
        else {
          statusOut.setValue(0, err.message);
        }
        that.parentPatch.mainloop.requestEvaluate();
      })
    }
  }

}
VVVV.Nodes.DeleteSQLite.prototype = new Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: Escape (SQLite String)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): ''
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.EscapeSQLite = function(id, graph) {
  this.constructor(id, "Escape (SQLite String)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['vux'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;

  // input pins
  var inputIn = this.addInputPin('Input', [''], VVVV.PinTypes.String);

  // output pins
  var outputOut = this.addOutputPin('Output', [''], VVVV.PinTypes.String);

  this.evaluate = function() {

  }

  this.getCode = function() {
    return "({Input}+\"\").replace(/'/g, \"''\")";
  }

}
VVVV.Nodes.EscapeSQLite.prototype = new Node();

});
<|endoftext|>


<commit_before>(function() {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

  var _ = Eventi._;
  module('Eventi on');

  test('3rd party/polyfill api presence', function() {
    ok(typeof Element.prototype.matches === "function", "Element.prototype.matches");
  });

  test('external api presence', function() {
    ok(typeof Eventi.on === "function", 'Eventi.on');
  });

  test('Eventi.fy({}).on', function() {
    equal(Eventi.fy({}).on, Eventi.on, 'should get on()');
  });

  test('Eventi.on(type,fn)', function() {
    expect(4);
    Eventi.on('type', function(e) {
      equal(e.type, 'type', 'should get event of type');
      equal(arguments.length, 1, 'should have only one arg here');
    });
    Eventi.fire('type');
    Eventi.on('data', function(e, data) {
      equal(e.type, 'data', 'should be a data event');
      equal(data, 'data', 'should have right data');
    }).fire('data', 'data');
    Eventi.off('type data');
  });

  test('Eventi.on(o,type,fn,data)', function() {
    expect(4);
    var o = {},
      fn = function(e, edata, hdata) {
        equal(e.type, 'type');
        equal(edata, 'edata');
        equal(hdata, 'hdata');
        equal(this, o);
      };
    Eventi.on(o, 'type', fn, 'hdata').fire(o, 'type', 'edata');
  });

  test('Eventi.on(type,selector,fn)', function() {
    var parent = document.querySelector('#on'),
      kid = parent.querySelector('.closest');
    Eventi.on('click', '#on', function(e, edata) {
      equal(e.type, 'click');
      equal(edata, 'edata');
      equal(this, parent);
      equal(e.target, kid);
    });
    Eventi.fire(kid, 'click', 'edata');
    Eventi.off('click');
  });

  test('_.listener', function() {
    var o = {},
      listener = _.listener(o);
    equal(typeof listener, "function", 'should get listener function back');
    equal(typeof listener.s, "object", "should have 's' object");
    equal(_.listener(o), listener, 'should always get same listener back');
    for (var key in o) {
      ok(false, 'object should not enumerate key: '+key);
    }
  });

  test('_.execute', function() {
    expect(4);
    var e = new Eventi('type'),
      target = {},
      fn = function(e, eventData, handlerData) {
        equal(e.type, 'type', 'should get event of proper type');
        equal(eventData, 'eventData', 'should get event data');
        equal(handlerData, 'handlerData', 'should get handler data');
        equal(this, target, 'should have target as context');
      },
      handler = { data: ['handlerData'], fn: fn };
      e.data = ['eventData'];
      _.execute(target, e, handler);
  });

  test('_.closest', function() {
    equal(_.closest(document, 'foo'), undefined, 'undefined for non Elements');
    var root = document.querySelector('#on'),
        div = root.querySelector('.closest');
    equal(_.closest(div, 'div'), div, 'el should prefer itself to parent');
    equal(_.closest(div, '#on'), root, 'should find parent when element does not match');
  });

  test('_.matches', function() {
    var e = new Eventi('cat:type#tag(detail)');
    ok(_.matches(e, {}), 'should always match empty object');
    ok(!_.matches(e, {foo:'bar'}), 'should not match random object');
    ok(_.matches(e, {type:'type'}), 'should match type alone');
    ok(_.matches(e, {category:'cat',type:'type',tag:true,detail:'detail'}), 'should match everything');
  });

  test('internal api presence', function() {
    ok(_.on, "_.on");
    ok(_.handler, "_.handler");
    ok(_.listener, "_.listener");
    ok(_.handle, "_.handle");
    ok(_.execute, "_.execute");
    ok(_.unhandle, "_.unhandle");
    ok(_.matches, "_.matches");
    ok(_.target, "_.target");
    ok(_.closest, "_.closest");
  });

}());
<commit_msg>no internal events on internal events<commit_after>(function() {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

  var _ = Eventi._;
  module('Eventi on');

  test('3rd party/polyfill api presence', function() {
    ok(typeof Element.prototype.matches === "function", "Element.prototype.matches");
  });

  test('external api presence', function() {
    ok(typeof Eventi.on === "function", 'Eventi.on');
  });

  test('Eventi.fy({}).on', function() {
    equal(Eventi.fy({}).on, Eventi.on, 'should get on()');
  });

  test('Eventi.on(type,fn)', function() {
    expect(4);
    Eventi.on('type', function(e) {
      equal(e.type, 'type', 'should get event of type');
      equal(arguments.length, 1, 'should have only one arg here');
    });
    Eventi.fire('type');
    Eventi.on('data', function(e, data) {
      equal(e.type, 'data', 'should be a data event');
      equal(data, 'data', 'should have right data');
    }).fire('data', 'data');
    Eventi.off('type data');
  });

  test('Eventi.on(o,type,fn,data)', function() {
    expect(4);
    var o = {},
      fn = function(e, edata, hdata) {
        equal(e.type, 'type');
        equal(edata, 'edata');
        equal(hdata, 'hdata');
        equal(this, o);
      };
    Eventi.on(o, 'type', fn, 'hdata').fire(o, 'type', 'edata');
  });

  test('Eventi.on(type,selector,fn)', function() {
    var parent = document.querySelector('#on'),
      kid = parent.querySelector('.closest');
    Eventi.on('click', '#on', function(e, edata) {
      equal(e.type, 'click');
      equal(edata, 'edata');
      equal(this, parent);
      equal(e.target, kid);
    });
    Eventi.fire(kid, 'click', 'edata');
    Eventi.off('click');
  });

  test('_.listener', function() {
    var o = {},
      listener = _.listener(o);
    equal(typeof listener, "function", 'should get listener function back');
    equal(typeof listener.s, "object", "should have 's' object");
    equal(_.listener(o), listener, 'should always get same listener back');
    for (var key in o) {
      ok(false, 'object should not enumerate key: '+key);
    }
  });

  test('_.execute', function() {
    expect(4);
    var e = new Eventi('type'),
      target = {},
      fn = function(e, eventData, handlerData) {
        equal(e.type, 'type', 'should get event of proper type');
        equal(eventData, 'eventData', 'should get event data');
        equal(handlerData, 'handlerData', 'should get handler data');
        equal(this, target, 'should have target as context');
      },
      handler = { data: ['handlerData'], fn: fn };
      e.data = ['eventData'];
      _.execute(target, e, handler);
  });

  test('_.closest', function() {
    equal(_.closest(document, 'foo'), undefined, 'undefined for non Elements');
    var root = document.querySelector('#on'),
        div = root.querySelector('.closest');
    equal(_.closest(div, 'div'), div, 'el should prefer itself to parent');
    equal(_.closest(div, '#on'), root, 'should find parent when element does not match');
  });

  test('_.matches', function() {
    var e = new Eventi('cat:type#tag(detail)');
    ok(_.matches(e, {}), 'should always match empty object');
    ok(!_.matches(e, {foo:'bar'}), 'should not match random object');
    ok(_.matches(e, {type:'type'}), 'should match type alone');
    ok(_.matches(e, {category:'cat',type:'type',tag:true,detail:'detail'}), 'should match everything');
  });

  test('handler#new event', function() {
    expect(4);
    var target = {},
      type = 'onevent',
      passed,
      fn = function(e, h) {
        if (h.text === type) {// don't let problems with _.off bug us
          ok(e['new']);
          equal(e.type, 'handler');
          passed = h;
        }
      };
    Eventi.on(_, 'handler#new', fn)
          .on(target, type, function(){})
          .off(_, 'handler#new', fn);
    var handler = target[_._key].s[type][0];
    ok(handler, 'should get new handler directly');
    ok(passed === handler, 'should pass new handler');
  });

  test('internal api presence', function() {
    ok(_.on, "_.on");
    ok(_.handler, "_.handler");
    ok(_.listener, "_.listener");
    ok(_.handle, "_.handle");
    ok(_.execute, "_.execute");
    ok(_.unhandle, "_.unhandle");
    ok(_.matches, "_.matches");
    ok(_.target, "_.target");
    ok(_.closest, "_.closest");
  });

}());
<|endoftext|>


<commit_before>// grunt-merge-data
// Copyright (c) 2013 - 2014 Shinnosuke Watanabe
// Licensed under the MIT license

module.exports = function (grunt) {
  'use strict';

  var path = require('path');

  function mergeObjects (destObj, srcObj) {
    for (var attrname in srcObj) {
      if (srcObj.hasOwnProperty(attrname)) {
        destObj[attrname] = srcObj[attrname];
      }
    }
  }

  function mergeFileData (sources) {
    var data = {};
    sources.filter(function (filePath) {
      // Warn on and remove invalid source files (if nonull was set)
      if (!grunt.file.exists(filePath)) {
        grunt.log.warn('Source file "' + filePath + '" not found.');
        return false;
      } else {
        return true;
      }

    }).forEach(function (filePath) {
      var basename = path.basename(filePath, path.extname(filePath));

      try {
        data[basename] = grunt.file.readJSON(filePath);
      } catch (e) {
        data[basename] = grunt.file.readYAML(filePath);
      }
    });

    return data;
  }

  var mergeDataTask = function () {
    // Merge task-specific and/or target-specific options with these defaults
    var options = this.options({
      data: null,
      space: null,
      asConfig: false
    });

    // Iterate over all specified src/dest file groups
    this.files.forEach(function (file) {
      var data = mergeFileData(file.src);

      if (options.data) {
        if (grunt.util.kindOf(options.data) === 'function') {
          mergeObjects(data, options.data(data));
        } else {
          mergeObjects(data, options.data);
        }
      }

      if (options.asConfig) {
        var targetConfig;
        if (grunt.util.kindOf(options.asConfig) === 'string') {
          targetConfig = options.asConfig;

        // Accept array of property name parts
        } else if (grunt.util.kindOf(options.asConfig) === 'array') {
          targetConfig = options.asConfig.join('.');

        } else if (options.asConfig === true) {
          targetConfig = grunt.task.current.nameArgs
                         .replace(':', '.') +
                         '.context';
        }

        grunt.config(targetConfig, data);
        grunt.log.writeln('Config "' + targetConfig + '" updated.');
      }

      // Write the destination file if 'dest' is specified
      if (file.dest) {
        grunt.file.write(
          file.dest,
          JSON.stringify(data, null, options.space)
        );
        // Print a success message
        grunt.log.writeln('File "' + file.dest + '" created.');

      } else if (!options.asConfig) {
        // when the task doesn't anything
        grunt.log.warn('Neither destination path or config specified.');
      }
    });
  };

  grunt.registerMultiTask(
    'merge_data',
    'Merge multiple data into a file or Grint config.',
    mergeDataTask
  );
};
<commit_msg>improve format check for source files<commit_after>// grunt-merge-data
// Copyright (c) 2013 - 2014 Shinnosuke Watanabe
// Licensed under the MIT license

module.exports = function (grunt) {
  'use strict';

  var path = require('path');

  function mergeObjects (destObj, srcObj) {
    for (var attrname in srcObj) {
      if (srcObj.hasOwnProperty(attrname)) {
        destObj[attrname] = srcObj[attrname];
      }
    }
  }

  function mergeFileData (sources) {
    var data = {};
    sources.filter(function (filePath) {
      // Warn on and remove invalid source files (if nonull was set)
      if (!grunt.file.exists(filePath)) {
        grunt.log.warn('Source file "' + filePath + '" not found.');
        return false;
      } else {
        return true;
      }

    }).forEach(function (filePath) {
      var basename = path.basename(filePath, path.extname(filePath));
      var ext = path.extname(filePath).toLowerCase();

      if(ext === '.json') {
        data[basename] = grunt.file.readJSON(filePath);
      } else if (ext === '.yml' || ext === '.yaml') {
        data[basename] = grunt.file.readYAML(filePath);
      } else {
        try {
          data[basename] = grunt.file.readJSON(filePath);
        } catch (e) {
          data[basename] = grunt.file.readYAML(filePath);
        }
      }
    });

    return data;
  }

  var mergeDataTask = function () {
    // Merge task-specific and/or target-specific options with these defaults
    var options = this.options({
      data: null,
      space: null,
      asConfig: false
    });

    // Iterate over all specified src/dest file groups
    this.files.forEach(function (file) {
      var data = mergeFileData(file.src);

      if (options.data) {
        if (grunt.util.kindOf(options.data) === 'function') {
          mergeObjects(data, options.data(data));
        } else {
          mergeObjects(data, options.data);
        }
      }

      if (options.asConfig) {
        var targetConfig;
        if (grunt.util.kindOf(options.asConfig) === 'string') {
          targetConfig = options.asConfig;

        // Accept array of property name parts
        } else if (grunt.util.kindOf(options.asConfig) === 'array') {
          targetConfig = options.asConfig.join('.');

        } else if (options.asConfig === true) {
          targetConfig = grunt.task.current.nameArgs
                         .replace(':', '.') +
                         '.context';
        }

        grunt.config(targetConfig, data);
        grunt.log.writeln('Config "' + targetConfig + '" updated.');
      }

      // Write the destination file if 'dest' is specified
      if (file.dest) {
        grunt.file.write(
          file.dest,
          JSON.stringify(data, null, options.space)
        );
        // Print a success message
        grunt.log.writeln('File "' + file.dest + '" created.');

      } else if (!options.asConfig) {
        // when the task doesn't anything
        grunt.log.warn('Neither destination path or config specified.');
      }
    });
  };

  grunt.registerMultiTask(
    'merge_data',
    'Merge multiple data into a file or Grint config.',
    mergeDataTask
  );
};
<|endoftext|>


<commit_before>exports.count = function(q, next){
    Favorite.count(q.args, function (err, count) {
        next(err, count);
    });
};

exports.find = function(q, Collection, next){
    var query = Collection.find();
    query.where(q.args);
    if(q.populated_fields){
        for(var i = 0; i< q.populated_fields.length; i++){
            query.populate(q.populated_fields[i].field, q.populated_fields[i].populate);
        }
    }
    if(q.select){ query.select(q.select); }
    if(q.sort){ query.sort(q.sort); }
    if(q.limit){ query.limit(q.limit); }
    query.exec(function(err, array) {
        next(err, array);
    });
};

exports.findById = function(id, Collection, next) {
    Collection.findById(id, function(err, entry) {
        next(err, entry);
    });
};

exports.findOne = function(q, Collection, next){
    var query = Collection.findOne();
    query.where(q.args);
    if(q.select){ query.select(q.select); }
    query.exec(function(err, entry) {
        next(err, entry);
    });
};

exports.saveNew = function(newEntry, Collection, next) {
    var newCollection = new Collection(newEntry);
    newCollection.save(function(err, entry) {
        //handle user saving error
        if(err && err.errors && err.errors.email && err.errors.email.message == 'That email is already in use'){
            return next({id: 6, message: 'That email is already in use'});
        }else if(err){
            return next(err);
        }
        next(err, entry);
    });
};

exports.update = function(q, Collection, next){
    var conditions = q.where;
    var update = q.update;
    var options = {new: true};
    if(q.select){ options.select = q.select; }
    var query = Collection.findOneAndUpdate(conditions, update, options);
    if(q.populated_fields){
        for(var i = 0; i< q.populated_fields.length; i++){
            query.populate(q.populated_fields[i].field, q.populated_fields[i].populate);
        }
    }
    query.exec(function(err, entry) {
        next(err, entry);
    });
};

exports.updateMultiple = function(q, Collection, next){
    var conditions = q.where;
    var update = q.update;
    var options = { multi: true };
    var query = Collection.update(conditions, update, options);
    query.exec(function(err, success) {
        next(err, success);
    });
};
<commit_msg>finding field population added<commit_after>exports.count = function(q, next){
    Favorite.count(q.args, function (err, count) {
        next(err, count);
    });
};

exports.find = function(q, Collection, next){
    var query = Collection.find();
    query.where(q.args);
    if(q.populated_fields){
        for(var i = 0; i< q.populated_fields.length; i++){
            query.populate(q.populated_fields[i].field, q.populated_fields[i].populate);
        }
    }
    if(q.select){ query.select(q.select); }
    if(q.sort){ query.sort(q.sort); }
    if(q.limit){ query.limit(q.limit); }
    query.exec(function(err, array) {
        next(err, array);
    });
};

exports.findById = function(id, Collection, next) {
    Collection.findById(id, function(err, entry) {
        next(err, entry);
    });
};

exports.findOne = function(q, Collection, next){
    var query = Collection.findOne();
    query.where(q.args);
    if(q.select){ query.select(q.select); }
    if(q.populated_fields){
        for(var i = 0; i< q.populated_fields.length; i++){
            query.populate(q.populated_fields[i].field, q.populated_fields[i].populate);
        }
    }
    query.exec(function(err, entry) {
        next(err, entry);
    });
};

exports.saveNew = function(newEntry, Collection, next) {
    var newCollection = new Collection(newEntry);
    newCollection.save(function(err, entry) {
        //handle user saving error
        if(err && err.errors && err.errors.email && err.errors.email.message == 'That email is already in use'){
            return next({id: 6, message: 'That email is already in use'});
        }else if(err){
            return next(err);
        }
        next(err, entry);
    });
};

exports.update = function(q, Collection, next){
    var conditions = q.where;
    var update = q.update;
    var options = {new: true};
    if(q.select){ options.select = q.select; }
    var query = Collection.findOneAndUpdate(conditions, update, options);
    if(q.populated_fields){
        for(var i = 0; i< q.populated_fields.length; i++){
            query.populate(q.populated_fields[i].field, q.populated_fields[i].populate);
        }
    }
    query.exec(function(err, entry) {
        next(err, entry);
    });
};

exports.updateMultiple = function(q, Collection, next){
    var conditions = q.where;
    var update = q.update;
    var options = { multi: true };
    var query = Collection.update(conditions, update, options);
    query.exec(function(err, success) {
        next(err, success);
    });
};
<|endoftext|>


<commit_before>

//Draws the spectrogram onto the canvas
function drawSpectrogram0(array) {
    "use strict";
    // copy the current canvas onto the temp canvas
    tempCtx0.drawImage(canvas0, 0, 0, 400, 256);

    // iterate over the elements from the array
    for (var i = 0; i < array.length; i += 1) {
        // draw each pixel with the specific color
        var value = array[i];
        ctx0.fillStyle = hot.getColor(value).hex();

        // draw the line at the right side of the canvas
        ctx0.fillRect(400 - 1, 256 - i, 1, 1);
    }

    // set translate on the canvas
    ctx0.translate(-1, 0);
    // draw the copied image
    ctx0.drawImage(tempCanvas0, 0, 0, 400, 256, 0, 0, 400, 256);
    // reset the transformation matrix
    ctx0.setTransform(1, 0, 0, 1, 0, 0);
}

//function called by the javascript node
function audioProcess0() {
    "use strict";
    // get the average for the first channel
    var array = new Uint8Array(analyser0.frequencyBinCount);
    analyser0.getByteFrequencyData(array);

    // draw the spectrogram
    if (!source0.mediaElement.paused) {
        //console.log(document.getElementById("src1").paused);
        drawSpectrogram0(array);
    }
}

//pull the canvas into a variable
canvas0 = document.getElementById("canvas0");

// get the audioCtx from the canvas to draw on
ctx0 = $("#canvas0").get()[0].getContext("2d");

// create a temp canvas we use for copying
tempCanvas0 = document.createElement("canvas");
tempCtx0 = tempCanvas0.getContext("2d");
tempCanvas0.width = 400;
tempCanvas0.height = 256;

// used for color distribution
hot = new chroma.ColorScale({
    colors: ['#000000', '#ff0000', '#ffff00', '#ffffff'],
    positions: [0, 0.25, 0.75, 1],
    mode: 'rgb',
    limits: [0, 300]
});

// setup a javascript node [affects speed]
javascriptNode0 = audioCtx.createScriptProcessor(2048, 1, 1);
// connect to destination, else it isn't called
javascriptNode0.connect(audioCtx.destination);

// setup a analyzer
analyser0 = audioCtx.createAnalyser();
analyser0.smoothingTimeConstant = 0;
analyser0.fftSize = 512;

// create a buffer source node
gainNode0.connect(analyser0);
analyser0.connect(javascriptNode0);

// when the javascript node is called
// we use information from the analyzer node
// to draw the volume
javascriptNode0.onaudioprocess = audioProcess0;<commit_msg>Added groundwork for bandpass<commit_after>

//Draws the spectrogram onto the canvas
function drawSpectrogram0(array) {
    "use strict";
    // copy the current canvas onto the temp canvas
    tempCtx0.drawImage(canvas0, 0, 0, 400, 256);

    // iterate over the elements from the array
    for (var i = 0; i < array.length; i += 1) {
        // draw each pixel with the specific color
        var value = array[i];
        ctx0.fillStyle = hot.getColor(value).hex();

        // draw the line at the right side of the canvas
        ctx0.fillRect(400 - 1, 256 - i, 1, 1);
    }

    // set translate on the canvas
    ctx0.translate(-1, 0);
    // draw the copied image
    ctx0.drawImage(tempCanvas0, 0, 0, 400, 256, 0, 0, 400, 256);
    // reset the transformation matrix
    ctx0.setTransform(1, 0, 0, 1, 0, 0);
}

//function called by the javascript node
function audioProcess0() {
    "use strict";
    // get the average for the first channel
    var array = new Uint8Array(analyser0.frequencyBinCount);
    analyser0.getByteFrequencyData(array);

    // draw the spectrogram
    if (!source0.mediaElement.paused) {
        //console.log(document.getElementById("src1").paused);
        drawSpectrogram0(array);
    }
}

//pull the canvas into a variable
canvas0 = document.getElementById("canvas0");

// get the audioCtx from the canvas to draw on
ctx0 = $("#canvas0").get()[0].getContext("2d");

// create a temp canvas we use for copying
tempCanvas0 = document.createElement("canvas");
tempCtx0 = tempCanvas0.getContext("2d");
tempCanvas0.width = 400;
tempCanvas0.height = 256;

// used for color distribution
hot = new chroma.ColorScale({
    colors: ['#000000', '#ff0000', '#ffff00', '#ffffff'],
    positions: [0, 0.25, 0.75, 1],
    mode: 'rgb',
    limits: [0, 300]
});

// setup a javascript node [affects speed]
javascriptNode0 = audioCtx.createScriptProcessor(2048, 1, 1);
// connect to destination, else it isn't called
javascriptNode0.connect(audioCtx.destination);

// setup a analyzer
var analyserArray0 = new Array(256);

//Q = center_frequency / (top_frequency - bottom_frequency)
//20 - 20,000, log 10
var stepFunc0 = 4 / 256;
var arrayNum0 = 0;
for(var j=1+stepFunc0 ; j <= 4; j+=stepFunc0){
    var num0 = 2*Math.pow(10, (j+j-stepFunc0)/2);
    analyserArray0[arrayNum0] = audioCtx.createBiquadFilter();
    analyserArray0[arrayNum0].type = "bandpass";
    analyserArray0[arrayNum0].frequency.value = num0;
    analyserArray0[arrayNum0].Q.value = num0 / (2*Math.pow(10, j) - 2*Math.pow(10, j-stepFunc0));
    arrayNum0++;
}
console.log(analyserArray0[0]);

analyser0 = audioCtx.createAnalyser();
analyser0.smoothingTimeConstant = 0;
analyser0.fftSize = 512;

// create a buffer source node
gainNode0.connect(analyser0);
analyser0.connect(javascriptNode0);

// when the javascript node is called
// we use information from the analyzer node
// to draw the volume
javascriptNode0.onaudioprocess = audioProcess0;<|endoftext|>


<commit_before>/**
* @ngdoc directive
* @name ionInput
* @parent ionic.directive:ionList
* @module ionic
* @restrict E
* Creates a text input group that can easily be focused
*
* @usage
*
* ```html
* <ion-list>
*   <ion-input>
*     <input type="text" placeholder="First Name">
*   <ion-input>
*
*   <ion-input>
*     <ion-label>Username</ion-label>
*     <input type="text">
*   </ion-input>
* </ion-list>
* ```
*/

var labelIds = -1;

IonicModule
.directive('ionInput', [function() {
  return {
    restrict: 'E',
    controller: ['$scope', '$element', function($scope, $element) {
      this.$scope = $scope;
      this.$element = $element;

      this.input = $element[0].querySelector('input,textarea');
    }]
  };
}]);

/**
* @ngdoc directive
* @name ionLabel
* @parent ionic.directive:ionList
* @module ionic
* @restrict E
*
* New in Ionic 1.2. It is strongly recommended that you use `<ion-label>` in place
* of any `<label>` elements for maximum cross-browser support and performance.
*
* Creates a label for a form input.
*
* @usage
*
* ```html
* <ion-list>
*   <ion-input>
*     <ion-label>Username</ion-label>
*     <input type="text">
*   </ion-input>
* </ion-list>
* ```
*/
IonicModule
.directive('ionLabel', ['$timeout', function($timeout) {
  return {
    restrict: 'E',
    require: '?^ionInput',
    compile: function() {

      return function link($scope, $element, $attrs, ionInputCtrl) {
        var element = $element[0];

        $element.addClass('input-label');

        $element.attr('aria-label', $element.text());
        var id = element.id || '_label-' + ++labelIds;

        if (!element.id) {
          $element.attr('id', id);
        }

        if (ionInputCtrl && ionInputCtrl.input) {
          ionInputCtrl.input.setAttribute('aria-labelledby', id);

          $element.on('click', function() {
            $timeout(function() {
              ionInputCtrl.input.focus();
            });
          });
        }
      };
    }
  };
}]);

/**
 * Input label adds accessibility to .
 */
IonicModule
.directive('inputLabel', [function() {
  return {
    restrict: 'C',
    require: '?^ionInput',
    compile: function() {

      return function link($scope, $element, $attrs, ionInputCtrl) {
        var element = $element[0];

        $element.attr('aria-label', $element.text());
        var id = element.id || '_label-' + ++labelIds;

        if (!element.id) {
          $element.attr('id', id);
        }

        if (ionInputCtrl && ionInputCtrl.input) {
          ionInputCtrl.input.setAttribute('aria-labelledby', id);
        }

      };
    }
  };
}]);
<commit_msg>fix(input): multi-input case. Fixes #4778<commit_after>/**
* @ngdoc directive
* @name ionInput
* @parent ionic.directive:ionList
* @module ionic
* @restrict E
* Creates a text input group that can easily be focused
*
* @usage
*
* ```html
* <ion-list>
*   <ion-input>
*     <input type="text" placeholder="First Name">
*   <ion-input>
*
*   <ion-input>
*     <ion-label>Username</ion-label>
*     <input type="text">
*   </ion-input>
* </ion-list>
* ```
*/

var labelIds = -1;

IonicModule
.directive('ionInput', [function() {
  return {
    restrict: 'E',
    controller: ['$scope', '$element', function($scope, $element) {
      this.$scope = $scope;
      this.$element = $element;

      this.setInputAriaLabeledBy = function(id) {
        var inputs = $element[0].querySelectorAll('input,textarea');
        inputs.length && inputs[0].setAttribute('aria-labelledby', id);
      };

      this.focus = function() {
        var inputs = $element[0].querySelectorAll('input,textarea');
        inputs.length && inputs[0].focus();
      };
    }]
  };
}]);

/**
* @ngdoc directive
* @name ionLabel
* @parent ionic.directive:ionList
* @module ionic
* @restrict E
*
* New in Ionic 1.2. It is strongly recommended that you use `<ion-label>` in place
* of any `<label>` elements for maximum cross-browser support and performance.
*
* Creates a label for a form input.
*
* @usage
*
* ```html
* <ion-list>
*   <ion-input>
*     <ion-label>Username</ion-label>
*     <input type="text">
*   </ion-input>
* </ion-list>
* ```
*/
IonicModule
.directive('ionLabel', ['$timeout', function($timeout) {
  return {
    restrict: 'E',
    require: '?^ionInput',
    compile: function() {

      return function link($scope, $element, $attrs, ionInputCtrl) {
        var element = $element[0];

        $element.addClass('input-label');

        $element.attr('aria-label', $element.text());
        var id = element.id || '_label-' + ++labelIds;

        if (!element.id) {
          $element.attr('id', id);
        }

        if (ionInputCtrl) {

          ionInputCtrl.setInputAriaLabeledBy(id);

          $element.on('click', function() {
            $timeout(function() {
              ionInputCtrl.focus();
            });
          });
        }
      };
    }
  };
}]);

/**
 * Input label adds accessibility to .
 */
IonicModule
.directive('inputLabel', [function() {
  return {
    restrict: 'C',
    require: '?^ionInput',
    compile: function() {

      return function link($scope, $element, $attrs, ionInputCtrl) {
        var element = $element[0];

        $element.attr('aria-label', $element.text());
        var id = element.id || '_label-' + ++labelIds;

        if (!element.id) {
          $element.attr('id', id);
        }

        if (ionInputCtrl) {
          ionInputCtrl.setInputAriaLabeledBy(id);
        }

      };
    }
  };
}]);
<|endoftext|>


<commit_before>var log = require('./log');

function isIncludedInUp(migration, destination) {
  if(!destination) {
    return true;
  }
  var migrationTest = migration.name.substring(0, Math.min(migration.name.length, destination.length));
  var destinationTest = destination.substring(0, Math.min(migration.name.length, destination.length));
  return migrationTest <= destinationTest;
}

exports.filterUp = function(allMigrations, completedMigrations, destination, count) {
  var sortFn = function(a, b) {
    return a.name.slice(0, a.name.indexOf('-')) - b.name.slice(0, b.name.indexOf('-'));
  };

  return allMigrations.sort(sortFn)
  .filter(function(migration) {
    var hasRun = completedMigrations.some(function(completedMigration) {
      return completedMigration.name === migration.name;
    });
    return !hasRun;
  })
  .filter(function(migration) {
    return isIncludedInUp(migration, destination);
  })
  .slice(0, count);
};

/**
  * Similar to the shadow driver, but we reduce to a subset of an existing
  * driver.
  */
exports.reduceToInterface = function(db, originInterface) {

  var Interface = {};
  Interface._original = {};

  for(var prop in db) {

    if (typeof Interface[prop] === "function" &&
        typeof db[prop] === "function") {

      Interface._original[prop] = db[prop];

      (function(property) {

        Interface[property] = function() { this._original[property].apply(this, arguments); };
      }(prop));
    }
    else if(typeof Interface[prop] === "function")
    {
      Interface[prop] = originInterface[prop];
    }
  }

  for(var prop in originInterface.deprecated) {

    if (typeof Interface[prop] === "function" &&
        typeof db[prop] === "function") {

      Interface._original[prop] = db[prop];

      (function(property) {

        Interface[property] = function() {

          log.warn('This function "' + property
          + '" is deprecated.' + "\n"
          + originInterface.deprecated[property + '_deprecation'] );

        this._original[property].apply(this, arguments);
      };
      }(prop));
    }
    else if(typeof Interface[prop] === "function")
    {
      Interface._original[prop] = originInterface[prop];

      (function(property) {

        Interface[property] = function() {

          log.warn('This function "' + property
          + '" is deprecated.' + "\n"
          + originInterface.deprecated[property + '_deprecation'] );

        this._original[property].apply(this, arguments);
      };
      }(prop));
    }
  }

  for(var prop in originInterface.extend) {

    if (typeof Interface[prop] === "function" &&
        typeof db[prop] === "function") {

      Interface[prop] = originInterface.extend[prop];
    }
    else if(typeof Interface[prop] === "function")
    {
      Interface[prop] = originInterface.extend[prop];
    }
  }

  return Interface;
};

exports.filterDown = function(completedMigrations, count) {
  return completedMigrations.slice(0, count);
};

exports.lpad = function(str, padChar, totalLength) {
  str = str.toString();
  var neededPadding = totalLength - str.length;
  for (var i = 0; i < neededPadding; i++) {
    str = padChar + str;
  }
  return str;
};

exports.shallowCopy = function(obj) {
  var newObj = {};
  for (var prop in obj) {
    newObj[prop] = obj[prop];
  }
  return newObj;
};

exports.toArray = function(obj) {
  var arr = [];
  for (var prop in obj) {
    arr[prop] = obj[prop];
  }
  return arr;
};

exports.isArray = function(obj) {
  return Object.prototype.toString.call(obj) == '[object Array]';
};

exports.isFunction = function(obj) {
  return typeof(obj) == 'function';
};

exports.isString = function(obj) {
  return typeof(obj) == 'string';
};
<commit_msg>fix behavior of reduceToInterface<commit_after>var log = require('./log');

function isIncludedInUp(migration, destination) {
  if(!destination) {
    return true;
  }
  var migrationTest = migration.name.substring(0, Math.min(migration.name.length, destination.length));
  var destinationTest = destination.substring(0, Math.min(migration.name.length, destination.length));
  return migrationTest <= destinationTest;
}

exports.filterUp = function(allMigrations, completedMigrations, destination, count) {
  var sortFn = function(a, b) {
    return a.name.slice(0, a.name.indexOf('-')) - b.name.slice(0, b.name.indexOf('-'));
  };

  return allMigrations.sort(sortFn)
  .filter(function(migration) {
    var hasRun = completedMigrations.some(function(completedMigration) {
      return completedMigration.name === migration.name;
    });
    return !hasRun;
  })
  .filter(function(migration) {
    return isIncludedInUp(migration, destination);
  })
  .slice(0, count);
};

/**
  * Similar to the shadow driver, but we reduce to a subset of an existing
  * driver.
  */
exports.reduceToInterface = function(db, originInterface) {

  var Interface = {};
  Interface._original = {};

  for(var prop in db) {

    if (typeof db[prop] === "function") {

      Interface.[prop] = db[prop];
    }
    else if(typeof originInterface[prop] === "function") {

      Interface[prop] = originInterface[prop];
    }
  }

  for(var prop in originInterface.deprecated) {

    if (typeof db[prop] === "function" &&
        typeof originInterface.deprecated[prop] === "function") {

      Interface._original[prop] = db[prop];

      (function(property) {

        Interface[property] = function() {

          log.warn('This function "' + property
          + '" is deprecated.' + "\n"
          + originInterface.deprecated[property + '_deprecation'] );

        this._original[property].apply(this, arguments);
      };
      }(prop));
    }
    else if(typeof originInterface[prop] === "function") {

      Interface._original[prop] = originInterface[prop];

      (function(property) {

        Interface[property] = function() {

          log.warn('This function "' + property
          + '" is deprecated.' + "\n"
          + originInterface.deprecated[property + '_deprecation'] );

        this._original[property].apply(this, arguments);
      };
      }(prop));
    }
  }

  for(var prop in originInterface.extend) {

    if (typeof db[prop] === "function" &&
        typeof originInterface.extend[prop] === "function") {

      Interface[prop] = originInterface.extend[prop];
    }
    else if(typeof originInterface[prop] === "function") {

      Interface[prop] = originInterface.extend[prop];
    }
  }

  return Interface;
};

exports.filterDown = function(completedMigrations, count) {
  return completedMigrations.slice(0, count);
};

exports.lpad = function(str, padChar, totalLength) {
  str = str.toString();
  var neededPadding = totalLength - str.length;
  for (var i = 0; i < neededPadding; i++) {
    str = padChar + str;
  }
  return str;
};

exports.shallowCopy = function(obj) {
  var newObj = {};
  for (var prop in obj) {
    newObj[prop] = obj[prop];
  }
  return newObj;
};

exports.toArray = function(obj) {
  var arr = [];
  for (var prop in obj) {
    arr[prop] = obj[prop];
  }
  return arr;
};

exports.isArray = function(obj) {
  return Object.prototype.toString.call(obj) == '[object Array]';
};

exports.isFunction = function(obj) {
  return typeof(obj) == 'function';
};

exports.isString = function(obj) {
  return typeof(obj) == 'string';
};
<|endoftext|>


<commit_before>var currentGIF = 0, // Show the GIFs in order
    timeOffset = 2; // Add (or subtract) a time offset to compensate for the location of my server

var config = require('./config.js'),
    slackbot = require('node-slackbot'),
    needle = require('needle');

var gifURL = 'http://www.jessemillar.com/andybernard/images/gifs/',
    gifs = [gifURL + 'awkward.gif', gifURL + 'dancing.gif', gifURL + 'flying.gif', gifURL + 'lachrymose.gif', gifURL + 'nailed.gif', gifURL + 'smug.gif'],
    closingTime = 'https://open.spotify.com/track/1A5V1sxyCLpKJezp75tUXn';

var date = new Date();
console.log('The current time is ' + Number(date.getHours() - timeOffset) + ':' + date.getMinutes());

setInterval(function() { // Tell everyone when it's time to go home (at 5pm)
    if (new Date().getHours() == (17 + timeOffset) && new Date().getMinutes() == 59) {
        needle.get('https://slack.com/api/chat.postMessage?token=' + config.apiToken + "&channel=%23general&text=It's%20closing%20time%2C%20everybody!%20https%3A%2F%2Fopen.spotify.com%2Ftrack%2F1A5V1sxyCLpKJezp75tUXn");
    }
}, 1000 * 60); // Check the time every minute

var andy = new slackbot(config.botToken); // Respond to messages

andy.use(function(message, callback) {
    if (message.type == 'message' && message.user) {
        needle.get('https://slack.com/api/users.info?token=' + config.apiToken + '&user=' + message.user, function(error, response) {
            if (!error) {
                if (!response.body.user.is_bot) { // Make sure we're not reading back one of our own messages
                    console.log(response.body.user.real_name + ' said, "' + message.text + '"');

                    andy.sendMessage(message.channel, gifs[currentGIF]); // The default response of a random GIF

                    if (currentGIF < gifs.length - 1) { // Show the GIFs in order
                        currentGIF++;
                    } else {
                        currentGIF = 0;
                    }
                }
            }
        });
    }

    callback();
});

andy.connect();
<commit_msg>Making things work on only weekdays<commit_after>var currentGIF = 0, // Show the GIFs in order
    timeOffset = 2; // Add (or subtract) a time offset to compensate for the location of my server

var config = require('./config.js'),
    slackbot = require('node-slackbot'),
    needle = require('needle');

var gifURL = 'http://www.jessemillar.com/andybernard/images/gifs/',
    gifs = [gifURL + 'awkward.gif', gifURL + 'dancing.gif', gifURL + 'flying.gif', gifURL + 'lachrymose.gif', gifURL + 'nailed.gif', gifURL + 'smug.gif'],
    closingTime = 'https://open.spotify.com/track/1A5V1sxyCLpKJezp75tUXn';

var date = new Date();
console.log('The current time is ' + Number(date.getHours() - timeOffset) + ':' + date.getMinutes() + ' on day index ' + date.getDay());

setInterval(function() { // Tell everyone when it's time to go home (at 5pm)
    var date = new Date();

    if (date.getDay() > 0 && date.getDay < 6) { // If it's a weekday
        if (date.getHours() == (16 + timeOffset) && date.getMinutes() == 59) { // Push a message one minute before 5pm
            needle.get('https://slack.com/api/chat.postMessage?token=' + config.apiToken + "&channel=%23general&text=It's%20closing%20time%2C%20everybody!%20https%3A%2F%2Fopen.spotify.com%2Ftrack%2F1A5V1sxyCLpKJezp75tUXn");
        }
    }
}, 1000 * 60); // Check the time every minute

var andy = new slackbot(config.botToken); // Respond to messages

andy.use(function(message, callback) {
    if (message.type == 'message' && message.user) {
        needle.get('https://slack.com/api/users.info?token=' + config.apiToken + '&user=' + message.user, function(error, response) {
            if (!error) {
                if (!response.body.user.is_bot) { // Make sure we're not reading back one of our own messages
                    console.log(response.body.user.real_name + ' said, "' + message.text + '"');

                    andy.sendMessage(message.channel, gifs[currentGIF]); // The default response of a random GIF

                    if (currentGIF < gifs.length - 1) { // Show the GIFs in order
                        currentGIF++;
                    } else {
                        currentGIF = 0;
                    }
                }
            }
        });
    }

    callback();
});

andy.connect();
<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(_path, _fs) {

  function readExif(data, cb) {
    cb(data); // TODO
  }

  function readPermission(mode) {
    return mode; // TODO
  }

  function pathJoin() {
    var s = _path.join.apply(null, arguments);
    return s.replace(/\\/g, '/');
  }

  function getRealPath(path, config, request) {
    var fullPath = null;
    var protocol = '';

    if ( path.match(/^osjs\:\/\//) ) {
      path = path.replace(/^osjs\:\/\//, '');
      fullPath = _path.join(config.distdir, path);
      protocol = 'osjs://';
    } else if ( path.match(/^home\:\/\//) ) {
      path = path.replace(/^home\:\/\//, '');
      var userdir = request.cookies.get('username');
      if ( !userdir ) {
        throw "No user session was found";
      }
      fullPath = _path.join(config.vfs.homes, userdir, path);
      protocol = 'home://';
    } else {
      var tmp = path.split(/^(\w+)\:\/\//);
      if ( tmp.length === 3 ) {
        tmp = tmp[1];
        if ( config.vfs.mounts && config.vfs.mounts[tmp] ) {
          protocol = tmp + '://';
          path = path.replace(/^(\w+)\:\/\//, '');
          fullPath = _path.join(config.vfs.mounts[tmp], path);
        }
      }
    }

    if ( !fullPath ) {
      throw new Error('Invalid mountpoint');
    }

    return {root: fullPath, path: path, protocol: protocol};
  }

  var vfs = {
    getRealPath: getRealPath,

    getMime : function(file, config) {
      var i = file.lastIndexOf("."),
          ext = (i === -1) ? "default" : file.substr(i),
          mimeTypes = config.mimes;
      return mimeTypes[ext.toLowerCase()] || mimeTypes.default;
    },

    // NOTE: This is pretty much deprecated ?!?!
    read : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( exists ) {
          _fs.readFile(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: null, error: 'Error reading file: ' + error});
            } else {
              data = "data:" + vfs.getMime(realPath.root, config) + ";base64," + (new Buffer(data).toString('base64'));
              respond({result: data.toString(), error: null});
            }
          });
        } else {
          respond({result: null, error: 'File not found!'});
        }
      });
    },

    write : function(args, request, respond, config) {
      var path = args[0];
      var data = args[1] || '';
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;
      data = data.replace(/^data\:(.*);base64\,/, "") || '';
      data = new Buffer(data, 'base64').toString('utf8');

      _fs.writeFile(realPath.root, data, function(error, data) {
        if ( error ) {
          respond({result: null, error: 'Error writing file: ' + error});
        } else {
          respond({result: true, error: null});
        }
      });
    },

    'delete' : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( !exists ) {
          respond({result: null, error: 'Target does not exist!'});
        } else {
          _fs.remove(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: false, error: 'Error deleting: ' + error});
            } else {
              respond({result: true, error: null});
            }
          });
        }
      });
    },

    copy : function(args, request, respond, config) {
      var src  = args[0];
      var dst  = args[1];
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realSrc = getRealPath(src, config, request);
      var realDst = getRealPath(dst, config, request);
      var srcPath = realSrc.root; //_path.join(realSrc.root, src);
      var dstPath = realDst.root; //_path.join(realDst.root, dst);
      _fs.exists(srcPath, function(exists) {
        if ( exists ) {
          _fs.exists(dstPath, function(exists) {
            if ( exists ) {
              respond({result: null, error: 'Target already exist!'});
            } else {
              _fs.copy(srcPath, dstPath, function(error, data) {
                if ( error ) {
                  respond({result: false, error: 'Error copying: ' + error});
                } else {
                  respond({result: true, error: null});
                }
              });
            }
          });
        } else {
          respond({result: null, error: 'Source does not exist!'});
        }
      });
    },

    move : function(args, request, respond, config) {
      var src  = args[0];
      var dst  = args[1];
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realSrc = getRealPath(src, config, request);
      var realDst = getRealPath(dst, config, request);
      var srcPath = realSrc.root; //_path.join(realSrc.root, src);
      var dstPath = realDst.root; //_path.join(realDst.root, dst);
      _fs.exists(srcPath, function(exists) {
        if ( exists ) {
          _fs.exists(dstPath, function(exists) {
            if ( exists ) {
              respond({result: null, error: 'Target already exist!'});
            } else {
              _fs.rename(srcPath, dstPath, function(error, data) {
                if ( error ) {
                  respond({result: false, error: 'Error renaming/moving: ' + error});
                } else {
                  respond({result: true, error: null});
                }
              });
            }
          });
        } else {
          respond({result: null, error: 'Source does not exist!'});
        }
      });
    },

    mkdir : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( exists ) {
          respond({result: null, error: 'Target already exist!'});
        } else {
          _fs.mkdir(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: false, error: 'Error creating directory: ' + error});
            } else {
              respond({result: true, error: null});
            }
          });
        }
      });
    },

    exists : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      _fs.exists(realPath.root, function(exists) {
        respond({result: exists, error: null});
      });
    },

    fileinfo : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;
      _fs.exists(realPath.root, function(exists) {
        if ( !exists ) {
          respond({result: null, error: 'No such file or directory!'});
        } else {
          _fs.stat(realPath.root, function(error, stat) {
            if ( error ) {
              respond({result: false, error: 'Error getting file information: ' + error});
            } else {

              var data = {
                path:         _path.dirname(realPath.root),
                filename:     _path.basename(realPath.root),
                size:         stat.size,
                mime:         vfs.getMime(realPath.root, config),
                permissions:  readPermission(stat.mode),
                ctime:        stat.ctime || null,
                mtime:        stat.mtime || null
              };

              readExif(data, function(data) {
                respond({result: data, error: null});
              });

            }
          });
        }
      });
    },

    scandir : function(args, request, respond, config) {
      var path = args[0];

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.readdir(realPath.root, function(error, files) {
        if ( error ) {
          respond({result: null, error: 'Error reading directory: ' + error});
        } else {
          var result = [];
          var ofpath, fpath, ftype, fsize, fstat, ctime, mtime;

          var tmp = realPath.path.replace(/^\/+?/, '');
          if ( tmp.length && tmp.split('/').length ) {
            tmp = tmp.split('/');
            tmp.pop();
            tmp = tmp.join('/');

            result.push({
              filename: '..',
              path:     realPath.protocol + _path.join('/', tmp),
              size:     0,
              mime:     '',
              type:     'dir',
              ctime:    null,
              mtime:    null
            });
          }

          for ( var i = 0; i < files.length; i++ ) {
            ofpath = pathJoin(path, files[i]);
            fpath  = _path.join(realPath.root, files[i]);

            try {
              fsstat = _fs.statSync(fpath);
              ftype  = fsstat.isFile() ? 'file' : 'dir';
              fsize  = fsstat.size;
              mtime  = fsstat.mtime;
              ctime  = fsstat.ctime;
            } catch ( e ) {
              ftype = 'file';
              fsize = 0;
              ctime = null;
              mtime = null;
            }

            result.push({
              filename: files[i],
              path:     realPath.protocol + ofpath,
              size:     fsize,
              mime:     ftype === 'file' ? vfs.getMime(files[i], config) : '',
              type:     ftype,
              ctime:    ctime,
              mtime:    mtime
            });
          }

          respond({result: result, error: null});
        }
      });
    }
  };

  module.exports = vfs;
})(
  require("path"),
  require("node-fs-extra")
);
<commit_msg>server-node: VFS fileinfo() now returns relative path<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(_path, _fs) {

  function readExif(data, cb) {
    cb(data); // TODO
  }

  function readPermission(mode) {
    return mode; // TODO
  }

  function pathJoin() {
    var s = _path.join.apply(null, arguments);
    return s.replace(/\\/g, '/');
  }

  function getRealPath(path, config, request) {
    var fullPath = null;
    var protocol = '';

    if ( path.match(/^osjs\:\/\//) ) {
      path = path.replace(/^osjs\:\/\//, '');
      fullPath = _path.join(config.distdir, path);
      protocol = 'osjs://';
    } else if ( path.match(/^home\:\/\//) ) {
      path = path.replace(/^home\:\/\//, '');
      var userdir = request.cookies.get('username');
      if ( !userdir ) {
        throw "No user session was found";
      }
      fullPath = _path.join(config.vfs.homes, userdir, path);
      protocol = 'home://';
    } else {
      var tmp = path.split(/^(\w+)\:\/\//);
      if ( tmp.length === 3 ) {
        tmp = tmp[1];
        if ( config.vfs.mounts && config.vfs.mounts[tmp] ) {
          protocol = tmp + '://';
          path = path.replace(/^(\w+)\:\/\//, '');
          fullPath = _path.join(config.vfs.mounts[tmp], path);
        }
      }
    }

    if ( !fullPath ) {
      throw new Error('Invalid mountpoint');
    }

    return {root: fullPath, path: path, protocol: protocol};
  }

  var vfs = {
    getRealPath: getRealPath,

    getMime : function(file, config) {
      var i = file.lastIndexOf("."),
          ext = (i === -1) ? "default" : file.substr(i),
          mimeTypes = config.mimes;
      return mimeTypes[ext.toLowerCase()] || mimeTypes.default;
    },

    // NOTE: This is pretty much deprecated ?!?!
    read : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( exists ) {
          _fs.readFile(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: null, error: 'Error reading file: ' + error});
            } else {
              data = "data:" + vfs.getMime(realPath.root, config) + ";base64," + (new Buffer(data).toString('base64'));
              respond({result: data.toString(), error: null});
            }
          });
        } else {
          respond({result: null, error: 'File not found!'});
        }
      });
    },

    write : function(args, request, respond, config) {
      var path = args[0];
      var data = args[1] || '';
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;
      data = data.replace(/^data\:(.*);base64\,/, "") || '';
      data = new Buffer(data, 'base64').toString('utf8');

      _fs.writeFile(realPath.root, data, function(error, data) {
        if ( error ) {
          respond({result: null, error: 'Error writing file: ' + error});
        } else {
          respond({result: true, error: null});
        }
      });
    },

    'delete' : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( !exists ) {
          respond({result: null, error: 'Target does not exist!'});
        } else {
          _fs.remove(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: false, error: 'Error deleting: ' + error});
            } else {
              respond({result: true, error: null});
            }
          });
        }
      });
    },

    copy : function(args, request, respond, config) {
      var src  = args[0];
      var dst  = args[1];
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realSrc = getRealPath(src, config, request);
      var realDst = getRealPath(dst, config, request);
      var srcPath = realSrc.root; //_path.join(realSrc.root, src);
      var dstPath = realDst.root; //_path.join(realDst.root, dst);
      _fs.exists(srcPath, function(exists) {
        if ( exists ) {
          _fs.exists(dstPath, function(exists) {
            if ( exists ) {
              respond({result: null, error: 'Target already exist!'});
            } else {
              _fs.copy(srcPath, dstPath, function(error, data) {
                if ( error ) {
                  respond({result: false, error: 'Error copying: ' + error});
                } else {
                  respond({result: true, error: null});
                }
              });
            }
          });
        } else {
          respond({result: null, error: 'Source does not exist!'});
        }
      });
    },

    move : function(args, request, respond, config) {
      var src  = args[0];
      var dst  = args[1];
      var opts = typeof args[2] === 'undefined' ? {} : (args[2] || {});

      var realSrc = getRealPath(src, config, request);
      var realDst = getRealPath(dst, config, request);
      var srcPath = realSrc.root; //_path.join(realSrc.root, src);
      var dstPath = realDst.root; //_path.join(realDst.root, dst);
      _fs.exists(srcPath, function(exists) {
        if ( exists ) {
          _fs.exists(dstPath, function(exists) {
            if ( exists ) {
              respond({result: null, error: 'Target already exist!'});
            } else {
              _fs.rename(srcPath, dstPath, function(error, data) {
                if ( error ) {
                  respond({result: false, error: 'Error renaming/moving: ' + error});
                } else {
                  respond({result: true, error: null});
                }
              });
            }
          });
        } else {
          respond({result: null, error: 'Source does not exist!'});
        }
      });
    },

    mkdir : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.exists(realPath.root, function(exists) {
        if ( exists ) {
          respond({result: null, error: 'Target already exist!'});
        } else {
          _fs.mkdir(realPath.root, function(error, data) {
            if ( error ) {
              respond({result: false, error: 'Error creating directory: ' + error});
            } else {
              respond({result: true, error: null});
            }
          });
        }
      });
    },

    exists : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      _fs.exists(realPath.root, function(exists) {
        respond({result: exists, error: null});
      });
    },

    fileinfo : function(args, request, respond, config) {
      var path = args[0];
      var opts = typeof args[1] === 'undefined' ? {} : (args[1] || {});

      var realPath = getRealPath(path, config, request);
      path = realPath.path;
      _fs.exists(realPath.root, function(exists) {
        if ( !exists ) {
          respond({result: null, error: 'No such file or directory!'});
        } else {
          _fs.stat(realPath.root, function(error, stat) {
            if ( error ) {
              respond({result: false, error: 'Error getting file information: ' + error});
            } else {

              var data = {
                path:         realPath.protocol + realPath.path,
                filename:     _path.basename(realPath.root),
                size:         stat.size,
                mime:         vfs.getMime(realPath.root, config),
                permissions:  readPermission(stat.mode),
                ctime:        stat.ctime || null,
                mtime:        stat.mtime || null
              };

              readExif(data, function(data) {
                respond({result: data, error: null});
              });

            }
          });
        }
      });
    },

    scandir : function(args, request, respond, config) {
      var path = args[0];

      var realPath = getRealPath(path, config, request);
      path = realPath.path;

      _fs.readdir(realPath.root, function(error, files) {
        if ( error ) {
          respond({result: null, error: 'Error reading directory: ' + error});
        } else {
          var result = [];
          var ofpath, fpath, ftype, fsize, fstat, ctime, mtime;

          var tmp = realPath.path.replace(/^\/+?/, '');
          if ( tmp.length && tmp.split('/').length ) {
            tmp = tmp.split('/');
            tmp.pop();
            tmp = tmp.join('/');

            result.push({
              filename: '..',
              path:     realPath.protocol + _path.join('/', tmp),
              size:     0,
              mime:     '',
              type:     'dir',
              ctime:    null,
              mtime:    null
            });
          }

          for ( var i = 0; i < files.length; i++ ) {
            ofpath = pathJoin(path, files[i]);
            fpath  = _path.join(realPath.root, files[i]);

            try {
              fsstat = _fs.statSync(fpath);
              ftype  = fsstat.isFile() ? 'file' : 'dir';
              fsize  = fsstat.size;
              mtime  = fsstat.mtime;
              ctime  = fsstat.ctime;
            } catch ( e ) {
              ftype = 'file';
              fsize = 0;
              ctime = null;
              mtime = null;
            }

            result.push({
              filename: files[i],
              path:     realPath.protocol + ofpath,
              size:     fsize,
              mime:     ftype === 'file' ? vfs.getMime(files[i], config) : '',
              type:     ftype,
              ctime:    ctime,
              mtime:    mtime
            });
          }

          respond({result: result, error: null});
        }
      });
    }
  };

  module.exports = vfs;
})(
  require("path"),
  require("node-fs-extra")
);
<|endoftext|>