<commit_before>'use strict'

// Setup
const JsAudio = require('./lib/jsaudio');
const JsAudioNative = require('./lib/jsaudio').JsAudioNative;
const JsPaStream = JsAudio.JsPaStream;
const formats = {
  paFloat32: 1,
  paInt32: 2,
  paInt24: 4,
  paInt16: 8,
  paInt8: 16,
  paUInt8: 32,
  paCustomFormat: 65536,
  paNonInterleaved: 2147483648
};
var streamOpts = {
  input: {
    device: 1,
    channelCount: 2,
    sampleFormat: formats.paFloat32,
    suggestedLatency: 0.09
  },
  output: {
    device: 10,
    channelCount: 2,
    sampleFormat: formats.paFloat32,
    suggestedLatency: 0.09
  },
  sampleRate: 44100,
  framesPerBuffer: 4096,
  streamFlags: 0
};

var stream = new JsPaStream();
streamOpts.stream = stream;
// Exports
module.exports = JsAudio;

// Test stuff, for now, needs to go into actual test assertions later
let jsAudio = JsAudio.new();
jsAudio
  .on('error', (e) => { console.log(e.stack) })
  .on('initialize-done', () => { console.log('initialized successfully!') })
  .on('get-version-done', (version) => { console.log(version) })
  .on('test-params-done', console.log)
  .on('get-host-api-count-done', console.log)
  .on('get-default-host-api-done', console.log)
  .on('get-host-api-info-done', console.log)
  .on('get-device-count-done', console.log)
  .on('get-default-input-device-done', console.log)
  .on('get-default-output-device-done', console.log)
  .on('get-device-info-done', console.log)
  .on('open-stream-done', console.log)
  .on('start-stream-done', console.log)
  .on('get-stream-write-available-done', console.log);

jsAudio.initialize();
jsAudio.getVersion();
jsAudio.getHostApiCount();
jsAudio.getDefaultHostApi();
jsAudio.getHostApiInfo();
jsAudio.getDeviceCount();
jsAudio.getDefaultInputDevice();
jsAudio.getDefaultOutputDevice();
jsAudio.getDeviceInfo(1);
jsAudio.getDeviceInfo(10);
jsAudio.openStream(streamOpts);
jsAudio.startStream(stream);

var buffer;
setTimeout(() => {
    var framesToWrite = 0,
        phase = 0,
        phaseIncrement = (2 * Math.PI * 80) / 44100.0;
    while(1) {
        framesToWrite = JsAudioNative.getStreamWriteAvailable(stream);
        if(framesToWrite === 0)
            continue;
        console.log(framesToWrite);
        buffer = new Float32Array(framesToWrite * 2);
        for(var i = 0; i <= framesToWrite; i++){
            buffer[i * 2] = Math.cos(phase) * 2 - 1;
            buffer[i * 2 + 1] = Math.cos(phase * 2) * 2 - 1;

            phase += phaseIncrement;
        }

        JsAudioNative.writeStream(stream, buffer);
    }
}, 1000);

<commit_msg>Code style edit<commit_after>'use strict'

// Setup
const JsAudio = require('./lib/jsaudio')
const JsAudioNative = require('./lib/jsaudio').JsAudioNative
const JsPaStream = JsAudio.JsPaStream
const formats = {
  paFloat32: 1,
  paInt32: 2,
  paInt24: 4,
  paInt16: 8,
  paInt8: 16,
  paUInt8: 32,
  paCustomFormat: 65536,
  paNonInterleaved: 2147483648
}
var streamOpts = {
  input: {
    device: 1,
    channelCount: 2,
    sampleFormat: formats.paFloat32,
    suggestedLatency: 0.09
  },
  output: {
    device: 10,
    channelCount: 2,
    sampleFormat: formats.paFloat32,
    suggestedLatency: 0.09
  },
  sampleRate: 44100,
  framesPerBuffer: 4096,
  streamFlags: 0
}

var stream = new JsPaStream()
streamOpts.stream = stream
// Exports
module.exports = JsAudio

// Test stuff, for now, needs to go into actual test assertions later
let jsAudio = JsAudio.new()
jsAudio
  .on('error', (e) => { console.log(e.stack) })
  .on('initialize-done', () => { console.log('initialized successfully!') })
  .on('get-version-done', (version) => { console.log(version) })
  .on('test-params-done', console.log)
  .on('get-host-api-count-done', console.log)
  .on('get-default-host-api-done', console.log)
  .on('get-host-api-info-done', console.log)
  .on('get-device-count-done', console.log)
  .on('get-default-input-device-done', console.log)
  .on('get-default-output-device-done', console.log)
  .on('get-device-info-done', console.log)
  .on('open-stream-done', console.log)
  .on('start-stream-done', console.log)
  .on('get-stream-write-available-done', console.log)

jsAudio.initialize()
jsAudio.getVersion()
jsAudio.getHostApiCount()
jsAudio.getDefaultHostApi()
jsAudio.getHostApiInfo()
jsAudio.getDeviceCount()
jsAudio.getDefaultInputDevice()
jsAudio.getDefaultOutputDevice()
jsAudio.getDeviceInfo(1)
jsAudio.getDeviceInfo(10)
jsAudio.openStream(streamOpts)
jsAudio.startStream(stream)

var buffer
setTimeout(() => {
  var framesToWrite = 0,
    phase = 0,
    phaseIncrement = (2 * Math.PI * 80) / 44100.0;
  while(1) {
    framesToWrite = JsAudioNative.getStreamWriteAvailable(stream);
    if(framesToWrite === 0)
      continue;
    console.log(framesToWrite);
    buffer = new Float32Array(framesToWrite * 2);
    for(var i = 0; i <= framesToWrite; i++){
      buffer[i * 2] = Math.cos(phase) * 2 - 1;
      buffer[i * 2 + 1] = Math.cos(phase * 2) * 2 - 1;

      phase += phaseIncrement;
    }

    JsAudioNative.writeStream(stream, buffer);
  }
}, 1000)

<|endoftext|>


<commit_before>//http://en.wikipedia.org/wiki/Haversine_formula
//http://www.movable-type.co.uk/scripts/latlong.html
var point = require('turf-point');

/**
 * Takes a {@link Point} feature and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
 *
 * @module turf/destination
 * @param {Point} start a Point feature at the starting point
 * @param {Number} distance distance from the starting point
 * @param {Number} bearing ranging from -180 to 180
 * @param {String} units miles, kilometers, degrees, or radians
 * @returns {Point} a Point feature at the destination
 * @example
 * var point1 = turf.point([-75.343, 39.984]);
 * var distance = 50;
 * var bearing = 90;
 * var units = 'miles';
 *
 * var destination = turf.destination(point1, distance, bearing, units);
 * point1.properties['marker-color'] = '#0f0';
 * destination.properties['marker-color'] = '#f00';
 *
 * var result = turf.featurecollection([point1, destination]);
 *
 * //=result
 */
module.exports = function (point1, distance, bearing, units) {
    var coordinates1 = point1.geometry.coordinates;
    var longitude1 = toRad(coordinates1[0]);
    var latitude1 = toRad(coordinates1[1]);
    var bearing_rad = toRad(bearing);

    var R = 0;
    switch (units) {
    case 'miles':
        R = 3960;
        break
    case 'kilometers':
        R = 6373;
        break
    case 'degrees':
        R = 57.2957795;
        break
    case 'radians':
        R = 1;
        break
    }

    var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(distance / R) +
        Math.cos(latitude1) * Math.sin(distance / R) * Math.cos(bearing_rad));
    var longitude2 = longitude1 + Math.atan2(Math.sin(bearing_rad) * Math.sin(distance / R) * Math.cos(latitude1),
        Math.cos(distance / R) - Math.sin(latitude1) * Math.sin(latitude2));

    return point([toDeg(longitude2), toDeg(latitude2)]);
};

function toRad(degree) {
    return degree * Math.PI / 180;
}

function toDeg(rad) {
    return rad * 180 / Math.PI;
}
<commit_msg>Switch example to geojson primitives<commit_after>//http://en.wikipedia.org/wiki/Haversine_formula
//http://www.movable-type.co.uk/scripts/latlong.html
var point = require('turf-point');

/**
 * Takes a {@link Point} feature and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
 *
 * @module turf/destination
 * @param {Point} start a Point feature at the starting point
 * @param {Number} distance distance from the starting point
 * @param {Number} bearing ranging from -180 to 180
 * @param {String} units miles, kilometers, degrees, or radians
 * @returns {Point} a Point feature at the destination
 * @example
 * var point = {
 *   "type": "Feature",
 *   "properties": {
 *     "marker-color": "#0f0"
 *   },
 *   "geometry": {
 *     "type": "Point",
 *     "coordinates": [-75.343, 39.984]
 *   }
 * };
 * var distance = 50;
 * var bearing = 90;
 * var units = 'miles';
 *
 * var destination = turf.destination(point, distance, bearing, units);
 * destination.properties['marker-color'] = '#f00';
 *
 * var result = {
 *   "type": "FeatureCollection",
 *   "features": [point, destination]
 * };
 *
 * //=result
 */
module.exports = function (point1, distance, bearing, units) {
    var coordinates1 = point1.geometry.coordinates;
    var longitude1 = toRad(coordinates1[0]);
    var latitude1 = toRad(coordinates1[1]);
    var bearing_rad = toRad(bearing);

    var R = 0;
    switch (units) {
    case 'miles':
        R = 3960;
        break
    case 'kilometers':
        R = 6373;
        break
    case 'degrees':
        R = 57.2957795;
        break
    case 'radians':
        R = 1;
        break
    }

    var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(distance / R) +
        Math.cos(latitude1) * Math.sin(distance / R) * Math.cos(bearing_rad));
    var longitude2 = longitude1 + Math.atan2(Math.sin(bearing_rad) * Math.sin(distance / R) * Math.cos(latitude1),
        Math.cos(distance / R) - Math.sin(latitude1) * Math.sin(latitude2));

    return point([toDeg(longitude2), toDeg(latitude2)]);
};

function toRad(degree) {
    return degree * Math.PI / 180;
}

function toDeg(rad) {
    return rad * 180 / Math.PI;
}
<|endoftext|>


<commit_before>/* jshint ignore:start */
'use strict';

const BbPromise = require('bluebird');
const _ = require('lodash');
const path = require('path');
const fse = require('fs-extra');
const {spawnSync} = require('child_process');
const zipDirectory = require('./zipService').zipDirectory;

BbPromise.promisifyAll(fse);

/**
 * Plugin for Serverless 1.x that bundles python requirements!
 */
class ServerlessPythonRequirements {
  /**
   * add the vendor helper to the current service tree
   * @return {Promise}
   */
  addVendorHelper() {
    if (this.custom().zip) {
      this.serverless.cli.log('Adding Python requirements helper...');

      this.serverless.service.package.include.push('unzip_requirements.py');

      return fse.copyAsync(
        path.resolve(__dirname, 'unzip_requirements.py'),
        path.join(this.serverless.config.servicePath, 'unzip_requirements.py'));
    }
  };

  /**
   * remove the vendor helper from the current service tree
   * @return {Promise}
   */
  removeVendorHelper() {
    if (this.custom().zip && this.custom().cleanupZipHelper) {
      this.serverless.cli.log('Removing Python requirements helper...');
      return fse.removeAsync('unzip_requirements.py');
    }
  };

