text:
require('../common/bootstrap');

var builds = [{
  sha: 'ac4d8d8a5bfd671f7f174c2eaa258856bd82fe29',
  released: '2015-05-18T02:21:57.856Z',
  version: '0.0.0'
}, {
  sha: '9a85c84f5a03c715908921baaaa9e7397985bc7f',
  released: '2015-08-12T03:01:57.856Z',
  version: '0.0.1'
}];

exports['controller.update'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.spinnerStart = this.sandbox.stub(log.spinner, 'start');
    this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');
    this.warn = this.sandbox.stub(log, 'warn');
    this.info = this.sandbox.stub(log, 'info');
    this.basic = this.sandbox.stub(log, 'basic');

    this.tessel = TesselSimulator();

    this.getTessel = this.sandbox.stub(Tessel, 'get', (opts) => {
      this.tessel.setLANConnectionPreference(opts.lanPrefer);
      return Promise.resolve(this.tessel);
    });

    this.update = this.sandbox.stub(Tessel.prototype, 'update', () => Promise.resolve());

    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', () => {
      return Promise.resolve('9a85c84f5a03c715908921baaaa9e7397985bc7f');
    });

    this.requestBuildList = this.sandbox.stub(updates, 'requestBuildList', () => Promise.resolve(builds));

    this.updateTesselWithVersion = this.sandbox.spy(controller, 'updateTesselWithVersion');
    this.closeTesselConnections = this.sandbox.spy(controller, 'closeTesselConnections');

    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    this.tessel.mockClose();

    // If builds were reversed, fix them.
    if (builds[0].version === '0.0.1') {
      builds.reverse();
    }
    done();
  },

  listBuilds: function(test) {
    test.expect(3);

    controller.printAvailableUpdates()
      .then(() => {
        test.equal(this.requestBuildList.callCount, 1);
        // Print info that these are log
        // 'Latest builds:'
        test.equal(this.info.callCount, 1);
        // Print each version out
        // '\t Version:', build.version, '\tPublished:', build.released.toLocaleString()
        test.equal(this.basic.callCount, 2);
        // Finish
        test.done();
      })
      .catch(error => {
        test.ok(false, `printAvailableUpdates failed: ${error.toString()}`);
        test.done();
      });
  },

  listBuildFetchError: function(test) {
    test.expect(2);

    var errMessage = 'Could not fetch builds';

    this.requestBuildList.restore();
    this.requestBuildList = this.sandbox.stub(updates, 'requestBuildList', function() {
      return Promise.reject(new Error(errMessage));
    });

    controller.printAvailableUpdates()
      .then(() => {
        test.equal(true, false, 'Build fetch should have failed.');
        test.done();
      })
      .catch(error => {
        // We tried to fetch the builds
        test.equal(this.requestBuildList.callCount, 1);
        // But it failed with the erroror message we specified
        test.equal(error.message, errMessage);
        test.done();
      });
  },

  buildOptionValid: function(test) {
    test.expect(9);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      version: '0.0.1',
      lanPrefer: true
    };
    controller.update(opts)
      .then(() => {
        // We have to fetch the build list to figure out what the sha is of this version
        test.equal(this.requestBuildList.callCount, 1);
        // We did fetch the specified build
        test.equal(this.fetchBuild.callCount, 1);
        // It was called with the correct args
        test.deepEqual(this.fetchBuild.lastCall.args[0], builds[1]);
        // We fetched the Tessel to update
        test.equal(this.getTessel.callCount, 1);
        // The Tessel was updated
        test.equal(this.update.callCount, 1);
        // The update used the appropriate binaries
        test.equal(this.update.calledWith(opts, binaries), true);
        // Then the Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(error => {
        test.ok(false, `update failed: ${error.toString()}`);
        test.done();
      });
  },

  buildOptionInvalid: function(test) {
    test.expect(3);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var errMessage = 'No such build exists';

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.reject(new Error(errMessage));
    });

    var opts = {
      version: '0.0.1'
    };
    controller.update(opts)
      .catch(error => {
        // We attempted to fetch a build
        test.equal(this.fetchBuild.callCount, 1);
        // But it failed with the error we specified
        test.equal(error.message, errMessage);
        // We need to close all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        test.done();
      });
  },

  buildLatest: function(test) {
    test.expect(8);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    this.fetchCurrentBuildInfo.restore();
    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', function() {
      return Promise.resolve('ac4d8d8a5bfd671f7f174c2eaa258856bd82fe29');
    });

    var opts = {
      lanPrefer: true
    };
    controller.update(opts)
      .then(() => {
        // Make sure we checked what the Tessel version is currently at
        test.equal(this.fetchCurrentBuildInfo.callCount, 1);
        // We fetched only one build
        test.equal(this.fetchBuild.callCount, 1);
        // It was the latest build
        test.equal(this.fetchBuild.calledWith(builds[1]), true);
        // Update Tessel was successfully called
        test.equal(this.update.callCount, 1);
        // It was provided the binaries
        test.equal(this.update.calledWith(opts, binaries), true);
        // Then Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(error => {
        test.ok(false, `update failed: ${error.toString()}`);
        test.done();
      });
  },

  buildLatestAlreadyCurrent: function(test) {
    test.expect(7);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      lanPrefer: true
    };
    controller.update(opts)
      .then(() => {
        // Make sure we checked what the Tessel version is currently at
        test.equal(this.fetchCurrentBuildInfo.callCount, 1);
        // We fetched the build list once
        test.equal(this.requestBuildList.callCount, 1);
        // We didn't fetch any builds because Tessel is already up to date
        test.equal(this.fetchBuild.callCount, 0);
        // Update Tessel was not called because it was already up to date
        test.equal(this.update.callCount, 0);
        // Then Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      });
  },

  buildLatestUpdateFailed: function(test) {
    test.expect(7);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    this.fetchCurrentBuildInfo.restore();
    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', function() {
      return Promise.resolve('ac4d8d8a5bfd671f7f174c2eaa258856bd82fe29');
    });

    var errMessage = 'Something absolutely dreadful happened. Your Tessel is bricked.';
    this.update.restore();
    this.update = this.sandbox.stub(Tessel.prototype, 'update', () => {
      return Promise.reject(new Error(errMessage));
    });

    var opts = {
      lanPrefer: true
    };
    controller.update(opts)
      .catch(error => {
        // We fetched only one build
        test.equal(this.fetchBuild.callCount, 1);
        // It was the latest build
        test.equal(this.fetchBuild.calledWith(builds[1]), true);
        // Update Tessel was not called because it was already up to date
        test.equal(this.update.callCount, 1);
        // The update failed with our error message
        test.equal(error.message, errMessage);
        // Then Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      });
  },

  buildLatestForce: function(test) {
    test.expect(7);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      force: true,
      lanPrefer: true
    };

    controller.update(opts)
      .then(() => {
        // We fetched only one build
        test.equal(this.fetchBuild.callCount, 1);
        // It was the latest build
        test.equal(this.fetchBuild.calledWith(builds[1]), true);
        // Update Tessel was not called because it was already up to date
        test.equal(this.update.callCount, 1);
        // It was provided the binaries
        test.equal(this.update.calledWith(opts, binaries), true);
        // Then Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(error => {
        test.ok(false, `update failed: ${error.toString()}`);
        test.done();
      });
  },

  buildLatestNoConfigSave: function(test) {
    test.expect(8);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      force: true,
      lanPrefer: true,
      n: true
    };

    controller.update(opts)
      .then(() => {
        // We fetched only one build
        test.equal(this.fetchBuild.callCount, 1);
        // It was the latest build
        test.equal(this.fetchBuild.calledWith(builds[1]), true);
        // Update Tessel was not called because it was already up to date
        test.equal(this.update.callCount, 1);
        // It was provided the binaries and options
        test.equal(this.update.calledWith(opts, binaries), true);
        // Provided Options match first parameter
        test.deepEqual(this.update.lastCall.args[0], opts);
        // Then Tessel was closed
        test.equal(this.tessel.closed, true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(error => {
        test.ok(false, `update failed: ${error.toString()}`);
        test.done();
      });
  },

  explicitLatestDoesntImmediatelyUpdate: function(test) {
    test.expect(3);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      version: 'latest',
      lanPrefer: true
    };

    controller.update(opts)
      .then(() => {
        test.equal(this.updateTesselWithVersion.callCount, 0);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(error => {
        test.ok(false, `update failed: ${error.toString()}`);
        test.done();
      });
  },

  noVerifiedVersion: function(test) {
    test.expect(2);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var opts = {
      version: 'x.x.x',
      lanPrefer: true
    };
    controller.update(opts)
      .catch(error => {
        test.equal(error, 'The requested build was not found. Please see the available builds with `t2 update -l`.');
        // We need to close all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        test.done();
      });
  },

  noVersionForcedUpdate: function(test) {
    test.expect(4);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    this.fetchCurrentBuildInfo.restore();
    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', function() {
      return Promise.reject(new Error('[Error: cat: can\'t open \'/etc/tessel-version\': No such file or directory]'));
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      lanPrefer: true
    };
    controller.update(opts)
      .then(() => {
        // It should attempt to fetch a build
        test.equal(this.fetchBuild.callCount, 1);
        // We should be requesting the latest build
        test.equal(this.fetchBuild.calledWith(builds[1]), true);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'It should force an update if the file version is not found');
        test.done();
      });
  },

  noVersionUnknownError: function(test) {
    test.expect(4);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var unknownError = new Error('Something totally weird happened.');

    this.fetchCurrentBuildInfo.restore();
    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', function() {
      return Promise.reject(unknownError);
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    var opts = {
      lanPrefer: true
    };
    controller.update(opts)
      .then(() => {
        test.ok(false, 'It should throw an error if we get an unknown error');
        test.done();
      })
      .catch(error => {
        // Make sure this error has the proper error message
        test.equal(error.message, unknownError.message);
        // It should not attempt to fetch any builds
        test.equal(this.fetchBuild.callCount, 0);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      });
  },

  properBuildCompare: function(test) {

    // use builds where the string compare of the versions
    // would lead to incorrect comparison ('0.0.7 > 0.0.10')
    var mixedBuilds = [{
      sha: 'ac4d8d8a5bfd671f7f174c2eaa258856bd82fe29',
      released: '2015-05-18T02:21:57.856Z',
      version: '0.0.7'
    }, {
      sha: '9a85c84f5a03c715908921baaaa9e7397985bc7f',
      released: '2015-08-12T03:01:57.856Z',
      version: '0.0.10'
    }];

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var binaries = {
      firmware: new Buffer(0),
      openwrt: new Buffer(0)
    };

    this.fetchCurrentBuildInfo.restore();
    this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo', function() {
      // Resolve with earlier build (0.0.7)
      return Promise.resolve(mixedBuilds[0].sha);
    });

    this.requestBuildList.restore();
    this.requestBuildList = this.sandbox.stub(updates, 'requestBuildList', function() {
      // Return our two mixed builds
      return Promise.resolve(mixedBuilds);
    });

    this.fetchBuild = this.sandbox.stub(updates, 'fetchBuild', function() {
      return Promise.resolve(binaries);
    });

    controller.update({})
      .then(() => {
        // It should attempt to fetch a build
        test.equal(this.fetchBuild.callCount, 1);
        // We should be requesting the latest build
        test.equal(this.fetchBuild.calledWith(mixedBuilds[1]), true);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'Update should not reject with valid options and builds.');
        test.done();
      });
  },
  updateWithLocalBuilds: function(test) {
    test.expect(3);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    this.loadLocalBinary = this.sandbox.stub(updates, 'loadLocalBinary').returns(Promise.resolve(new Buffer(0)));

    var opts = {
      lanPrefer: true,
      'openwrt-path': 'somepath/foo',
      'firmware-path': 'somepath/bar',
    };

    controller.update(opts)
      .then(() => {
        // It should attempt to fetch a build
        test.equal(this.loadLocalBinary.callCount, 2);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'It should update from local binary paths');
        test.done();
      });
  },
  failLocalBadPath: function(test) {
    test.expect(4);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    var err = new Error('Bad local binary path');
    this.loadLocalBinary = this.sandbox.stub(updates, 'loadLocalBinary').returns(Promise.reject(err));

    var opts = {
      lanPrefer: true,
      'openwrt-path': 'somepath/foo',
      'firmware-path': 'somepath/bar',
    };

    controller.update(opts)
      .then(() => {
        test.ok(false, 'Update should not resolve with invalid binary paths');
        test.done();
      })
      .catch((deliveredErr) => {
        test.deepEqual(deliveredErr, err);
        // It should attempt to fetch a build
        test.equal(this.loadLocalBinary.callCount, 2);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      });
  },
  onlyFirmwareImageUpdate: function(test) {
    test.expect(3);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    this.loadLocalBinary = this.sandbox.stub(updates, 'loadLocalBinary').returns(Promise.resolve(new Buffer(0)));

    var opts = {
      lanPrefer: true,
      'firmware-path': 'somepath/bar',
    };

    controller.update(opts)
      .then(() => {
        // It should attempt to fetch a build
        test.equal(this.loadLocalBinary.callCount, 1);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'It should update from local binary paths');
        test.done();
      });
  },
  onlyOpenWRTImageUpdate: function(test) {
    test.expect(3);

    // Create a Tessel sim
    this.tessel = TesselSimulator({
      type: 'USB',
      end: () => Promise.resolve()
    });

    this.loadLocalBinary = this.sandbox.stub(updates, 'loadLocalBinary').returns(Promise.resolve(new Buffer(0)));

    var opts = {
      lanPrefer: true,
      'openwrt-path': 'somepath/foo',
    };

    controller.update(opts)
      .then(() => {
        // It should attempt to fetch a build
        test.equal(this.loadLocalBinary.callCount, 1);
        // We closed all open Tessel connections
        test.equal(this.closeTesselConnections.callCount, 1);
        // We called the close function with an array
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'It should update from local binary paths');
        test.done();
      });
  }
};

