<commit_before>var path = require('path');
var mkdirp = require('mkdirp');
var includePathSearcher = require('include-path-searcher');
var CachingWriter = require('broccoli-caching-writer');
var nodeSass = require('node-sass');
var assign = require('object-assign');
var rsvp = require('rsvp');
var Promise = rsvp.Promise;
var fs = require('fs');
var writeFile = rsvp.denodeify(fs.writeFile);

module.exports = SassCompiler;
SassCompiler.prototype = Object.create(CachingWriter.prototype);
SassCompiler.prototype.constructor = SassCompiler;

function SassCompiler (inputNodes, inputFile, outputFile, options) {
  if (!(this instanceof SassCompiler)) { return new SassCompiler(inputNodes, inputFile, outputFile, options); }
  if (!Array.isArray(inputNodes)) { throw new Error('Expected array for first argument - did you mean [tree] instead of tree?'); }

  CachingWriter.call(this, inputNodes, {
    annotation: options.annotation,
    cacheInclude: options.cacheInclude,
    cacheExclude: options.cacheExclude
  });

  this.inputFile = inputFile;
  this.outputFile = outputFile;
  options = options || {};
  this.options = {
    nodeSass: options.nodeSass
  };

  var sass = this.options.nodeSass || nodeSass;

  this.renderSass = rsvp.denodeify(sass.render);

  this.sassOptions = {
    importer: options.importer,
    functions: options.functions,
    indentedSyntax: options.indentedSyntax,
    omitSourceMapUrl: options.omitSourceMapUrl,
    outputStyle: options.outputStyle,
    precision: options.precision,
    sourceComments: options.sourceComments,
    sourceMap: options.sourceMap,
    sourceMapEmbed: options.sourceMapEmbed,
    sourceMapContents: options.sourceMapContents,
    sourceMapRoot: options.sourceMapRoot
  };
}

SassCompiler.prototype.build = function() {
  var destFile = path.join(this.outputPath, this.outputFile);
  var sourceMapFile = this.sassOptions.sourceMap;

  if (typeof sourceMapFile !== 'string') {
    sourceMapFile = destFile + '.map';
  }

  mkdirp.sync(path.dirname(destFile));

  var sassOptions = {
    file: includePathSearcher.findFileSync(this.inputFile, this.inputPaths),
    includePaths: this.inputPaths,
    outFile: destFile
  };

  assign(sassOptions, this.sassOptions);

  return this.renderSass(sassOptions).then(function(result) {
    var files = [
      writeFile(destFile, result.css)
    ];

    if (this.sassOptions.sourceMap && !this.sassOptions.sourceMapEmbed) {
      files.push(writeFile(sourceMapFile, result.map));
    }

    return Promise.all(files);
  }.bind(this));
};
<commit_msg>fix Sass errors for better Ember CLI error messages<commit_after>var path = require('path');
var mkdirp = require('mkdirp');
var includePathSearcher = require('include-path-searcher');
var CachingWriter = require('broccoli-caching-writer');
var nodeSass = require('node-sass');
var assign = require('object-assign');
var rsvp = require('rsvp');
var Promise = rsvp.Promise;
var fs = require('fs');
var writeFile = rsvp.denodeify(fs.writeFile);

module.exports = SassCompiler;
SassCompiler.prototype = Object.create(CachingWriter.prototype);
SassCompiler.prototype.constructor = SassCompiler;

function SassCompiler (inputNodes, inputFile, outputFile, options) {
  if (!(this instanceof SassCompiler)) { return new SassCompiler(inputNodes, inputFile, outputFile, options); }
  if (!Array.isArray(inputNodes)) { throw new Error('Expected array for first argument - did you mean [tree] instead of tree?'); }

  CachingWriter.call(this, inputNodes, {
    annotation: options.annotation,
    cacheInclude: options.cacheInclude,
    cacheExclude: options.cacheExclude
  });

  this.inputFile = inputFile;
  this.outputFile = outputFile;
  options = options || {};
  this.options = {
    nodeSass: options.nodeSass
  };

  var sass = this.options.nodeSass || nodeSass;

  this.renderSass = rsvp.denodeify(sass.render);

  this.sassOptions = {
    importer: options.importer,
    functions: options.functions,
    indentedSyntax: options.indentedSyntax,
    omitSourceMapUrl: options.omitSourceMapUrl,
    outputStyle: options.outputStyle,
    precision: options.precision,
    sourceComments: options.sourceComments,
    sourceMap: options.sourceMap,
    sourceMapEmbed: options.sourceMapEmbed,
    sourceMapContents: options.sourceMapContents,
    sourceMapRoot: options.sourceMapRoot
  };
}

/**
 * Mutates the error to include properties expected by Ember CLI.
 * See https://github.com/ember-cli/ember-cli/blob/master/docs/ERRORS.md#error-object
 * @param {Error} error
 */
function rethrowBuildError(error) {
  if (typeof error === 'string') {
    throw new Error('[string exception] ' + error);
  } else {
    error.type = 'Sass Syntax Error';
    error.message = error.formatted;
    error.location = {
      line: error.line,
      column: error.column
    };

    throw error;
  }
}

SassCompiler.prototype.build = function() {
  var destFile = path.join(this.outputPath, this.outputFile);
  var sourceMapFile = this.sassOptions.sourceMap;

  if (typeof sourceMapFile !== 'string') {
    sourceMapFile = destFile + '.map';
  }

  mkdirp.sync(path.dirname(destFile));

  var sassOptions = {
    file: includePathSearcher.findFileSync(this.inputFile, this.inputPaths),
    includePaths: this.inputPaths,
    outFile: destFile
  };

  assign(sassOptions, this.sassOptions);

  return this.renderSass(sassOptions).then(function(result) {
    var files = [
      writeFile(destFile, result.css)
    ];

    if (this.sassOptions.sourceMap && !this.sassOptions.sourceMapEmbed) {
      files.push(writeFile(sourceMapFile, result.map));
    }

    return Promise.all(files);
  }.bind(this)).catch(rethrowBuildError);
};
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

const path = require('path');
const SilentError = require('silent-error');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const Babel = require('broccoli-babel-transpiler');
const merge = require('broccoli-merge-trees');
const semver = require('semver');
const version = require('./lib/version');
const BroccoliDebug = require('broccoli-debug');
const calculateCacheKeyForTree = require('calculate-cache-key-for-tree');

// allow toggling of heimdall instrumentation
let INSTRUMENT_HEIMDALL = false;
let args = process.argv;

for (let i = 1; i < args.length; i++) {
  if (args[i] === '--instrument') {
    INSTRUMENT_HEIMDALL = true;
    break;
  }
}
const NOOP_TREE = function(dir) {
  return { inputTree: dir, rebuild() { return []; } };
};

process.env.INSTRUMENT_HEIMDALL = INSTRUMENT_HEIMDALL;

function isProductionEnv() {
  let isProd = /production/.test(process.env.EMBER_ENV);
  let isTest = process.env.EMBER_CLI_TEST_COMMAND;

  return isProd && !isTest;
}

function isInstrumentedBuild() {
  return INSTRUMENT_HEIMDALL;
}

module.exports = {
  name: 'ember-data',

  _prodLikeWarning() {
    let emberEnv = process.env.EMBER_ENV
    if(emberEnv !== 'production' && /production/.test(emberEnv)) {
      this._warn(`Production-like values for EMBER_ENV are deprecated (your EMBER_ENV is "${emberEnv}") and support will be removed in Ember Data 4.0.0. If using ember-cli-deploy, please configure your build using 'production'. Otherwise please set your EMBER_ENV to 'production' for production builds.`);
    }
  },

  _warn(message) {
    let chalk = require('chalk');
    let warning = chalk.yellow('WARNING: ' + message);

    if (this.ui && this.ui.writeWarnLine) {
      this.ui.writeWarnLine(message);
    } else if (this.ui) {
      this.ui.writeLine(warning);
    } else {
      console.log(warning);
    }
  },

  getOutputDirForVersion() {
    let VersionChecker = require('ember-cli-version-checker');
    let checker = new VersionChecker(this);
    let emberCli = checker.for('ember-cli', 'npm');

    let requiresModulesDir = emberCli.satisfies('< 3.0.0');

    return requiresModulesDir ? 'modules' : '';
  },

  init() {
    this._super.init && this._super.init.apply(this, arguments);
    this._prodLikeWarning();
    this.debugTree = BroccoliDebug.buildDebugCallback('ember-data');

    let bowerDeps = this.project.bowerDependencies();

    let VersionChecker = require('ember-cli-version-checker');
    let options = this.options = this.options || {};

    let checker = new VersionChecker(this);
    // prevent errors when ember-cli-shims is no longer required
    let shims = bowerDeps['ember-cli-shims'] && checker.for('ember-cli-shims', 'bower');

    let version = require('./package').version;

    if (process.env.EMBER_DATA_SKIP_VERSION_CHECKING_DO_NOT_USE_THIS_ENV_VARIABLE) {
      // Skip for node tests as we can't currently override the version of ember-cli-shims
      // before the test helpers run.
      return;
    }

    let hasShims = !!shims;
    let shimsHasEmberDataShims = hasShims && shims.satisfies('< 0.1.0');
    let emberDataNPMWithShimsIncluded = semver.satisfies(version, '^2.3.0-beta.3');

    if (bowerDeps['ember-data']) {
      this._warn('Please remove `ember-data` from `bower.json`. As of Ember Data 2.3.0, only the NPM package is needed. If you need an ' +
                'earlier version of ember-data (< 2.3.0), you can leave this unchanged for now, but we strongly suggest you upgrade your version of Ember Data ' +
                'as soon as possible.');
      this._forceBowerUsage = true;

      let emberDataBower = checker.for('ember-data', 'bower');
      let emberDataBowerWithShimsIncluded = emberDataBower.satisfies('>= 2.3.0-beta.3');

      if (hasShims && !shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims greater than or equal to 0.1.0 will cause errors while loading Ember Data < 2.3.0-beta.3 Please update ember-cli-shims from ' + shims.version + ' to 0.0.6');
      }

      if (hasShims && shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims prior to 0.1.0 will cause errors while loading Ember Data 2.3.0-beta.3+. Please update ember-cli-shims from ' + shims.version + ' to 0.1.0.');
      }

    } else {
      // NPM only, but ember-cli-shims does not match
      if (hasShims && shimsHasEmberDataShims && emberDataNPMWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims prior to 0.1.0 will cause errors while loading Ember Data 2.3.0-beta.3+. Please update ember-cli-shims from ' + shims.version + ' to 0.1.0.');
      }
    }
  },

  blueprintsPath() {
    return path.join(__dirname, 'blueprints');
  },

  treeForApp(dir) {
    if (this._forceBowerUsage) { return NOOP_TREE(dir); }

    // this._super.treeForApp is undefined in ember-cli (1.13) for some reason.
    // TODO: investigate why treeForApp isn't on _super
    return dir;
  },

  treeForAddon(tree) {
    if (this._forceBowerUsage) { return NOOP_TREE(tree); }

    tree = this.debugTree(tree, 'input');

    let babel = this.addons.find(addon => addon.name === 'ember-cli-babel');

    let treeWithVersion = merge([
      tree,
      version() // compile the VERSION into the build
    ]);

    let withPrivate    = new Funnel(tree, { include: ['-private/**'] });
    let withoutPrivate = new Funnel(treeWithVersion, {
      exclude: [
        '-private',
        isProductionEnv() && !isInstrumentedBuild() ? '-debug' : false
      ].filter(Boolean),

      destDir: 'ember-data'
    });

    let privateTree = babel.transpileTree(this.debugTree(withPrivate, 'babel-private:input'), {
      babel: this.buildBabelOptions(),
      'ember-cli-babel': {
        compileModules: false
      }
    });

    privateTree = this.debugTree(privateTree, 'babel-private:output');

    // use the default options
    let publicTree = babel.transpileTree(this.debugTree(withoutPrivate, 'babel-public:input'));

    publicTree = this.debugTree(publicTree, 'babel-public:output');

    privateTree = new Rollup(privateTree, {
      rollup: {
        entry: '-private/index.js',
        targets: [
          { dest: 'ember-data/-private.js', format: babel.shouldCompileModules() ? 'amd' : 'es', moduleId: 'ember-data/-private' }
        ],
        external: [
          'ember',
          'ember-inflector',
          'ember-data/version',
          'ember-data/-debug',
          'ember-data/adapters/errors'
        ]
        // cache: true|false Defaults to true
      }
    });

    privateTree = this.debugTree(privateTree, 'rollup-output');

    let destDir = this.getOutputDirForVersion();

    publicTree  = new Funnel(publicTree,  { destDir });
    privateTree = new Funnel(privateTree, { destDir });

    return this.debugTree(merge([
      publicTree,
      privateTree
    ]), 'final');
  },

  buildBabelOptions() {
    let customPlugins = require('./lib/stripped-build-plugins')(process.env.EMBER_ENV);

    return {
      loose: true,
      plugins: customPlugins.plugins,
      postTransformPlugins: customPlugins.postTransformPlugins,
      exclude: [
        'transform-es2015-block-scoping',
        'transform-es2015-typeof-symbol'
      ]
    };
  },

  _setupBabelOptions() {
    if (this._hasSetupBabelOptions) {
      return;
    }

    this.options.babel = this.buildBabelOptions();

    this._hasSetupBabelOptions = true;
  },

  included(app) {
    this._super.included.apply(this, arguments);

    this._setupBabelOptions();

    if (this._forceBowerUsage) {
      this.app.import({
        development: app.bowerDirectory + '/ember-data/ember-data.js',
        production: app.bowerDirectory + '/ember-data/ember-data.prod.js'
      });
    }
  },

  cacheKeyForTree(treeType) {
    return calculateCacheKeyForTree(treeType, this);
  }
};
<commit_msg>fix external ordered set dependency<commit_after>/* eslint-env node */
'use strict';