  /**
   * pip install the requirements to the .requirements directory
   * @return {Promise}
   */
  installRequirements() {
    const fileName = this.custom().fileName || 'requirements.txt';
    if (!fse.existsSync(path.join(this.serverless.config.servicePath,
                                  fileName))) {
      return BbPromise.resolve();
    }

    const runtime = this.serverless.service.provider.runtime;
    const pythonBin = this.custom().pythonBin || runtime;
    this.serverless.cli.log(
      `Installing required Python packages for runtime ${runtime}...`);

    return new BbPromise((resolve, reject) => {
      let cmd;
      let options;
      const pipCmd = [
        pythonBin, '-m', 'pip', '--isolated', 'install',
        '-t', '.requirements', '-r', fileName,
      ];
      if (this.custom().pipCmdExtraArgs) {
        pipCmd.push(...this.custom().pipCmdExtraArgs);
      }
      if (!this.custom().dockerizePip) {
        // Check if pip has Debian's --system option and set it if so
        const pipTestRes = spawnSync(
          pythonBin, ['-m', 'pip', 'help', 'install']);
          if (pipTestRes.error) {
            if (pipTestRes.error.code === 'ENOENT')
              return reject(`${pythonBin} not found! ` +
                            'Try the pythonBin option.');
            return reject(pipTestRes.error);
          }
        if (pipTestRes.stdout.toString().indexOf('--system') >= 0)
          pipCmd.push('--system');
      }
      if (this.custom().dockerizePip) {
        cmd = 'docker';

        const image = this.custom().dockerImage
         || `lambci/lambda:build-${runtime}`;
        this.serverless.cli.log(`Docker Image: ${image}`);

        options = [
          'run', '--rm',
          '-v', `${this.serverless.config.servicePath}:/var/task:z`,
          `${image}`,
        ];
        if (process.platform === 'linux')
          options.push('-u', `${process.getuid()}:${process.getgid()}`);
        options.push(...pipCmd);
      } else {
        cmd = pipCmd[0];
        options = pipCmd.slice(1);
      }
      const res = spawnSync(cmd, options);
      if (res.error) {
        if (res.error.code === 'ENOENT')
          return reject(`${pythonBin} not found! Try the pythonBin option.`);
        return reject(res.error);
      }
      if (res.status != 0)
        return reject(res.stderr);
      resolve();
    });
  };

  /**
   * zip up .requirements
   * @return {Promise}
   */
  packRequirements() {
    return this.installRequirements().then(() => {
      if (this.custom().zip) {
        this.serverless.cli.log('Zipping required Python packages...');
        this.serverless.service.package.include.push('.requirements.zip');
        return zipDirectory('.requirements', '.requirements.zip');
      }
    });
  }

  /**
   * link all the files in .requirements to the service directory root
   * @return {undefined}
   */
  linkRequirements() {
    if (!this.custom().zip && fse.existsSync('.requirements')) {
      this.serverless.cli.log('Linking required Python packages...');
      const noDeploy = new Set(this.custom().noDeploy || []);
      fse.readdirSync('.requirements').map((file) => {
        if (noDeploy.has(file))
          return;
        this.serverless.service.package.include.push(file);
        this.serverless.service.package.include.push(`${file}/**`);
        try {
          fse.symlinkSync(`.requirements/${file}`, `./${file}`);
        } catch (exception) {
          let linkDest = null;
          try {
            linkDest = fse.readlinkSync(`./${file}`);
          } catch (e) {}
          if (linkDest !== `.requirements/${file}`)
          throw new Error(`Unable to link dependency '${file}' because a file
                          by the same name exists in this service`);
        }
      });
    }
  }

  /**
   * unlink all the files in .requirements from the service directory root
   * @return {undefined}
   */
  unlinkRequirements() {
    if (!this.custom().zip && fse.existsSync('.requirements')) {
      this.serverless.cli.log('Unlinking required Python packages...');
      fse.readdirSync('.requirements').map((file) => fse.unlinkSync(file));
    }
  }

  /**
   * clean up .requirements and .requirements.zip and unzip_requirements.py
   * @return {Promise}
   */
  cleanup() {
    const artifacts = ['.requirements'];
    if (this.custom().zip) {
      artifacts.push('.requirements.zip');
      artifacts.push('unzip_requirements.py');
    }

    return BbPromise.all(_.map(artifacts, (artifact) => fse.removeAsync(
      path.join(this.serverless.config.servicePath, artifact))));
  };

  /**
   * get the custom.pythonRequirements contents, with defaults set
   * @return {Object}
   */
  custom() {
    return Object.assign({
      zip: false,
      cleanupZipHelper: true,
      invalidateCaches: false,
    }, this.serverless.service.custom &&
    this.serverless.service.custom.pythonRequirements || {});
  }

  /**
   * The plugin constructor
   * @param {Object} serverless
   * @param {Object} options
   * makes
   * @return {undefined}
   */
  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options;

    if (!_.get(this.serverless.service, 'package.exclude'))
      _.set(this.serverless.service, ['package', 'exclude'], []);
    this.serverless.service.package.exclude.push('.requirements/**');
    if (!_.get(this.serverless.service, 'package.include'))
      _.set(this.serverless.service, ['package', 'include'], []);

    this.commands = {
      requirements: {
        commands: {
          clean: {
            usage: 'Remove .requirements and requirements.zip',
            lifecycleEvents: [
              'clean',
            ],
          },
          install: {
            usage: 'install requirements manually',
            lifecycleEvents: [
              'install',
            ],
          },
        },
      },
    };

    const before = () => BbPromise.bind(this)
      .then(this.addVendorHelper)
      .then(this.packRequirements)
      .then(this.linkRequirements);

    const after = () => BbPromise.bind(this)
      .then(this.removeVendorHelper)
      .then(this.unlinkRequirements);

    const invalidateCaches = () => {
      if (this.custom().invalidateCaches) {
        return BbPromise.bind(this)
          .then(this.cleanup)
          .then(this.removeVendorHelper);
      } else {
        return BbPromise.resolve();
      }
    };

    this.hooks = {
      'after:package:cleanup': invalidateCaches,
      'before:package:createDeploymentArtifacts': before,
      'after:package:createDeploymentArtifacts': after,
      'before:deploy:function:packageFunction': before,
      'after:deploy:function:packageFunction': after,
      'requirements:install:install': () => BbPromise.bind(this)
        .then(this.addVendorHelper)
        .then(this.packRequirements),
      'requirements:clean:clean': () => BbPromise.bind(this)
        .then(this.cleanup)
        .then(this.removeVendorHelper),
    };
  }
}

module.exports = ServerlessPythonRequirements;
<commit_msg>Remove unnecessary else<commit_after>/* jshint ignore:start */
'use strict';

const BbPromise = require('bluebird');
const _ = require('lodash');
const path = require('path');
const fse = require('fs-extra');
const {spawnSync} = require('child_process');
const zipDirectory = require('./zipService').zipDirectory;

BbPromise.promisifyAll(fse);

/**
 * Plugin for Serverless 1.x that bundles python requirements!
 */
class ServerlessPythonRequirements {
  /**
   * add the vendor helper to the current service tree
   * @return {Promise}
   */
  addVendorHelper() {
    if (this.custom().zip) {
      this.serverless.cli.log('Adding Python requirements helper...');

      this.serverless.service.package.include.push('unzip_requirements.py');

      return fse.copyAsync(
        path.resolve(__dirname, 'unzip_requirements.py'),
        path.join(this.serverless.config.servicePath, 'unzip_requirements.py'));
    }
  };

  /**
   * remove the vendor helper from the current service tree
   * @return {Promise}
   */
  removeVendorHelper() {
    if (this.custom().zip && this.custom().cleanupZipHelper) {
      this.serverless.cli.log('Removing Python requirements helper...');
      return fse.removeAsync('unzip_requirements.py');
    }
  };

  /**
   * pip install the requirements to the .requirements directory
   * @return {Promise}
   */
  installRequirements() {
    const fileName = this.custom().fileName || 'requirements.txt';
    if (!fse.existsSync(path.join(this.serverless.config.servicePath,
                                  fileName))) {
      return BbPromise.resolve();
    }

    const runtime = this.serverless.service.provider.runtime;
    const pythonBin = this.custom().pythonBin || runtime;
    this.serverless.cli.log(
      `Installing required Python packages for runtime ${runtime}...`);

    return new BbPromise((resolve, reject) => {
      let cmd;
      let options;
      const pipCmd = [
        pythonBin, '-m', 'pip', '--isolated', 'install',
        '-t', '.requirements', '-r', fileName,
      ];
      if (this.custom().pipCmdExtraArgs) {
        pipCmd.push(...this.custom().pipCmdExtraArgs);
      }
      if (!this.custom().dockerizePip) {
        // Check if pip has Debian's --system option and set it if so
        const pipTestRes = spawnSync(
          pythonBin, ['-m', 'pip', 'help', 'install']);
          if (pipTestRes.error) {
            if (pipTestRes.error.code === 'ENOENT')
              return reject(`${pythonBin} not found! ` +
                            'Try the pythonBin option.');
            return reject(pipTestRes.error);
          }
        if (pipTestRes.stdout.toString().indexOf('--system') >= 0)
          pipCmd.push('--system');
      }
      if (this.custom().dockerizePip) {
        cmd = 'docker';

        const image = this.custom().dockerImage
         || `lambci/lambda:build-${runtime}`;
        this.serverless.cli.log(`Docker Image: ${image}`);

        options = [
          'run', '--rm',
          '-v', `${this.serverless.config.servicePath}:/var/task:z`,
          `${image}`,
        ];
        if (process.platform === 'linux')
          options.push('-u', `${process.getuid()}:${process.getgid()}`);
        options.push(...pipCmd);
      } else {
        cmd = pipCmd[0];
        options = pipCmd.slice(1);
      }
      const res = spawnSync(cmd, options);
      if (res.error) {
        if (res.error.code === 'ENOENT')
          return reject(`${pythonBin} not found! Try the pythonBin option.`);
        return reject(res.error);
      }
      if (res.status != 0)
        return reject(res.stderr);
      resolve();
    });
  };

  /**
   * zip up .requirements
   * @return {Promise}
   */
  packRequirements() {
    return this.installRequirements().then(() => {
      if (this.custom().zip) {
        this.serverless.cli.log('Zipping required Python packages...');
        this.serverless.service.package.include.push('.requirements.zip');
        return zipDirectory('.requirements', '.requirements.zip');
      }
    });
  }

  /**
   * link all the files in .requirements to the service directory root
   * @return {undefined}
   */
  linkRequirements() {
    if (!this.custom().zip && fse.existsSync('.requirements')) {
      this.serverless.cli.log('Linking required Python packages...');
      const noDeploy = new Set(this.custom().noDeploy || []);
      fse.readdirSync('.requirements').map((file) => {
        if (noDeploy.has(file))
          return;
        this.serverless.service.package.include.push(file);
        this.serverless.service.package.include.push(`${file}/**`);
        try {
          fse.symlinkSync(`.requirements/${file}`, `./${file}`);
        } catch (exception) {
          let linkDest = null;
          try {
            linkDest = fse.readlinkSync(`./${file}`);
          } catch (e) {}
          if (linkDest !== `.requirements/${file}`)
          throw new Error(`Unable to link dependency '${file}' because a file
                          by the same name exists in this service`);
        }
      });
    }
  }