exports['update-fetch'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.spinnerStart = this.sandbox.stub(log.spinner, 'start');
    this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');

    this.warn = this.sandbox.stub(log, 'warn');
    this.info = this.sandbox.stub(log, 'info');
    this.basic = this.sandbox.stub(log, 'basic');

    var mixedBuilds = [{
      sha: 'ac4d8d8a5bfd671f7f174c2eaa258856bd82fe29',
      released: '2015-05-18T02:21:57.856Z',
      version: '0.0.0'
    }, {
      sha: '9a85c84f5a03c715908921baaaa9e7397985bc7f',
      released: '2015-08-12T03:01:57.856Z',
      version: '0.0.4'
    }, {
      sha: '789432897cd7829a988888b8843274cd8de89a98',
      released: '2015-06-12T03:01:57.856Z',
      version: '0.0.1'
    }];

    this.requestGet = this.sandbox.stub(request, 'get', function(url, cb) {
      cb(null, {
        statusCode: 200
      }, JSON.stringify(mixedBuilds));
    });
    done();
  },
  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },
  buildsSorted: function(test) {
    test.expect(4);

    // Request the out of order builds
    updates.requestBuildList()
      .then((builds) => {
        // Ensure they were put back in order
        test.ok(builds.length === 3);
        test.ok(builds[0].version === '0.0.0');
        test.ok(builds[1].version === '0.0.1');
        test.ok(builds[2].version === '0.0.4');
        test.done();
      })
      .catch(() => {
        test.ok(false, 'An error was returned when the list fetch should succeed');
        test.done();
      });
  }
};