const path = require('path');
const SilentError = require('silent-error');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const Babel = require('broccoli-babel-transpiler');
const merge = require('broccoli-merge-trees');
const semver = require('semver');
const version = require('./lib/version');
const BroccoliDebug = require('broccoli-debug');
const calculateCacheKeyForTree = require('calculate-cache-key-for-tree');

// allow toggling of heimdall instrumentation
let INSTRUMENT_HEIMDALL = false;
let args = process.argv;

for (let i = 1; i < args.length; i++) {
  if (args[i] === '--instrument') {
    INSTRUMENT_HEIMDALL = true;
    break;
  }
}
const NOOP_TREE = function(dir) {
  return { inputTree: dir, rebuild() { return []; } };
};

process.env.INSTRUMENT_HEIMDALL = INSTRUMENT_HEIMDALL;

function isProductionEnv() {
  let isProd = /production/.test(process.env.EMBER_ENV);
  let isTest = process.env.EMBER_CLI_TEST_COMMAND;

  return isProd && !isTest;
}

function isInstrumentedBuild() {
  return INSTRUMENT_HEIMDALL;
}

module.exports = {
  name: 'ember-data',

  _prodLikeWarning() {
    let emberEnv = process.env.EMBER_ENV
    if(emberEnv !== 'production' && /production/.test(emberEnv)) {
      this._warn(`Production-like values for EMBER_ENV are deprecated (your EMBER_ENV is "${emberEnv}") and support will be removed in Ember Data 4.0.0. If using ember-cli-deploy, please configure your build using 'production'. Otherwise please set your EMBER_ENV to 'production' for production builds.`);
    }
  },

  _warn(message) {
    let chalk = require('chalk');
    let warning = chalk.yellow('WARNING: ' + message);

    if (this.ui && this.ui.writeWarnLine) {
      this.ui.writeWarnLine(message);
    } else if (this.ui) {
      this.ui.writeLine(warning);
    } else {
      console.log(warning);
    }
  },

  getOutputDirForVersion() {
    let VersionChecker = require('ember-cli-version-checker');
    let checker = new VersionChecker(this);
    let emberCli = checker.for('ember-cli', 'npm');

    let requiresModulesDir = emberCli.satisfies('< 3.0.0');

    return requiresModulesDir ? 'modules' : '';
  },

  init() {
    this._super.init && this._super.init.apply(this, arguments);
    this._prodLikeWarning();
    this.debugTree = BroccoliDebug.buildDebugCallback('ember-data');

    let bowerDeps = this.project.bowerDependencies();

    let VersionChecker = require('ember-cli-version-checker');
    let options = this.options = this.options || {};

    let checker = new VersionChecker(this);
    // prevent errors when ember-cli-shims is no longer required
    let shims = bowerDeps['ember-cli-shims'] && checker.for('ember-cli-shims', 'bower');

    let version = require('./package').version;

    if (process.env.EMBER_DATA_SKIP_VERSION_CHECKING_DO_NOT_USE_THIS_ENV_VARIABLE) {
      // Skip for node tests as we can't currently override the version of ember-cli-shims
      // before the test helpers run.
      return;
    }

    let hasShims = !!shims;
    let shimsHasEmberDataShims = hasShims && shims.satisfies('< 0.1.0');
    let emberDataNPMWithShimsIncluded = semver.satisfies(version, '^2.3.0-beta.3');

    if (bowerDeps['ember-data']) {
      this._warn('Please remove `ember-data` from `bower.json`. As of Ember Data 2.3.0, only the NPM package is needed. If you need an ' +
                'earlier version of ember-data (< 2.3.0), you can leave this unchanged for now, but we strongly suggest you upgrade your version of Ember Data ' +
                'as soon as possible.');
      this._forceBowerUsage = true;

      let emberDataBower = checker.for('ember-data', 'bower');
      let emberDataBowerWithShimsIncluded = emberDataBower.satisfies('>= 2.3.0-beta.3');

      if (hasShims && !shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims greater than or equal to 0.1.0 will cause errors while loading Ember Data < 2.3.0-beta.3 Please update ember-cli-shims from ' + shims.version + ' to 0.0.6');
      }

      if (hasShims && shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims prior to 0.1.0 will cause errors while loading Ember Data 2.3.0-beta.3+. Please update ember-cli-shims from ' + shims.version + ' to 0.1.0.');
      }

    } else {
      // NPM only, but ember-cli-shims does not match
      if (hasShims && shimsHasEmberDataShims && emberDataNPMWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims prior to 0.1.0 will cause errors while loading Ember Data 2.3.0-beta.3+. Please update ember-cli-shims from ' + shims.version + ' to 0.1.0.');
      }
    }
  },

  blueprintsPath() {
    return path.join(__dirname, 'blueprints');
  },

  treeForApp(dir) {
    if (this._forceBowerUsage) { return NOOP_TREE(dir); }

    // this._super.treeForApp is undefined in ember-cli (1.13) for some reason.
    // TODO: investigate why treeForApp isn't on _super
    return dir;
  },

  treeForAddon(tree) {
    if (this._forceBowerUsage) { return NOOP_TREE(tree); }

    tree = this.debugTree(tree, 'input');

    let babel = this.addons.find(addon => addon.name === 'ember-cli-babel');

    let treeWithVersion = merge([
      tree,
      version() // compile the VERSION into the build
    ]);

    let withPrivate    = new Funnel(tree, { include: ['-private/**'] });
    let withoutPrivate = new Funnel(treeWithVersion, {
      exclude: [
        '-private',
        isProductionEnv() && !isInstrumentedBuild() ? '-debug' : false
      ].filter(Boolean),

      destDir: 'ember-data'
    });

    let privateTree = babel.transpileTree(this.debugTree(withPrivate, 'babel-private:input'), {
      babel: this.buildBabelOptions(),
      'ember-cli-babel': {
        compileModules: false
      }
    });

    privateTree = this.debugTree(privateTree, 'babel-private:output');

    // use the default options
    let publicTree = babel.transpileTree(this.debugTree(withoutPrivate, 'babel-public:input'));

    publicTree = this.debugTree(publicTree, 'babel-public:output');

    privateTree = new Rollup(privateTree, {
      rollup: {
        entry: '-private/index.js',
        targets: [
          { dest: 'ember-data/-private.js', format: babel.shouldCompileModules() ? 'amd' : 'es', moduleId: 'ember-data/-private' }
        ],
        external: [
          'ember',
          'ember-inflector',
          'ember-data/version',
          'ember-data/-debug',
          'ember-data/adapters/errors',
          '@ember/ordered-set'
        ]
        // cache: true|false Defaults to true
      }
    });

    privateTree = this.debugTree(privateTree, 'rollup-output');

    let destDir = this.getOutputDirForVersion();

    publicTree  = new Funnel(publicTree,  { destDir });
    privateTree = new Funnel(privateTree, { destDir });

    return this.debugTree(merge([
      publicTree,
      privateTree
    ]), 'final');
  },

  buildBabelOptions() {
    let customPlugins = require('./lib/stripped-build-plugins')(process.env.EMBER_ENV);

    return {
      loose: true,
      plugins: customPlugins.plugins,
      postTransformPlugins: customPlugins.postTransformPlugins,
      exclude: [
        'transform-es2015-block-scoping',
        'transform-es2015-typeof-symbol'
      ]
    };
  },

  _setupBabelOptions() {
    if (this._hasSetupBabelOptions) {
      return;
    }

    this.options.babel = this.buildBabelOptions();

    this._hasSetupBabelOptions = true;
  },

  included(app) {
    this._super.included.apply(this, arguments);

    this._setupBabelOptions();

    if (this._forceBowerUsage) {
      this.app.import({
        development: app.bowerDirectory + '/ember-data/ember-data.js',
        production: app.bowerDirectory + '/ember-data/ember-data.prod.js'
      });
    }
  },

  cacheKeyForTree(treeType) {
    return calculateCacheKeyForTree(treeType, this);
  }
};
<|endoftext|>


<commit_before>// reference:
// http://cs1.bradley.edu/public/jcm/weileratherton.html
// http://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm
var inside = require('turf-inside');
var polygon = require('turf-polygon');
var point = require('turf-point');

module.exports = function (subject, clip) {
    var subjectPolygon = subject;
    subjectPolygon.push([subjectPolygon[0], subjectPolygon[1]]);
    //var clipPolygon = polygon([clip])
    var subjectList = new Polygon();
    var clipList = new Polygon();

    for(var i = 0; i < subject.length; i++){
        subjectList.add(new Point(subject[i][0], subject[i][1]));
    }
    for(var i = 0; i < clip.length; i++){
        clipList.add(new Point(clip[i][0], clip[i][1]));
    }

    var currentSubject = subjectList.first;
    var clipList = clipList.first;
    for(var i = 0; i < subject.length; i++) {
        for(var k = 0; k < clip.length; k++) {
            console.log(k)
            var intersection = lineIntersects(
                currentSubject.point.x,
                currentSubject.point.y,
                currentSubject.next.point.x,
                currentSubject.next.point.y,
                currentClip.point.x,
                currentClip.point.y,
                currentClip.next.point.x,
                currentClip.next.point.y);

            if(intersection) {
                var isEntering = !isInside([currentClip.point.x, currentClip.point.y], subjectPolygon);
                subjectList.insertBefore(new Point(intersection[0], intersection[1], isEntering), currentSubject.next);
                console.log(currentClip)
                clipList.insertBefore(new Point(intersection[0], intersection[1], isEntering), currentClip.next);
            }
            currentClip = currentClip.next;
        }
        currentSubject = currentSubject.next;
    }
}

// modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {
    // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point
    var denominator, a, b, numerator1, numerator2, result = {
        x: null,
        y: null,
        onLine1: false,
        onLine2: false
    };
    denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY));
    if (denominator == 0) {
        if(result.x != null && result.y != null) {
            return result;
        } else {
            return false;
        }
    }
    a = line1StartY - line2StartY;
    b = line1StartX - line2StartX;
    numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b);
    numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b);
    a = numerator1 / denominator;
    b = numerator2 / denominator;

    // if we cast these lines infinitely in both directions, they intersect here:
    result.x = line1StartX + (a * (line1EndX - line1StartX));
    result.y = line1StartY + (a * (line1EndY - line1StartY));

    // if line1 is a segment and line2 is infinite, they intersect if:
    if (a > 0 && a < 1) {
        result.onLine1 = true;
    }
    // if line2 is a segment and line1 is infinite, they intersect if:
    if (b > 0 && b < 1) {
        result.onLine2 = true;
    }
    // if line1 and line2 are segments, they intersect if both of the above are true
    if(result.onLine1 && result.onLine2){
        return [result.x, result.y];
    }
    else {
        return false;
    }
}

// polygon contour as a doubly linked list
// https://github.com/mapbox/seidel/blob/master/src/polygon.js
function Polygon() {
    this.length = 0;
    this.first = null;
    this.last = null;
}

function PolygonNode(point) {
    this.point = point;
    this.next = null;
    this.prev = null;
    this.ear = false;
}

Polygon.prototype = {
    add: function (point) {
        var node = new PolygonNode(point);

        if (!this.length) {
            this.first = this.last = node;

        } else {
            this.last.next = node;
            node.prev = this.last;
            this.last = node;
        }

        this.length++;
    },

    remove: function (node) {
        if (!this.length) return;

        if (node === this.first) {
            this.first = this.first.next;

            if (!this.first) this.last = null;
            else this.first.prev = null;

        } else if (node === this.last) {
            this.last = this.last.prev;
            this.last.next = null;

        } else {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }

        node.prev = null;
        node.next = null;

        this.length--;
    },

    insertBefore: function (point, node) {
        //console.log(node)
        var newNode = new PolygonNode(point);
        newNode.prev = node.prev;
        newNode.next = node;

        if (!node.prev) this.first = newNode;
        else node.prev.next = newNode;

        node.prev = newNode;

        this.length++;
    }
};

//modified from https://github.com/mapbox/seidel/blob/master/src/point.js
function Point(x, y, entering) {
    this.x = x;
    this.y = y;
    this.entering = entering;
}

//modified from https://github.com/Turfjs/turf-inside/blob/master/index.js
function isInside(point, polygon){
  var x = point[0];
  var y = point[1];
  var vs = polygon;

  var isInside = false;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i][0], yi = vs[i][1];
    var xj = vs[j][0], yj = vs[j][1];

    var intersect = ((yi > y) != (yj > y))
        && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) isInside = !isInside;
  }
  return isInside;
}<commit_msg>remove dead require statements<commit_after>// reference:
// http://cs1.bradley.edu/public/jcm/weileratherton.html
// http://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm

module.exports = function (subject, clip) {
    var subjectPolygon = subject;
    subjectPolygon.push([subjectPolygon[0], subjectPolygon[1]]);
    //var clipPolygon = polygon([clip])
    var subjectList = new Polygon();
    var clipList = new Polygon();

    for(var i = 0; i < subject.length; i++){
        subjectList.add(new Point(subject[i][0], subject[i][1]));
    }
    for(var i = 0; i < clip.length; i++){
        clipList.add(new Point(clip[i][0], clip[i][1]));
    }

    var currentSubject = subjectList.first;
    var clipList = clipList.first;
    for(var i = 0; i < subject.length; i++) {
        for(var k = 0; k < clip.length; k++) {
            console.log(k)
            var intersection = lineIntersects(
                currentSubject.point.x,
                currentSubject.point.y,
                currentSubject.next.point.x,
                currentSubject.next.point.y,
                currentClip.point.x,
                currentClip.point.y,
                currentClip.next.point.x,
                currentClip.next.point.y);

            if(intersection) {
                var isEntering = !isInside([currentClip.point.x, currentClip.point.y], subjectPolygon);
                subjectList.insertBefore(new Point(intersection[0], intersection[1], isEntering), currentSubject.next);
                console.log(currentClip)
                clipList.insertBefore(new Point(intersection[0], intersection[1], isEntering), currentClip.next);
            }
            currentClip = currentClip.next;
        }
        currentSubject = currentSubject.next;
    }
}

// modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
function lineIntersects(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY) {
    // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point
    var denominator, a, b, numerator1, numerator2, result = {
        x: null,
        y: null,
        onLine1: false,
        onLine2: false
    };
    denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY));
    if (denominator == 0) {
        if(result.x != null && result.y != null) {
            return result;
        } else {
            return false;
        }
    }
    a = line1StartY - line2StartY;
    b = line1StartX - line2StartX;
    numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b);
    numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b);
    a = numerator1 / denominator;
    b = numerator2 / denominator;

    // if we cast these lines infinitely in both directions, they intersect here:
    result.x = line1StartX + (a * (line1EndX - line1StartX));
    result.y = line1StartY + (a * (line1EndY - line1StartY));

    // if line1 is a segment and line2 is infinite, they intersect if:
    if (a > 0 && a < 1) {
        result.onLine1 = true;
    }
    // if line2 is a segment and line1 is infinite, they intersect if:
    if (b > 0 && b < 1) {
        result.onLine2 = true;
    }
    // if line1 and line2 are segments, they intersect if both of the above are true
    if(result.onLine1 && result.onLine2){
        return [result.x, result.y];
    }
    else {
        return false;
    }
}

// polygon contour as a doubly linked list
// https://github.com/mapbox/seidel/blob/master/src/polygon.js
function Polygon() {
    this.length = 0;
    this.first = null;
    this.last = null;
}

function PolygonNode(point) {
    this.point = point;
    this.next = null;
    this.prev = null;
    this.ear = false;
}

Polygon.prototype = {
    add: function (point) {
        var node = new PolygonNode(point);

        if (!this.length) {
            this.first = this.last = node;

        } else {
            this.last.next = node;
            node.prev = this.last;
            this.last = node;
        }

        this.length++;
    },

    remove: function (node) {
        if (!this.length) return;

        if (node === this.first) {
            this.first = this.first.next;

            if (!this.first) this.last = null;
            else this.first.prev = null;

        } else if (node === this.last) {
            this.last = this.last.prev;
            this.last.next = null;

        } else {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }

        node.prev = null;
        node.next = null;

        this.length--;
    },

    insertBefore: function (point, node) {
        //console.log(node)
        var newNode = new PolygonNode(point);
        newNode.prev = node.prev;
        newNode.next = node;

        if (!node.prev) this.first = newNode;
        else node.prev.next = newNode;

        node.prev = newNode;

        this.length++;
    }
};

//modified from https://github.com/mapbox/seidel/blob/master/src/point.js
function Point(x, y, entering) {
    this.x = x;
    this.y = y;
    this.entering = entering;
}

//modified from https://github.com/Turfjs/turf-inside/blob/master/index.js
function isInside(point, polygon){
  var x = point[0];
  var y = point[1];
  var vs = polygon;

  var isInside = false;
  for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    var xi = vs[i][0], yi = vs[i][1];
    var xj = vs[j][0], yj = vs[j][1];

    var intersect = ((yi > y) != (yj > y))
        && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
    if (intersect) isInside = !isInside;
  }
  return isInside;
}<|endoftext|>


<commit_before>'use strict';

var curly = require('curly');
var crypto = require('crypto');
var parseURL = require('url').parse;

var signer = function (publicKey, secretKey) {
  var stringToSign = function (verb, resource, headers) {
    var lowerCaseHeaders = {};

    Object.keys(headers).forEach(function (header) {
      lowerCaseHeaders[header.toLowerCase()] = headers[header];
    });

    var res = [
      verb,
      lowerCaseHeaders['content-md5'] || '',
      lowerCaseHeaders['content-type'] || '',
      ''
    ];

    Object.keys(lowerCaseHeaders)
      .filter(function (header) {
        return header.indexOf('x-amz-') === 0;
      })
      .sort(function (a, b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
      })
      .forEach(function (header) {
        res.push(header + ':' + lowerCaseHeaders[header]);
      });

    res.push(resource);

    return res.join('\n');
  };

  return function (verb, resource, headers) {
    headers = headers || {};
    headers.date = new Date().toUTCString();
    headers['x-amz-date'] = headers.date;

    var hash = crypto.createHmac('sha1', secretKey).update(stringToSign(verb, resource, headers)).digest('base64');

    headers.authorization = 'AWS ' + publicKey + ':' + hash;

    return headers;
  };
};

exports.create = function (options) {
  var that = {},
      auth, publicKey, secretKey, sign, prefix;

  options = typeof options === 'string' ? parseURL(options) : options;

  that.pathname = options.pathname || '';
  that.bucket = options.hostname.split('.')[0];

  auth = options.auth.split(':');
  publicKey = auth[0];
  secretKey = auth[1];

  sign = signer(publicKey, secretKey);
  prefix = that.bucket + '.s3.amazonaws.com' + that.pathname;

  ['put', 'post', 'get', 'del', 'head'].forEach(function (method) {
    var verb = method.replace('del', 'delete').toUpperCase();

    that[method] = function (pathname, options, callback) {
      var signing = '/' + that.bucket + that.pathname + pathname;

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

      options = options || {};
      options.pool = false;
      options.headers = sign(verb, signing, options.headers);

      return curly[method](prefix + pathname, options, callback);
    };
  });

  return that;
};
<commit_msg>Code cleanup<commit_after>'use strict';

var curly = require('curly');
var crypto = require('crypto');
var parseURL = require('url').parse;

var signer = function (publicKey, secretKey) {
  var getStringToSign = function (verb, resource, headers) {
    var lowerCaseHeaders = {};

    Object.keys(headers).forEach(function (header) {
      lowerCaseHeaders[header.toLowerCase()] = headers[header];
    });

    var res = [
      verb,
      lowerCaseHeaders['content-md5'] || '',
      lowerCaseHeaders['content-type'] || '',
      ''
    ];

    Object.keys(lowerCaseHeaders)
      .filter(function (header) {
        return header.indexOf('x-amz-') === 0;
      })
      .sort(function (a, b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
      })
      .forEach(function (header) {
        res.push(header + ':' + lowerCaseHeaders[header]);
      });

    res.push(resource);

    return res.join('\n');
  };

  return function (verb, resource, headers) {
    headers = headers || {};
    headers.date = new Date().toUTCString();
    headers['x-amz-date'] = headers.date;

    var stringToSign = getStringToSign(verb, resource, headers);
    var hash = crypto.createHmac('sha1', secretKey).update(stringToSign).digest('base64');

    headers.authorization = 'AWS ' + publicKey + ':' + hash;

    return headers;
  };
};