  /**
   * unlink all the files in .requirements from the service directory root
   * @return {undefined}
   */
  unlinkRequirements() {
    if (!this.custom().zip && fse.existsSync('.requirements')) {
      this.serverless.cli.log('Unlinking required Python packages...');
      fse.readdirSync('.requirements').map((file) => fse.unlinkSync(file));
    }
  }

  /**
   * clean up .requirements and .requirements.zip and unzip_requirements.py
   * @return {Promise}
   */
  cleanup() {
    const artifacts = ['.requirements'];
    if (this.custom().zip) {
      artifacts.push('.requirements.zip');
      artifacts.push('unzip_requirements.py');
    }

    return BbPromise.all(_.map(artifacts, (artifact) => fse.removeAsync(
      path.join(this.serverless.config.servicePath, artifact))));
  };

  /**
   * get the custom.pythonRequirements contents, with defaults set
   * @return {Object}
   */
  custom() {
    return Object.assign({
      zip: false,
      cleanupZipHelper: true,
      invalidateCaches: false,
    }, this.serverless.service.custom &&
    this.serverless.service.custom.pythonRequirements || {});
  }

  /**
   * The plugin constructor
   * @param {Object} serverless
   * @param {Object} options
   * makes
   * @return {undefined}
   */
  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options;

    if (!_.get(this.serverless.service, 'package.exclude'))
      _.set(this.serverless.service, ['package', 'exclude'], []);
    this.serverless.service.package.exclude.push('.requirements/**');
    if (!_.get(this.serverless.service, 'package.include'))
      _.set(this.serverless.service, ['package', 'include'], []);

    this.commands = {
      requirements: {
        commands: {
          clean: {
            usage: 'Remove .requirements and requirements.zip',
            lifecycleEvents: [
              'clean',
            ],
          },
          install: {
            usage: 'install requirements manually',
            lifecycleEvents: [
              'install',
            ],
          },
        },
      },
    };

    const before = () => BbPromise.bind(this)
      .then(this.addVendorHelper)
      .then(this.packRequirements)
      .then(this.linkRequirements);

    const after = () => BbPromise.bind(this)
      .then(this.removeVendorHelper)
      .then(this.unlinkRequirements);

    const invalidateCaches = () => {
      if (this.custom().invalidateCaches) {
        return BbPromise.bind(this)
          .then(this.cleanup)
          .then(this.removeVendorHelper);
      }
      return BbPromise.resolve();
    };

    this.hooks = {
      'after:package:cleanup': invalidateCaches,
      'before:package:createDeploymentArtifacts': before,
      'after:package:createDeploymentArtifacts': after,
      'before:deploy:function:packageFunction': before,
      'after:deploy:function:packageFunction': after,
      'requirements:install:install': () => BbPromise.bind(this)
        .then(this.addVendorHelper)
        .then(this.packRequirements),
      'requirements:clean:clean': () => BbPromise.bind(this)
        .then(this.cleanup)
        .then(this.removeVendorHelper),
    };
  }
}

module.exports = ServerlessPythonRequirements;
<|endoftext|>


<commit_before>var logger = require('./logger')
var transport = require('./transport')
var utils = require('./utils')
var stacktraceGps = require('stacktrace-gps')
var StackTrace = require('stacktrace-js')

var sourceCache = {}

module.exports = {
  processWindowError: function (msg, file, line, col, error, options) {
    StackTrace.fromError(error, {
      sourceCache: sourceCache
    }).then(function (stackFrames) {
      var exception = {
        'message': error.message,
        'type': error.name,
        'fileurl': file,
        'lineno': line,
        'colno': col,
        'stack': stackFrames
      }

      this.stackInfoToOpbeatException(exception, options).then(function (exception) {
        this.processException(exception, options)
      }.bind(this))

    }.bind(this))

  },

  buildOpbeatFrame: function buildOpbeatFrame (stack, options) {
    options = options || {}

    return new Promise(function (resolve, reject) {

      // Build Opbeat frame data
      var frame = {
        'filename': this.cleanFileUrl(stack.fileName),
        'lineno': stack.lineNumber,
        'colno': stack.columnNumber,
        'function': stack.functionName || '[anonymous]'
      }

      // Resolve contexts
      var contextsResolver = this.getExceptionContexts(stack.fileName, stack.lineNumber);
      contextsResolver.then(function (contexts) {
        frame.pre_context = contexts.preContext
        frame.context_line = contexts.contextLine
        frame.post_context = contexts.postContext
      })

        resolve(frame)
      })

    }.bind(this))

  },

  stackInfoToOpbeatException: function (stackInfo, options) {
    options = options || {}

    return new Promise(function (resolve, reject) {
      if (stackInfo.stack && stackInfo.stack.length) {
        var framesPromises = stackInfo.stack.map(function (stack, i) {
          return this.buildOpbeatFrame(stack)
        }.bind(this))

        Promise.all(framesPromises).then(function (frames) {
          stackInfo.frames = frames
          stackInfo.stack = null
          resolve(stackInfo)
        })
      }

    }.bind(this))

    stackInfo.frames = []

    return stackInfo

  },

  cleanFileUrl: function (fileUrl) {
    if (!fileUrl) {
      fileUrl = ''
    }

    var origin = window.location.origin || window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '')

    if (fileUrl.indexOf(origin) > -1) {
      fileUrl = fileUrl.replace(origin + '/', '')
    }

    return fileUrl
  },

  processException: function processException (exception, options) {
    options = options || {}

    var stacktrace

    var type = exception.type
    var message = String(exception.message) || 'Script error'
    var fileUrl = this.cleanFileUrl(exception.fileurl)
    var frames = exception.frames || []

    if (frames && frames.length) {
      // Opbeat.com expects frames oldest to newest and JS sends them as newest to oldest
      frames.reverse()
    } else if (fileUrl) {
      frames.push({
        filename: fileUrl,
        lineno: exception.lineno
      })
    }

    stacktrace = {
      frames: frames
    }

    // Set fileUrl from last frame, if filename is missing
    if (!fileUrl && frames.length) {
      var lastFrame = frames[frames.length - 1]
      if (lastFrame.filename) {
        fileUrl = lastFrame.filename
      } else {
        // If filename empty, use location path and assume inline script
        fileUrl = window.location.pathname + ' (inline script)'
      }
    }

    var culprit = fileUrl

    var data = {
      message: type + ': ' + message,
      culprit: culprit,
      exception: {
        type: type,
        value: message
      },
      stacktrace: stacktrace,
      user: options.context ? options.context.user : null,
      timestamp: parseInt((new Date).getTime() / 1000, 10),
      level: null,
      logger: null,
      machine: null
    }

    data.extra = this.getBrowserSpecificMetadata()

    if (options.context && options.context.extra) {
      data.extra = utils.mergeObject(data.extra, options.context.extra)
    }

    logger.log('opbeat.exceptionst.processException', data)
    transport.sendToOpbeat(data, options)

  },

  getFileSourceMapUrl: function (fileUrl) {
    function _findSourceMappingURL (source) {
      var m = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)$/.exec(source)
      if (m && m[1]) {
        return m[1]
      }
      return null
    }

    if(fileUrl.split('/').length >1) {
      fileBasePath = fileUrl.split('/').slice(0, -1).join('/') + '/'
    } else {
      fileBasePath = '/'
    }

    return new Promise(function (resolve, reject) {
      var gps = new stacktraceGps({
        sourceCache: sourceCache
      })

      gps._get(fileUrl).then(function (source) {
        var sourceMapUrl = _findSourceMappingURL(source)
        if (sourceMapUrl) {
          sourceMapUrl = fileBasePath + sourceMapUrl
          resolve(sourceMapUrl)
        } else {
          reject(null)
        }
      }).catch(function(e) {
        console.error('e', e);
      })

    })
  },

  getExceptionContexts: function (url, line) {
    return new Promise(function (resolve, reject ) {
      var gps = new stacktraceGps({
        sourceCache: sourceCache
      })

      gps._get(url).then(function (source) {
        source = source.split('\n')
        line -= 1; // convert line to 0-based index

        var linesBefore = 5
        var linesAfter = 5

        var contexts = {
          preContext: [],
          contextLine: null,
          postContext: []
        }

        if (source.length) {
          // Pre context
          var preStartIndex = Math.max(0, line - linesBefore - 1)
          var preEndIndex = Math.min(source.length, line - 1)
          for (var i = preStartIndex; i <= preEndIndex; ++i) {
            if (!utils.isUndefined(source[i])) {
              contexts.preContext.push(source[i])
            }
          }

          // Line context
          contexts.contextLine = source[line]

          // Post context
          var postStartIndex = Math.min(source.length, line + 1)
          var postEndIndex = Math.min(source.length, line + linesAfter)
          for (var i = postStartIndex; i <= postEndIndex; ++i) {
            if (!utils.isUndefined(source[i])) {
              contexts.postContext.push(source[i])
            }
          }
        }

        logger.log('Opbeat.getExceptionContexts', contexts)
        resolve(contexts)
      })

    })

  },

  getBrowserSpecificMetadata: function () {
    var viewportInfo = utils.getViewPortInfo()
    var extra = {
      'environment': {
        'utcOffset': new Date().getTimezoneOffset() / -60.0,
        'browserWidth': viewportInfo.width,
        'browserHeight': viewportInfo.height,
        'screenWidth': window.screen.width,
        'screenHeight': window.screen.height,
        'language': navigator.language,
        'userAgent': navigator.userAgent,
        'platform': navigator.platform
      },
      'page': {
        'referer': document.referrer,
        'host': document.domain,
        'location': window.location.href
      }
    }

    return extra
  }

}
<commit_msg>Detect source maps for each stack frame.<commit_after>var logger = require('./logger')
var transport = require('./transport')
var utils = require('./utils')
var stacktraceGps = require('stacktrace-gps')
var StackTrace = require('stacktrace-js')

var sourceCache = {}