exports['Tessel.update'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.spinnerStart = this.sandbox.stub(log.spinner, 'start');
    this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');

    this.warn = this.sandbox.stub(log, 'warn');
    this.info = this.sandbox.stub(log, 'info');
    this.basic = this.sandbox.stub(log, 'basic');
    this.tessel = TesselSimulator();

    this.tessel.connection.enterBootloader = function() {};
    this.updateFirmware = sinon.spy(this.tessel, 'updateFirmware');
    this.enterBootloader = sinon.stub(this.tessel.connection, 'enterBootloader').returns(Promise.resolve());
    this.tessel.writeFlash = function() {};
    this.writeFlash = sinon.stub(this.tessel, 'writeFlash').returns(Promise.resolve());
    this.fixOldUpdateScripts = sinon.stub(this.tessel, 'fixOldUpdateScripts').returns(Promise.resolve());

    this.newImage = {
      openwrt: new Buffer(1),
      firmware: new Buffer(1)
    };

    done();
  },
  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  updatePathMustNotByPathNormalized: function(test) {
    test.expect(4);

    var updatePath = `/tmp/${updates.OPENWRT_BINARY_FILE}`;

    this.exec = this.sandbox.stub(this.tessel.connection, 'exec', (command, handler) => {
      handler(null, this.tessel._rps);
      setImmediate(() => {
        this.tessel._rps.stdout.emit('data', new Buffer('Upgrade completed'));
        this.tessel._rps.emit('close');
      });
    });

    this.openStdinToFile = this.sandbox.stub(commands, 'openStdinToFile');
    this.sysupgrade = this.sandbox.stub(commands, 'sysupgrade');

    this.tessel.updateOpenWRT({}, this.newImage.openwrt).then(() => {
      test.equal(this.openStdinToFile.callCount, 1);
      test.equal(this.sysupgrade.callCount, 1);
      test.equal(this.openStdinToFile.lastCall.args[0], updatePath);
      test.equal(this.sysupgrade.lastCall.args[0], updatePath);
      test.done();
    }).catch((error) => {
      test.ok(false, error);
      test.done();
    });
  },

  configurationShouldNotBeSaved: function(test) {
    var updatePath = `/tmp/${updates.OPENWRT_BINARY_FILE}`;

    this.exec = this.sandbox.stub(this.tessel.connection, 'exec', (command, handler) => {
      handler(null, this.tessel._rps);
      setImmediate(() => {
        this.tessel._rps.stdout.emit('data', new Buffer('Upgrade completed'));
        this.tessel._rps.emit('close');
      });
    });

    this.openStdinToFile = this.sandbox.stub(commands, 'openStdinToFile');
    this.sysupgradeNoSaveConfig = this.sandbox.stub(commands, 'sysupgradeNoSaveConfig');

    this.tessel.updateOpenWRT({
      n: true
    }, this.newImage.openwrt).then(() => {
      test.equal(this.openStdinToFile.callCount, 1);
      test.equal(this.sysupgradeNoSaveConfig.callCount, 1);
      test.equal(this.openStdinToFile.lastCall.args[0], updatePath);
      test.equal(this.sysupgradeNoSaveConfig.lastCall.args[0], updatePath);
      test.done();
    }).catch((error) => {
      test.ok(false, error);
      test.done();
    });
  },

  standardUpdate: function(test) {
    // Set the amount of time Tessel waits for the OpenWRT update
    // to complete to 1ms so we don't wait forever
    Tessel.openWRTUpdateTime = 1;
    var updatePath = `/tmp/${updates.OPENWRT_BINARY_FILE}`;
    // The exec commands that should be run to update OpenWRT
    var expectedCommands = [commands.openStdinToFile(updatePath), commands.sysupgrade(updatePath)];
    // Which command is being written
    var commandsWritten = 0;
    // When we get a command
    this.tessel._rps.on('control', (data) => {
      // Switch based on the number of command this is
      switch (commandsWritten) {
        // If it's the first command
        case 0:
          // Ensure that it's attempting to write the openwrt image to /tmp
          test.equal(data.toString(), expectedCommands[commandsWritten].join(' '));
          // Once we receive stdin of the image
          this.tessel._rps.on('stdin', (data) => {
            // Ensure it's the proper image
            test.deepEqual(data, this.newImage.openwrt);
            // Close the process to continue with updates
            this.tessel._rps.emit('close');
          });
          break;
        case 1:
          // Ensure that it's attempting to run sysupgrade
          test.equal(data.toString(), expectedCommands[commandsWritten].join(' '));
          // Emit that the upgrade has complete to continue
          setImmediate(() => this.tessel._rps.stdout.push('Upgrade completed'));
      }

      commandsWritten++;
    });

    // Begin the update
    this.tessel.update({}, this.newImage)
      // Update completed as expected
      .then(() => {
        test.equal(this.updateFirmware.callCount, 1);
        test.equal(this.enterBootloader.callCount, 1);
        test.equal(this.writeFlash.callCount, 1);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'Update test failed with valid options and builds');
        test.done();
      });
  }
};


text:
package com.james.eggplantfastpass.ui.activity;

/**
 * Created by 1 on 2017/2/15.
 */

public class ConnectComputerActivity {
}

redpajama_set_name: RedPajamaGithub


text:
<content-header>

    All Products

      <product-type-show-modal
        title="Add A Product"
        message="Select the type of product you will be creating"
        product-types="vm.productTypes"
        on-ok="vm.createType(productType)"></product-type-show-modal>

      <view-mode-switch view-mode="vm.viewMode"></view-mode-switch>

</content-header>

<catalog-category ng-repeat="category in vm.catalog" category="category" view-mode="vm.viewMode"
                  comparable="false" link-to="admin.products.edit"></catalog-category>


text:
'''
@author:       Pedram Amini
@license:      GNU General Public License 2.0 or later
@contact:      pedram.amini@gmail.com
@organization: www.openrce.org
'''

from ctypes import *

########################################################################################################################
def _construct (typ, raw_bytes):
    '''
    This routine is called by _reduce for unmarshaling purposes. The object type is used to instantiate a new object of
    the desired type. The raw bytes are then directly written into the address space of the newly instantiated object
    via the ctypes routines memmove() and addressof().

    @type  typ:       Class object
    @param typ:       The class type of the object we are unmarshaling.
    @type  raw_bytes: Raw bytes (in a string buffer)
    @param raw_bytes: The raw bytes

    @rtype:  Mixed
    @return: Unmarshaled object.
    '''

    obj = typ.__new__(typ)
    memmove(addressof(obj), raw_bytes, len(raw_bytes))

    return obj

########################################################################################################################
def _reduce (self):
    '''
    cPickle will allow an object to marshal itself if the __reduce__ function is defined. Because cPickle is unable to
    handle ctype primitives or the objects derived on those primitives we define this function that later is assigned
    as the __reduce__ method for all types. This method relies on _construct for unmarshaling. As per the Python docs
    __reduce__ must return a tuple where the first element is "A callable object that will be called to create the
    initial version of the object. The next element of the tuple will provide arguments for this callable...". In this
    case we pass the object class and the raw data bytes of the object to _construct.

    @rtype:  Tuple
    @return: Tuple, as specified per the cPickle __reduce__ Python docs.
    '''

    return (_construct, (self.__class__, str(buffer(self))))