exports.create = function (options) {
  var that = {},
      auth, publicKey, secretKey, sign, prefix;

  options = typeof options === 'string' ? parseURL(options) : options;

  that.pathname = options.pathname || '';
  that.bucket = options.hostname.split('.')[0];

  auth = options.auth.split(':');
  publicKey = auth[0];
  secretKey = auth[1];

  sign = signer(publicKey, secretKey);
  prefix = that.bucket + '.s3.amazonaws.com' + that.pathname;

  ['put', 'post', 'get', 'del', 'head'].forEach(function (method) {
    var verb = method.replace('del', 'delete').toUpperCase();

    that[method] = function (pathname, options, callback) {
      var signing = '/' + that.bucket + that.pathname + pathname;

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

      options = options || {};
      options.pool = false;
      options.headers = sign(verb, signing, options.headers);

      return curly[method](prefix + pathname, options, callback);
    };
  });

  return that;
};
<|endoftext|>


<commit_before>module.exports =
(function(stdin, stdout, argv){
  "use strict";
  var lib = require("./lib"),

  Cluster = function(params){
    var self = this;
    this.params = params || {};
    this.lib = lib;

    /* Old tests that used a version of Interface I forgot to commit:
    this.interface = new lib.Interface(stdin, stdout, argv, lib);
    this.interface.input(function(data){
      self.interface.output(data);
    });*/

    if (typeof this.params !== "undefined") console.log(this.params);
  };

  /* Check if we're launching as a client
   * instead of using as a module.  Then
   * use the API.
   */
  if (stdin.isTTY) {
    var cluster = new Cluster({
      host: argv[0],
      port: argv[1]
    });
  }

  // Pass value to anonymous function,
  // which is set to module export.
  // So it can be used a API.
  return Cluster;
}(process.stdin,
  process.stdout,
  process.argv.slice(2, process.argv.length)));
<commit_msg>Removed index.js, as index.coffee substitutes.<commit_after><|endoftext|>


<commit_before>// Dependencies
var Request = require("request");

// Constants
const PROVIDER = "http://labs.bible.org/api/?type=json&passage=";

// Constructor
var BibleEnglish = module.exports = {};

/**
 * getVerse
 * Gets the reference using labs.bible.org provider.
 *
 * @name getVerse
 * @function
 * @param {String} reference Bible verse reference
 * @param {Function} callback The callback function
 * @return
 */
BibleEnglish.getVerse = function (reference, callback) {
    Request.get({
        json: true
      , url: PROVIDER + reference
    }, function (err, response, body) {

        if (err || response.statusCode !== 200) {
            return callback (err || response.message);
        }

        // TODO check response
        callback (null, body);
    });
};
<commit_msg>Take non-parsed reference<commit_after>// Dependencies
var Request = require("request");

// Constants
const PROVIDER = "http://labs.bible.org/api/?type=json&passage=";

// Constructor
var BibleEnglish = module.exports = {};

/**
 * getVerse
 * Gets the reference using labs.bible.org provider.
 *
 * @name getVerse
 * @function
 * @param {String} reference Bible verse reference
 * @param {Function} callback The callback function
 * @return
 */
BibleEnglish.getVerse = function (reference, callback) {

    if (typeof reference === "object") {
        reference = this.reference;
    }

    Request.get({
        json: true
      , url: PROVIDER + reference
    }, function (err, response, body) {

        if (err || response.statusCode !== 200) {
            return callback (err || response.message);
        }

        // TODO check response
        callback (null, body);
    });
};
<|endoftext|>


<commit_before>module.exports = {
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "ecmaFeatures": {
        "jsx": true
    },
    "env": {
		"amd": true,
		"browser": true,
		"jquery": true,
		"node": true,
		"es6": true,
		"worker": true
	},
    "plugins": [
        "react"
    ],
    "rules": {
        // require the use of === and !==, except in certain cases
        // where it makes sense to use == and !=
        // http://eslint.org/docs/rules/eqeqeq
        "eqeqeq": ["error", "smart"],

        // 	disallow trailing commas
        "comma-dangle": [2, "never"],

        // enforce consistent indentation of 4 spaces
        "indent": [ "error", 4 ],

        // allow the use of console
        "no-console": 0,

        // disallow the use of debugger
        "no-debugger": 2,

        // 	disallow unnecessary parentheses only around function expressions
        "no-extra-parens": [ 2, "functions" ],

        //  disallow unnecessary semicolons
        "no-extra-semi": 2,

        // allow irregular whitespace outside of strings and comments
        "no-irregular-whitespace": 0,

        // allow the use of undeclared and disallow use of unused variables
        "no-undef": 0,
        "no-unused-vars": [2, { "args": "none", "ignoreRestSiblings": true }],

        // enforce consistent spacing inside braces
        "object-curly-spacing": [2, "always"],

        // require semicolons instead of ASI
        "semi": 2,

        // enforces spacing after semicolons and disallows spacing before semicolons
        "semi-spacing": 2,

        // require single quotes where possible and allow strings to use backtick
        "quotes": [2, "single", { "allowTemplateLiterals": true }],

        // 	enforce valid JSDoc comments
        "valid-jsdoc": [
          2,
          { "requireReturn": false }
        ],

        // React rules

        // enforces closing bracket after props always
        "react/jsx-closing-bracket-location": [
          2,
          {
            "selfClosing": "after-props",
            "nonEmpty": "after-props"
          }
        ],

        // enforce spaces between curly braces
        "react/jsx-curly-spacing": 2,

        // do not enforce consistent props indentation
        "react/jsx-indent-props": 0,

        // do not enforce max props per line
        "react/jsx-max-props-per-line": 0,

        // prevent duplicate props in JSX
        "react/jsx-no-duplicate-props": 2,

        // allow unwrapped literals (e.g. {'test'} vs test)
        "react/jsx-no-literals": 0,

        // disallow undeclared variables
        "react/jsx-no-undef": 2,

        // require prop types to be alpha sorted
        "react/sort-prop-types": 2,

        // do not enforce alpha sorted props passed in
        "react/jsx-sort-props": 0,

        // prevent React to be incorrectly marked as unused
        "react/jsx-uses-react": 2,

        // [revent variables used in JSX to be incorrectly marked as unused
        "react/jsx-uses-vars": 2,

        // allow usage of dangerous JSX properties
        "react/no-danger": 0,

        // prevent usage of setState in componentDidMount
        "react/no-did-mount-set-state": 2,

        // prevent uage of setSate in componentDidUpdate
        "react/no-did-update-set-state": 2,

        // prevent direct mutation of this.state
        "react/no-direct-mutation-state": 2,

        // prevent multiple component definition per file except for stateless components
        "react/no-multi-comp": [
          2,
          { "ignoreStateless": true }
        ],

        // allow usage of setState
        "react/no-set-state": 0,

        // warn on usage of unknown DOM property
        "react/no-unknown-property": 1,

        // prevent missing props validation in a React component definition
        "react/prop-types": [2, { "ignore": ["children"] }],

        // prevent missing React when using JSX
        "react/react-in-jsx-scope": 0,

        // prevent extra closing tags for components without children
        "react/self-closing-comp": 2,

        // enforce component methods order
        "react/sort-comp": 2,

        // prevent missing parentheses around multilines JSX
        "react/jsx-wrap-multilines": 2
      }
};
<commit_msg>Alphabetization after changing deprecated wrap-multilines rule<commit_after>module.exports = {
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "ecmaFeatures": {
        "jsx": true
    },
    "env": {
		"amd": true,
		"browser": true,
		"jquery": true,
		"node": true,
		"es6": true,
		"worker": true
	},
    "plugins": [
        "react"
    ],
    "rules": {
        // require the use of === and !==, except in certain cases
        // where it makes sense to use == and !=
        // http://eslint.org/docs/rules/eqeqeq
        "eqeqeq": ["error", "smart"],

        // 	disallow trailing commas
        "comma-dangle": [2, "never"],

        // enforce consistent indentation of 4 spaces
        "indent": [ "error", 4 ],

        // allow the use of console
        "no-console": 0,

        // disallow the use of debugger
        "no-debugger": 2,

        // 	disallow unnecessary parentheses only around function expressions
        "no-extra-parens": [ 2, "functions" ],

        //  disallow unnecessary semicolons
        "no-extra-semi": 2,

        // allow irregular whitespace outside of strings and comments
        "no-irregular-whitespace": 0,

        // allow the use of undeclared and disallow use of unused variables
        "no-undef": 0,
        "no-unused-vars": [2, { "args": "none", "ignoreRestSiblings": true }],

        // enforce consistent spacing inside braces
        "object-curly-spacing": [2, "always"],

        // require semicolons instead of ASI
        "semi": 2,

        // enforces spacing after semicolons and disallows spacing before semicolons
        "semi-spacing": 2,

        // require single quotes where possible and allow strings to use backtick
        "quotes": [2, "single", { "allowTemplateLiterals": true }],

        // 	enforce valid JSDoc comments
        "valid-jsdoc": [
          2,
          { "requireReturn": false }
        ],

        // React rules

        // enforces closing bracket after props always
        "react/jsx-closing-bracket-location": [
          2,
          {
            "selfClosing": "after-props",
            "nonEmpty": "after-props"
          }
        ],

        // enforce spaces between curly braces
        "react/jsx-curly-spacing": 2,

        // do not enforce consistent props indentation
        "react/jsx-indent-props": 0,

        // do not enforce max props per line
        "react/jsx-max-props-per-line": 0,

        // prevent duplicate props in JSX
        "react/jsx-no-duplicate-props": 2,

        // allow unwrapped literals (e.g. {'test'} vs test)
        "react/jsx-no-literals": 0,

        // disallow undeclared variables
        "react/jsx-no-undef": 2,

        // require prop types to be alpha sorted
        "react/sort-prop-types": 2,

        // do not enforce alpha sorted props passed in
        "react/jsx-sort-props": 0,

        // prevent React to be incorrectly marked as unused
        "react/jsx-uses-react": 2,

        // [revent variables used in JSX to be incorrectly marked as unused
        "react/jsx-uses-vars": 2,

        // prevent missing parentheses around multilines JSX
        "react/jsx-wrap-multilines": 2,

        // allow usage of dangerous JSX properties
        "react/no-danger": 0,

        // prevent usage of setState in componentDidMount
        "react/no-did-mount-set-state": 2,

        // prevent uage of setSate in componentDidUpdate
        "react/no-did-update-set-state": 2,

        // prevent direct mutation of this.state
        "react/no-direct-mutation-state": 2,

        // prevent multiple component definition per file except for stateless components
        "react/no-multi-comp": [
          2,
          { "ignoreStateless": true }
        ],

        // allow usage of setState
        "react/no-set-state": 0,

        // warn on usage of unknown DOM property
        "react/no-unknown-property": 1,

        // prevent missing props validation in a React component definition
        "react/prop-types": [2, { "ignore": ["children"] }],

        // prevent missing React when using JSX
        "react/react-in-jsx-scope": 0,

        // prevent extra closing tags for components without children
        "react/self-closing-comp": 2,

        // enforce component methods order
        "react/sort-comp": 2,
      }
};
<|endoftext|>


<commit_before>'use strict';

var keys = require('object-keys');
var foreach = require('foreach');

var toStr = Object.prototype.toString;

var isFunction = function (fn) {
	return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};

var arePropertyDescriptorsSupported = function () {
	var obj = {};
	try {
		Object.defineProperty(obj, 'x', { value: obj });
		return obj.x === obj;
	} catch (e) { /* this is IE 8. */
		return false;
	}
};
var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();

var defineProperty = function (object, name, value, predicate) {
	if (name in object && (!isFunction(predicate) || !predicate())) {
		return;
	}
	if (supportsDescriptors) {
		Object.defineProperty(object, name, {
			configurable: true,
			enumerable: false,
			writable: true,
			value: value
		});
	} else {
		object[name] = value;
	}
};