module.exports = {
  processWindowError: function (msg, file, line, col, error, options) {
    StackTrace.fromError(error, {
      sourceCache: sourceCache
    }).then(function (stackFrames) {
      var exception = {
        'message': error.message,
        'type': error.name,
        'fileurl': file,
        'lineno': line,
        'colno': col,
        'stack': stackFrames
      }

      this.stackInfoToOpbeatException(exception, options).then(function (exception) {
        this.processException(exception, options)
      }.bind(this))

    }.bind(this))

  },

  buildOpbeatFrame: function buildOpbeatFrame (stack, options) {
    options = options || {}

    return new Promise(function (resolve, reject) {

      // Build Opbeat frame data
      var frame = {
        'filename': this.cleanFileUrl(stack.fileName),
        'lineno': stack.lineNumber,
        'colno': stack.columnNumber,
        'function': stack.functionName || '[anonymous]'
      }

      // Resolve contexts
      var contextsResolver = this.getExceptionContexts(stack.fileName, stack.lineNumber);
      contextsResolver.then(function (contexts) {
        frame.pre_context = contexts.preContext
        frame.context_line = contexts.contextLine
        frame.post_context = contexts.postContext
      })

      // Detect Sourcemaps
      var sourceMapResolver = this.getFileSourceMapUrl(stack.fileName);
      sourceMapResolver.then(function(sourceMapUrl) {
        frame.sourcemap_url = sourceMapUrl
      }).catch(function() {})

      // Resolve frame when everything is over
      utils.promiseAny([sourceMapResolver, contextsResolver]).then(function() {
        resolve(frame)
      });

    }.bind(this))

  },

  stackInfoToOpbeatException: function (stackInfo, options) {
    options = options || {}

    return new Promise(function (resolve, reject) {
      if (stackInfo.stack && stackInfo.stack.length) {
        var framesPromises = stackInfo.stack.map(function (stack, i) {
          return this.buildOpbeatFrame(stack)
        }.bind(this))

        Promise.all(framesPromises).then(function (frames) {
          stackInfo.frames = frames
          stackInfo.stack = null
          resolve(stackInfo)
        })
      }

    }.bind(this))

    stackInfo.frames = []

    return stackInfo

  },

  cleanFileUrl: function (fileUrl) {
    if (!fileUrl) {
      fileUrl = ''
    }

    var origin = window.location.origin || window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '')

    if (fileUrl.indexOf(origin) > -1) {
      fileUrl = fileUrl.replace(origin + '/', '')
    }

    return fileUrl
  },

  processException: function processException (exception, options) {
    options = options || {}

    var stacktrace

    var type = exception.type
    var message = String(exception.message) || 'Script error'
    var fileUrl = this.cleanFileUrl(exception.fileurl)
    var frames = exception.frames || []

    if (frames && frames.length) {
      // Opbeat.com expects frames oldest to newest and JS sends them as newest to oldest
      frames.reverse()
    } else if (fileUrl) {
      frames.push({
        filename: fileUrl,
        lineno: exception.lineno
      })
    }

    stacktrace = {
      frames: frames
    }

    // Set fileUrl from last frame, if filename is missing
    if (!fileUrl && frames.length) {
      var lastFrame = frames[frames.length - 1]
      if (lastFrame.filename) {
        fileUrl = lastFrame.filename
      } else {
        // If filename empty, use location path and assume inline script
        fileUrl = window.location.pathname + ' (inline script)'
      }
    }

    var culprit = fileUrl

    var data = {
      message: type + ': ' + message,
      culprit: culprit,
      exception: {
        type: type,
        value: message
      },
      stacktrace: stacktrace,
      user: options.context ? options.context.user : null,
      timestamp: parseInt((new Date).getTime() / 1000, 10),
      level: null,
      logger: null,
      machine: null
    }

    data.extra = this.getBrowserSpecificMetadata()

    if (options.context && options.context.extra) {
      data.extra = utils.mergeObject(data.extra, options.context.extra)
    }

    logger.log('opbeat.exceptionst.processException', data)
    transport.sendToOpbeat(data, options)

  },

  getFileSourceMapUrl: function (fileUrl) {
    function _findSourceMappingURL (source) {
      var m = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)$/.exec(source)
      if (m && m[1]) {
        return m[1]
      }
      return null
    }

    if(fileUrl.split('/').length >1) {
      fileBasePath = fileUrl.split('/').slice(0, -1).join('/') + '/'
    } else {
      fileBasePath = '/'
    }

    return new Promise(function (resolve, reject) {
      var gps = new stacktraceGps({
        sourceCache: sourceCache
      })

      gps._get(fileUrl).then(function (source) {
        var sourceMapUrl = _findSourceMappingURL(source)
        if (sourceMapUrl) {
          sourceMapUrl = fileBasePath + sourceMapUrl
          resolve(sourceMapUrl)
        } else {
          reject(null)
        }
      }).catch(function(e) {
        console.error('e', e);
      })

    })
  },

  getExceptionContexts: function (url, line) {
    return new Promise(function (resolve, reject ) {
      var gps = new stacktraceGps({
        sourceCache: sourceCache
      })

      gps._get(url).then(function (source) {
        source = source.split('\n')
        line -= 1; // convert line to 0-based index

        var linesBefore = 5
        var linesAfter = 5

        var contexts = {
          preContext: [],
          contextLine: null,
          postContext: []
        }

        if (source.length) {
          // Pre context
          var preStartIndex = Math.max(0, line - linesBefore - 1)
          var preEndIndex = Math.min(source.length, line - 1)
          for (var i = preStartIndex; i <= preEndIndex; ++i) {
            if (!utils.isUndefined(source[i])) {
              contexts.preContext.push(source[i])
            }
          }

          // Line context
          contexts.contextLine = source[line]

          // Post context
          var postStartIndex = Math.min(source.length, line + 1)
          var postEndIndex = Math.min(source.length, line + linesAfter)
          for (var i = postStartIndex; i <= postEndIndex; ++i) {
            if (!utils.isUndefined(source[i])) {
              contexts.postContext.push(source[i])
            }
          }
        }

        logger.log('Opbeat.getExceptionContexts', contexts)
        resolve(contexts)
      })

    })

  },

  getBrowserSpecificMetadata: function () {
    var viewportInfo = utils.getViewPortInfo()
    var extra = {
      'environment': {
        'utcOffset': new Date().getTimezoneOffset() / -60.0,
        'browserWidth': viewportInfo.width,
        'browserHeight': viewportInfo.height,
        'screenWidth': window.screen.width,
        'screenHeight': window.screen.height,
        'language': navigator.language,
        'userAgent': navigator.userAgent,
        'platform': navigator.platform
      },
      'page': {
        'referer': document.referrer,
        'host': document.domain,
        'location': window.location.href
      }
    }

    return extra
  }

}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