########################################################################################################################
c_types = (Structure, c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, \
           c_ulonglong, c_float, c_double, c_char_p, c_wchar_p, c_void_p)

# for each ctype we need to marshal, set it's __reduce__ routine.
#for typ in c_types:
#    typ.__reduce__ = _reduce


text:
package com.google.gerrit.client.changes;

import com.google.gerrit.common.data.ChangeDetailService;
import com.google.gerrit.common.data.ChangeListService;
import com.google.gerrit.common.data.ChangeManageService;
import com.google.gerrit.reviewdb.Change;
import com.google.gwt.core.client.GWT;
import com.google.gwtjsonrpc.client.JsonUtil;

public class Util {
  public static final ChangeConstants C = GWT.create(ChangeConstants.class);
  public static final ChangeMessages M = GWT.create(ChangeMessages.class);
  public static final ChangeResources R = GWT.create(ChangeResources.class);

  public static final ChangeDetailService DETAIL_SVC;
  public static final ChangeListService LIST_SVC;
  public static final ChangeManageService MANAGE_SVC;

  static {
    DETAIL_SVC = GWT.create(ChangeDetailService.class);
    JsonUtil.bind(DETAIL_SVC, "rpc/ChangeDetailService");

    LIST_SVC = GWT.create(ChangeListService.class);
    JsonUtil.bind(LIST_SVC, "rpc/ChangeListService");

    MANAGE_SVC = GWT.create(ChangeManageService.class);
    JsonUtil.bind(MANAGE_SVC, "rpc/ChangeManageService");
  }

  public static String toLongString(final Change.Status status) {
    if (status == null) {
      return "";
    }
    switch (status) {
      case NEW:
        return C.statusLongNew();
      case SUBMITTED:
        return C.statusLongSubmitted();
      case MERGED:
        return C.statusLongMerged();
      case ABANDONED:
        return C.statusLongAbandoned();
      default:
        return status.name();
    }
  }
}


text:
package com.palantir.docker.compose.connection;

import static java.util.stream.Collectors.joining;

import com.google.common.base.Splitter;
import java.util.Arrays;
import java.util.List;
import org.immutables.value.Value;

@Value.Immutable
@SuppressWarnings("checkstyle:DesignForExtension")
public abstract class ContainerName {

    public abstract String rawName();

    public abstract String semanticName();

    @Override
    public String toString() {
        return semanticName();
    }

    public static ContainerName fromPsLine(String psLine) {
        List<String> lineComponents = Splitter.on(" ").splitToList(psLine);
        String rawName = lineComponents.get(0);

        if (probablyCustomName(rawName)) {
            return ImmutableContainerName.builder()
                    .rawName(rawName)
                    .semanticName(rawName)
                    .build();
        }

        String semanticName = withoutDirectory(withoutScaleNumber(rawName));
        return ImmutableContainerName.builder()
                .rawName(rawName)
                .semanticName(semanticName)
                .build();
    }

    private static boolean probablyCustomName(String rawName) {
        return !(rawName.split("_").length >= 3);
    }

    private static String withoutDirectory(String rawName) {
        return Arrays.stream(rawName.split("_")).skip(1).collect(joining("_"));
    }

    public static String withoutScaleNumber(String rawName) {
        String[] components = rawName.split("_");
        return Arrays.stream(components).limit(components.length - 1).collect(joining("_"));
    }
}


text:
namespace ozz {
namespace animation {
namespace offline {

// Forward declare offline track types.
struct RawFloatTrack;
struct RawFloat2Track;
struct RawFloat3Track;
struct RawFloat4Track;
struct RawQuaternionTrack;

// TrackOptimizer is responsible for optimizing an offline raw track instance.
// Optimization is a keyframe reduction process. Redundant and interpolable
// keyframes (within a tolerance value) are removed from the track. Default
// optimization tolerances are set in order to favor quality over runtime
// performances and memory footprint.
class TrackOptimizer {
 public:
  // Initializes the optimizer with default tolerances (favoring quality).
  TrackOptimizer();

  // Optimizes _input using *this parameters.
  // Returns true on success and fills _output track with the optimized
  // version of _input track.
  // *_output must be a valid Raw*Track instance.
  // Returns false on failure and resets _output to an empty track.
  // See Raw*Track::Validate() for more details about failure reasons.
  bool operator()(const RawFloatTrack& _input, RawFloatTrack* _output) const;
  bool operator()(const RawFloat2Track& _input, RawFloat2Track* _output) const;
  bool operator()(const RawFloat3Track& _input, RawFloat3Track* _output) const;
  bool operator()(const RawFloat4Track& _input, RawFloat4Track* _output) const;
  bool operator()(const RawQuaternionTrack& _input,
                  RawQuaternionTrack* _output) const;

  // Optimization tolerance.
  float tolerance;
};
}  // namespace offline
}  // namespace animation
}  // namespace ozz
#endif  // OZZ_OZZ_ANIMATION_OFFLINE_TRACK_OPTIMIZER_H_


text:
<?php

namespace App\Modules\Content\Controllers;

use App\Modules\Content\AbstractContentController;

Class Privacy extends AbstractContentController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $view = new \Zewa\View();
        $view->setView('privacy');
        $view->setLayout('marketplace');
        $view->setProperty($this->data);

        return $view->render();
    }
}


text:
package org.apache.camel.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * An XML parser that uses SAX to include line and column number for each XML element in the parsed Document.
 *

 * The line number and column number can be obtained from a Node/Element using
 *

 *   String lineNumber = (String) node.getUserData(XmlLineNumberParser.LINE_NUMBER);
 *   String lineNumberEnd = (String) node.getUserData(XmlLineNumberParser.LINE_NUMBER_END);
 *   String columnNumber = (String) node.getUserData(XmlLineNumberParser.COLUMN_NUMBER);
 *   String columnNumberEnd = (String) node.getUserData(XmlLineNumberParser.COLUMN_NUMBER_END);
 *

 */
public final class XmlLineNumberParser {

    public static final String LINE_NUMBER = "lineNumber";
    public static final String COLUMN_NUMBER = "colNumber";
    public static final String LINE_NUMBER_END = "lineNumberEnd";
    public static final String COLUMN_NUMBER_END = "colNumberEnd";

    /**
     * Allows to plugin a custom text transformer in the parser, that can transform all the text content
     */
    public interface XmlTextTransformer {

        String transform(String text);

    }

    private XmlLineNumberParser() {
    }

    /**
     * Parses the XML.
     *
     * @param is the XML content as an input stream
     * @return the DOM model
     * @throws Exception is thrown if error parsing
     */
    public static Document parseXml(final InputStream is) throws Exception {
        return parseXml(is, null);
    }

    /**
     * Parses the XML.
     *
     * @param is             the XML content as an input stream
     * @param xmlTransformer the XML transformer
     * @return the DOM model
     * @throws Exception is thrown if error parsing
     */
    public static Document parseXml(final InputStream is, final XmlTextTransformer xmlTransformer) throws Exception {
        return parseXml(is, xmlTransformer, null, null);
    }