var defineProperties = function (object, map) {
	var predicates = arguments.length > 2 ? arguments[2] : {};
	foreach(keys(map), function (name) {
		defineProperty(object, name, map[name], predicates[name]);
	});
};

defineProperties.supportsDescriptors = !!supportsDescriptors;

module.exports = defineProperties;
<commit_msg>Using a more reliable check for supported property descriptors.<commit_after>'use strict';

var keys = require('object-keys');
var foreach = require('foreach');

var toStr = Object.prototype.toString;

var isFunction = function (fn) {
	return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};

var arePropertyDescriptorsSupported = function () {
	var obj = {};
	try {
		Object.defineProperty(obj, 'x', { value: obj, enumerable: false });
        /* eslint-disable no-unused-vars */
        for (var _ in obj) { return false; }
        /* eslint-enable no-unused-vars */
		return obj.x === obj;
	} catch (e) { /* this is IE 8. */
		return false;
	}
};
var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();

var defineProperty = function (object, name, value, predicate) {
	if (name in object && (!isFunction(predicate) || !predicate())) {
		return;
	}
	if (supportsDescriptors) {
		Object.defineProperty(object, name, {
			configurable: true,
			enumerable: false,
			writable: true,
			value: value
		});
	} else {
		object[name] = value;
	}
};

var defineProperties = function (object, map) {
	var predicates = arguments.length > 2 ? arguments[2] : {};
	foreach(keys(map), function (name) {
		defineProperty(object, name, map[name], predicates[name]);
	});
};

defineProperties.supportsDescriptors = !!supportsDescriptors;

module.exports = defineProperties;
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var fs = require('fs')
  , Ware = require('ware')

/**
 * `Model' constructor
 *
 * @api public
 * @param {Function} query
 */

module.exports = Model;
function Model (query) {
  if (!(this instanceof Model)) {
    return new Model(query);
  }

  this.bindings = {};
  this.filters = {};
  this.query = query;
}

/**
 * Executes a query ignoring filters or
 * usage of a `Binding'
 *
 * @api public
 * @param {String} sql
 * @param {Array} params
 * @param {Function} done
 */

Model.prototype.exec = function (sql, params, done) {
  if (3 == arguments.length) {
    this.query(String(sql), params, done);
  } else if (2 == arguments.length) {
    this.query(String(sql), params);
  } else {
    throw new Error("incorrect arguments");
  }
  return this;
};

/**
 * Creates a binding for
 * a model and attaches as a
 * method to instance
 *
 * @api public
 * @param {String} name
 * @param {Object} map
 * @param {String} sql
 */

Model.prototype.bind = function (name, map, sql) {
  var binding = new Binding(map, String(sql), this.query.bind(this));
  var filters = this.filters;
  this.bindings[name] = binding;
  this[name] = function (o, fn) {
    // object with callback
    if (2 == arguments.length) {
      binding.query(this.filter(o), fn);
    } else if (1 == arguments.length) {
      binding.query(o);
    } else {
      throw new Error("incorrect arguments");
    }
    return this;
  };
  return this;
};

/**
 * Installs plugin for property found in binding
 * maps
 *
 * @api public
 * @param {String} name
 * @param {Function} fn
 */

Model.prototype.use = function (name, fn) {
  (this.filters[name] = this.filters[name] || []).push(fn);
  return this;
};

/**
 * Applies set filters to an object
 *
 * @api public
 * @param {Object} o
 */

Model.prototype.filter = function (o) {
  var filters = this.filters;
  Object.keys(o).forEach(function (k) {
    if (filters[k]) {
      filters[k].forEach(function (fn) {
        var r = fn(o[k]);
        if (r) { o[k] = r; }
      });
    }
  });
  return o;
};

/**
 * `Binding' constructor
 *
 * @api public
 * @param {Object} map
 * @param {String} sql
 * @param {Function} query
 */

module.exports.Binding = Binding;
function Binding (map, sql, query) {
  if (!(this instanceof Binding)) {
    return new Binding(map, sql);
  }

  this.map = map;
  this.sql = sql;
  this._query = query;
}

// `_query' interface
Binding.prototype._query = function () {
  throw new Error("not implemented");
};

/**
 * Query with underlying query function
 * and data bound to params
 *
 * @api public
 * @param {Object} data - optional
 * @param {Function} fn
 */

Binding.prototype.query = function (data, fn) {
  if (2 == arguments.length) {
    this._query(this.sql, this.params(data), fn);
  } else if (1 == arguments.length) {
    this._query(this.sql, fn);
  } else {
    throw new Error("incorrect arguments");
  }
  return this;
};

/**
 * Builds SQL parameters
 *
 * @api public
 * @param {Object} data
 */

Binding.prototype.params = function (data) {
  var map = this.map;
  return params = (
    Object.keys(map)
    .map(function (k) { return {key: k, value: String(map[k])}; })
    .filter(function (_) { return /\$?[0-9]+/.test(_.value); })
    .map(function (_) { return {key: _.key, value: _.value.replace(/\$/, '')}; })
    .sort(function (a, b) { return a.value < b.value ? -1 : a.value == b.value ? 0 : 1; })
    .map(function (_) { return data[_.key]; })
    .map(function (v) { return v || null; })
  );
};

<commit_msg>enhance<commit_after>
/**
 * Module dependencies
 */

var fs = require('fs')
  , Ware = require('ware')

/**
 * `Model' constructor
 *
 * @api public
 * @param {Function} query
 */

module.exports = Model;
function Model (query) {
  if (!(this instanceof Model)) {
    return new Model(query);
  }

  this.bindings = {};
  this.filters = {};
  this.query = query;
}

/**
 * Executes a query ignoring filters or
 * usage of a `Binding'
 *
 * @api public
 * @param {String} sql
 * @param {Array} params
 * @param {Function} done
 */

Model.prototype.exec = function (sql, params, done) {
  if (3 == arguments.length) {
    this.query(String(sql), params, done);
  } else if (2 == arguments.length) {
    this.query(String(sql), params);
  } else {
    throw new Error("incorrect arguments");
  }
  return this;
};

/**
 * Creates a binding for
 * a model and attaches as a
 * method to instance
 *
 * @api public
 * @param {String} name
 * @param {Object} map
 * @param {String} sql
 */

Model.prototype.bind = function (name, map, sql) {
  var binding = null;
  var filters = null;
  if ('function' == typeof this[name]) {
    throw new Error("binding already defined");
  }
  binding = new Binding(map, String(sql), this.query.bind(this));
  filters = this.filters;
  this.bindings[name] = binding;
  this[name] = function (o, fn) {
    // object with callback
    if (2 == arguments.length) {
      binding.query(this.filter(o), fn);
    } else if (1 == arguments.length) {
      binding.query(o);
    } else {
      throw new Error("incorrect arguments");
    }
    return this;
  };
  return this;
};

/**
 * Installs plugin for property found in binding
 * maps
 *
 * @api public
 * @param {String} name
 * @param {Function} fn
 */

Model.prototype.use = function (name, fn) {
  (this.filters[name] = this.filters[name] || []).push(fn);
  return this;
};

/**
 * Applies set filters to an object
 *
 * @api public
 * @param {Object} o
 */

Model.prototype.filter = function (o) {
  var filters = this.filters;
  Object.keys(o).forEach(function (k) {
    if (filters[k]) {
      filters[k].forEach(function (fn) {
        var r = fn(o[k]);
        if (r) { o[k] = r; }
      });
    }
  });
  return o;
};

/**
 * `Binding' constructor
 *
 * @api public
 * @param {Object} map
 * @param {String} sql
 * @param {Function} query
 */

module.exports.Binding = Binding;
function Binding (map, sql, query) {
  if (!(this instanceof Binding)) {
    return new Binding(map, sql);
  }

  if (Array.isArray(map)) {
    map = map.reduce(function (p, c, i) {
      p[c] = i;
      return p;
    }, {});
  }

  this.map = map;
  this.sql = sql;
  this._query = query;
}

// `_query' interface
Binding.prototype._query = function () {
  throw new Error("not implemented");
};

/**
 * Query with underlying query function
 * and data bound to params
 *
 * @api public
 * @param {Object} data - optional
 * @param {Function} fn
 */

Binding.prototype.query = function (data, fn) {
  if (2 == arguments.length) {
    this._query(this.sql, this.params(data), fn);
  } else if (1 == arguments.length) {
    this._query(this.sql, fn);
  } else {
    throw new Error("incorrect arguments");
  }
  return this;
};

/**
 * Set default values
 *
 * @api public
 * @param {String} property
 * @param {Mixed} value
 */

Binding.prototype.default = function (property, value) {
  this.defaults[property] = value;
  return this;
};

/**
 * Builds SQL parameters
 *
 * @api public
 * @param {Object} data
 */

Binding.prototype.params = function (data) {
  var map = this.map;
  var params = [];
  Object.keys(map).forEach(function (key) {
    var i = map[key];
    params[i] = key;
  });
  return params.filter(Boolean).map(function (k) {
    if ('undefined' == typeof data[k]) {
      return null;
    } else {
      return data[k];
    }
  });
};

<|endoftext|>


<commit_before>var midpoint = require('turf-midpoint');
var point = require('turf-point');
var distance = require('turf-distance');

/**
 * Calculates the minimum square bounding box for another bounding box.
 *
 * @module turf/square
 * @param {Array<number>} bbox
 * @return {Array<number>} A square surrounding that bounding box
 * @example
 * var bbox = [0,0,5,10];
 * var squared = turf.square(bbox)
 * var features = turf.featurecollection([
 *   turf.bboxPolygon(bbox),
 *   turf.bboxPolygon(squared)]);
 * //=features
 */
module.exports = function(bbox){
  var squareBbox = [0,0,0,0];
  var lowLeft = point(bbox[0], bbox[1]);
  var topLeft = point(bbox[0], bbox[3]);
  var topRight = point(bbox[2], bbox[3]);
  var lowRight = point(bbox[2], bbox[1]);

  var horizontalDistance = distance(lowLeft, lowRight, 'miles');
  var verticalDistance = distance(lowLeft, topLeft, 'miles');
  if(horizontalDistance >= verticalDistance){
    squareBbox[0] = bbox[0];
    squareBbox[2] = bbox[2];
    var verticalMidpoint = midpoint(lowLeft, topLeft);
    squareBbox[1] = verticalMidpoint.geometry.coordinates[1] - ((bbox[2] - bbox[0]) / 2);
    squareBbox[3] = verticalMidpoint.geometry.coordinates[1] + ((bbox[2] - bbox[0]) / 2);
    return squareBbox;
  }
  else {
    squareBbox[1] = bbox[1];
    squareBbox[3] = bbox[3];
    var horzontalMidpoint = midpoint(lowLeft, lowRight);
    squareBbox[0] = horzontalMidpoint.geometry.coordinates[0] - ((bbox[3] - bbox[1]) / 2);
    squareBbox[2] = horzontalMidpoint.geometry.coordinates[0] + ((bbox[3] - bbox[1]) / 2);
    return squareBbox;
  }
}

<commit_msg>Change description<commit_after>var midpoint = require('turf-midpoint');
var point = require('turf-point');
var distance = require('turf-distance');

/**
 * Takes a bounding box and calculates the minimum square bounding box that would contain the input.
 *
 * @module turf/square
 * @param {Array<number>} bbox
 * @return {Array<number>} A square surrounding that bounding box
 * @example
 * var bbox = [0,0,5,10];
 * var squared = turf.square(bbox)
 * var features = turf.featurecollection([
 *   turf.bboxPolygon(bbox),
 *   turf.bboxPolygon(squared)]);
 * //=features
 */