module.exports = function(options) {
  var seneca = this;
  var plugin = 'events';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({role: plugin, cmd: 'getEvent'}, proxy);
  seneca.add({role: plugin, cmd: 'listEvents'}, proxy);
  seneca.add({role: plugin, cmd: 'searchEvents'}, proxy);
  seneca.add({role: plugin, cmd: 'applyForEvent'}, proxy);
  seneca.add({role: plugin, cmd: 'searchApplications'}, proxy);
  seneca.add({role: plugin, cmd: 'searchAttendance'}, proxy);
  seneca.add({role: plugin, cmd: 'userDojosEvents'}, proxy);

  // Has validation
  seneca.add({role: plugin, cmd: 'saveEvent'}, eventValidationProxy);
  seneca.add({role: plugin, cmd: 'loadEventApplications'}, eventValidationProxy);
  seneca.add({role: plugin, cmd: 'updateApplication'}, applicationValidationProxy);
  seneca.add({role: plugin, cmd: 'bulkUpdateApplications'}, bulkUpdateApplicationValidationProxy);
  seneca.add({role: plugin, cmd: 'deleteApplication'}, deleteApplicationValidationProxy);
  seneca.add({role: plugin, cmd: 'saveApplication'}, applicationValidationProxy);
  seneca.add({role: plugin, cmd: 'saveAttendance'}, attendanceValidationProxy);

  function proxy(args, done) {
    var user = null;
    var locality = (args.req$ && args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$ && args.req$.headers['accept-language'];
    locality = formatLocaleCode(locality);
    if(args.req$) user = args.req$.seneca.user;
    sendToEventsService(user, args, locality, done);
  }

  function attendanceValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var attendance = args.attendance;

    if(!attendance) return done(new Error('Attendance Record must exist'));

    var eventId = attendance.eventId || attendance.event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function eventValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var eventInfo = args.eventInfo;
    var eventId = args.eventId || args.event_id;

    if(!user) {
      return done(new Error('User must exist'));
    }

    if(!eventId && !eventInfo) {
      return done(new Error('EventId or eventInfo must exist'));
    }

    if(eventInfo) {
      var dojoId = eventInfo.dojoId;

      return checkUserPermissionsAndAct(user, dojoId, args, done);
    }

    // Get dojo id
    getEventById(eventId, function(err, event){
      if (err) {
        return done(err);
      }

      var dojoId = event.dojoId;

      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function applicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var application = args.application;

    if(!application) return done(new Error('Application must exist'));

    var eventId = application.eventId || application.event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function bulkUpdateApplicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var applications = args.applications;

    if(applications.length === 0) return done(new Error('Applications must exist'));
    var eventId = applications[0].eventId || applications[0].event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function deleteApplicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var applicationId = args.applicationId;
    var eventId = args.eventId;

    if(!applicationId || !eventId) return done(new Error('Application ID or Event ID missing'));

    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function checkUserPermissionsAndAct(user, dojoId, args, done) {
    checkUserPermissions(user.id, dojoId, function(err, hasPermission) {
      if (err) {
        return done(err);
      }
      return proxy(args, done);
    });
  }

  function sendToEventsService(user, args, locality, done) {
    seneca.act(seneca.util.argprops(
      {user:user, locality:locality, fatal$: false},
      args,
      {role: 'cd-events'}
    ), done);
  }

  function getEventById(eventId, done) {
    seneca.act({
      role: plugin,
      cmd: 'getEvent',
      id: eventId
    }, function(err, event) {
      if (err) {
        return done(err);
      }

      if(!event) {
        return done(new Error('Couldn\'t get event'));
      }

      return done(null, event);
    });
  }

  // Check that user is a member, champion and ticketing admin
  function checkUserPermissions(userId, dojoId, done) {
    var isTicketingAdmin = false;

    seneca.act({
      role: 'cd-dojos',
      cmd: 'load_usersdojos',
      query: {
        userId: userId,
        dojoId: dojoId
      }
    }, function(err, result) {
      if (err) {
        return done(err);
      }

      if (_.isEmpty(result)) {
        return done(new Error('No permission, user is not a member'));
      }

      var userDojoEntity = result[0];
      var userTypes = userDojoEntity.userTypes;
      var userPermissions = userDojoEntity.userPermissions;
      var isTicketingAdmin = _.find(userPermissions, function(userPermission) {
        return userPermission.name === 'ticketing-admin';
      });

      if (!isTicketingAdmin) {
        return done(new Error('No permission, user is not a ticketing admin'));
      }

      // Has permission
      return done(null, true);
    });
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  // web interface
  seneca.act({ role: 'web', use: {
    prefix: options.prefix + version + '/',
    pin: { role: plugin, cmd: '*' },
    map: {
      'saveEvent': { POST: true, alias: 'save-event' },
      'getEvent': { GET: true, alias: 'events/:id' },
      'listEvents': { POST: true, alias: 'events'},
      'searchEvents': {POST: true, alias: 'events/search'},
      'applyForEvent': {POST: true, alias: 'events/:eventId/apply'},
      'loadEventApplications': {GET: true, alias: 'events/applications/:eventId'},
      'updateApplication': {PUT: true, alias: 'events/applications/:applicationId'},
      'searchApplications': {POST: true, alias: 'events/applications/search'},
      'bulkUpdateApplications': {POST: true, alias: 'events/applications/bulk_update'},
      'deleteApplication': {DELETE: true, alias: 'events/applications/:eventId/:applicationId'},
      'saveApplication': {POST: true, alias: 'events/applications'},
      'searchAttendance': {POST: true, alias: 'events/attendance/search'},
      'saveAttendance': {POST: true, alias: 'events/attendance/save'},
      'userDojosEvents': {POST: true, alias: 'events/user-dojos-events'}
    }
  }});

  return {
    name: plugin
  }
};
<commit_msg>fix events splice undefined<commit_after>'use strict';

var _ = require('lodash');

module.exports = function(options) {
  var seneca = this;
  var plugin = 'events';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({role: plugin, cmd: 'getEvent'}, proxy);
  seneca.add({role: plugin, cmd: 'listEvents'}, proxy);
  seneca.add({role: plugin, cmd: 'searchEvents'}, proxy);
  seneca.add({role: plugin, cmd: 'applyForEvent'}, proxy);
  seneca.add({role: plugin, cmd: 'searchApplications'}, proxy);
  seneca.add({role: plugin, cmd: 'searchAttendance'}, proxy);
  seneca.add({role: plugin, cmd: 'userDojosEvents'}, proxy);

  // Has validation
  seneca.add({role: plugin, cmd: 'saveEvent'}, eventValidationProxy);
  seneca.add({role: plugin, cmd: 'loadEventApplications'}, eventValidationProxy);
  seneca.add({role: plugin, cmd: 'updateApplication'}, applicationValidationProxy);
  seneca.add({role: plugin, cmd: 'bulkUpdateApplications'}, bulkUpdateApplicationValidationProxy);
  seneca.add({role: plugin, cmd: 'deleteApplication'}, deleteApplicationValidationProxy);
  seneca.add({role: plugin, cmd: 'saveApplication'}, applicationValidationProxy);
  seneca.add({role: plugin, cmd: 'saveAttendance'}, attendanceValidationProxy);

  function proxy(args, done) {
    var user = null;
    var locality = (args.req$ && args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$ && args.req$.headers['accept-language'];
    if(!locality) locality = 'en_US';
    locality = formatLocaleCode(locality);
    if(args.req$) user = args.req$.seneca.user;
    sendToEventsService(user, args, locality, done);
  }

  function attendanceValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var attendance = args.attendance;

    if(!attendance) return done(new Error('Attendance Record must exist'));

    var eventId = attendance.eventId || attendance.event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function eventValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var eventInfo = args.eventInfo;
    var eventId = args.eventId || args.event_id;

    if(!user) {
      return done(new Error('User must exist'));
    }

    if(!eventId && !eventInfo) {
      return done(new Error('EventId or eventInfo must exist'));
    }

    if(eventInfo) {
      var dojoId = eventInfo.dojoId;

      return checkUserPermissionsAndAct(user, dojoId, args, done);
    }

    // Get dojo id
    getEventById(eventId, function(err, event){
      if (err) {
        return done(err);
      }

      var dojoId = event.dojoId;

      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function applicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var application = args.application;

    if(!application) return done(new Error('Application must exist'));

    var eventId = application.eventId || application.event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function bulkUpdateApplicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var applications = args.applications;

    if(applications.length === 0) return done(new Error('Applications must exist'));
    var eventId = applications[0].eventId || applications[0].event_id;
    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function deleteApplicationValidationProxy(args, done) {
    var user = args.req$.seneca.user;
    var applicationId = args.applicationId;
    var eventId = args.eventId;

    if(!applicationId || !eventId) return done(new Error('Application ID or Event ID missing'));

    getEventById(eventId, function(err, event){
      if (err) return done(err);
      var dojoId = event.dojoId;
      checkUserPermissionsAndAct(user, dojoId, args, done);
    });
  }

  function checkUserPermissionsAndAct(user, dojoId, args, done) {
    checkUserPermissions(user.id, dojoId, function(err, hasPermission) {
      if (err) {
        return done(err);
      }
      return proxy(args, done);
    });
  }

  function sendToEventsService(user, args, locality, done) {
    seneca.act(seneca.util.argprops(
      {user:user, locality:locality, fatal$: false},
      args,
      {role: 'cd-events'}
    ), done);
  }

  function getEventById(eventId, done) {
    seneca.act({
      role: plugin,
      cmd: 'getEvent',
      id: eventId
    }, function(err, event) {
      if (err) {
        return done(err);
      }

      if(!event) {
        return done(new Error('Couldn\'t get event'));
      }

      return done(null, event);
    });
  }

  // Check that user is a member, champion and ticketing admin
  function checkUserPermissions(userId, dojoId, done) {
    var isTicketingAdmin = false;

    seneca.act({
      role: 'cd-dojos',
      cmd: 'load_usersdojos',
      query: {
        userId: userId,
        dojoId: dojoId
      }
    }, function(err, result) {
      if (err) {
        return done(err);
      }

      if (_.isEmpty(result)) {
        return done(new Error('No permission, user is not a member'));
      }

      var userDojoEntity = result[0];
      var userTypes = userDojoEntity.userTypes;
      var userPermissions = userDojoEntity.userPermissions;
      var isTicketingAdmin = _.find(userPermissions, function(userPermission) {
        return userPermission.name === 'ticketing-admin';
      });

      if (!isTicketingAdmin) {
        return done(new Error('No permission, user is not a ticketing admin'));
      }

      // Has permission
      return done(null, true);
    });
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  // web interface
  seneca.act({ role: 'web', use: {
    prefix: options.prefix + version + '/',
    pin: { role: plugin, cmd: '*' },
    map: {
      'saveEvent': { POST: true, alias: 'save-event' },
      'getEvent': { GET: true, alias: 'events/:id' },
      'listEvents': { POST: true, alias: 'events'},
      'searchEvents': {POST: true, alias: 'events/search'},
      'applyForEvent': {POST: true, alias: 'events/:eventId/apply'},
      'loadEventApplications': {GET: true, alias: 'events/applications/:eventId'},
      'updateApplication': {PUT: true, alias: 'events/applications/:applicationId'},
      'searchApplications': {POST: true, alias: 'events/applications/search'},
      'bulkUpdateApplications': {POST: true, alias: 'events/applications/bulk_update'},
      'deleteApplication': {DELETE: true, alias: 'events/applications/:eventId/:applicationId'},
      'saveApplication': {POST: true, alias: 'events/applications'},
      'searchAttendance': {POST: true, alias: 'events/attendance/search'},
      'saveAttendance': {POST: true, alias: 'events/attendance/save'},
      'userDojosEvents': {POST: true, alias: 'events/user-dojos-events'}
    }
  }});

  return {
    name: plugin
  }
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var connector = require("./database/connector.js");
var twilio = require('twilio');

app.set('port', (process.env.PORT || 5000));

app.get("/api",function(req,res){
   connector.executeQuery("SELECT * from users",function(err,rows){
          res.end( JSON.stringify(rows) ) ;
   })
})

app.post("/welcome/sms/reply/",function(req,res){

  var twilio = require('twilio');
      var twiml = new twilio.TwimlResponse();
          twiml.message(function() {
		        this.body('The Robots are coming! Head for the hills!');
			      this.media('https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg');
			          });
	      res.writeHead(200, {'Content-Type': 'text/xml'});
	          res.end(twiml.toString());

})

app.get('/', function(request, response) {
  response.end("END");
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<commit_msg>twilio<commit_after>var express = require('express');
var app = express();
var connector = require("./database/connector.js");
const MessagingResponse = require('twilio').twiml.MessagingResponse;

app.set('port', (process.env.PORT || 5000));

app.get("/api",function(req,res){
   connector.executeQuery("SELECT * from users",function(err,rows){
          res.end( JSON.stringify(rows) ) ;
   })
})

app.post("/welcome/sms/reply/",function(req,res){
  const twiml = new MessagingResponse();

    twiml.message('The Robots are coming! Head for the hills!');

      res.writeHead(200, {'Content-Type': 'text/xml'});
        res.end(twiml.toString());
})

app.get('/', function(request, response) {
  response.end("END");
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<|endoftext|>


<commit_before>'use strict';

// @flow

import path from 'path';

import badge from 'badge-up';

import {mkdirp, writeFile} from './promisified';

import type {FlowCoverageSummaryData} from './flow';
import type {FlowCoverageReportOptions} from './index';

function saveBadgeReport(
  coverageData: FlowCoverageSummaryData,
  opts: FlowCoverageReportOptions
): Promise<void> {
  const percent = coverageData.percent;
  const threshold = opts.threshold || 80;
  const difference = percent - threshold;

  let color;

  if (difference < -40) {
    color = 'red';
  } else if (difference < -30) {
    color = 'orange';
  } else if (difference < -20) {
    color = 'yellow';
  } else if (difference < -10) {
    color = 'yellowgreen';
  } else if (difference < 0) {
    color = 'green';
  } else {
    color = 'brightgreen';
  }

  const badgeGen = () => new Promise((resolve, reject) => {
    badge('flow', `${percent}%`, badge.colors[color], (err, svg) => {
      if (err) {
        reject(err);
      } else {
        resolve(svg);
      }
    });
  });

  const projectDir = opts.projectDir;
  const outputDir = opts.outputDir || path.join(projectDir, 'flow-coverage');

  return mkdirp(outputDir).then(badgeGen).then(svg => {
    return writeFile(path.join(outputDir, 'flow-coverage.svg'), svg);
  });
}

export default {
  generate: saveBadgeReport
};
<commit_msg>feat: Minor tweaks and added flow badge to the new badge reporter<commit_after>'use strict';

// @flow

import path from 'path';

import badge from 'badge-up';

import {mkdirp, writeFile} from './promisified';

import type {FlowCoverageSummaryData} from './flow';
import type {FlowCoverageReportOptions} from './index';

async function saveBadgeReport(
  coverageData: FlowCoverageSummaryData,
  opts: FlowCoverageReportOptions
): Promise<void> {
  const percent = coverageData.percent;
  const threshold = opts.threshold || 80;
  const hasFlowErrors = !coverageData.flowStatus.passed;

  const generateFlowCoverageBadge = () => new Promise((resolve, reject) => {
    let color;

    if (percent < (threshold / 2)) {
      color = 'red';
    } else if (percent < (threshold * 5 / 8)) {
      color = 'orange';
    } else if (percent < (threshold * 6 / 8)) {
      color = 'yellow';
    } else if (percent < (threshold * 7 / 8)) {
      color = 'yellowgreen';
    } else if (percent < threshold) {
      color = 'green';
    } else {
      color = 'brightgreen';
    }

    badge('flow-coverage', `${percent}%`, badge.colors[color], (err, svg) => {
      if (err) {
        reject(err);
      } else {
        resolve(svg);
      }
    });
  });

  const generateFlowBadge = () => new Promise((resolve, reject) => {
    const color = hasFlowErrors ? 'red' : 'brightgreen';
    const result = hasFlowErrors ? 'failing' : 'passing';

    badge('flow', result, badge.colors[color], (err, svg) => {
      if (err) {
        reject(err);
      } else {
        resolve(svg);
      }
    });
  });

  const projectDir = opts.projectDir;
  const outputDir = opts.outputDir || path.join(projectDir, 'flow-coverage');

  await mkdirp(outputDir);
  const flowCoverageSVG = await generateFlowCoverageBadge();
  await writeFile(path.join(outputDir, 'flow-coverage-badge.svg'), flowCoverageSVG);

  const flowSVG = await generateFlowBadge();
  await writeFile(path.join(outputDir, 'flow-badge.svg'), flowSVG);
}

export default {
  generate: saveBadgeReport
};
<|endoftext|>


<commit_before>const debug = require('debug');
const url = require('url');
const qs = require('querystring');
const BrowserWindow = require('electron').BrowserWindow;

const VK_AUTHORIZE_URL = 'https://oauth.vk.com/authorize';
const VK_REDIRECT_URL = 'https://oauth.vk.com/blank.html';

/**
 * Opens a new window to perform VK authentication.
 * @returns {Promise} A promise fillfilled with accessToken, userId and expiresIn values,
 * or rejected promise if login request was cancelled.
 */
function authenticateVK(options, windowOptions) {
    const opts = Object.assign({}, {
        authorizeUrl: VK_AUTHORIZE_URL,
        redirectUri: VK_REDIRECT_URL,
        scope: null,
        display: 'popup',
        revoke: false,
    }, options);

    if (!opts.appId) {
        return Promise.reject(new Error('App id is not specified'));
    }

    const windowOpts = Object.assign({}, {
        height: 430,
        width: 655,
    }, windowOptions);

    const state = Math.floor(Math.random() * 10000);
    const response_type = 'token';

    const query = qs.stringify({
        state,
        response_type,
        client_id: opts.appId,
        scope: opts.scope,
        display: opts.display,
        revoke: opts.revoke ? 1 : 0,
        redirect_uri: opts.redirectUri,
    });

    const vkurl = `${opts.authorizeUrl}?${query}`;

    const win = new BrowserWindow(windowOpts);

    debug('open vk auth window %s', vkurl);
    win.loadURL(vkurl);

    return new Promise((resolve, reject) => {
        win.webContents.on('did-get-redirect-request', function (event, oldUrl, newUrl) {
            const data = url.parse(newUrl);
            debug(data);
            // http://stackoverflow.com/questions/16733863/oauth2-0-implicit-grant-flow-why-use-url-hash-fragments
            if (data.host === 'oauth.vk.com' && data.pathname === '/blank.html' && data.hash) {
                const query = qs.parse(data.hash.substring(1));
                debug(query);

                if(!('state' in query && query.state === String(state))) {
                    reject(new Error(`Incorrect state: expected ${query.state} to equal ${state}`));
                } else if ('error' in query) {
                    reject(new Error(query.error_description));
                } else if ('access_token' in query && 'user_id' in query && 'expires_in' in query) {
                    resolve({
                        accessToken: query.access_token,
                        userId: query.user_id,
                        expiresIn: query.expires_in,
                    });
                }
                win.destroy();
            }
        });
        win.on('closed', () => {
            reject(new Error('Auth window was closed before completing authentication'))
        });
    });
}

module.exports = authenticateVK;
<commit_msg>check redirect_uri in did-get-redirect-request function<commit_after>const debug = require('debug');
const url = require('url');
const qs = require('querystring');
const BrowserWindow = require('electron').BrowserWindow;

const VK_AUTHORIZE_URL = 'https://oauth.vk.com/authorize';
const VK_REDIRECT_URL = 'https://oauth.vk.com/blank.html';

/**
 * Opens a new window to perform VK authentication.
 * @returns {Promise} A promise fillfilled with accessToken, userId and expiresIn values,
 * or rejected promise if login request was cancelled.
 */
function authenticateVK(options, windowOptions) {
    const opts = Object.assign({}, {
        authorizeUrl: VK_AUTHORIZE_URL,
        redirectUri: VK_REDIRECT_URL,
        scope: null,
        display: 'popup',
        revoke: false,
    }, options);

    if (!opts.appId) {
        return Promise.reject(new Error('App id is not specified'));
    }

    const windowOpts = Object.assign({}, {
        height: 430,
        width: 655,
    }, windowOptions);

    const state = Math.floor(Math.random() * 10000);
    const response_type = 'token';

    const query = qs.stringify({
        state,
        response_type,
        client_id: opts.appId,
        scope: opts.scope,
        display: opts.display,
        revoke: opts.revoke ? 1 : 0,
        redirect_uri: opts.redirectUri,
    });

    const vkurl = `${opts.authorizeUrl}?${query}`;

    const win = new BrowserWindow(windowOpts);

    debug('open vk auth window %s', vkurl);
    win.loadURL(vkurl);

    return new Promise((resolve, reject) => {
        win.webContents.on('did-get-redirect-request', (event, oldUrl, newUrl) => {
            const data = url.parse(newUrl);
            debug(data);
            // http://stackoverflow.com/questions/16733863/oauth2-0-implicit-grant-flow-why-use-url-hash-fragments
            if (`${data.protocol}//${data.host}${data.pathname}` === opts.redirectUri && data.hash) {
                const query = qs.parse(data.hash.substring(1));
                debug(query);

                if(!('state' in query && query.state === String(state))) {
                    reject(new Error(`Incorrect state: expected ${query.state} to equal ${state}`));
                } else if ('error' in query) {
                    reject(new Error(query.error_description));
                } else if ('access_token' in query && 'user_id' in query && 'expires_in' in query) {
                    resolve({
                        accessToken: query.access_token,
                        userId: query.user_id,
                        expiresIn: query.expires_in,
                    });
                }
                win.destroy();
            }
        });
        win.on('closed', () => {
            reject(new Error('Auth window was closed before completing authentication'))
        });
    });
}

module.exports = authenticateVK;
<|endoftext|>


<commit_before>// setup database connection
var MongoClient = require('mongodb').MongoClient;
var user = process.env.MONGODB_USER || 'dummy';
var pass = process.env.MONGODB_PASSWORD || 'dummy';
var dbip = process.env.MONGODB_SERVICE_HOST || 'db.local';
//var dbip = 'localhost';
var dbport = process.env.MONGODB_SERVICE_PORT || 27017;
var dbcoll = process.env.MONGODB_DATABASE || 'sampledb';
var db = null;
var url = 'mongodb://'+user+':'+pass+'@'+dbip+':'+dbport+'/'+dbcoll;
// uncomment to use without authentication
//var url = 'mongodb://'+dbip+':'+dbport+'/'+dbcoll

var mongoCreatedCollections = false;
var initMongo = function(errcallback) {
   console.log('attempting mongoDB connection to ' + url);
   MongoClient.connect(url, function(err, mydb) {
      if (err) {
         console.log('unable to connect to mongo database -' + err);
         errcallback(err);
         return;
      } else {
         db = mydb;
         console.log('connected to mongo database...');
         mongoCreatedCollections = true;
      }
   });
}

// setup webserver
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
   console.log('GET request');

   var requestip = req.headers['x-forwarded-for'] ||
     req.connection.remoteAddress ||
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;

   var os = require('os');
   var interfaces = os.networkInterfaces();
   var addresses = [];
   for (var k in interfaces) {
       for (var k2 in interfaces[k]) {
           var address = interfaces[k][k2];
           if (address.family === 'IPv4' && !address.internal) {
               addresses.push(address.address);
           }
       }
   }

   // Respond with some HTML
   var respHTML = '<link rel="stylesheet" href="bootstrap.min.css">';
   respHTML += '<title>Node.JS OpenShift Example</title>';
   respHTML += '
';
   respHTML += '

Hello Node + Mongo
';
   respHTML += '
requesting IP:'+requestip+'
'
   respHTML += '
my IP(s):'+addresses+'

';
   if (!mongoCreatedCollections) {
     respHTML += '
ERROR, could not connect to DB

';
     respHTML += '';
     res.send(respHTML); return;
   }

   // store this info
   var stamp = getDateTime();
   console.log('inserting from:' + requestip + ' served by node ' + addresses);
   db.createCollection('history', {strict:false}, function(err, collection) {
      collection.insert({date:stamp,theirIp:requestip,myIp:addresses}, function(err, records) { if (err) throw err;});
   });

   respHTML += '
';
   respHTML += '
GET Requests History
';
   respHTML += '

';
   db.collection('history').find().toArray(function(err, items) {
      for (var i = items.length - 1; i >= 0; i--) {
         var itemout = '
 date:' + items[i].date+', them:'+items[i].theirIp+', us:'+items[i].myIp+'
';
         //console.log(itemout);
         respHTML += itemout;
      };
      respHTML += '

';
      respHTML += '

this page updated on:' + stamp + '
';
      respHTML += '
'
      res.send(respHTML);
   });
});

// setup MongoDB
initMongo(function(err){ console.log('Couldnt connent to mongoDB: ' +err); });

// start listening for client connections
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function() {
   console.log("Listening on " + server_ip_address + ", server_port " + server_port)
});

//------------------------------------------------
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}
<commit_msg>change to force develop ahead of master (for demonstration purposes)<commit_after>// setup database connection
var MongoClient = require('mongodb').MongoClient;
var user = process.env.MONGODB_USER || 'dummy';
var pass = process.env.MONGODB_PASSWORD || 'dummy';
var dbip = process.env.MONGODB_SERVICE_HOST || 'db.local';
//var dbip = 'localhost';
var dbport = process.env.MONGODB_SERVICE_PORT || 27017;
var dbcoll = process.env.MONGODB_DATABASE || 'sampledb';
var db = null;
var url = 'mongodb://'+user+':'+pass+'@'+dbip+':'+dbport+'/'+dbcoll;
// uncomment to use without authentication
//var url = 'mongodb://'+dbip+':'+dbport+'/'+dbcoll

var mongoCreatedCollections = false;
var initMongo = function(errcallback) {
   console.log('attempting mongoDB connection to ' + url);
   MongoClient.connect(url, function(err, mydb) {
      if (err) {
         console.log('unable to connect to mongo database -' + err);
         errcallback(err);
         return;
      } else {
         db = mydb;
         console.log('connected to mongo database...');
         mongoCreatedCollections = true;
      }
   });
}

// setup webserver
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
   console.log('GET request');

   var requestip = req.headers['x-forwarded-for'] ||
     req.connection.remoteAddress ||
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;

   var os = require('os');
   var interfaces = os.networkInterfaces();
   var addresses = [];
   for (var k in interfaces) {
       for (var k2 in interfaces[k]) {
           var address = interfaces[k][k2];
           if (address.family === 'IPv4' && !address.internal) {
               addresses.push(address.address);
           }
       }
   }

   // Respond with some HTML
   var respHTML = '<link rel="stylesheet" href="bootstrap.min.css">';
   respHTML += '<title>NodeMongo OpenShift Example</title>';
   respHTML += '
';
   respHTML += '

Hello Node + Mongo
';
   respHTML += '
requesting IP:'+requestip+'
'
   respHTML += '
my IP(s):'+addresses+'

';
   if (!mongoCreatedCollections) {
     respHTML += '
ERROR, could not connect to DB

';
     respHTML += '';
     res.send(respHTML); return;
   }

   // store this info
   var stamp = getDateTime();
   console.log('inserting from:' + requestip + ' served by node ' + addresses);
   db.createCollection('history', {strict:false}, function(err, collection) {
      collection.insert({date:stamp,theirIp:requestip,myIp:addresses}, function(err, records) { if (err) throw err;});
   });

   respHTML += '
';
   respHTML += '
GET Requests History
';
   respHTML += '

';
   db.collection('history').find().toArray(function(err, items) {
      for (var i = items.length - 1; i >= 0; i--) {
         var itemout = '
 date:' + items[i].date+', them:'+items[i].theirIp+', us:'+items[i].myIp+'
';
         //console.log(itemout);
         respHTML += itemout;
      };
      respHTML += '

';
      respHTML += '

this page updated on:' + stamp + '
';
      respHTML += '
'
      res.send(respHTML);
   });
});

// setup MongoDB
initMongo(function(err){ console.log('Couldnt connent to mongoDB: ' +err); });

// start listening for client connections
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function() {
   console.log("Listening on " + server_ip_address + ", server_port " + server_port)
});

//------------------------------------------------
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}
<|endoftext|>


<commit_before>'use strict';
/* global window */
var debounce = require('lodash/debounce');
var assign = require('lodash/assign');

function LaserCarousel(el, opts) {
    var self = this;

    self.el = el.children[0];

    self.opts = {
        itemWidth: '100px',
        namespace: '',
        initialSlide: 0,
        itemNavigation: true,
        currentItemSpacing: 1,
        touch: true,
        speed: 300,
        dots: true
    };

    assign(self.opts, opts);

    self.currentItemIdx = self.opts.initialSlide;

    self.items = [];
    self.storeItems();
    self.itemCount = self.items.length;

    self.currentX = 0;
    self.trackWidth = 0;
    self.dragging = false;

    self.settings = {};
    self.initialised = false;

    self.initialize();
}

LaserCarousel.prototype = {
    swipe: require('./swipe'),

    storeItems: function() {
        var self = this,
            items = self.el.getElementsByClassName(self.opts.namespace + 'carousel__item'),
            i = items.length - 1;

        for (i; i >= 0; i--) {
            self.items[i] = {};
            self.items[i].el = items[i].cloneNode(true);
            self.el.removeChild(items[i]);
        }
    },

    applyTrackTransition: function() {
        var self = this;
        self.track.style.transitionProperty = 'transform';
        self.track.style.transitionDuration = self.opts.speed + 'ms';
    },

    panToCurrent: function() {
        var self = this,
            idx = self.currentItemIdx,
            itemWidth = self.el.offsetWidth;

        self.currentX = -idx * itemWidth;
        self.track.style.transform = 'translate3d(' + self.currentX + 'px, 0 ,0)';
    },

    addTrack: function() {
        var self = this,
            i,
            items = self.items;

        self.track = document.createElement('div');
        self.track.classList.add(self.opts.namespace + 'carousel__track');
        self.el.insertBefore(self.track, self.el.firstChild);

        for (i = 0; i < self.items.length; i++) {
            self.track.appendChild(self.items[i].el);
        }
    },

    setTrackWidth: function() {
        var self = this;
        var itemWidth = self.el.offsetWidth;
        itemWidth = parseInt(itemWidth);

        self.trackWidth = itemWidth * self.items.length;
        self.track.style.width = self.trackWidth + 'px';
    },

    addDots: function() {
        var self = this,
            html = '';

        self.carouselNavigation = document.createElement('ul');
        self.carouselNavigation.classList.add(self.opts.namespace + 'carousel__navigation');
        self.el.appendChild(self.carouselNavigation);

        for (var i = 0; i < self.items.length; i++) {
            html += '
' + (i + 1) + '
\n';
        }

        self.carouselNavigation.innerHTML = html;
    },

    setCurrent: function(idx) {
        var self = this,
            items,
            current;

        if (self.currentItem) {
            self.currentItem.classList.remove(self.opts.namespace + 'carousel__item--current');
        }

        self.currentItem = self.items[idx].el;

        if (self.currentItem) {
            self.currentItemIdx = idx;
            self.currentItem.classList.add(self.opts.namespace + 'carousel__item--current');
        }

        if (self.carouselNavigation) {
            current = self.carouselNavigation.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item--current')[0];

            if (current) {
                current.classList.remove(self.opts.namespace + 'carousel__navigation-item--current');
            }

            items = self.carouselNavigation.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item');

            if (items[idx]) {
                items[idx].classList.add(self.opts.namespace + 'carousel__navigation-item--current');
            }
        }
    },

    positionItems: function() {
        var self = this;
        var idx = 0;
        var current;
        var isCurrent = false;

        for (var i = 0; i < self.items.length; i++) {
            current = self.items[i].el;
            isCurrent = false;

            if (self.currentItem && current === self.currentItem) {
                isCurrent = true;
                idx = idx + self.opts.currentItemSpacing;
            }

            current.style.width = self.el.offsetWidth + 'px';
            current.style.transform = 'translate3d(' + (i * 100) + '%, 0%, 0)';
            current.style.display = 'block';
        }
    },

    goto: function(idx) {
        var self = this;
        self.setCurrent(idx);
        self.positionItems();
        self.panToCurrent();
    },

    next: function() {
        var self = this;

        if (self.currentItemIdx + 1 <= self.itemCount - 1 ) {
            self.goto(self.currentItemIdx + 1);
        } else {
            self.goto(self.currentItemIdx);
        }
    },

    previous: function() {
        var self = this;

        if (self.currentItemIdx - 1 >= 0) {
            self.goto(self.currentItemIdx - 1);
        } else {
            self.goto(self.currentItemIdx);
        }
    },

    attachNavigationHandler: function() {
        var self = this;
        var items = self.el.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item');

        var attachClickHandler = function(el, idx) {
            el.addEventListener('click', function(e) {
                if (!self.dragging) {
                    self.goto(idx);
                }

                e.preventDefault();
            });
        };

        for (var i = 0; i < items.length; i++) {
            attachClickHandler(items[i], i);

            if (self.opts.itemNavigation) {
                attachClickHandler(self.items[i].el, i);
            }
        }
    },

    settingsFromBreakpoint: function(breakpoint) {
        var self = this;

        self.settings.itemWidth = breakpoint.itemWidth || self.opts.itemWidth;
        self.settings.initialSlide = breakpoint.initialSlide || self.opts.initialSlide;
        self.settings.currentItemSpacing = breakpoint.currentItemSpacing || self.opts.currentItemSpacing;
        self.settings.speed = breakpoint.speed || self.opts.speed;
    },

    settingsByScreenSize: function() {
        var self = this,
            wWidth = window.offsetWidth,
            breakpointToUse = false;

        // Reset to defaults.
        self.settings.itemWidth = self.opts.itemWidth;
        self.settings.initialSlide = self.opts.initialSlide;
        self.settings.currentItemSpacing = self.opts.currentItemSpacing;
        self.settings.speed = self.opts.speed;

        if (self.opts.responsive) {
            for (var key in self.opts.responsive) {
                if (wWidth > key) {
                    breakpointToUse = key;
                }
            }
        }

        if (breakpointToUse) {
            self.settingsFromBreakpoint(self.opts.responsive[breakpointToUse]);
        }
    },

    start: function() {
        var self = this;

        self.setTrackWidth();
        self.setCurrent(self.currentItemIdx);
        self.positionItems();

        self.panToCurrent();
        self.applyTrackTransition();
    },

    initialize: function() {
        var self = this;

        self.addTrack();

        window.addEventListener('resize', debounce(self.start.bind(self), 300));

        if (self.opts.dots) {
            self.addDots();
        }

        if (self.opts.touch) {
            self.swipe();
        }

        self.start();

        self.attachNavigationHandler();
    }
};

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = LaserCarousel;
} else {
    window.LaserCarousel = LaserCarousel;
}
<commit_msg>added polyfill for classlist<commit_after>'use strict';
/* global window */
require('classlist-polyfill');
var debounce = require('lodash/debounce');
var assign = require('lodash/assign');

function LaserCarousel(el, opts) {
    var self = this;

    self.el = el.children[0];

    self.opts = {
        itemWidth: '100px',
        namespace: '',
        initialSlide: 0,
        itemNavigation: true,
        currentItemSpacing: 1,
        touch: true,
        speed: 300,
        dots: true
    };

    assign(self.opts, opts);

    self.currentItemIdx = self.opts.initialSlide;

    self.items = [];
    self.storeItems();
    self.itemCount = self.items.length;

    self.currentX = 0;
    self.trackWidth = 0;
    self.dragging = false;

    self.settings = {};
    self.initialised = false;

    self.initialize();
}

LaserCarousel.prototype = {
    swipe: require('./swipe'),

    storeItems: function() {
        var self = this,
            items = self.el.getElementsByClassName(self.opts.namespace + 'carousel__item'),
            i = items.length - 1;

        for (i; i >= 0; i--) {
            self.items[i] = {};
            self.items[i].el = items[i].cloneNode(true);
            self.el.removeChild(items[i]);
        }
    },

    applyTrackTransition: function() {
        var self = this;
        self.track.style.transitionProperty = 'transform';
        self.track.style.transitionDuration = self.opts.speed + 'ms';
    },

    panToCurrent: function() {
        var self = this,
            idx = self.currentItemIdx,
            itemWidth = self.el.offsetWidth;

        self.currentX = -idx * itemWidth;
        self.track.style.transform = 'translate3d(' + self.currentX + 'px, 0 ,0)';
    },

    addTrack: function() {
        var self = this,
            i,
            items = self.items;

        self.track = document.createElement('div');
        self.track.classList.add(self.opts.namespace + 'carousel__track');
        self.el.insertBefore(self.track, self.el.firstChild);

        for (i = 0; i < self.items.length; i++) {
            self.track.appendChild(self.items[i].el);
        }
    },

    setTrackWidth: function() {
        var self = this;
        var itemWidth = self.el.offsetWidth;
        itemWidth = parseInt(itemWidth);

        self.trackWidth = itemWidth * self.items.length;
        self.track.style.width = self.trackWidth + 'px';
    },

    addDots: function() {
        var self = this,
            html = '';

        self.carouselNavigation = document.createElement('ul');
        self.carouselNavigation.classList.add(self.opts.namespace + 'carousel__navigation');
        self.el.appendChild(self.carouselNavigation);

        for (var i = 0; i < self.items.length; i++) {
            html += '
' + (i + 1) + '
\n';
        }

        self.carouselNavigation.innerHTML = html;
    },

    setCurrent: function(idx) {
        var self = this,
            items,
            current;

        if (self.currentItem) {
            self.currentItem.classList.remove(self.opts.namespace + 'carousel__item--current');
        }

        self.currentItem = self.items[idx].el;

        if (self.currentItem) {
            self.currentItemIdx = idx;
            self.currentItem.classList.add(self.opts.namespace + 'carousel__item--current');
        }

        if (self.carouselNavigation) {
            current = self.carouselNavigation.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item--current')[0];

            if (current) {
                current.classList.remove(self.opts.namespace + 'carousel__navigation-item--current');
            }

            items = self.carouselNavigation.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item');

            if (items[idx]) {
                items[idx].classList.add(self.opts.namespace + 'carousel__navigation-item--current');
            }
        }
    },

    positionItems: function() {
        var self = this;
        var idx = 0;
        var current;
        var isCurrent = false;

        for (var i = 0; i < self.items.length; i++) {
            current = self.items[i].el;
            isCurrent = false;

            if (self.currentItem && current === self.currentItem) {
                isCurrent = true;
                idx = idx + self.opts.currentItemSpacing;
            }

            current.style.width = self.el.offsetWidth + 'px';
            current.style.transform = 'translate3d(' + (i * 100) + '%, 0%, 0)';
            current.style.display = 'block';
        }
    },

    goto: function(idx) {
        var self = this;
        self.setCurrent(idx);
        self.positionItems();
        self.panToCurrent();
    },

    next: function() {
        var self = this;

        if (self.currentItemIdx + 1 <= self.itemCount - 1 ) {
            self.goto(self.currentItemIdx + 1);
        } else {
            self.goto(self.currentItemIdx);
        }
    },

    previous: function() {
        var self = this;

        if (self.currentItemIdx - 1 >= 0) {
            self.goto(self.currentItemIdx - 1);
        } else {
            self.goto(self.currentItemIdx);
        }
    },

    attachNavigationHandler: function() {
        var self = this;
        var items = self.el.getElementsByClassName(self.opts.namespace + 'carousel__navigation-item');

        var attachClickHandler = function(el, idx) {
            el.addEventListener('click', function(e) {
                if (!self.dragging) {
                    self.goto(idx);
                }

                e.preventDefault();
            });
        };

        for (var i = 0; i < items.length; i++) {
            attachClickHandler(items[i], i);

            if (self.opts.itemNavigation) {
                attachClickHandler(self.items[i].el, i);
            }
        }
    },

    settingsFromBreakpoint: function(breakpoint) {
        var self = this;

        self.settings.itemWidth = breakpoint.itemWidth || self.opts.itemWidth;
        self.settings.initialSlide = breakpoint.initialSlide || self.opts.initialSlide;
        self.settings.currentItemSpacing = breakpoint.currentItemSpacing || self.opts.currentItemSpacing;
        self.settings.speed = breakpoint.speed || self.opts.speed;
    },

    settingsByScreenSize: function() {
        var self = this,
            wWidth = window.offsetWidth,
            breakpointToUse = false;

        // Reset to defaults.
        self.settings.itemWidth = self.opts.itemWidth;
        self.settings.initialSlide = self.opts.initialSlide;
        self.settings.currentItemSpacing = self.opts.currentItemSpacing;
        self.settings.speed = self.opts.speed;

        if (self.opts.responsive) {
            for (var key in self.opts.responsive) {
                if (wWidth > key) {
                    breakpointToUse = key;
                }
            }
        }

        if (breakpointToUse) {
            self.settingsFromBreakpoint(self.opts.responsive[breakpointToUse]);
        }
    },

    start: function() {
        var self = this;

        self.setTrackWidth();
        self.setCurrent(self.currentItemIdx);
        self.positionItems();

        self.panToCurrent();
        self.applyTrackTransition();
    },

    initialize: function() {
        var self = this;

        self.addTrack();

        window.addEventListener('resize', debounce(self.start.bind(self), 300));

        if (self.opts.dots) {
            self.addDots();
        }

        if (self.opts.touch) {
            self.swipe();
        }

        self.start();

        self.attachNavigationHandler();
    }
};

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = LaserCarousel;
} else {
    window.LaserCarousel = LaserCarousel;
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var match = require('posthtml-match-helper');
var genericNames = require('generic-names');

var postcss = require('postcss');
var Values = require('postcss-modules-values');
var LocalByDefault = require('postcss-modules-local-by-default');
var ExtractImports = require('postcss-modules-extract-imports');
var Scope = require('postcss-modules-scope');
var Parser = require('postcss-modules-parser');

/**
 * ⚒ @todo
 * 1. Fix generateScopeName path resolving
 * 2. Fix fetch path resolving (compose: className from '../mixins.css')
 */

/**
 * retieves content of node element
 * or reads file from href attribute of <link module>
 * @param  {Object} node
 * @return {Promise<String>} contents of file or <style> tag
 */
function getContentFromNode(options, node) {
	return new Promise(function (resolve, reject) {
		if (node.tag === 'link') {
			// Path resolving seems ok here 👍
			var filePath = path.join(path.isAbsolute(node.attrs.href) ? options.root : path.dirname(options.from), node.attrs.href);
			return fs.readFile(filePath, 'utf8', function (err, res) {
				return err ? reject(err) : resolve(res);
			});
		}

		return resolve(node.content);
	});
}

/**
 * processes css with css-modules plugins
 * @param  {Object} options [plugin's options]
 * @return {Function}
 */
function processContentWithPostCSS(options, node) {
	/**
	 * @param  {String} content [css to process]
	 * @return {Object}         [object with css tokens and css itself]
	 */
	return function (content) {
		if (options.generateScopedName) {
			options.generateScopedName = typeof options.generateScopedName === 'function' ?
				options.generateScopedName :
				genericNames(options.generateScopedName, {context: options.from || options.root});
		} else {
			options.generateScopedName = function (local, filename) {
				// @todo
				// 😭 Wondering how to fix name resolving...
				var filePath = path.join(path.dirname(options.from), path.basename(node.attrs.href || filename)).replace(options.root, '');
				return Scope.generateScopedName(local, filePath);
			};
		}

		// Setup css-modules plugins 💼
		var runner = postcss([
			Values,
			LocalByDefault,
			ExtractImports,
			new Scope({generateScopedName: options.generateScopedName}),
			new Parser({fetch: fetch})
		].concat(options.plugins));

		function fetch(to) {
			// @todo
			// 😭 Wondering how to fix name resolving...
			var filePath = path.join(path.isAbsolute(to) ? options.root : path.dirname(options.from), to);

			return new Promise(function (resolve, reject) {
				return fs.readFile(filePath, 'utf8', function (err, css) {
					/* istanbul ignore next: just error handler */
					if (err) {
						return reject(err);
					}

					return runner.process(css, {from: filePath})
						.then(function (result) {
							return resolve(result.root.tokens);
						}).catch(reject);
				});
			});
		}

		return runner.process(content);
	};
}

module.exports = function plugin(options) {
	options = options || {};
	options.root = path.resolve(options.root || './');
	options.plugins = options.plugins || [];
	options.from = options.from || '';

	return function parse(tree) {
		var promises = [];

		tree.match(match('link[module][href], style[module]'), function (node) {
			promises.push(getContentFromNode(options, node)
				.then(processContentWithPostCSS(options, node))
				.then(function (processed) {
					/**
					 * Replacing all classname attributes in html,
					 * which classes from css
					 */
					Object.keys(processed.root.tokens).forEach(function (key) {
						tree.match({attrs: {classname: new RegExp('(?:^|\\s)' + key + '(?:\\s|$)')}}, function (node) {
							node.attrs.class = node.attrs.class ? node.attrs.class + ' ' + processed.root.tokens[key] : processed.root.tokens[key];
							return node;
						});
					});

					// Remove classnames attribute from everything
					tree.match(match('[classname]'), function (node) {
						delete node.attrs.classname;
						return node;
					});

					/**
					 * Remove href and module attributes
					 * and replace tag with <style>
					 * and content with parsed css, hooray! 🙌
					 */
					delete node.attrs.href;
					delete node.attrs.module;
					node.tag = 'style';
					node.content = processed.css;
				})
			);

			return node;
		});

		return promises.length ? Promise.all(promises).then(function () {
			return tree;
		}) : tree;
	};
};
<commit_msg>Fix paths resolving. (untested)<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var match = require('posthtml-match-helper');
var genericNames = require('generic-names');

var postcss = require('postcss');
var Values = require('postcss-modules-values');
var LocalByDefault = require('postcss-modules-local-by-default');
var ExtractImports = require('postcss-modules-extract-imports');
var Scope = require('postcss-modules-scope');
var Parser = require('postcss-modules-parser');

/**
 * retieves content of node element
 * or reads file from href attribute of <link module>
 * @param  {Object} node
 * @return {Promise<String>} contents of file or <style> tag
 */
function getContentFromNode(options, node) {
	return new Promise(function (resolve, reject) {
		if (node.tag === 'link') {
			return fs.readFile(normalizePath(node.attrs.href, options.root, options.from), 'utf8', function (err, res) {
				return err ? reject(err) : resolve(res);
			});
		}

		return resolve(node.content);
	});
}

/**
 * [normalizePath description]
 * @param  {String} href  [path to the file]
 * @param  {String} _root [context]
 * @param  {String} _from [relative file]
 * @return {String}       [absolute path to file]
 */
function normalizePath(href, _root, _from) {
	return path.join(path.isAbsolute(href) ? _root : path.dirname(_from), href);
}

/**
 * processes css with css-modules plugins
 * @param  {Object} options [plugin's options]
 * @return {Function}
 */
function processContentWithPostCSS(options, href) {
	/**
	 * @param  {String} content [css to process]
	 * @return {Object}         [object with css tokens and css itself]
	 */
	return function (content) {
		if (options.generateScopedName) {
			options.generateScopedName = typeof options.generateScopedName === 'function' ?
				options.generateScopedName :
				genericNames(options.generateScopedName, {context: options.root});
		} else {
			options.generateScopedName = function (local, filename) {
				return Scope.generateScopedName(local, path.relative(options.root, filename));
			};
		}

		function fetch(_to, _from) {
			// Seems ok 👏
			var filePath = normalizePath(_to, options.root, _from);

			return new Promise(function (resolve, reject) {
				return fs.readFile(filePath, 'utf8', function (err, content) {
					/* istanbul ignore next: just error handler */
					if (err) {
						return reject(err);
					}

					return runner.process(content, {from: filePath})
						.then(function (result) {
							return resolve(result.root.tokens);
						}).catch(reject);
				});
			});
		}

		// Setup css-modules plugins 💼
		var runner = postcss([
			Values,
			LocalByDefault,
			ExtractImports,
			new Scope({generateScopedName: options.generateScopedName}),
			new Parser({fetch: fetch})
		].concat(options.plugins));

		return runner.process(content, {from: normalizePath(href, options.root, options.from)});
	};
}

module.exports = function plugin(options) {
	options = options || {};
	options.root = path.resolve(options.root || './');
	options.plugins = options.plugins || [];
	options.from = options.from || '';

	return function parse(tree) {
		var promises = [];

		tree.match(match('link[module][href]'), function (node) {
			promises.push(getContentFromNode(options, node)
				.then(processContentWithPostCSS(options, node.attrs && node.attrs.href))
				.then(function (processed) {
					/**
					 * Replacing all classname attributes in html,
					 * with classes from css
					 */
					Object.keys(processed.root.tokens).forEach(function (key) {
						tree.match({attrs: {classname: new RegExp('(?:^|\\s)' + key + '(?:\\s|$)')}}, function (node) {
							node.attrs.class = node.attrs.class ? node.attrs.class + ' ' + processed.root.tokens[key] : processed.root.tokens[key];
							return node;
						});
					});

					// Remove classname attribute from everything
					tree.match(match('[classname]'), function (node) {
						delete node.attrs.classname;
						return node;
					});

					/**
					 * Remove href and module attributes
					 * and replace tag with <style>
					 * and content with parsed css, hooray! 🙌
					 */
					delete node.attrs.href;
					delete node.attrs.module;
					node.tag = 'style';
					node.content = processed.css;
				})
			);

			return node;
		});

		return promises.length ? Promise.all(promises).then(function () {
			return tree;
		}) : tree;
	};
};
<|endoftext|>