    /**
     * Parses the XML.
     *
     * @param is              the XML content as an input stream
     * @param xmlTransformer  the XML transformer
     * @param rootNames       one or more root names that is used as baseline for beginning the parsing, for example camelContext to start parsing
     *                        when Camel is discovered. Multiple names can be defined separated by comma
     * @param forceNamespace  an optional namespaces to force assign to each node. This may be needed for JAXB unmarshalling from XML -> POJO.
     * @return the DOM model
     * @throws Exception is thrown if error parsing
     */
    public static Document parseXml(final InputStream is, XmlTextTransformer xmlTransformer, String rootNames, final String forceNamespace) throws Exception {
        ObjectHelper.notNull(is, "is");

        final XmlTextTransformer transformer = xmlTransformer == null ? new NoopTransformer() : xmlTransformer;
        final Document doc;
        SAXParser parser;
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        parser = factory.newSAXParser();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // turn off validator and loading external dtd
        dbf.setValidating(false);
        dbf.setNamespaceAware(true);
        dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        final DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        doc = docBuilder.newDocument();

        final Stack<Element> elementStack = new Stack<>();
        final StringBuilder textBuffer = new StringBuilder();
        final DefaultHandler handler = new DefaultHandler() {
            private Locator locator;
            private boolean found;

            @Override
            public void setDocumentLocator(final Locator locator) {
                this.locator = locator; // Save the locator, so that it can be used later for line tracking when traversing nodes.
                this.found = rootNames == null;
            }

            private boolean isRootName(String qName) {
                for (String root : rootNames.split(",")) {
                    if (qName.equals(root)) {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
                addTextIfNeeded();

                if (rootNames != null && !found) {
                    if (isRootName(qName)) {
                        found = true;
                    }
                }

                if (found) {
                    Element el;
                    if (forceNamespace != null) {
                        el = doc.createElementNS(forceNamespace, qName);
                    } else {
                        el = doc.createElement(qName);
                    }

                    for (int i = 0; i < attributes.getLength(); i++) {
                        el.setAttribute(transformer.transform(attributes.getQName(i)), transformer.transform(attributes.getValue(i)));
                    }

                    el.setUserData(LINE_NUMBER, String.valueOf(this.locator.getLineNumber()), null);
                    el.setUserData(COLUMN_NUMBER, String.valueOf(this.locator.getColumnNumber()), null);
                    elementStack.push(el);
                }
            }

            @Override
            public void endElement(final String uri, final String localName, final String qName) {
                if (!found) {
                    return;
                }

                addTextIfNeeded();

                final Element closedEl = elementStack.isEmpty() ? null : elementStack.pop();
                if (closedEl != null) {
                    if (elementStack.isEmpty()) {
                        // Is this the root element?
                        doc.appendChild(closedEl);
                    } else {
                        final Element parentEl = elementStack.peek();
                        parentEl.appendChild(closedEl);
                    }

                    closedEl.setUserData(LINE_NUMBER_END, String.valueOf(this.locator.getLineNumber()), null);
                    closedEl.setUserData(COLUMN_NUMBER_END, String.valueOf(this.locator.getColumnNumber()), null);
                }
            }

            @Override
            public void characters(final char ch[], final int start, final int length) throws SAXException {
                char[] chars = new char[length];
                System.arraycopy(ch, start, chars, 0, length);
                String s = new String(chars);
                s = transformer.transform(s);
                textBuffer.append(s);
            }

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
                // do not resolve external dtd
                return new InputSource(new StringReader(""));
            }

            // Outputs text accumulated under the current node
            private void addTextIfNeeded() {
                if (textBuffer.length() > 0) {
                    final Element el = elementStack.isEmpty() ? null : elementStack.peek();
                    if (el != null) {
                        final Node textNode = doc.createTextNode(textBuffer.toString());
                        el.appendChild(textNode);
                        textBuffer.delete(0, textBuffer.length());
                    }
                }
            }
        };
        parser.parse(is, handler);

        return doc;
    }

    private static final class NoopTransformer implements XmlTextTransformer {

        @Override
        public String transform(String text) {
            return text;
        }

    }

}


text:
def mock_env(remote_addr, path = '/')
  Rack::MockRequest.env_for path, { 'REMOTE_ADDR' => remote_addr }
end

def mock_deflecter(app, options = {})
  Deflectable::Watcher.new(app, options)
end


text:
package org.osc.core.broker.service.tasks.conformance.openstack.sfc;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;

import org.osc.core.broker.job.TaskGraph;
import org.osc.core.broker.model.entities.appliance.Appliance;
import org.osc.core.broker.model.entities.appliance.ApplianceSoftwareVersion;
import org.osc.core.broker.model.entities.appliance.DistributedAppliance;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.management.ApplianceManagerConnector;
import org.osc.core.broker.model.entities.management.Domain;
import org.osc.core.broker.model.entities.virtualization.SecurityGroup;
import org.osc.core.broker.model.entities.virtualization.ServiceFunctionChain;
import org.osc.core.broker.model.entities.virtualization.VirtualizationConnector;
import org.osc.core.broker.model.entities.virtualization.openstack.DeploymentSpec;
import org.osc.core.broker.model.sdn.PortPairGroupNetworkElementImpl;
import org.osc.core.common.virtualization.VirtualizationType;

public class CheckServiceFunctionChainMetaTaskTestData {
	public static boolean DB_POPULATED = false;

	static PortPairGroupNetworkElementImpl PPG_NETWORK_ELEMENT_MATCHING = new PortPairGroupNetworkElementImpl(
			"PORT_PAIR_GROUP");

	static PortPairGroupNetworkElementImpl PPG_NETWORK_ELEMENT_NOT_MATCHING = new PortPairGroupNetworkElementImpl(
			"PORT_PAIR_GROUP_NOT_MATCHING");

	private static final ServiceFunctionChain SERVICE_FUCNTION_CHAIN_CREATE = createSFC("CREATE");
	private static final ServiceFunctionChain SERVICE_FUCNTION_CHAIN_UPDATE = createSFC("UPDATE");
	private static final ServiceFunctionChain SG_DELETE_SERVICE_FUCNTION_CHAIN_DELETE = createSFC("DELETE");
	private static final VirtualizationConnector VIRTUALIZATION_CONNECTOR = createVC();

	static final SecurityGroup SECURITY_GROUP_SFC_BINDED_CREATE_SFC = createSG("SG_1", false,
			SERVICE_FUCNTION_CHAIN_CREATE, VIRTUALIZATION_CONNECTOR, "PROJECT_ID_1", null);
	static final SecurityGroup SECURITY_GROUP_SFC_BINDED_UPDATE_SFC = createSG("SG_2", false,
			SERVICE_FUCNTION_CHAIN_UPDATE, VIRTUALIZATION_CONNECTOR, "PROJECT_ID_2", "NETWORK_ELEMENT_ID_2");
	static final SecurityGroup SECURITY_GROUP_SFC_BINDED_DELETE_SFC = createSG("SG_3", false, null,
			VIRTUALIZATION_CONNECTOR, "PROJECT_ID_3", "NETWORK_ELEMENT_ID_3");
	static final SecurityGroup SECURITY_GROUP_MARK_DELETE_SFC_BINDED_DELETE_SFC = createSG("SG_4", true,
			SG_DELETE_SERVICE_FUCNTION_CHAIN_DELETE, VIRTUALIZATION_CONNECTOR, "PROJECT_ID_4", "NETWORK_ELEMENT_ID_4");

	public static TaskGraph createSFCGraph(SecurityGroup sg) {
		TaskGraph expectedGraph = new TaskGraph();

		expectedGraph.appendTask(
				new CreateServiceFunctionChainTask().create(sg, Arrays.asList(PPG_NETWORK_ELEMENT_MATCHING)));

		return expectedGraph;
	}

	public static TaskGraph updateSFCGraph(SecurityGroup sg) {
		TaskGraph expectedGraph = new TaskGraph();

		expectedGraph.appendTask(
				new UpdateServiceFunctionChainTask().create(sg, Arrays.asList(PPG_NETWORK_ELEMENT_MATCHING)));

		return expectedGraph;
	}