module.exports = function(bbox){
  var squareBbox = [0,0,0,0];
  var lowLeft = point(bbox[0], bbox[1]);
  var topLeft = point(bbox[0], bbox[3]);
  var topRight = point(bbox[2], bbox[3]);
  var lowRight = point(bbox[2], bbox[1]);

  var horizontalDistance = distance(lowLeft, lowRight, 'miles');
  var verticalDistance = distance(lowLeft, topLeft, 'miles');
  if(horizontalDistance >= verticalDistance){
    squareBbox[0] = bbox[0];
    squareBbox[2] = bbox[2];
    var verticalMidpoint = midpoint(lowLeft, topLeft);
    squareBbox[1] = verticalMidpoint.geometry.coordinates[1] - ((bbox[2] - bbox[0]) / 2);
    squareBbox[3] = verticalMidpoint.geometry.coordinates[1] + ((bbox[2] - bbox[0]) / 2);
    return squareBbox;
  }
  else {
    squareBbox[1] = bbox[1];
    squareBbox[3] = bbox[3];
    var horzontalMidpoint = midpoint(lowLeft, lowRight);
    squareBbox[0] = horzontalMidpoint.geometry.coordinates[0] - ((bbox[3] - bbox[1]) / 2);
    squareBbox[2] = horzontalMidpoint.geometry.coordinates[0] + ((bbox[3] - bbox[1]) / 2);
    return squareBbox;
  }
}

<|endoftext|>


<commit_before>/**
 * Created by KlimMalgin on 04.03.2015.
 */

var curry = require('core.lambda').curry,
    // --
    fcommon = require('fantasy-fkit-common'),
    operationWrap = fcommon.operationWrap,
    conditionResult = fcommon.conditionResult;

var gtOp =  curry(2, function (meV, valueV) { return conditionResult(meV > valueV, meV); });
var gteOp = curry(2, function (meV, valueV) { return conditionResult(meV >= valueV, meV); });

var ltOp =  curry(2, function (meV, valueV) { return conditionResult(meV < valueV, meV); });
var lteOp = curry(2, function (meV, valueV) { return conditionResult(meV <= valueV, meV); });

var equalOp =    curry(2, function (meV, valueV) { return conditionResult(meV == valueV, meV); });
var notEqualOp = curry(2, function (meV, valueV) { return conditionResult(meV != valueV, meV); });

module.exports = {

    gt: operationWrap(gtOp),
    gte: operationWrap(gteOp),
    lt: operationWrap(ltOp),
    lte: operationWrap(lteOp),

    equal: operationWrap(equalOp),
    notEqual: operationWrap(notEqualOp)

};
<commit_msg>fix operations<commit_after>/**
 * Created by KlimMalgin on 04.03.2015.
 */

var curry = require('core.lambda').curry,
    // --
    fcommon = require('common'),
    operationWrap = fcommon.operationWrap,
    conditionResult = fcommon.conditionResult;

var gtOp =  curry(2, function (meV, valueV) { return conditionResult(meV > valueV, meV); });
var gteOp = curry(2, function (meV, valueV) { return conditionResult(meV >= valueV, meV); });

var ltOp =  curry(2, function (meV, valueV) { return conditionResult(meV < valueV, meV); });
var lteOp = curry(2, function (meV, valueV) { return conditionResult(meV <= valueV, meV); });

var equalOp =    curry(2, function (meV, valueV) { return conditionResult(meV == valueV, meV); });
var notEqualOp = curry(2, function (meV, valueV) { return conditionResult(meV != valueV, meV); });

module.exports = {

    gt: function (valueO) {
        return operationWrap(this, gtOp, valueO);
    },
    gte: function (valueO) {
        return operationWrap(this, gteOp, valueO);
    },
    lt: function (valueO) {
        return operationWrap(this, ltOp, valueO);
    },
    lte: function (valueO) {
        return operationWrap(this, lteOp, valueO);
    },

    equal: function (valueO) {
        return operationWrap(this, equalOp, valueO)
    },
    notEqual: function (valueO) {
        return operationWrap(this, notEqualOp, valueO)
    }

};
<|endoftext|>


<commit_before>window.onload = function () {
  var passageSearchField = $("#passage-search");
  passageSearchField.focus();

  document.onkeypress = function(evt) {
     evt = evt || window.event;
     var charCode = evt.which || evt.keyCode;
     var charStr = String.fromCharCode(charCode);
     if (/[a-z0-9]/i.test(charStr) && !passageSearchField.is(":focus")) {
       passageSearchField.focus();
     }
  };

  // https://stackoverflow.com/a/30810322
  function copyTextToClipboard(reference, text) {
    $('.alert').hide();
    var textArea = document.createElement("textarea");

    //
    // *** This styling is an extra step which is likely not required. ***
    //
    // Why is it here? To ensure:
    // 1. the element is able to have focus and selection.
    // 2. if element was to flash render it has minimal visual impact.
    // 3. less flakyness with selection and copying which **might** occur if
    //    the textarea element is not visible.
    //
    // The likelihood is the element won't even render, not even a flash,
    // so some of these are just precautions. However in IE the element
    // is visible whilst the popup box asking the user for permission for
    // the web page to copy to the clipboard.
    //

    // Place in top-left corner of screen regardless of scroll position.
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;

    // Ensure it has a small width and height. Setting to 1px / 1em
    // doesn't work as this gives a negative w/h on some browsers.
    textArea.style.width = '2em';
    textArea.style.height = '2em';

    // We don't need padding, reducing the size if it does flash render.
    textArea.style.padding = 0;

    // Clean up any borders.
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';

    // Avoid flash of white box if rendered for any reason.
    textArea.style.background = 'transparent';

    textArea.value = text;

    document.body.appendChild(textArea);

    textArea.select();

    function showError() {
      $('#copied-error').fadeOut(200, function complete() {
        $('.copied-reference').text(reference);
        $('#copied-error').fadeIn(200);
      });
    }

    try {
      var successful = document.execCommand('copy');
      if (successful) {
        console.log('Copy succeeded.');
        $('#copied-success').fadeOut(200, function complete() {
          $('.copied-reference').text(reference);
          $('#copied-success').fadeIn(200);
        });
      } else {
        console.log('Copy failed.');
        showError();
      }
    } catch (err) {
      console.log('Copy failed: ', err);
      showError();
    }

    document.body.removeChild(textArea);
  }

  var placePassages = function () {
    var passagesPlacement = $('.jumbotron').position().top + $('.jumbotron').height() + 60;
    $('#passages').css('margin-top', passagesPlacement);
  };

  $("#search").submit(function (e) {
    e.preventDefault();
    var query = passageSearchField.val();

    function showQueryError() {
      $('#query-error').fadeOut(200, function complete() {
        $('.query-attempt').text(query);
        $('#query-error').fadeIn(200);
      });

      passageSearchField
        .val("")
        .focus();
    }

    var request = $.ajax({
      url: "http://nasb.literalword.com",
      method: "GET",
      data: {
        q: query,
        format: "json",
      },
      async: false, // Otherwise copy to clipboard won't work: https://stackoverflow.com/questions/31925944/execcommandcopy-does-not-work-in-xhr-callback
      success: function (data) {
        var reference;
        var text;
        $.each(data, function (key, value) {
          reference = key;
          text = value;
        });

        if (text.length === 0) {
          showQueryError();
          return;
        }

        var combo = reference + ' ' + text
        $('#passages .passage-text').addClass('old-passage');

        var template = $("#passage-template");

        var passage = template.clone()
          .removeAttr('id');

        var passageClickHandler = function (e) {
          copyTextToClipboard(reference, combo);
        };

        passage
          .find(".passage-text")
          .text(combo)
          .click(passageClickHandler);

        passage
          .prependTo("#passages");

        copyTextToClipboard(reference, combo);

        passageSearchField
          .val("")
          .focus();

      },
      error: function (jqXHR, textStatus, err) {
        $('.alert').hide();

        showQueryError();
      },
      complete: placePassages,
    });
    console.log('Submitted search for ' + query);
  });

  $(window).resize(function () {
    placePassages();
  });
};

<commit_msg>Scroll to top on successful query.<commit_after>window.onload = function () {
  var passageSearchField = $("#passage-search");
  passageSearchField.focus();

  document.onkeypress = function(evt) {
     evt = evt || window.event;
     var charCode = evt.which || evt.keyCode;
     var charStr = String.fromCharCode(charCode);
     if (/[a-z0-9]/i.test(charStr) && !passageSearchField.is(":focus")) {
       passageSearchField.focus();
     }
  };

  // https://stackoverflow.com/a/30810322
  function copyTextToClipboard(reference, text) {
    $('.alert').hide();
    var textArea = document.createElement("textarea");

    //
    // *** This styling is an extra step which is likely not required. ***
    //
    // Why is it here? To ensure:
    // 1. the element is able to have focus and selection.
    // 2. if element was to flash render it has minimal visual impact.
    // 3. less flakyness with selection and copying which **might** occur if
    //    the textarea element is not visible.
    //
    // The likelihood is the element won't even render, not even a flash,
    // so some of these are just precautions. However in IE the element
    // is visible whilst the popup box asking the user for permission for
    // the web page to copy to the clipboard.
    //

    // Place in top-left corner of screen regardless of scroll position.
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;

    // Ensure it has a small width and height. Setting to 1px / 1em
    // doesn't work as this gives a negative w/h on some browsers.
    textArea.style.width = '2em';
    textArea.style.height = '2em';

    // We don't need padding, reducing the size if it does flash render.
    textArea.style.padding = 0;

    // Clean up any borders.
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';

    // Avoid flash of white box if rendered for any reason.
    textArea.style.background = 'transparent';

    textArea.value = text;

    document.body.appendChild(textArea);

    textArea.select();

    function showError() {
      $('#copied-error').fadeOut(200, function complete() {
        $('.copied-reference').text(reference);
        $('#copied-error').fadeIn(200);
      });
    }

    try {
      var successful = document.execCommand('copy');
      if (successful) {
        console.log('Copy succeeded.');
        $('#copied-success').fadeOut(200, function complete() {
          $('.copied-reference').text(reference);
          $('#copied-success').fadeIn(200);
        });
      } else {
        console.log('Copy failed.');
        showError();
      }
    } catch (err) {
      console.log('Copy failed: ', err);
      showError();
    }

    document.body.removeChild(textArea);
  }

  var placePassages = function () {
    var passagesPlacement = $('.jumbotron').position().top + $('.jumbotron').height() + 60;
    $('#passages').css('margin-top', passagesPlacement);
  };

  $("#search").submit(function (e) {
    e.preventDefault();
    var query = passageSearchField.val();

    function showQueryError() {
      $('#query-error').fadeOut(200, function complete() {
        $('.query-attempt').text(query);
        $('#query-error').fadeIn(200);
      });

      passageSearchField
        .val("")
        .focus();
    }

    var request = $.ajax({
      url: "http://nasb.literalword.com",
      method: "GET",
      data: {
        q: query,
        format: "json",
      },
      async: false, // Otherwise copy to clipboard won't work: https://stackoverflow.com/questions/31925944/execcommandcopy-does-not-work-in-xhr-callback
      success: function (data) {
        var reference;
        var text;
        $.each(data, function (key, value) {
          reference = key;
          text = value;
        });

        if (text.length === 0) {
          showQueryError();
          return;
        }

        var combo = reference + ' ' + text
        $('#passages .passage-text').addClass('old-passage');

        var template = $("#passage-template");

        var passage = template.clone()
          .removeAttr('id');

        var passageClickHandler = function (e) {
          copyTextToClipboard(reference, combo);
        };

        passage
          .find(".passage-text")
          .text(combo)
          .click(passageClickHandler);

        passage
          .prependTo("#passages");

        copyTextToClipboard(reference, combo);

        passageSearchField
          .val("")
          .focus();

        $(window).scrollTop(0);
      },
      error: function (jqXHR, textStatus, err) {
        $('.alert').hide();

        showQueryError();
      },
      complete: placePassages,
    });
    console.log('Submitted search for ' + query);
  });

  $(window).resize(function () {
    placePassages();
  });
};