	public static TaskGraph deleteSFCGraph(SecurityGroup sg) {
		TaskGraph expectedGraph = new TaskGraph();

		expectedGraph.appendTask(new DeleteServiceFunctionChainTask().create(sg));

		return expectedGraph;
	}

	static void persist(SecurityGroup sg, EntityManager em) {
		VirtualizationConnector vc = sg.getVirtualizationConnector();
		Set<VirtualSystem> virtualSystems = vc.getVirtualSystems();
		ServiceFunctionChain sfc = sg.getServiceFunctionChain();
		// If the entity already has an id it already has been persisted.
		if (sg.getId() == null) {
			if (vc.getId() == null) {
				em.persist(vc);
			}
			em.persist(sg);
			if (sfc != null && sfc.getId() == null) {
				em.persist(sfc);
			}

			for (VirtualSystem vs : virtualSystems) {
				em.persist(vs.getDomain().getApplianceManagerConnector());
				em.persist(vs.getApplianceSoftwareVersion().getAppliance());
				em.persist(vs.getApplianceSoftwareVersion());
				em.persist(vs.getDistributedAppliance());
				em.persist(vs.getDomain());
				em.persist(vs);
				for (DeploymentSpec ds : vs.getDeploymentSpecs()) {
					em.persist(ds);
				}
			}
		}
	}

	private static ServiceFunctionChain createSFC(String name) {
		ServiceFunctionChain sfc = new ServiceFunctionChain();
		sfc.setName(name);
		return sfc;
	}

	private static VirtualizationConnector createVC() {
		VirtualizationConnector vc = new VirtualizationConnector();
		vc.setName("vc");
		vc.setVirtualizationType(VirtualizationType.OPENSTACK);
		vc.setVirtualizationSoftwareVersion("vcSoftwareVersion");
		vc.setProviderIpAddress("providerIp");
		vc.setProviderUsername("foo");
		vc.setProviderPassword("********");
		return vc;
	}

	private static SecurityGroup createSG(String baseName, boolean markedForDeletion, ServiceFunctionChain sfc,
			VirtualizationConnector vc, String projectId, String networkElementId) {
		VirtualSystem vs = createVirtualSystem(baseName, "NSM", vc, projectId);

		SecurityGroup sg = new SecurityGroup(vs.getVirtualizationConnector(), projectId, "PROJECT_NAME");
		sg.setName(baseName + "_sg");
		sg.setNetworkElementId(networkElementId);
		sg.setMarkedForDeletion(markedForDeletion);

		if (sfc != null) {
			sfc.addVirtualSystem(vs);
			sfc.setVirtualizationConnector(vs.getVirtualizationConnector());
			sg.setServiceFunctionChain(sfc);
		}

		return sg;
	}

	private static VirtualSystem createVirtualSystem(String baseName, String mgrType, VirtualizationConnector vc,
			String projectId) {
		ApplianceManagerConnector mc = new ApplianceManagerConnector();
		mc.setIpAddress(baseName + "_mcIp");
		mc.setName(baseName + "_mc");
		mc.setServiceType("foobar");
		mc.setManagerType(mgrType.toString());

		Domain domain = new Domain(mc);
		domain.setName(baseName + "_domain");
		vc.setAdminDomainId(domain.getName());

		Appliance app = new Appliance();
		app.setManagerSoftwareVersion("fizz");
		app.setManagerType(mgrType);
		app.setModel(baseName + "_model");

		ApplianceSoftwareVersion asv = new ApplianceSoftwareVersion(app);
		asv.setApplianceSoftwareVersion("softwareVersion");
		asv.setImageUrl(baseName + "_image");
		asv.setVirtualizarionSoftwareVersion(vc.getVirtualizationSoftwareVersion());
		asv.setVirtualizationType(vc.getVirtualizationType());

		DistributedAppliance da = new DistributedAppliance(mc);
		da.setName(baseName + "_da");
		da.setApplianceVersion("foo");
		da.setAppliance(app);

		VirtualSystem vs = new VirtualSystem(da);
		vs.setApplianceSoftwareVersion(asv);
		vs.setDomain(domain);
		vs.setVirtualizationConnector(vc);
		vs.setMarkedForDeletion(false);
		vs.setName(baseName + "_vs");
		vs.setMgrId(baseName + "_mgrId");

		DeploymentSpec ds = new DeploymentSpec(vs, "RegionOne", projectId, null, null, null);
		ds.setName(baseName + "_ds");
		ds.setPortGroupId("PORT_PAIR_GROUP");
		ds.setInstanceCount(1);

		vs.setDeploymentSpecs(new HashSet<>(Arrays.asList(ds)));

		vc.getVirtualSystems().add(vs);
		return vs;
	}

}


text:
Source of [thlorenz.com](http://thlorenz.com)

## What is this?

thlorenz.com is a static site built with [Metalsmith](http://www.metalsmith.io/).

Find more information how this works at [github
help](https://help.github.com/articles/setting-up-a-custom-domain-with-github-pages/).

## License

MIT


text:
Piwik is the leading Free/Libre open analytics platform.

Piwik is a full featured PHP MySQL software program that you download and install on your own webserver.
At the end of the five minute installation process you will be given a JavaScript code.
Simply copy and paste this tag on websites you wish to track and access your analytics reports in real time.

Piwik aims to be a Free software alternative to Google Analytics, and is already used on more than 1,000,000 websites. Privacy is built-in!

## Mission Statement

> « To create, as a community, the leading international Free/Libre web analytics platform, providing access to all functionality through open components and open APIs. »

Or in short:
> « Liberate Web Analytics »

## License

Piwik is released under the GPL v3 (or later) license, see [misc/gpl-3.0.txt](misc/gpl-3.0.txt)

## Requirements

  * PHP 5.3.2 or greater
  * MySQL 4.1 or greater, and either MySQLi or PDO library must be enabled
  * Piwik is OS / server independent

See http://piwik.org/docs/requirements/

## Install

  * Upload piwik to your webserver
  * Point your browser to the directory
  * Follow the steps
  * Add the given javascript code to your pages
  * (You may also generate fake data to experiment, by enabling the plugin VisitorGenerator)

See http://piwik.org/docs/installation/

If you do not have a server, consider our Piwik Hosting partner: http://piwik.org/hosting/

## Changelog

For the list of all tickets closed in the current and past releases, see http://piwik.org/changelog/. For the list of technical changes in the Piwik platform, see [http://developer.piwik.org/changelog](http://developer.piwik.org/changelog).

## Participate!

We believe in liberating Web Analytics, providing a free platform for simple and advanced analytics. Piwik was built by dozens of people like you,
and we need your help to make Piwik better… Why not participate in a useful project today?

You will find pointers on how you can participate in Piwik at http://piwik.org/get-involved/

## Contact

http://piwik.org

hello@piwik.org

About us: http://piwik.org/the-piwik-team/

## More information

What makes Piwik unique from the competition:

  * Real time web analytics reports: in Piwik, reports are by default generated in real time.
    For high traffic websites, you can choose the frequency for reports to be processed.

  * You own your web analytics data: since Piwik is installed on your server, the data is stored in your own database and you can get all the statistics
  using the powerful Piwik Analytics API.

  * Piwik is a Free Software which can easily be configured to respect your visitors privacy.

  * Modern, easy to use User Interface: you can fully customize your dashboard, drag and drop widgets and more.

  * Piwik features are built inside plugins: you can add new features and remove the ones you don't need.
    You can build your own web analytics plugins or hire a consultant to have your custom feature built in Piwik

  * Vibrant international Open community of more than 200,000 active users (tracking even more websites!)

  * Advanced Web Analytics capabilities such as Ecommerce Tracking, Goal tracking, Campaign tracking,
    Custom Variables, Email Reports, Custom Segment Editor, Geo Location, Real time maps, and more!

Documentation and more info on http://piwik.org

## We're seeking a talented Software Engineer

Are you looking for a new challenge? We are currently seeking a software engineer or software developer who is passionate about data processing, security, privacy, the open source and free/libre philosophy and usable interface design.

[View Job Description](http://piwik.org/blog/2014/05/piwik-expanding-seeking-talented-software-engineer-new-zealand-poland/) - [Apply online](http://piwik.org/jobs/)

We are grateful if you can share the Job Description with your friends and colleagues. We can help the right candidate relocate to beautiful New Zealand.

## Code Status
The Piwik project uses an ever-expanding comprehensive set of thousands of unit tests and dozens of integration [tests](https://github.com/piwik/piwik/tree/master/tests),
 running on the hosted distributed continuous integration platform Travis-CI.

Build status (master branch) [![Build Status](https://travis-ci.org/piwik/piwik.png?branch=master)](https://travis-ci.org/piwik/piwik) - Screenshot tests Build  [![Build Status](https://travis-ci.org/piwik/piwik-ui-tests.png?branch=master)](https://travis-ci.org/piwik/piwik-ui-tests)

Code Coverage: [![Coverage Status](https://coveralls.io/repos/piwik/piwik/badge.png?branch=master)](https://coveralls.io/r/piwik/piwik?branch=master)

Issue tracker metrics: [![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/piwik/piwik.svg)](http://isitmaintained.com/project/piwik/piwik "Average time to resolve an issue") - [![Percentage of issues still open](http://isitmaintained.com/badge/open/piwik/piwik.svg)](http://isitmaintained.com/project/piwik/piwik "Percentage of issues still open")


text:
class ChangeDateContactedToDateInWaitingLists < ActiveRecord::Migration
  def change
    reversible do |dir|
      change_table :waiting_lists do |t|
        dir.up do
          t.change :date_contacted, :date
        end
        dir.down { t.change :date_contacted, :datetime }
      end
    end
  end
end


text:
/**
 * Tap Change component.
 * User can change the Keg on a Tap.
 */

import React from 'react';
import reactPropTypes from 'prop-types';
import { Container } from 'flux/utils';

import tapChangeStore from '../../stores/tap-change';
import { fetchTapWithKegs, changeTap } from '../../actions/taps';

import Loader from '../loader';

// return the passed string or null if empty.
function stringOrNull(str) {
  return str === '' ? null : str;
}

// same as above but convert to number
function numberOrNull(str) {
  return str === '' ? null : Number(str);
}

class TapChange extends React.Component {

  constructor() {
    super();
    this.state = {
      tapped: '',
      untapped: '',
      kegId: null,
    };

    this.selectChangeHandler = this.selectChangeHandler.bind(this);
    this.inputChangeHandler = this.inputChangeHandler.bind(this);
    this.saveAction = this.saveAction.bind(this);
  }

  selectChangeHandler(evt) {
    this.setState({
      kegId: evt.target.value,
    });
  }

  inputChangeHandler(evt) {
    this.setState(Object.assign(this.state, {
      [evt.target.name]: evt.target.value,
    }));
  }

  saveAction() {
    const { tapped, untapped, kegId } = this.state;

    const payload = {
      tapId: this.props.tap.id,
      tapped: stringOrNull(tapped),
      untapped: stringOrNull(untapped),
      kegId: numberOrNull(kegId),
    };

    return changeTap(payload)
    .then(() => {
      document.location.hash = '/taps/';
    });
  }

  render() {
    const { kegs, tap, fetching } = this.props;

    const { tapped, untapped, kegId } = this.state;

    if (!tap || fetching) {
      return <Loader />;
    }

    const { Keg } = tap;

    return (

{tap.name}

        {Keg ? (

Currently on tap

{Keg ? Keg.Beer.name : 'No Service'}

              {Keg.Beer.variety && `${Keg.Beer.variety} `}
              by {Keg.Beer.Brewery.name}

        ) : (

No Service

        )}

Change tap

          New Keg
          <select onChange={this.selectChangeHandler} value={kegId} name="kegId">
            <option value="">None (Untap current keg)</option>
            <option disabled="true">-----</option>
            { kegs.map(keg => (
              <option
                key={keg.id}
                value={keg.id}
                disabled={keg.Tap}
              >{keg.Beer.name} ({keg.Beer.Brewery.name})</option>
            )) }
          </select>

          New Keg Tapped Date (YYYY-MM-DD)
          <input name="tapped" value={tapped} onChange={this.inputChangeHandler} />

          Old Keg Untapped Date (YYYY-MM-DD)
          <input name="untapped" value={untapped} onChange={this.inputChangeHandler} />

          <button className="btn" onClick={this.saveAction}>Save</button>

    );
  }
}

class TapChangeContainer extends React.Component {
  static propTypes() {
    return {
      tapId: reactPropTypes.number,
    };
  }

  static getStores() {
    return [tapChangeStore];
  }

  static calculateState() {
    return tapChangeStore.getState();
  }

  componentWillMount() {
    fetchTapWithKegs(this.props.tapId);
  }

  render() {
    return <TapChange kegs={this.state.kegs} tap={this.state.tap} profile={this.state.profile} />
  }
}

export default Container.create(TapChangeContainer, { withProps: true });


text:
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;

namespace MyPersonalShortner.ShortnerApp.NinjectWebApi
{
	public class NinjectResolver : NinjectScope, IDependencyResolver
	{
		private IKernel _kernel;
		public NinjectResolver(IKernel kernel)
			: base(kernel)
		{
			_kernel = kernel;
		}
		public IDependencyScope BeginScope()
		{
			return new NinjectScope(_kernel.BeginBlock());
		}
	}
}


text:
import sys
from collections import namedtuple
from logging import getLogger
from .domecab import do_mecab, do_mecab_iter

logger = getLogger(__name__)

Token = namedtuple("Token", [
    "surface"
    ,"pos"
    ,"pos1"
    ,"pos2"
    ,"pos3"
    ,"infl_type"
    ,"infl_form"
    ,"baseform"
    ,"reading"
    ,"phoenetic"
    # additional info available for unidic dictionary
    ,"lemma"          # goiso
    ,"lemma_reading"  # goiso reading
])

def str_token(token):
    fmt = u"%s\t" + u",".join([u"%s"] * (len(token)-1))
    return fmt % tuple([u"*" if t is None else t for t in token])

def print_token(token):
    print(str_token(token))

def mecab_batch_iter(x, dictionary=None, mecab_enc=None, unidic_format=None,
                     format_func=None, pos_filter=None, filter_func=None, separators=None,
                     **kwargs):
    """
    Tokenize a batch of strings

    :param x:              list of strings to parse
    :param mecab_enc:      encoding mecab dictionary;
                           if None, automatically detected
    :param dictionary:     system dictionary directory
                           folder name is allowed if it is in mecab's dicdir
    :param unidic_format:  bool indicating if the dictionary is in unidic format
    :param format_func:    function Token->Any to parse token
    :param pos_filter:     list of part-of-speeches to keep
    :param filter_func:    function Token->bool to filter tokens
    :param separators:     Strings or length 2. (token_sep, info_sep).
                           These should be strings that do not appear in data.
                           If None, automatically chosen from unicode upto 100
    :param kwargs:         Optional arguments passed to do_mecab_iter.

    :return:               generator of list of tokens
    """
    def _find_safe_separators(x, n=2):
        seps = []
        for i in range(1, 100):
            if len(seps) >= n:
                logger.debug("Chosen separators: %s (decimal code %s)",
                             seps[0:n], [ord(s) for s in seps])
                return seps[0:n]
            candidate = chr(i)
            flg = True
            for a in x:
                if a.find(candidate) >= 0:
                    flg = False
                    break
            if flg:
                seps.append(candidate)
        logger.error("Could not find a good separators")
        raise ValueError("Could not find a good separators." + \
                         "Please explicitly specify `separators=(tokensep, infosep)`.")
    if separators is None:
        tokensep, infosep = _find_safe_separators(x, n=2)
    else:
        tokensep, infosep = separators

    if unidic_format is None and \
        (dictionary is not None and dictionary.find("unidic") >= 0):
        print("`unidic_format` is set to true")
        unidic_format = True

    if unidic_format:
        tmp = ["%m"] + ["%f[{}]".format(i) for i in range(6)] + \
          ["%f[10]", "", "%f[9]"] + ["%f[7]", "%f[6]"]
        out_format = "-F{}{}".format(infosep.join(tmp), tokensep)
        tmp = ["%m"] + ["%f[{}]".format(i) for i in range(6)] + [""] * 5
        unk_format = "-U{}{}".format(infosep.join(tmp), tokensep)
    else:
        tmp = ["%m"] + ["%f[{}]".format(i) for i in range(9)] + [""] * 2
        out_format = "-F{}{}".format(infosep.join(tmp), tokensep)
        tmp = ["%m"] + ["%f[{}]".format(i) for i in range(7)] + [""] * 4
        unk_format = "-U{}{}".format(infosep.join(tmp), tokensep)

    def _to_token(line):
        infos = line.split(infosep)
        if len(infos) < 2:
            # skip EOS line
            return None
        if len(infos) != 12:
            raise ValueError("Assume all lines have 12 elements, but got {} from {}".format(
                len(infos), line))

        infos = [None if i=="" else i for i in infos]
        if len(infos) == 12:
            return Token(*infos)
        raise ValueError()

    for doc in do_mecab_iter(x, "-E ", out_format, unk_format,
                             dictionary=dictionary, mecab_enc=mecab_enc,
                             **kwargs):
        lines = doc.split(tokensep)
        tokens = [_to_token(line) for line in lines]
        tokens = [t for t in tokens if t is not None]
        if filter_func is not None:
            tokens = [t for t in tokens if filter_func(t)]
        if pos_filter is not None:
            pos_filter = set(pos_filter)
            tokens = [t for t in tokens if t.pos in pos_filter]
        if format_func is not None:
            tokens = [format_func(t) for t in tokens]
        yield tokens

def mecab_batch(x, dictionary=None, mecab_enc=None, unidic_format=None,
                format_func=None, pos_filter=None, filter_func=None, separators=None,
                **kwargs):
    """
    Tokenize a batch of strings

    :param x:              list of strings to parse
    :param mecab_enc:      encoding mecab dictionary;
                           if None, automatically detected
    :param dictionary:     system dictionary directory
                           folder name is allowed if it is in mecab's dicdir
    :param unidic_format:  bool indicating if the dictionary is in unidic format
    :param format_func:    function Token->Any to parse token
    :param pos_filter:     list of part-of-speeches to keep
    :param filter_func:    function Token->bool to filter tokens
    :param separators:     Strings or length 2. (token_sep, info_sep).
                           These should be strings that do not appear in data.
                           If None, automatically chosen from unicode upto 100
    :param kwargs:         Optional arguments passed to do_mecab_iter.

    :return:               list of list of tokens
    """
    return list(mecab_batch_iter(
        x, dictionary=dictionary, mecab_enc=mecab_enc, unidic_format=unidic_format,
        format_func=format_func, pos_filter=pos_filter, filter_func=filter_func,
        separators=separators, **kwargs))

class MecabTokenizer:
    def __init__(self, dictionary=None, mecab_enc=None, unidic_format=None,
                 format_func=None, pos_filter=None, filter_func=None,
                 return_generator=False, **kwargs):
        self.dictionary = dictionary
        self.mecab_enc = mecab_enc
        self.unidic_format = unidic_format
        self.format_func = format_func
        self.pos_filter = pos_filter
        self.filter_func = filter_func
        self.return_generator = return_generator
        self.kwargs = kwargs
    """
    Scikit-learn compatible tokenizer for a batch of strings

    :param mecab_enc:        encoding mecab dictionary;
                             if None, automatically detected
    :param dictionary:       system dictionary directory
                             folder name is allowed if it is in mecab's dicdir
    :param unidic_format:    bool indicating if the dictionary is in unidic format
    :param format_func:      function Token->Any to parse token
    :param pos_filter:       list of part-of-speeches to keep
    :param filter_func:      function Token->bool to filter tokens
    :param return_generator: bool indicating if transformer should return a generator
                             if false, returns a list
    :param kwargs:           Optional arguments passed to do_mecab_iter.
    """
    def fit_transform(self, X, y=None, **fit_params):
        return self.transform(X)

    def fit(self, X, y=None):
        # there is nothing to fit
        return self

    def transform(self, X):
        if self.return_generator:
            return mecab_batch_iter(X,
                                    dictionary=self.dictionary,
                                    mecab_enc=self.mecab_enc,
                                    unidic_format=self.unidic_format,
                                    format_func=self.format_func,
                                    pos_filter=self.pos_filter,
                                    filter_func=self.filter_func,
                                    **self.kwargs)
        else:
            return mecab_batch(X,
                               dictionary=self.dictionary,
                               mecab_enc=self.mecab_enc,
                               unidic_format=self.unidic_format,
                               format_func=self.format_func,
                               pos_filter=self.pos_filter,
                               filter_func=self.filter_func,
                               **self.kwargs)

def tokenize(x, mecab_enc=None, sysdic=None, userdic=None, **kwargs):
    """
    Tokenize a string

    :param x:         unicode string
    :param mecab_enc: encoding mecab dictionary;
                      if None, automatically detected
    :param sysdic:    system dictionary directory
    :param userdic:   user dictionary file
    :param kwargs:    Optional arguments passed to do_mecab_iter.

    :return:          List of tokens
    """

    # collect mecab options
    opts = []
    if sysdic is not None:
        opts += ['-d', sysdic]
    if userdic is not None:
        opts += ['-u', userdic]

    res = mecab_batch([x], *opts, mecab_enc=mecab_enc, **kwargs)
    if len(res) > 0:
        return res[0]
    else:
        return []


text:
using System;
using System.Reflection;

namespace AspNetIdentityDependencyInjectionSample.Areas.HelpPage.ModelDescriptions
{
    public interface IModelDocumentationProvider
    {
        string GetDocumentation(MemberInfo member);

        string GetDocumentation(Type type);
    }
}


text:
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 5000;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');

var configDB = require('./config/database.js');
var users = require('./app/models/user.js');
var _ = require('lodash')
var voters;
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration
 users.find(function(err,users){

                voters = _.map(users,function(user){
                    return {vote:user.facebook.vote,name:user.facebook.name};
                })
                require('./app/routes.js')(app, passport,voters); // load our routes and pass in our app and fully configured passport
                // console.log(voters)
            })
// set up our express application
// app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/app/'));
app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================

// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);


text:
require_relative File.expand_path("../argosnap/version", __FILE__)
require_relative File.expand_path("../argosnap/install", __FILE__)
require_relative File.expand_path("../argosnap/config", __FILE__)
require_relative File.expand_path("../argosnap/helpers", __FILE__)
require_relative File.expand_path("../argosnap/balance", __FILE__)
require_relative File.expand_path("../argosnap/notifications", __FILE__)