<|endoftext|>


<commit_before>/* jshint node: true */

'use strict';

var filesize = require('filesize'),
    gutil = require('gulp-util'),
    path = require('path'),
    map = require('map-stream');

var bytediff = function() {
    return map(function(file, cb) {
        // Persist the original size of the file for later
        file.bytediff = Buffer.byteLength(String(file.contents));
        cb(null, file);
    });
};

// Convenience method
bytediff.start = bytediff;

bytediff.stop = function() {
    return map(function(file, cb) {
        var finalsize = Buffer.byteLength(String(file.contents)),
            saving    = 0,
            didsave   = ' saved ',
            report    = '',
            newsize;

        if (finalsize > file.bytediff) {
            saving  = finalsize - file.bytediff,
            newsize = gutil.colors.yellow(filesize(finalsize));
            didsave = ' gained ';
        } else {
            saving  = file.bytediff - finalsize;
            newsize = gutil.colors.green(filesize(finalsize));
        }

        if (saving > 0) {
            report = ' (' + filesize(file.bytediff) + ' -> ' + newsize + ')';
        }
        gutil.log(path.basename(file.path) + didsave + filesize(saving) + report);
        cb(null, file);
    });
};

module.exports = bytediff;
<commit_msg>Fixed comma.<commit_after>/* jshint node: true */

'use strict';

var filesize = require('filesize'),
    gutil = require('gulp-util'),
    path = require('path'),
    map = require('map-stream');

var bytediff = function() {
    return map(function(file, cb) {
        // Persist the original size of the file for later
        file.bytediff = Buffer.byteLength(String(file.contents));
        cb(null, file);
    });
};

// Convenience method
bytediff.start = bytediff;

bytediff.stop = function() {
    return map(function(file, cb) {
        var finalsize = Buffer.byteLength(String(file.contents)),
            saving    = 0,
            didsave   = ' saved ',
            report    = '',
            newsize;

        if (finalsize > file.bytediff) {
            saving  = finalsize - file.bytediff;
            newsize = gutil.colors.yellow(filesize(finalsize));
            didsave = ' gained ';
        } else {
            saving  = file.bytediff - finalsize;
            newsize = gutil.colors.green(filesize(finalsize));
        }

        if (saving > 0) {
            report = ' (' + filesize(file.bytediff) + ' -> ' + newsize + ')';
        }
        gutil.log(path.basename(file.path) + didsave + filesize(saving) + report);
        cb(null, file);
    });
};

module.exports = bytediff;
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

function readfile(filepath){
  return fs.readFileSync(path.resolve(filepath), 'utf-8');
}

function writefile(filepath, contents){
  fs.writeFileSync(path.resolve(filepath), contents);
  return contents;
}

module.exports = function(input, output, locals){
  var buffer = [];
  var source = readfile(input);
  var reg = /^.+diverge:if([\s\S]+?)diverge:fi.*$/gm;

  while ((res = reg.exec(source))){
    var before = res[0];
    var after = parse_conditional_block(before, locals);
    source = source.replace(before + '\n', after);
  }

  writefile(output, source);
};

function parse_conditional_block(block, locals){

  var buffer = '';
  var passed = 0;
  var capturing = false;

  var i, line, lines = block.split('\n');

  for(i in lines){

    line = lines[i];

    // if, elif
    if(/diverge:(if|elif)/.test(line)) {
      var cond = line.match(/(\w+)\s*(\!?=)\s*(\w+)/);
      var cond_parts = cond.slice(1);

      var key = cond_parts[0];
      var mode = cond_parts[1];
      var value = cond_parts[2];

      if(mode === '=')
        capturing = locals[key] == value;
      else if(mode === '!=')
        capturing = locals[key] !== value;

      if(capturing) passed++;

      continue;
    }

    // else
    else if(/diverge:else/.test(line)){
      capturing = passed === 0;
      continue;
    }

    // fi
    // else if(/diverge:fi/.test(line))
    //   return buffer;

    // capturing lines
    else if(capturing){
      buffer += line + '\n';
    }
  }

  return buffer;
}
<commit_msg>minor adjustments<commit_after>var fs = require('fs');
var path = require('path');

module.exports = diverge;

function readfile(filepath){
  return fs.readFileSync(path.resolve(filepath), 'utf-8');
}

function writefile(filepath, contents){
  fs.writeFileSync(path.resolve(filepath), contents);
  return contents;
}

function diverge(input, output, locals){
  var buffer = [];
  var source = readfile(input);
  var reg = /^.+diverge:if([\s\S]+?)diverge:fi.*$/gm;

  while ((res = reg.exec(source))){
    var before = res[0];
    var after = parse_conditional_block(before, locals);
    source = source.replace(before + '\n', after);
  }

  writefile(output, source);
};

function parse_conditional_block(block, locals){

  var buffer = '';
  var passed = 0;
  var capturing = false;

  var i, line, lines = block.split('\n');

  for(i in lines){

    line = lines[i];

    // if, elif
    if(/diverge:(if|elif)/.test(line)) {
      var cond = line.match(/(\w+)\s*(\!?=)\s*(\w+)/);
      var cond_parts = cond.slice(1);

      var key = cond_parts[0];
      var mode = cond_parts[1];
      var value = cond_parts[2];

      if(mode === '=')
        capturing = locals[key] == value;
      else if(mode === '!=')
        capturing = locals[key] !== value;

      if(capturing) passed++;

      continue;
    }

    // else
    else if(/diverge:else/.test(line)){
      capturing = passed === 0;
      continue;
    }

    // fi
    else if(/diverge:fi/.test(line)){
      return buffer;
    }

    // capturing lines
    else if(capturing){
      buffer += line + '\n';
    }
  }
}
<|endoftext|>


<commit_before>
const dotenv        = require('dotenv');
const Twit          = require('twit');
const schedule      = require('node-schedule');
const debounce      = require('debounce');
const quotesWrapper = require('./quotes');
const twitterHelper = require('./twitter');
const buttonHelper  = require('./button');
const soundHelper   = require('./sounds');

dotenv.config();

const TIME_TO_TOUCH = .5 * 60 * 1000; // time to desactivate the button
const TWITTER_MENTION = '@guillaumewuip';

const
  SPREADSHEET_ID = (() => {
    if (!process.env.SPREADSHEET_ID) {
      throw new Error('Need SPREADSHEET_ID env var');
    }

    return process.env.SPREADSHEET_ID;
  })(),

  GOOGLE_API_KEY = (() => {
    if (!process.env.GOOGLE_API_KEY) {
      throw new Error('Need GOOGLE_API_KEY env var');
    }

    return process.env.GOOGLE_API_KEY;
  })(),

  TWITTER_CONSUMER_KEY = (() => {
    if (!process.env.TWITTER_CONSUMER_KEY) {
      throw new Error('Need TWITTER_CONSUMER_KEY');
    }
    return process.env.TWITTER_CONSUMER_KEY;
  })(),

  TWITTER_CONSUMER_SECRET = (() => {
    if (!process.env.TWITTER_CONSUMER_SECRET) {
      throw new Error('Need TWITTER_CONSUMER_SECRET');
    }
    return process.env.TWITTER_CONSUMER_SECRET;
  })(),

  TWITTER_ACCESS_TOKEN = (() => {
    if (!process.env.TWITTER_ACCESS_TOKEN) {
      throw new Error('Need TWITTER_ACCESS_TOKEN');
    }
    return process.env.TWITTER_ACCESS_TOKEN;
  })(),

  TWITTER_ACCESS_TOKEN_SECRET = (() => {
    if (!process.env.TWITTER_ACCESS_TOKEN_SECRET) {
      throw new Error('Need TWITTER_ACCESS_TOKEN_SECRET');
    }
    return process.env.TWITTER_ACCESS_TOKEN_SECRET;
  })();

const quotes = quotesWrapper({ SPREADSHEET_ID, GOOGLE_API_KEY });

const T = new Twit({
  consumer_key:        TWITTER_CONSUMER_KEY,
  consumer_secret:     TWITTER_CONSUMER_SECRET,
  access_token:        TWITTER_ACCESS_TOKEN,
  access_token_secret: TWITTER_ACCESS_TOKEN_SECRET,
  timeout_ms:          60 * 1000, //not too low because stream will fail
});

const sendTweets = (T, id) => {
  return (msgs) => Promise.all(
    msgs.map((msg) => twitterHelper.send(T)(msg, id))
  );
};

const sendRandomQuote = (T) => {
  quotes.random()
    .then((msg) => ({
      content: `${TWITTER_MENTION} ${msg.content}`,
      author:  msg.author,
    }))
    .then(twitterHelper.buildQuote)
    .then(twitterHelper.buildTweets)
    .then(sendTweets(T))
    .then(() => {
      console.log('Twitter status send');
    })
    .catch((err) => {
      console.error(err);
    });
};

const timeout = {
  isSet: false,
  _timeout: null,
  clear: () => {
    if (timeout._timeout) {
      clearTimeout(timeout._timeout);
      timeout.isSet = false;
    }
  },
  setTimeout: (callback, time) => {
    timeout._timeout = setTimeout(callback, time);
    timeout.isSet = true;
  },
};

const watchHandler = (err) => {
  if (err) {
    console.error(err);
  }

  if (timeout.isSet) {
    timeout.clear();
    soundHelper.playRandom();
    buttonHelper.off();
  }
};

buttonHelper.watch(debounce(watchHandler, 500));

const fire = () => {
  buttonHelper.on();
  timeout.setTimeout(() => {
    sendRandomQuote(T);
  }, TIME_TO_TOUCH);
};

schedule.scheduleJob('0 */2 8-18 * * *', fire); // TODO remove every 2 min
fire();

<commit_msg>Fix hours<commit_after>
const dotenv        = require('dotenv');
const Twit          = require('twit');
const schedule      = require('node-schedule');
const debounce      = require('debounce');
const quotesWrapper = require('./quotes');
const twitterHelper = require('./twitter');
const buttonHelper  = require('./button');
const soundHelper   = require('./sounds');

dotenv.config();

const TIME_TO_TOUCH = .5 * 60 * 1000; // time to desactivate the button
const TWITTER_MENTION = '@guillaumewuip';

const
  SPREADSHEET_ID = (() => {
    if (!process.env.SPREADSHEET_ID) {
      throw new Error('Need SPREADSHEET_ID env var');
    }

    return process.env.SPREADSHEET_ID;
  })(),

  GOOGLE_API_KEY = (() => {
    if (!process.env.GOOGLE_API_KEY) {
      throw new Error('Need GOOGLE_API_KEY env var');
    }

    return process.env.GOOGLE_API_KEY;
  })(),

  TWITTER_CONSUMER_KEY = (() => {
    if (!process.env.TWITTER_CONSUMER_KEY) {
      throw new Error('Need TWITTER_CONSUMER_KEY');
    }
    return process.env.TWITTER_CONSUMER_KEY;
  })(),

  TWITTER_CONSUMER_SECRET = (() => {
    if (!process.env.TWITTER_CONSUMER_SECRET) {
      throw new Error('Need TWITTER_CONSUMER_SECRET');
    }
    return process.env.TWITTER_CONSUMER_SECRET;
  })(),

  TWITTER_ACCESS_TOKEN = (() => {
    if (!process.env.TWITTER_ACCESS_TOKEN) {
      throw new Error('Need TWITTER_ACCESS_TOKEN');
    }
    return process.env.TWITTER_ACCESS_TOKEN;
  })(),

  TWITTER_ACCESS_TOKEN_SECRET = (() => {
    if (!process.env.TWITTER_ACCESS_TOKEN_SECRET) {
      throw new Error('Need TWITTER_ACCESS_TOKEN_SECRET');
    }
    return process.env.TWITTER_ACCESS_TOKEN_SECRET;
  })();

const quotes = quotesWrapper({ SPREADSHEET_ID, GOOGLE_API_KEY });

const T = new Twit({
  consumer_key:        TWITTER_CONSUMER_KEY,
  consumer_secret:     TWITTER_CONSUMER_SECRET,
  access_token:        TWITTER_ACCESS_TOKEN,
  access_token_secret: TWITTER_ACCESS_TOKEN_SECRET,
  timeout_ms:          60 * 1000, //not too low because stream will fail
});

const sendTweets = (T, id) => {
  return (msgs) => Promise.all(
    msgs.map((msg) => twitterHelper.send(T)(msg, id))
  );
};

const sendRandomQuote = (T) => {
  quotes.random()
    .then((msg) => ({
      content: `${TWITTER_MENTION} ${msg.content}`,
      author:  msg.author,
    }))
    .then(twitterHelper.buildQuote)
    .then(twitterHelper.buildTweets)
    .then(sendTweets(T))
    .then(() => {
      console.log('Twitter status send');
    })
    .catch((err) => {
      console.error(err);
    });
};

const timeout = {
  isSet: false,
  _timeout: null,
  clear: () => {
    if (timeout._timeout) {
      clearTimeout(timeout._timeout);
      timeout.isSet = false;
    }
  },
  setTimeout: (callback, time) => {
    timeout._timeout = setTimeout(callback, time);
    timeout.isSet = true;
  },
};

const watchHandler = (err) => {
  if (err) {
    console.error(err);
  }

  if (timeout.isSet) {
    timeout.clear();
    soundHelper.playRandom();
    buttonHelper.off();
  }
};

buttonHelper.watch(debounce(watchHandler, 500));

const fire = () => {
  buttonHelper.on();
  timeout.setTimeout(() => {
    sendRandomQuote(T);
  }, TIME_TO_TOUCH);
};

schedule.scheduleJob('0 */2 6-16 * * *', fire); // TODO remove every 2 min
fire();

<|endoftext|>


<commit_before>module.exports = Kineograph;

/**
*		Initialize a new `Kineograph`.
*
*		@api public
*/

function Kineograph(imgs) {

	if(!document || !imgs) return;

	var el = mixin( document.createElement('div') );

	el.className = 'kineograph';

	if(imgs instanceof Array)
		imgs = {'_default':imgs};

	for(var i in imgs){
		for(var j in imgs[i]){
			image.apply(el, [imgs[i][j], i]);
		}
	}

  return el;

};

/**
*		Public variables
*
*		@api public
*/

Kineograph.prototype._images = [];
Kineograph.prototype._animations = [];
Kineograph.prototype._animating = undefined;
Kineograph.prototype._unloop = false;
Kineograph.prototype._timeouts = [];
Kineograph.prototype._finish = false;
Kineograph.prototype._fps = 25;

/**
*		Add an animation to the end of the cue and start playing if it isn't already.
*
*		@param {String} ani - the animation name to add
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.play = function(ani, loop, callback){

	add.apply(this, [ani, loop, callback]);

	if(!this._animating) this.next();

	return this;

}

/**
*		Begin animating the next animation in the cue
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.next = function(){

	this._unloop = false;
	this.stop();

	if(!this._animations.length){ this._animating = false; return; }

	this._animating = this._animations.shift();

	play.apply(this, [this._animating.ani, this._animating.loop, this._animating.callback]);

	return this;

}

/**
*		Unloop any currently looping animations and allow the sequence to move onwards.
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.unloop = function(){

	this._unloop = true;

	return this;

}

/**
*		Stop any currently playing animations, without prejudice.
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.stop = function(){

	while(this._timeouts.length){

		clearTimeout(this._timeouts.shift());

	}

	this._animating = undefined;

	return this;

}

/**
*		Mixin the emitter properties.
*
*		@param {HTMLElement} el
*		@return {HTMLElement}
*		@api private
*/

function mixin(el) {

  for (var key in Kineograph.prototype){
    el[key] = Kineograph.prototype[key];
  }

  return el;

}

/**
*		Add a frame to the animation
*
*		@param {String} path - the relative path to the image
*		@param {String} key - an animtion name for the image
*		@api private
*/

function image(path, key){

	var img = this.appendChild( document.createElement( 'img' ) );
	img.src = path;
	img.style.visibility = 'hidden';

	if(!this._images)
		this._images = {};

	if(this._images[key])
		this._images[key].push(img);
	else
		this._images[key] = [img];

}

/**
*		Add an animation to the cue
*
*		@param {String} ani - the animation name to add
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@api private
*/

function add(ani, loop, callback){

	ani = typeof ani === 'string' ? ani : '_default';
	loop = typeof loop === 'number' ? parseInt(loop) : 1;

	if(!this._images[ani])
		throw new Error(ani + 'does not exist');

	this._animations.push({ani:ani, loop:loop, callback:callback});

}

/**
*		Play a sequence of images from start to end
*
*		@param {String} ani - the animation name to play
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@api private
*/

function play(ani, loop, callback){

	var indefinate = !loop;

	loop--;

	var self = this;

	for(var i = 0; i < this._images[ani].length; i++){

		var timeout = setTimeout(function(img, last){

			return function(){

				show(img);

				if(last){

					if(indefinate && !self._unloop){
						play.apply(self, [ani, loop, callback]);
					}else{
						if(!loop || self._unloop){
							if(callback)
								callback();
							self.next();
						}else{
							play.apply(self, [ani, loop, callback]);
						}
					}
				}
			}

		}(this._images[ani][i], !(i < this._images[ani].length - 1)), 1000 / this._fps * i);

		this._timeouts.push(timeout);

	}
}

/**
*		Show a particular image
*
*		@param {HTMLElement} img - the image element to show
*		@api private
*/

function show(img){

	img.style.visibility = 'visible';

	if(this._showing)
		this._showing.style.visibility = 'hidden';

	this._showing = img;

}<commit_msg>show an image at start<commit_after>module.exports = Kineograph;

/**
*		Initialize a new `Kineograph`.
*
*		@api public
*/

function Kineograph(imgs) {

	if(!document || !imgs) return;

	var el = mixin( document.createElement('div') );

	el.className = 'kineograph';

	if(imgs instanceof Array)
		imgs = {'_default':imgs};

	for(var i in imgs){
		for(var j in imgs[i]){
			image.apply(el, [imgs[i][j], i]);
		}
	}

  return el;

};

/**
*		Public variables
*
*		@api public
*/

Kineograph.prototype._images = [];
Kineograph.prototype._animations = [];
Kineograph.prototype._animating = undefined;
Kineograph.prototype._unloop = false;
Kineograph.prototype._timeouts = [];
Kineograph.prototype._finish = false;
Kineograph.prototype._fps = 25;

/**
*		Add an animation to the end of the cue and start playing if it isn't already.
*
*		@param {String} ani - the animation name to add
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.play = function(ani, loop, callback){

	add.apply(this, [ani, loop, callback]);

	if(!this._animating) this.next();

	return this;

}

/**
*		Begin animating the next animation in the cue
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.next = function(){

	this._unloop = false;
	this.stop();

	if(!this._animations.length){ this._animating = false; return; }

	this._animating = this._animations.shift();

	play.apply(this, [this._animating.ani, this._animating.loop, this._animating.callback]);

	return this;

}

/**
*		Unloop any currently looping animations and allow the sequence to move onwards.
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.unloop = function(){

	this._unloop = true;

	return this;

}

/**
*		Stop any currently playing animations, without prejudice.
*
*		@return {Kineograph}
*		@api public
*/

Kineograph.prototype.stop = function(){

	while(this._timeouts.length){

		clearTimeout(this._timeouts.shift());

	}

	this._animating = undefined;

	return this;

}

/**
*		Mixin the emitter properties.
*
*		@param {HTMLElement} el
*		@return {HTMLElement}
*		@api private
*/

function mixin(el) {

  for (var key in Kineograph.prototype){
    el[key] = Kineograph.prototype[key];
  }

  return el;

}

/**
*		Add a frame to the animation
*
*		@param {String} path - the relative path to the image
*		@param {String} key - an animtion name for the image
*		@api private
*/

function image(path, key){

	var img = this.appendChild( document.createElement( 'img' ) );
	img.src = path;

	if(!this._images.length)
		show.apply(this, [img])
	else
		img.style.visibility = 'hidden';

	if(!this._images)
		this._images = {};

	if(this._images[key])
		this._images[key].push(img);
	else
		this._images[key] = [img];

}

/**
*		Add an animation to the cue
*
*		@param {String} ani - the animation name to add
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@api private
*/

function add(ani, loop, callback){

	ani = typeof ani === 'string' ? ani : '_default';
	loop = typeof loop === 'number' ? parseInt(loop) : 1;

	if(!this._images[ani])
		throw new Error(ani + 'does not exist');

	this._animations.push({ani:ani, loop:loop, callback:callback});

}

/**
*		Play a sequence of images from start to end
*
*		@param {String} ani - the animation name to play
*		@param {Number} loop - the number of times the animation should play
*		@param {Function} callback - the optional method to call when finished
*		@api private
*/

function play(ani, loop, callback){

	var indefinate = !loop;

	loop--;

	var self = this;

	for(var i = 0; i < this._images[ani].length; i++){

		var timeout = setTimeout(function(img, last){

			return function(){

				show(img);

				if(last){

					if(indefinate && !self._unloop){
						play.apply(self, [ani, loop, callback]);
					}else{
						if(!loop || self._unloop){
							if(callback)
								callback();
							self.next();
						}else{
							play.apply(self, [ani, loop, callback]);
						}
					}
				}
			}

		}(this._images[ani][i], !(i < this._images[ani].length - 1)), 1000 / this._fps * i);

		this._timeouts.push(timeout);

	}
}

/**
*		Show a particular image
*
*		@param {HTMLElement} img - the image element to show
*		@api private
*/

function show(img){

	img.style.visibility = 'visible';

	if(this._showing)
		this._showing.style.visibility = 'hidden';

	this._showing = img;

}<|endoftext|>


<commit_before>'use strict';

var request = require('request')
  , isUrl = require('is-url')
  , articleTitle = require('article-title')
  ;

module.exports = function(url, callback){
	if(!isUrl(url)){
		throw new Error('Invalid url');
		return;
	}

	if(!callback){
		throw new Error('Callback must be set to recieve the title for the url.');
		return;
	}

    request(url, function (error, response, body) {
	  if (!error && response.statusCode == 200) {
		  var title = articleTitle(body)
		    ;

			if(callback){
				callback(title);
			}
	  }
	});
};<commit_msg>Still call callback even if title lookup fails.<commit_after>'use strict';

var request = require('request')
  , isUrl = require('is-url')
  , articleTitle = require('article-title')
  ;

module.exports = function(url, callback){
	if(!isUrl(url)){
		throw new Error('Invalid url');
		return;
	}

	if(!callback){
		throw new Error('Callback must be set to recieve the title for the url.');
		return;
	}

    request(url, function (error, response, body) {
	  var title;
      if (!error && response.statusCode == 200) {
	    title = articleTitle(body);
      }
	  callback(title);
	});
};<|endoftext|>