<commit_before>#!/usr/bin/env node
// Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.

const path = require('path')
const repolinter = require('..')

if (process.argv[2] === '--git') {
  const git = require('simple-git')()
  const uuidv4 = require('uuid/v4')
  const rimraf = require('rimraf')
  const tmpDir = path.resolve(process.cwd(), 'tmp', uuidv4())

  git.clone(process.argv[3], tmpDir)
  repolinter(tmpDir)
  rimraf(tmpDir, function () {})
} else {
  repolinter(path.resolve(process.cwd(), process.argv[2] || '.'))
}
<commit_msg>When cloning a repo, do not run repolinter before cloning has finished<commit_after>#!/usr/bin/env node
// Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.

const path = require('path')
const repolinter = require('..')

if (process.argv[2] === '--git') {
  const git = require('simple-git')()
  const uuidv4 = require('uuid/v4')
  const rimraf = require('rimraf')
  const tmpDir = path.resolve(process.cwd(), 'tmp', uuidv4())

  git.clone(process.argv[3], tmpDir, (error) => {
    if (!error) {
      repolinter(tmpDir)
    }
    rimraf(tmpDir, function () {})
  })
} else {
  repolinter(path.resolve(process.cwd(), process.argv[2] || '.'))
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var CP = require('child_process');
var FilePath = require('../').FilePath;
var Promise = require('bluebird');

exports.main = function () {
	console.log(' ### running lint_runner ###');
	var execFile = process.platform === 'win32' ? 'xo.cmd' : 'xo';
	return new Promise(function (resolve, reject) {
		var exec = FilePath.create().append('node_modules', '.bin', execFile);
		var proc = CP.spawn(exec.toString());
		proc.stdout.pipe(process.stdout);
		proc.stderr.pipe(process.stderr);
		proc.on('close', function (code) {
			if (code === 0) {
				return resolve(0);
			}
			return reject(new Error('Failed linter'));
		});
	});
};

if (require.main === module) {
	exports.main()
		.then(function () {
			console.log('lint_runner succeeded :)');
		})
		.catch(function (err) {
			console.error('lint_runner failed:');
			console.error(err.stack || err.message || err);
		});
}
<commit_msg>Removes deprecated lint runner.<commit_after><|endoftext|>


<commit_before>export default {
  ui: {
    sections: {
      instances: [
        'summary',
        'tags',
        'metadata',
        'networks',
        'firewall',
        'dns',
        'snapshots'
      ]
    }
  }
};
<commit_msg>fix(my-joy-beta): don't show not ready sections<commit_after>export default {
  ui: {
    sections: {
      instances: ['summary', 'tags', 'metadata', 'snapshots']
    }
  }
};
<|endoftext|>


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

var hitSchema = mongoose.Schema({
    name: String,
    condition: {
        firstTask: String, // i.e. basic, training, fast
        laterTasks:String  // i.e. basic, feedback, training, fast
    },
    type: String, // e.g. Image tagging
    items: [Number],
    // The name of the model for items, e.g. 'pin'.
    // Should correspond to a mondel in models/{{itemModel}}.js
    itemModel: String,
    setsPerItem: Number,
    maxSetSize: Number,
    timer: { type: Number, default: null },
});

var Hit = mongoose.connection.model('Hit', hitSchema);

module.exports = Hit;
<commit_msg>Comments on conditions<commit_after>var mongoose = require('mongoose');

var hitSchema = mongoose.Schema({
    name: String,
    condition: {
        // i.e. basic, training, fast
        firstTask: String,
        // Note that 'feedback' is extra decoration on top of
        // a task, so specifying this condition will pair it based on
        // the firstTask. If firstTask is 'fast', the feedback will be
        // paired with the fast design; otherwise, it is paired with
        // the basic design
        laterTasks:String  // i.e. basic, feedback, training, fast
    },
    type: String, // e.g. Image tagging
    items: [Number],
    // The name of the model for items, e.g. 'pin'.
    // Should correspond to a mondel in models/{{itemModel}}.js
    itemModel: String,
    setsPerItem: Number,
    maxSetSize: Number,
    // Used for estimating how long the task will take
    // Not used for the 'fast' condition, because the timer
    // time is the best estimate
    itemTimeEstimate: Number,
    // Specifies the task-completion timer in 'fast' condition
    timer: { type: Number, default: null },
});

var Hit = mongoose.connection.model('Hit', hitSchema);

module.exports = Hit;
<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

// Do this as the first thing so that any code reading it knows the right env.
process.env.NODE_ENV = 'production';

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});

var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var filesize = require('filesize');
var gzipSize = require('gzip-size').sync;
var webpack = require('webpack');
var config = require('../config/webpack.config.prod');
var paths = require('../config/paths');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var recursive = require('recursive-readdir');
var stripAnsi = require('strip-ansi');

var useYarn = fs.existsSync(paths.yarnLockFile);

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Input: /User/dan/app/build/static/js/main.82be8.js
// Output: /static/js/main.js
function removeFileNameHash(fileName) {
  return fileName
    .replace(paths.appBuild, '')
    .replace(/\/?(.*)(\.\w+)(\.js|\.css)/, (match, p1, p2, p3) => p1 + p3);
}

// Input: 1024, 2048
// Output: "(+1 KB)"
function getDifferenceLabel(currentSize, previousSize) {
  var FIFTY_KILOBYTES = 1024 * 50;
  var difference = currentSize - previousSize;
  var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
  if (difference >= FIFTY_KILOBYTES) {
    return chalk.red('+' + fileSize);
  } else if (difference < FIFTY_KILOBYTES && difference > 0) {
    return chalk.yellow('+' + fileSize);
  } else if (difference < 0) {
    return chalk.green(fileSize);
  } else {
    return '';
  }
}

// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
recursive(paths.appBuild, (err, fileNames) => {
  var previousSizeMap = (fileNames || [])
    .filter(fileName => /\.(js|css)$/.test(fileName))
    .reduce((memo, fileName) => {
      var contents = fs.readFileSync(fileName);
      var key = removeFileNameHash(fileName);
      memo[key] = gzipSize(contents);
      return memo;
    }, {});

  // Remove all content but keep the directory so that
  // if you're in it, you don't end up in Trash
  fs.emptyDirSync(paths.appBuild);

  // Start the webpack build
  build(previousSizeMap);

  // Merge with the public folder
  copyPublicFolder();
});

// Print a detailed summary of build files.
function printFileSizes(stats, previousSizeMap) {
  var assets = stats.toJson().assets
    .filter(asset => /\.(js|css)$/.test(asset.name))
    .map(asset => {
      var fileContents = fs.readFileSync(paths.appBuild + '/' + asset.name);
      var size = gzipSize(fileContents);
      var previousSize = previousSizeMap[removeFileNameHash(asset.name)];
      var difference = getDifferenceLabel(size, previousSize);
      return {
        folder: path.join('build', path.dirname(asset.name)),
        name: path.basename(asset.name),
        size: size,
        sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : '')
      };
    });
  assets.sort((a, b) => b.size - a.size);
  var longestSizeLabelLength = Math.max.apply(null,
    assets.map(a => stripAnsi(a.sizeLabel).length)
  );
  assets.forEach(asset => {
    var sizeLabel = asset.sizeLabel;
    var sizeLength = stripAnsi(sizeLabel).length;
    if (sizeLength < longestSizeLabelLength) {
      var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
      sizeLabel += rightPadding;
    }
    console.log(
      '  ' + sizeLabel +
      '  ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name)
    );
  });
}

// Print out errors
function printErrors(summary, errors) {
  console.log(chalk.red(summary));
  console.log();
  errors.forEach(err => {
    console.log(err.message || err);
    console.log();
  });
}

// Create the production build and print the deployment instructions.
function build(previousSizeMap) {
  console.log('Creating an optimized production build...');

  var compiler;
  try {
    compiler = webpack(config);
  } catch (err) {
    printErrors('Failed to compile.', [err]);
    process.exit(1);
  }

  compiler.run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
     printErrors('Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.', stats.compilation.warnings);
     process.exit(1);
   }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizes(stats, previousSizeMap);
    console.log();

    var openCommand = process.platform === 'win32' ? 'start' : 'open';
    var appPackage  = require(paths.appPackageJson);
    var publicUrl = paths.publicUrl;
    var publicPath = config.output.publicPath;
    var publicPathname = url.parse(publicPath).pathname;
    if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('To publish it at ' + chalk.green(publicUrl) + ', run:');
      // If script deploy has been added to package.json, skip the instructions
      if (typeof appPackage.scripts.deploy === 'undefined') {
        console.log();
        if (useYarn) {
          console.log('  ' + chalk.cyan('yarn') +  ' add --dev gh-pages');
        } else {
          console.log('  ' + chalk.cyan('npm') +  ' install --save-dev gh-pages');
        }
        console.log();
        console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
        console.log();
        console.log('    ' + chalk.dim('// ...'));
        console.log('    ' + chalk.yellow('"scripts"') + ': {');
        console.log('      ' + chalk.dim('// ...'));
        console.log('      ' + chalk.yellow('"predeploy"') + ': ' + chalk.yellow('"npm run build",'));
        console.log('      ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"gh-pages -d build"'));
        console.log('    }');
        console.log();
        console.log('Then run:');
      }
      console.log();
      console.log('  ' + chalk.cyan(useYarn ? 'yarn' : 'npm') +  ' run deploy');
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log();
    } else {
      if (publicUrl) {
        // "homepage": "http://mywebsite.com"
        console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) +  '.');
        console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
        console.log();
      } else {
        // no homepage
        console.log('The project was built assuming it is hosted at the server root.');
        console.log('To override this, specify the ' + chalk.green('homepage') + ' in your '  + chalk.cyan('package.json') + '.');
        console.log('For example, add this to build it for GitHub Pages:')
        console.log();
        console.log('  ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
        console.log();
      }
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('You may also serve it locally with a static server:')
      console.log();
      if (useYarn) {
        console.log('  ' + chalk.cyan('yarn') +  ' global add pushstate-server');
      } else {
        console.log('  ' + chalk.cyan('npm') +  ' install -g pushstate-server');
      }
      console.log('  ' + chalk.cyan('pushstate-server') + ' build');
      console.log('  ' + chalk.cyan(openCommand) + ' http://localhost:9000');
      console.log();
    }
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml
  });
}
<commit_msg>Use real build path name in build output (#1478)<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

// Do this as the first thing so that any code reading it knows the right env.
process.env.NODE_ENV = 'production';

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});

var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var filesize = require('filesize');
var gzipSize = require('gzip-size').sync;
var webpack = require('webpack');
var config = require('../config/webpack.config.prod');
var paths = require('../config/paths');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var recursive = require('recursive-readdir');
var stripAnsi = require('strip-ansi');

var useYarn = fs.existsSync(paths.yarnLockFile);

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Input: /User/dan/app/build/static/js/main.82be8.js
// Output: /static/js/main.js
function removeFileNameHash(fileName) {
  return fileName
    .replace(paths.appBuild, '')
    .replace(/\/?(.*)(\.\w+)(\.js|\.css)/, (match, p1, p2, p3) => p1 + p3);
}

// Input: 1024, 2048
// Output: "(+1 KB)"
function getDifferenceLabel(currentSize, previousSize) {
  var FIFTY_KILOBYTES = 1024 * 50;
  var difference = currentSize - previousSize;
  var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
  if (difference >= FIFTY_KILOBYTES) {
    return chalk.red('+' + fileSize);
  } else if (difference < FIFTY_KILOBYTES && difference > 0) {
    return chalk.yellow('+' + fileSize);
  } else if (difference < 0) {
    return chalk.green(fileSize);
  } else {
    return '';
  }
}

// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
recursive(paths.appBuild, (err, fileNames) => {
  var previousSizeMap = (fileNames || [])
    .filter(fileName => /\.(js|css)$/.test(fileName))
    .reduce((memo, fileName) => {
      var contents = fs.readFileSync(fileName);
      var key = removeFileNameHash(fileName);
      memo[key] = gzipSize(contents);
      return memo;
    }, {});

  // Remove all content but keep the directory so that
  // if you're in it, you don't end up in Trash
  fs.emptyDirSync(paths.appBuild);

  // Start the webpack build
  build(previousSizeMap);

  // Merge with the public folder
  copyPublicFolder();
});

// Print a detailed summary of build files.
function printFileSizes(stats, previousSizeMap) {
  var assets = stats.toJson().assets
    .filter(asset => /\.(js|css)$/.test(asset.name))
    .map(asset => {
      var fileContents = fs.readFileSync(paths.appBuild + '/' + asset.name);
      var size = gzipSize(fileContents);
      var previousSize = previousSizeMap[removeFileNameHash(asset.name)];
      var difference = getDifferenceLabel(size, previousSize);
      return {
        folder: path.join('build', path.dirname(asset.name)),
        name: path.basename(asset.name),
        size: size,
        sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : '')
      };
    });
  assets.sort((a, b) => b.size - a.size);
  var longestSizeLabelLength = Math.max.apply(null,
    assets.map(a => stripAnsi(a.sizeLabel).length)
  );
  assets.forEach(asset => {
    var sizeLabel = asset.sizeLabel;
    var sizeLength = stripAnsi(sizeLabel).length;
    if (sizeLength < longestSizeLabelLength) {
      var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
      sizeLabel += rightPadding;
    }
    console.log(
      '  ' + sizeLabel +
      '  ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name)
    );
  });
}

// Print out errors
function printErrors(summary, errors) {
  console.log(chalk.red(summary));
  console.log();
  errors.forEach(err => {
    console.log(err.message || err);
    console.log();
  });
}

// Create the production build and print the deployment instructions.
function build(previousSizeMap) {
  console.log('Creating an optimized production build...');

  var compiler;
  try {
    compiler = webpack(config);
  } catch (err) {
    printErrors('Failed to compile.', [err]);
    process.exit(1);
  }

  compiler.run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
     printErrors('Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.', stats.compilation.warnings);
     process.exit(1);
   }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizes(stats, previousSizeMap);
    console.log();

    var openCommand = process.platform === 'win32' ? 'start' : 'open';
    var appPackage  = require(paths.appPackageJson);
    var publicUrl = paths.publicUrl;
    var publicPath = config.output.publicPath;
    var publicPathname = url.parse(publicPath).pathname;
    if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('To publish it at ' + chalk.green(publicUrl) + ', run:');
      // If script deploy has been added to package.json, skip the instructions
      if (typeof appPackage.scripts.deploy === 'undefined') {
        console.log();
        if (useYarn) {
          console.log('  ' + chalk.cyan('yarn') +  ' add --dev gh-pages');
        } else {
          console.log('  ' + chalk.cyan('npm') +  ' install --save-dev gh-pages');
        }
        console.log();
        console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
        console.log();
        console.log('    ' + chalk.dim('// ...'));
        console.log('    ' + chalk.yellow('"scripts"') + ': {');
        console.log('      ' + chalk.dim('// ...'));
        console.log('      ' + chalk.yellow('"predeploy"') + ': ' + chalk.yellow('"npm run build",'));
        console.log('      ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"gh-pages -d build"'));
        console.log('    }');
        console.log();
        console.log('Then run:');
      }
      console.log();
      console.log('  ' + chalk.cyan(useYarn ? 'yarn' : 'npm') +  ' run deploy');
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log();
    } else {
      if (publicUrl) {
        // "homepage": "http://mywebsite.com"
        console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) +  '.');
        console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
        console.log();
      } else {
        // no homepage
        console.log('The project was built assuming it is hosted at the server root.');
        console.log('To override this, specify the ' + chalk.green('homepage') + ' in your '  + chalk.cyan('package.json') + '.');
        console.log('For example, add this to build it for GitHub Pages:')
        console.log();
        console.log('  ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
        console.log();
      }
      var build = path.relative(process.cwd(), paths.appBuild);
      console.log('The ' + chalk.cyan(build) + ' folder is ready to be deployed.');
      console.log('You may also serve it locally with a static server:')
      console.log();
      if (useYarn) {
        console.log('  ' + chalk.cyan('yarn') +  ' global add pushstate-server');
      } else {
        console.log('  ' + chalk.cyan('npm') +  ' install -g pushstate-server');
      }
      console.log('  ' + chalk.cyan('pushstate-server') + ' ' + build);
      console.log('  ' + chalk.cyan(openCommand) + ' http://localhost:9000');
      console.log();
    }
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml
  });
}
<|endoftext|>


<commit_before>/*
@TODO:
  - handle package.individually?
    https://github.com/serverless/serverless/blob/master/lib/plugins/package/lib/packageService.js#L37
  - support for enabling chrome only on specific functions?
  - instead of including fs-p dep, use the fs methods from the Utils class provided by Serverless
    or use fs-extra directly.
  - config option to, instead of including chrome in artifact zip, download it on
    cold-start invocations this could be useful for development, instead of having
    to upload 50MB each deploy
  - tests.
  - custom.chrome.functions breaks when a wrapped and non-wrapped function have the
    same handler.js file
*/

import * as path from 'path'
import * as fs from 'fs-p' // deprecated. use fs-extra?
import globby from 'globby'

import { SERVERLESS_FOLDER, BUILD_FOLDER, INCLUDES } from './constants'
import {
  throwIfUnsupportedProvider,
  throwIfUnsupportedRuntime,
  throwIfWrongPluginOrder,
  getHandlerFileAndExportName,
} from './utils'

const wrapperTemplateMap = {
  'aws-nodejs6.10': 'wrapper-aws-nodejs.js',
  'aws-nodejs8.10': 'wrapper-aws-nodejs.js',
}

export default class ServerlessChrome {
  constructor (serverless, options) {
    this.serverless = serverless
    this.options = options

    const {
      provider: { name: providerName, runtime },
      plugins,
    } = serverless.service

    throwIfUnsupportedProvider(providerName)
    throwIfUnsupportedRuntime(runtime)
    throwIfWrongPluginOrder(plugins)

    this.hooks = {
      'before:offline:start:init': this.beforeCreateDeploymentArtifacts.bind(this),
      'before:package:createDeploymentArtifacts': this.beforeCreateDeploymentArtifacts.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'before:invoke:local:invoke': this.beforeCreateDeploymentArtifacts.bind(this),
      'after:invoke:local:invoke': this.cleanup.bind(this),

      'before:webpack:package:packExternalModules': this.webpackPackageBinaries.bind(this),
    }

    // only mess with the service path if we're not already known to be within a .build folder
    this.messWithServicePath = !plugins.includes('serverless-plugin-typescript')

    // annoyingly we have to do stuff differently if using serverless-webpack plugin. lame.
    this.webpack = plugins.includes('serverless-webpack')
  }

  async webpackPackageBinaries () {
    const { servicePath } = this.serverless.config

    await fs.copy(
      path.join(
        servicePath,
        'node_modules/@serverless-chrome/lambda/dist/headless-chromium'
      ),
      path.resolve(servicePath, '.webpack/service/headless-chromium')
    )
  }

  async beforeCreateDeploymentArtifacts () {
    const {
      config,
      cli,
      utils,
      service,
      service: {
        provider: { name: providerName, runtime },
      },
    } = this.serverless

    const functionsToWrap =
      (service.custom &&
        service.custom.chrome &&
        service.custom.chrome.functions) ||
      service.getAllFunctions()

    service.package.include = service.package.include || []

    cli.log('Injecting Headless Chrome...')

    // Save original service path and functions
    this.originalServicePath = config.servicePath

    // Fake service path so that serverless will know what to zip
    // Unless, we're already in a .build folder from another plugin
    if (this.messWithServicePath) {
      config.servicePath = path.join(this.originalServicePath, BUILD_FOLDER)

      if (!fs.existsSync(config.servicePath)) {
        fs.mkdirpSync(config.servicePath)
      }

      // include node_modules into build
      if (
        !fs.existsSync(path.resolve(path.join(BUILD_FOLDER, 'node_modules')))
      ) {
        fs.symlinkSync(
          path.resolve('node_modules'),
          path.resolve(path.join(BUILD_FOLDER, 'node_modules')),
          'junction'
        )
      }

      // include any "extras" from the "include" section
      const files = await globby(
        [...service.package.include, '**', '!node_modules/**'],
        {
          cwd: this.originalServicePath,
        }
      )

      files.forEach((filename) => {
        const sourceFile = path.resolve(path.join(this.originalServicePath, filename))
        const destFileName = path.resolve(path.join(config.servicePath, filename))

        const dirname = path.dirname(destFileName)

        if (!fs.existsSync(dirname)) {
          fs.mkdirpSync(dirname)
        }

        if (!fs.existsSync(destFileName)) {
          fs.copySync(sourceFile, destFileName)
        }
      })
    }

    // Add our node_modules dependencies to the package includes
    service.package.include = [...service.package.include, ...INCLUDES]

    await Promise.all(functionsToWrap.map(async (functionName) => {
      const { handler } = service.getFunction(functionName)
      const { filePath, fileName, exportName } = getHandlerFileAndExportName(handler)
      const handlerCodePath = path.join(config.servicePath, filePath)

      const originalFileRenamed = `${utils.generateShortId()}___${fileName}`

      const customPluginOptions =
          (service.custom && service.custom.chrome) || {}

      const launcherOptions = {
        ...customPluginOptions,
        flags: customPluginOptions.flags || [],
        chromePath: this.webpack ? '/var/task/headless-chromium' : undefined,
      }

      // Read in the wrapper handler code template
      const wrapperTemplate = await utils.readFile(path.resolve(
        __dirname,
        '..',
        'src',
        wrapperTemplateMap[`${providerName}-${runtime}`]
      ))

      // Include the original handler via require
      const wrapperCode = wrapperTemplate
        .replace(
          "'REPLACE_WITH_HANDLER_REQUIRE'",
          `require('./${originalFileRenamed}')`
        )
        .replace("'REPLACE_WITH_OPTIONS'", JSON.stringify(launcherOptions))
        .replace(/REPLACE_WITH_EXPORT_NAME/gm, exportName)

        // Move the original handler's file aside
      await fs.move(
        path.resolve(handlerCodePath, fileName),
        path.resolve(handlerCodePath, originalFileRenamed)
      )

      // Write the wrapper code to the function's handler path
      await utils.writeFile(
        path.resolve(handlerCodePath, fileName),
        wrapperCode
      )
    }))
  }

  async afterCreateDeploymentArtifacts () {
    if (this.messWithServicePath) {
      // Copy .build to .serverless
      await fs.copy(
        path.join(this.originalServicePath, BUILD_FOLDER, SERVERLESS_FOLDER),
        path.join(this.originalServicePath, SERVERLESS_FOLDER)
      )

      // this.serverless.service.package.artifact = path.join(
      //   this.originalServicePath,
      //   SERVERLESS_FOLDER
      //   path.basename(this.serverless.service.package.artifact)
      // )

      // Cleanup after everything is copied
      await this.cleanup()
    }
  }

  async cleanup () {
    // Restore service path
    this.serverless.config.servicePath = this.originalServicePath

    // Remove temp build folder
    fs.removeSync(path.join(this.originalServicePath, BUILD_FOLDER))
  }
}
<commit_msg>feat: add support for packaging individually in serverless-plugin (#237)<commit_after>/*
@TODO:
  - handle package.individually?
    https://github.com/serverless/serverless/blob/master/lib/plugins/package/lib/packageService.js#L37
  - support for enabling chrome only on specific functions?
  - instead of including fs-p dep, use the fs methods from the Utils class provided by Serverless
    or use fs-extra directly.
  - config option to, instead of including chrome in artifact zip, download it on
    cold-start invocations this could be useful for development, instead of having
    to upload 50MB each deploy
  - tests.
  - custom.chrome.functions breaks when a wrapped and non-wrapped function have the
    same handler.js file
*/

import * as path from 'path'
import * as fs from 'fs-p' // deprecated. use fs-extra?
import globby from 'globby'

import { SERVERLESS_FOLDER, BUILD_FOLDER, INCLUDES } from './constants'
import {
  throwIfUnsupportedProvider,
  throwIfUnsupportedRuntime,
  throwIfWrongPluginOrder,
  getHandlerFileAndExportName,
} from './utils'

const wrapperTemplateMap = {
  'aws-nodejs6.10': 'wrapper-aws-nodejs.js',
  'aws-nodejs8.10': 'wrapper-aws-nodejs.js',
}

export default class ServerlessChrome {
  constructor (serverless, options) {
    this.serverless = serverless
    this.options = options

    const {
      provider: { name: providerName, runtime },
      plugins,
    } = serverless.service

    throwIfUnsupportedProvider(providerName)
    throwIfUnsupportedRuntime(runtime)
    throwIfWrongPluginOrder(plugins)

    this.hooks = {
      'before:offline:start:init': this.beforeCreateDeploymentArtifacts.bind(this),
      'before:package:createDeploymentArtifacts': this.beforeCreateDeploymentArtifacts.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'before:invoke:local:invoke': this.beforeCreateDeploymentArtifacts.bind(this),
      'after:invoke:local:invoke': this.cleanup.bind(this),

      'before:webpack:package:packExternalModules': this.webpackPackageBinaries.bind(this),
    }

    // only mess with the service path if we're not already known to be within a .build folder
    this.messWithServicePath = !plugins.includes('serverless-plugin-typescript')

    // annoyingly we have to do stuff differently if using serverless-webpack plugin. lame.
    this.webpack = plugins.includes('serverless-webpack')
  }

  async webpackPackageBinaries () {
    const { config: { servicePath }, service } = this.serverless
    const packagedIdividually = service.package && service.package.individually

    if (packagedIdividually) {
      const functionsToCopyTo =
        (service.custom && service.custom.chrome && service.custom.chrome.functions) ||
        service.getAllFunctions()

      await Promise.all(functionsToCopyTo.map(async (functionName) => {
        await fs.copy(
          path.join(servicePath, 'node_modules/@serverless-chrome/lambda/dist/headless-chromium'),
          path.resolve(servicePath, `.webpack/${functionName}/headless-chromium`)
        )
      }))
    } else {
      await fs.copy(
        path.join(servicePath, 'node_modules/@serverless-chrome/lambda/dist/headless-chromium'),
        path.resolve(servicePath, '.webpack/service/headless-chromium')
      )
    }
  }

  async beforeCreateDeploymentArtifacts () {
    const {
      config,
      cli,
      utils,
      service,
      service: {
        provider: { name: providerName, runtime },
      },
    } = this.serverless

    const functionsToWrap =
      (service.custom &&
        service.custom.chrome &&
        service.custom.chrome.functions) ||
      service.getAllFunctions()

    service.package.include = service.package.include || []

    cli.log('Injecting Headless Chrome...')

    // Save original service path and functions
    this.originalServicePath = config.servicePath

    // Fake service path so that serverless will know what to zip
    // Unless, we're already in a .build folder from another plugin
    if (this.messWithServicePath) {
      config.servicePath = path.join(this.originalServicePath, BUILD_FOLDER)

      if (!fs.existsSync(config.servicePath)) {
        fs.mkdirpSync(config.servicePath)
      }

      // include node_modules into build
      if (
        !fs.existsSync(path.resolve(path.join(BUILD_FOLDER, 'node_modules')))
      ) {
        fs.symlinkSync(
          path.resolve('node_modules'),
          path.resolve(path.join(BUILD_FOLDER, 'node_modules')),
          'junction'
        )
      }

      // include any "extras" from the "include" section
      const files = await globby(
        [...service.package.include, '**', '!node_modules/**'],
        {
          cwd: this.originalServicePath,
        }
      )

      files.forEach((filename) => {
        const sourceFile = path.resolve(path.join(this.originalServicePath, filename))
        const destFileName = path.resolve(path.join(config.servicePath, filename))

        const dirname = path.dirname(destFileName)

        if (!fs.existsSync(dirname)) {
          fs.mkdirpSync(dirname)
        }

        if (!fs.existsSync(destFileName)) {
          fs.copySync(sourceFile, destFileName)
        }
      })
    }

    // Add our node_modules dependencies to the package includes
    service.package.include = [...service.package.include, ...INCLUDES]

    await Promise.all(functionsToWrap.map(async (functionName) => {
      const { handler } = service.getFunction(functionName)
      const { filePath, fileName, exportName } = getHandlerFileAndExportName(handler)
      const handlerCodePath = path.join(config.servicePath, filePath)

      const originalFileRenamed = `${utils.generateShortId()}___${fileName}`

      const customPluginOptions =
          (service.custom && service.custom.chrome) || {}

      const launcherOptions = {
        ...customPluginOptions,
        flags: customPluginOptions.flags || [],
        chromePath: this.webpack ? '/var/task/headless-chromium' : undefined,
      }

      // Read in the wrapper handler code template
      const wrapperTemplate = await utils.readFile(path.resolve(
        __dirname,
        '..',
        'src',
        wrapperTemplateMap[`${providerName}-${runtime}`]
      ))

      // Include the original handler via require
      const wrapperCode = wrapperTemplate
        .replace(
          "'REPLACE_WITH_HANDLER_REQUIRE'",
          `require('./${originalFileRenamed}')`
        )
        .replace("'REPLACE_WITH_OPTIONS'", JSON.stringify(launcherOptions))
        .replace(/REPLACE_WITH_EXPORT_NAME/gm, exportName)

        // Move the original handler's file aside
      await fs.move(
        path.resolve(handlerCodePath, fileName),
        path.resolve(handlerCodePath, originalFileRenamed)
      )

      // Write the wrapper code to the function's handler path
      await utils.writeFile(
        path.resolve(handlerCodePath, fileName),
        wrapperCode
      )
    }))
  }

  async afterCreateDeploymentArtifacts () {
    if (this.messWithServicePath) {
      // Copy .build to .serverless
      await fs.copy(
        path.join(this.originalServicePath, BUILD_FOLDER, SERVERLESS_FOLDER),
        path.join(this.originalServicePath, SERVERLESS_FOLDER)
      )

      // this.serverless.service.package.artifact = path.join(
      //   this.originalServicePath,
      //   SERVERLESS_FOLDER
      //   path.basename(this.serverless.service.package.artifact)
      // )

      // Cleanup after everything is copied
      await this.cleanup()
    }
  }

  async cleanup () {
    // Restore service path
    this.serverless.config.servicePath = this.originalServicePath

    // Remove temp build folder
    fs.removeSync(path.join(this.originalServicePath, BUILD_FOLDER))
  }
}
<|endoftext|>


<commit_before>$.getJSON("../js/json_test.JSON", function(animator){

    var mainDiv = document.getElementById("outputJSON");
    const processDivClassName = "processes";
    const betweenDivClassname = "betweenProcesses";
    const lifelines = "lifeLine";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        div.appendChild(lifeLineDiv);

        if (i < animator.processes.length -1) {
            var emptyDiv = document.createElement("div");
            emptyDiv.className = betweenDivClassname;

            mainDiv.appendChild(emptyDiv);
        }
    }
});<commit_msg>local storage retrieval in animator.js<commit_after>window.onload = function animateJSON() {

    animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const betweenDivClassname = "betweenProcesses";
    const lifelines = "lifeLine";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        div.appendChild(lifeLineDiv);

        if (i < animator.processes.length -1) {
            var emptyDiv = document.createElement("div");
            emptyDiv.className = betweenDivClassname;

            mainDiv.appendChild(emptyDiv);
        }
    }
};<|endoftext|>


<commit_before>#!/usr/bin/env node
/*jshint node:true*/

(function () {
    'use strict';

    var commander = require('commander');
    var helper = require('../lib/helper');

    function run() {
        var args = readCommandLineArgs();
        validate(args);
        processInputFile(args.filepath);
    }

    function readCommandLineArgs() {
        commander
            .version('0.0.1')
            .usage('[options]')
            .option('-f, --filepath [filepath]', 'path of the file that contains test json data')
            .parse(process.argv);

        return {
            filepath: commander.filepath
        }
    }

    function validate(args) {
        if(!args.filepath) {
            commander.help();
            process.exit(1);
        }
    }

    function processInputFile(filepath) {
        var input = require(filepath);

        var nodes = input.nodes;

        function callback(response) {
            console.log(response.statusCode);
        }

        for(var i = 0; i < nodes.length; i++) {

            var request = nodes[i].request;
            if(request.name === 'GET') {
                var url = request.scheme.name + '://' + request.uri.path;
                helper.get(url, callback);
            }
            else {
                console.log('some other method: ' + request.name);
            }
        }
    }

    run();

}.call(this));
<commit_msg>we now only process nodes of type Request<commit_after>#!/usr/bin/env node
/*jshint node:true*/

(function () {
    'use strict';

    var commander = require('commander');
    var helper = require('../lib/helper');

    function run() {
        var args = readCommandLineArgs();
        validate(args);
        processInputFile(args.filepath);
    }

    function readCommandLineArgs() {
        commander
            .version('0.0.1')
            .usage('[options]')
            .option('-f, --filepath [filepath]', 'path of the file that contains test json data')
            .parse(process.argv);

        return {
            filepath: commander.filepath
        }
    }

    function validate(args) {
        if(!args.filepath) {
            commander.help();
            process.exit(1);
        }
    }

    function processInputFile(filepath) {
        var input = require(filepath);

        var nodes = input.nodes;

        function callback(response) {
            console.log(response.statusCode);
        }

        for(var i = 0; i < nodes.length; i++) {

            if(nodes[i].type !== 'Request') return;

            var request = nodes[i].request;
            if(request.name === 'GET') {
                var url = request.scheme.name + '://' + request.uri.path;
                helper.get(url, callback);
            }
            else {
                console.log('some other method: ' + request.name);
            }
        }
    }

    run();

}.call(this));
<|endoftext|>


<commit_before>#!/usr/bin/env node

const cli = require('../lib/cli');
cli.execute(process.argv, (run) => {
  if (run || run.reportedTests().length < 1) {
    process.exit(0);
  } else {
    process.exit(1);
  }
});
<commit_msg>Fixed bug that would cause error when reporting error<commit_after>#!/usr/bin/env node

const cli = require('../lib/cli');
cli.execute(process.argv, (run) => {
  if (!run || run && run.reportedTests().length > 0) {
    process.exit(1);
  } else {
    process.exit(0);
  }
});
<|endoftext|>


<commit_before>'use strict'
const { resolve, join } = require('path')

const source = resolve(process.cwd(), 'src')
const app = resolve(source, 'app')
const build = resolve(process.cwd(), 'build')

const reactDll = require(join(build, 'React.json'))
const vendorDll = require(join(build, 'Vendor.json'))

const isProd = process.env.NODE_ENV === 'production'

/* TODO: use options instead of shorthand
         notation in webpack */

const rules = [
  /*{
    test: /\.tsx?$/,
    enforce: "pre",
    loader: 'tslint-loader',
    options: {
      failOnHint: false
    }
  }, */{
    enforce: 'pre',
    test: /\.js$/,
    loader: 'source-map-loader',
  }, {
    enforce: 'pre',
    test: /\.tsx?$/,
    loader: 'source-map-loader',
  }, {
    test: /\.tsx?$/,
    // loader: 'react-hot-loader!ts'
    exclude: /node_modules/,
    use: [
      'babel-loader',
      { loader: 'ts-loader', options: { transpileOnly: true } },
    ],
  }, {
    test: /\.css$/,
    include: app,
    use: [
      'style-loader',
      {
        loader: 'css-loader',
        options: {
          modules: true,
          importLoaders: 2,
          localIdentName: '[local]___[hash:base64:5]',
        },
      },
      'postcss-loader',
    ],
  }, {
    test: /\.css$/,
    exclude: app,
    loaders: [
      'style-loader',
      'css-loader',
    ],
  },
  {
    test: /\.eot(\?.*)?$/,
    loader: 'file-loader?name=fonts/[hash].[ext]',
  }, {
    test: /\.(woff|woff2)(\?.*)?$/,
    loader: 'file-loader?name=fonts/[hash].[ext]',
  }, {
    test: /\.ttf(\?.*)?$/,
    loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[hash].[ext]',
  }, {
    test: /\.svg(\?.*)?$/,
    loader: 'url-loader?limit=10000&mimetype=image/svg+xml&name=fonts/[hash].[ext]',
  }, {
    test: /\.(jpe?g|png|gif)$/i,
    loader: 'url-loader?limit=1000&name=images/[hash].[ext]',
  },
]

const unifiedConfig = {
  node: {
    fs: 'empty',
    net: 'empty',
  },
  context: source,
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    modules: [
      source,
      'app',
      'store',
      'node_modules',
    ],
  },

  output: {
    path: build,
    publicPath: '/',
    filename: 'bundle.js',
    pathinfo: true,
  },

  module: {
    rules,
  },
}

const getConfig = () => isProd ? require('./prod') : require('./dev')

module.exports = Object.assign(unifiedConfig, getConfig())
<commit_msg>refactor(treact/webpack): add mode property<commit_after>'use strict'
const { resolve, join } = require('path')

const source = resolve(process.cwd(), 'src')
const app = resolve(source, 'app')
const build = resolve(process.cwd(), 'build')

const reactDll = require(join(build, 'React.json'))
const vendorDll = require(join(build, 'Vendor.json'))

const isProd = process.env.NODE_ENV === 'production'

/* TODO: use options instead of shorthand
         notation in webpack */

const rules = [
  /*{
    test: /\.tsx?$/,
    enforce: "pre",
    loader: 'tslint-loader',
    options: {
      failOnHint: false
    }
  }, */{
    enforce: 'pre',
    test: /\.js$/,
    loader: 'source-map-loader',
  }, {
    enforce: 'pre',
    test: /\.tsx?$/,
    loader: 'source-map-loader',
  }, {
    test: /\.tsx?$/,
    // loader: 'react-hot-loader!ts'
    exclude: /node_modules/,
    use: [
      'babel-loader',
      { loader: 'ts-loader', options: { transpileOnly: true } },
    ],
  }, {
    test: /\.css$/,
    include: app,
    use: [
      'style-loader',
      {
        loader: 'css-loader',
        options: {
          modules: true,
          importLoaders: 2,
          localIdentName: '[local]___[hash:base64:5]',
        },
      },
      'postcss-loader',
    ],
  }, {
    test: /\.css$/,
    exclude: app,
    loaders: [
      'style-loader',
      'css-loader',
    ],
  },
  {
    test: /\.eot(\?.*)?$/,
    loader: 'file-loader?name=fonts/[hash].[ext]',
  }, {
    test: /\.(woff|woff2)(\?.*)?$/,
    loader: 'file-loader?name=fonts/[hash].[ext]',
  }, {
    test: /\.ttf(\?.*)?$/,
    loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[hash].[ext]',
  }, {
    test: /\.svg(\?.*)?$/,
    loader: 'url-loader?limit=10000&mimetype=image/svg+xml&name=fonts/[hash].[ext]',
  }, {
    test: /\.(jpe?g|png|gif)$/i,
    loader: 'url-loader?limit=1000&name=images/[hash].[ext]',
  },
]

const unifiedConfig = {
  mode: isProd ? 'production' : 'development',
  node: {
    fs: 'empty',
    net: 'empty',
  },
  context: source,
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    modules: [
      source,
      'app',
      'store',
      'node_modules',
    ],
  },

  output: {
    path: build,
    publicPath: '/',
    filename: 'bundle.js',
    pathinfo: true,
    globalObject: 'self',
  },

  module: {
    rules,
  },
}

const getConfig = () => isProd ? require('./prod') : require('./dev')

module.exports = Object.assign(unifiedConfig, getConfig())
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var read = require('../lib/read');
var write = require('../lib/write');
var Frame = require('./frame');

module.exports = ErrorResponse;

var emptyBuffer = new Buffer(0);

// TODO: enforce message ID of this frame is Frame.NullId when
// errorBody.code.ProtocolError = ErrorResponse.Codes.ProtocolError

// code:1 id:4 message~2
function ErrorResponse(code, id, message) {
    if (!(this instanceof ErrorResponse)) {
        return new ErrorResponse(code, id, message);
    }
    var self = this;
    self.code = code;
    if (id === null || id === undefined) {
        self.id = Frame.NullId;
    } else {
        self.id = id;
    }
    self.message = message ? write.bufferOrString(message) : emptyBuffer;
}

ErrorResponse.TypeCode = 0xff;

var Codes = {
    // 0x00 not a valid value for "code", do not use.
    Timeout: 0x01,
    Cancelled: 0x02,
    Busy: 0x03,
    Declined: 0x04,
    UnexpectedError: 0x05,
    BadRequest: 0x06,
    ProtocolError: 0xff
};

var CodeNames = {};
CodeNames[Codes.Timeout] = 'timeout';
CodeNames[Codes.Cancelled] = 'canceled';
CodeNames[Codes.Busy] = 'busy';
CodeNames[Codes.Declined] = 'declined';
CodeNames[Codes.UnexpectedError] = 'unexpected error';
CodeNames[Codes.BadRequest] = 'bad request';
CodeNames[Codes.ProtocolError] = 'protocol error';

var CodeErrors = {};
CodeErrors[Codes.Timeout] = TypedError({
    type: 'tchannel.timeout',
    isErrorFrame: true,
    errorCode: Codes.Timeout,
    originalId: null
});
CodeErrors[Codes.Cancelled] = TypedError({
    type: 'tchannel.canceled',
    isErrorFrame: true,
    errorCode: Codes.Cancelled,
    originalId: null
});
CodeErrors[Codes.Busy] = TypedError({
    type: 'tchannel.busy',
    isErrorFrame: true,
    errorCode: Codes.Busy,
    originalId: null
});
CodeErrors[Codes.Declined] = TypedError({
    type: 'tchannel.declined',
    isErrorFrame: true,
    errorCode: Codes.Declined,
    originalId: null
});
CodeErrors[Codes.UnexpectedError] = TypedError({
    type: 'tchannel.unexpected',
    isErrorFrame: true,
    errorCode: Codes.UnexpectedError,
    originalId: null
});
CodeErrors[Codes.BadRequest] = TypedError({
    type: 'tchannel.bad-request',
    isErrorFrame: true,
    errorCode: Codes.BadRequest,
    originalId: null
});
CodeErrors[Codes.ProtocolError] = TypedError({
    type: 'tchannel.protocol',
    isErrorFrame: true,
    errorCode: Codes.ProtocolError,
    originalId: null
});

ErrorResponse.Codes = Codes;
ErrorResponse.CodeNames = CodeNames;
ErrorResponse.CodeErrors = CodeErrors;

ErrorResponse.read = read.chained(read.series([
    read.UInt8,    // code:1
    read.UInt32BE, // id:4
    read.buf2      // message~2
]), function buildErrorRes(results, buffer, offset) {
    var code = results[0];
    var id = results[1];
    var message = results[2];
    var res = new ErrorResponse(code, id, message);
    return [null, offset, res];
});

ErrorResponse.prototype.write = function writeErrorRes() {
    var self = this;
    return write.series([
        write.UInt8(self.code, 'ErrorResponse code'),  // code:1
        write.UInt32BE(self.id, 'ErrorResponse id'),   // id:4
        write.buf2(self.message, 'ErrorResponse arg1') // message~2
    ]);
};
<commit_msg>Use null-prototyped objects for error code lookup<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var read = require('../lib/read');
var write = require('../lib/write');
var Frame = require('./frame');

module.exports = ErrorResponse;

var emptyBuffer = new Buffer(0);

// TODO: enforce message ID of this frame is Frame.NullId when
// errorBody.code.ProtocolError = ErrorResponse.Codes.ProtocolError

// code:1 id:4 message~2
function ErrorResponse(code, id, message) {
    if (!(this instanceof ErrorResponse)) {
        return new ErrorResponse(code, id, message);
    }
    var self = this;
    self.code = code;
    if (id === null || id === undefined) {
        self.id = Frame.NullId;
    } else {
        self.id = id;
    }
    self.message = message ? write.bufferOrString(message) : emptyBuffer;
}

ErrorResponse.TypeCode = 0xff;

var Codes = Object.create(null);
// 0x00 not a valid value for "code", do not use.
Codes.Timeout = 0x01;
Codes.Cancelled = 0x02;
Codes.Busy = 0x03;
Codes.Declined = 0x04;
Codes.UnexpectedError = 0x05;
Codes.BadRequest = 0x06;
Codes.ProtocolError = 0xf;

var CodeNames = Object.create(null);
CodeNames[Codes.Timeout] = 'timeout';
CodeNames[Codes.Cancelled] = 'canceled';
CodeNames[Codes.Busy] = 'busy';
CodeNames[Codes.Declined] = 'declined';
CodeNames[Codes.UnexpectedError] = 'unexpected error';
CodeNames[Codes.BadRequest] = 'bad request';
CodeNames[Codes.ProtocolError] = 'protocol error';

var CodeErrors = Object.create(null);
CodeErrors[Codes.Timeout] = TypedError({
    type: 'tchannel.timeout',
    isErrorFrame: true,
    errorCode: Codes.Timeout,
    originalId: null
});
CodeErrors[Codes.Cancelled] = TypedError({
    type: 'tchannel.canceled',
    isErrorFrame: true,
    errorCode: Codes.Cancelled,
    originalId: null
});
CodeErrors[Codes.Busy] = TypedError({
    type: 'tchannel.busy',
    isErrorFrame: true,
    errorCode: Codes.Busy,
    originalId: null
});
CodeErrors[Codes.Declined] = TypedError({
    type: 'tchannel.declined',
    isErrorFrame: true,
    errorCode: Codes.Declined,
    originalId: null
});
CodeErrors[Codes.UnexpectedError] = TypedError({
    type: 'tchannel.unexpected',
    isErrorFrame: true,
    errorCode: Codes.UnexpectedError,
    originalId: null
});
CodeErrors[Codes.BadRequest] = TypedError({
    type: 'tchannel.bad-request',
    isErrorFrame: true,
    errorCode: Codes.BadRequest,
    originalId: null
});
CodeErrors[Codes.ProtocolError] = TypedError({
    type: 'tchannel.protocol',
    isErrorFrame: true,
    errorCode: Codes.ProtocolError,
    originalId: null
});

ErrorResponse.Codes = Codes;
ErrorResponse.CodeNames = CodeNames;
ErrorResponse.CodeErrors = CodeErrors;

ErrorResponse.read = read.chained(read.series([
    read.UInt8,    // code:1
    read.UInt32BE, // id:4
    read.buf2      // message~2
]), function buildErrorRes(results, buffer, offset) {
    var code = results[0];
    var id = results[1];
    var message = results[2];
    var res = new ErrorResponse(code, id, message);
    return [null, offset, res];
});

ErrorResponse.prototype.write = function writeErrorRes() {
    var self = this;
    return write.series([
        write.UInt8(self.code, 'ErrorResponse code'),  // code:1
        write.UInt32BE(self.id, 'ErrorResponse id'),   // id:4
        write.buf2(self.message, 'ErrorResponse arg1') // message~2
    ]);
};
<|endoftext|>


<commit_before>import pager from "./pager.vue";
import VSelect from "../../v-select/index";

export default{
    name: 'v-pagination',
    props: {
        layout: {
            type: Array,
            default(){
                return ['total', 'prev', 'pager', 'next', 'sizer','jumper']
            }
        },

        // 总条数
        total: {
            type: Number,
            require: true
        },

        // 当前页
        pageIndex: {
            type: Number
        },

        // 最多显示几个数字按钮
        showPagingCount: {
            type: Number,
            default: 11
        },

        // 每页大小
        pageSize: {
            type: Number,
            default: 10
        },

        // 每页大小下拉配置
        pageSizeOption: {
            type: Array,
            default: function () {
                return [10, 20, 30]
            }
        }
    },
    data(){
        return {
            newPageIndex: (this.pageIndex && this.pageIndex > 0) ? parseInt(this.pageIndex) : 1,

            newPageSize: this.pageSize
        }
    },

    computed: {
        pageCount(){
            return Math.ceil(this.total / this.newPageSize)
        }
    },

    render(h){
        let template =

;

        var comps = {
            //'total','prev','pager','next','sizer','jumper'
            'total': <total></total>,
            'prev': <prev></prev>,
            'pager': <pager pageCount={this.pageCount} pageIndex={this.newPageIndex}
                            showPagingCount={this.showPagingCount}
                            onJumpPageHandler={this.jumpPageHandler}></pager>,
            'next': <next></next>,
            'sizer': <sizer></sizer>,
            'jumper':<jumper></jumper>
        }

        this.layout.forEach(item => {
            template.children.push(comps[item]);
        })

        return template

    },

    components: {

        Total: {
            render(h){
                return (
                    共 {this.$parent.total} 条
                )
            }
        },

        Prev: {
            render(h){
                return (

)
            }
        },

        pager,

        Next: {
            render(h){
                return (

                )
            }
        },

        Sizer: {
            components: {
                VSelect
            },
            render(h){
                return (
                    <v-select onSelectChangeHandler={this.$parent.pageSizeChangeHandler} class="et-page-select" labels={this.$parent.pageSizeOption}
                              currentLabel={this.$parent.pageSize}></v-select>
                )
            }
        },

        Jumper:{
            methods:{
                jumperEnter(event){
                    if (event.keyCode !== 13) return

                    var val = this.$parent.getValidNum(event.target.value)

                    this.$parent.newPageIndex = val

                    event.target.value = val
                }
            },
            render(h){
                return (
                    前往 <input
                        class="et-page-goto-input"
                        domProps-value={this.$parent.newPageIndex}
                        on-keyup={this.jumperEnter}
                        type="input"
                        /> 页
                )
            }
        }
    },

    methods: {

        getValidNum(value){
            let result=1

            value = parseInt(value, 10);

            if (isNaN(value) || value < 1){
                result = 1
            }else{
                if (value < 1) {
                    result = 1;
                } else if (value > this.pageCount) {
                    result = this.pageCount;
                }else{
                    result = value
                }
            }
            return result
        },

        jumpPageHandler(newPageIndex){
            this.newPageIndex = newPageIndex
            this.$emit('page-change', this.newPageIndex)
        },

        // 上一页
        prevPage(){
            if (this.newPageIndex > 1) {
                this.newPageIndex = this.newPageIndex - 1
                this.$emit('page-change', this.newPageIndex)
            }
        },

        // 下一页
        nextPage(){
            if (this.newPageIndex < this.pageCount) {
                this.newPageIndex = this.newPageIndex + 1
                this.$emit('page-change', this.newPageIndex)
            }
        },

        // 改变页面大小
        pageSizeChangeHandler(newPageSize){
            this.newPageSize = newPageSize
            this.newPageIndex = 1
            this.$emit('page-size-change', this.newPageSize)
        }

    },
    created(){

    },
    mounted(){
    }

}<commit_msg>修改默认显示数字按钮的个数<commit_after>import pager from "./pager.vue";
import VSelect from "../../v-select/index";

export default{
    name: 'v-pagination',
    props: {
        layout: {
            type: Array,
            default(){
                return ['total', 'prev', 'pager', 'next', 'sizer','jumper']
            }
        },

        // 总条数
        total: {
            type: Number,
            require: true
        },

        // 当前页
        pageIndex: {
            type: Number
        },

        // 最多显示几个数字按钮
        showPagingCount: {
            type: Number,
            default: 5
        },

        // 每页大小
        pageSize: {
            type: Number,
            default: 10
        },

        // 每页大小下拉配置
        pageSizeOption: {
            type: Array,
            default: function () {
                return [10, 20, 30]
            }
        }
    },
    data(){
        return {
            newPageIndex: (this.pageIndex && this.pageIndex > 0) ? parseInt(this.pageIndex) : 1,

            newPageSize: this.pageSize
        }
    },

    computed: {
        pageCount(){
            return Math.ceil(this.total / this.newPageSize)
        }
    },

    render(h){
        let template =

;

        var comps = {
            //'total','prev','pager','next','sizer','jumper'
            'total': <total></total>,
            'prev': <prev></prev>,
            'pager': <pager pageCount={this.pageCount} pageIndex={this.newPageIndex}
                            showPagingCount={this.showPagingCount}
                            onJumpPageHandler={this.jumpPageHandler}></pager>,
            'next': <next></next>,
            'sizer': <sizer></sizer>,
            'jumper':<jumper></jumper>
        }

        this.layout.forEach(item => {
            template.children.push(comps[item]);
        })

        return template

    },

    components: {

        Total: {
            render(h){
                return (
                    共 {this.$parent.total} 条
                )
            }
        },

        Prev: {
            render(h){
                return (

)
            }
        },

        pager,

        Next: {
            render(h){
                return (

                )
            }
        },

        Sizer: {
            components: {
                VSelect
            },
            render(h){
                return (
                    <v-select onSelectChangeHandler={this.$parent.pageSizeChangeHandler} class="et-page-select" labels={this.$parent.pageSizeOption}
                              currentLabel={this.$parent.pageSize}></v-select>
                )
            }
        },

        Jumper:{
            methods:{
                jumperEnter(event){
                    if (event.keyCode !== 13) return

                    var val = this.$parent.getValidNum(event.target.value)

                    this.$parent.newPageIndex = val

                    event.target.value = val
                }
            },
            render(h){
                return (
                    前往 <input
                        class="et-page-goto-input"
                        domProps-value={this.$parent.newPageIndex}
                        on-keyup={this.jumperEnter}
                        type="input"
                        /> 页
                )
            }
        }
    },

    methods: {

        getValidNum(value){
            let result=1

            value = parseInt(value, 10);

            if (isNaN(value) || value < 1){
                result = 1
            }else{
                if (value < 1) {
                    result = 1;
                } else if (value > this.pageCount) {
                    result = this.pageCount;
                }else{
                    result = value
                }
            }
            return result
        },

        jumpPageHandler(newPageIndex){
            this.newPageIndex = newPageIndex
            this.$emit('page-change', this.newPageIndex)
        },

        // 上一页
        prevPage(){
            if (this.newPageIndex > 1) {
                this.newPageIndex = this.newPageIndex - 1
                this.$emit('page-change', this.newPageIndex)
            }
        },

        // 下一页
        nextPage(){
            if (this.newPageIndex < this.pageCount) {
                this.newPageIndex = this.newPageIndex + 1
                this.$emit('page-change', this.newPageIndex)
            }
        },

        // 改变页面大小
        pageSizeChangeHandler(newPageSize){
            this.newPageSize = newPageSize
            this.newPageIndex = 1
            this.$emit('page-size-change', this.newPageSize)
        }

    },
    created(){

    },
    mounted(){
    }

}<|endoftext|>


<commit_before>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form>';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<button type="submit" class="btn btn-success" id="submitMake">Submit</button>';
    content += ' <button class="btn btn-info" id="submitPlugin">Run Later</button>';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr. You will see your API key in the footer of every page. Right click on the Chrome extention to get to your Options page where you add your API key.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
          var type = '',
              confidence = json.response.confidence,
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else if (!json.response.email) {
            content = "Sorry, no email address was found.";
            type = 'alert alert-danger';
          }
          else {
            type = 'alert alert-success';
            content = '';
            $.each(['first', 'last', 'domain', 'email', 'confidence'], function(i, id){
              content += '
' + id + ':' + '' + json.response[id] + '
';
            })
            content += '
';
            content += '

';
          }
          return {type: type, content: content};
        }

        var processPluginResponse = function(json) {
          var type = '';
          type = 'alert alert-success';
          content = 'Check your plugin history for this email address.';
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.response.confidence,
            content = '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.response) return "Bad response";
          else if (json.response.error) return json.response.error;
          else return false;
        }

        $('#submitMake').click( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/guess' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'http://toofr.com/api/test' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

        $('#submitPlugin').click( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/plugin' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processPluginResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();<commit_msg>Set "Run later" as default submit action<commit_after>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form id="submitName">';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<input type="button" class="btn btn-success" id="submitMake" value="Submit">';
    content += ' <input type="submit" class="btn btn-info" id="submitPlugin" value="Run Later">';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr. You will see your API key in the footer of every page. Right click on the Chrome extention to get to your Options page where you add your API key.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
          var type = '',
              confidence = json.response.confidence,
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else if (!json.response.email) {
            content = "Sorry, no email address was found.";
            type = 'alert alert-danger';
          }
          else {
            type = 'alert alert-success';
            content = '';
            $.each(['first', 'last', 'domain', 'email', 'confidence'], function(i, id){
              content += '
' + id + ':' + '' + json.response[id] + '
';
            })
            content += '
';
            content += '

';
          }
          return {type: type, content: content};
        }

        var processPluginResponse = function(json) {
          var type = '';
          type = 'alert alert-success';
          content = 'Check your plugin history for this email address.';
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.response.confidence,
            content = '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.response) return "Bad response";
          else if (json.response.error) return json.response.error;
          else return false;
        }

        $('#submitName').submit(function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/plugin' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processPluginResponse);
        });

        $('#submitMake').click( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/guess' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'http://toofr.com/api/test' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();
<|endoftext|>


<commit_before>const win = window
const doc = document.body
const docEl = document.documentElement

export const Observer = win.MutationObserver || win.WebKitMutationObserver
export const requestAnimationFrame = win.requestAnimationFrame || (fn => setTimeout(fn, 1000 / 60))

// var hasTouchEvents = 'ontouchstart' in win
// var hasPointerEvents = win.PointerEvent
// export const hasTouch = 'ontouchstart' in win ||
//     win.DocumentTouch && doc instanceof DocumentTouch ||
//     navigator.msPointerEnabled && navigator.msMaxTouchPoints || // IE 10
//     navigator.pointerEnabled && navigator.maxTouchPoints // IE >=11

// export const pointerDown = !hasTouch ? 'mousedown' : `mousedown ${hasTouchEvents ? 'touchstart' : 'pointerdown'}`
// export const pointerMove = !hasTouch ? 'mousemove' : `mousemove ${hasTouchEvents ? 'touchmove' : 'pointermove'}`
// export const pointerUp = !hasTouch ? 'mouseup' : `mouseup ${hasTouchEvents ? 'touchend' : 'pointerup'}`
// export const pointerEnter = hasTouch && hasPointerEvents ? 'pointerenter' : 'mouseenter'
// export const pointerLeave = hasTouch && hasPointerEvents ? 'pointerleave' : 'mouseleave'

export const transitionend = prefix('transition', 'transition-end')
export const animationstart = prefix('animation', 'animation-start')
export const animationend = prefix('animation', 'animation-end')

function prefix (name, event) {
  const ucase = classify(name)
  const lowered = classify(event).toLowerCase()
  const classified = classify(event)
  const element = doc.body || docEl
  const names = {
    [name]: lowered,
    [`Webkit${ucase}`]: `webkit${classified}`,
    [`Moz${ucase}`]: lowered,
    [`o${ucase}`]: `o${classified} o${lowered}`
  }

  for (name in names) {
    if (element.style[name] !== undefined) {
      return names[name]
    }
  }
}

function classify (str) {
  return str.replace(/(?:^|[-_/])(\w)/g, (_, c) => c ? c.toUpperCase() : '')
}
<commit_msg>fix minor helper issue<commit_after>const win = window
const doc = document
const docEl = document.documentElement

export const Observer = win.MutationObserver || win.WebKitMutationObserver
export const requestAnimationFrame = win.requestAnimationFrame || (fn => setTimeout(fn, 1000 / 60))

// var hasTouchEvents = 'ontouchstart' in win
// var hasPointerEvents = win.PointerEvent
// export const hasTouch = 'ontouchstart' in win ||
//     win.DocumentTouch && doc instanceof DocumentTouch ||
//     navigator.msPointerEnabled && navigator.msMaxTouchPoints || // IE 10
//     navigator.pointerEnabled && navigator.maxTouchPoints // IE >=11

// export const pointerDown = !hasTouch ? 'mousedown' : `mousedown ${hasTouchEvents ? 'touchstart' : 'pointerdown'}`
// export const pointerMove = !hasTouch ? 'mousemove' : `mousemove ${hasTouchEvents ? 'touchmove' : 'pointermove'}`
// export const pointerUp = !hasTouch ? 'mouseup' : `mouseup ${hasTouchEvents ? 'touchend' : 'pointerup'}`
// export const pointerEnter = hasTouch && hasPointerEvents ? 'pointerenter' : 'mouseenter'
// export const pointerLeave = hasTouch && hasPointerEvents ? 'pointerleave' : 'mouseleave'

export const transitionend = prefix('transition', 'transition-end')
export const animationstart = prefix('animation', 'animation-start')
export const animationend = prefix('animation', 'animation-end')

function prefix (name, event) {
  const ucase = classify(name)
  const lowered = classify(event).toLowerCase()
  const classified = classify(event)
  const element = doc.body || docEl
  const names = {
    [name]: lowered,
    [`Webkit${ucase}`]: `webkit${classified}`,
    [`Moz${ucase}`]: lowered,
    [`o${ucase}`]: `o${classified} o${lowered}`
  }

  for (name in names) {
    if (element.style[name] !== undefined) {
      return names[name]
    }
  }
}

function classify (str) {
  return str.replace(/(?:^|[-_/])(\w)/g, (_, c) => c ? c.toUpperCase() : '')
}
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import Chart from "react-google-charts";
// Ref : https://developers.google.com/chart/interactive/docs/gallery/histogram

const data = [
  ["Name", "Salary", "Full time employee"],
  ["Mike", { v: 10000, f: "$10,000" }, true],
  ["Jim", { v: 8000, f: "$8,000" }, false],
  ["Alice", { v: 12500, f: "$12,500" }, true],
  ["Bob", { v: 7000, f: "$7,000" }, true]
];
const options = {
  title: "Company Performance",
  curveType: "function",
  legend: { position: "bottom" }
};
class App extends React.Component {
  render() {
    return (

        <Chart
          chartType="Table"
          width="100%"
          height="400px"
          data={data}
          options={options}
        />

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<commit_msg>Add pagesize to table demo.<commit_after>import React from "react";
import ReactDOM from "react-dom";
import Chart from "react-google-charts";
// Ref : https://developers.google.com/chart/interactive/docs/gallery/histogram

const data = [
  ["Name", "Salary", "Full time employee"],
  ["Mike", { v: 10000, f: "$10,000" }, true],
  ["Jim", { v: 8000, f: "$8,000" }, false],
  ["Alice", { v: 12500, f: "$12,500" }, true],
  ["Bob", { v: 7000, f: "$7,000" }, true]
];
const options = {
  title: "Company Performance",
  curveType: "function",
  legend: { position: "bottom" },
  pageSize: 1
};
class App extends React.Component {
  render() {
    return (

        <Chart
          chartType="Table"
          width="100%"
          height="400px"
          data={data}
          options={options}
        />

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();

// Connect and perform routine maintenance.
client.on('ready', () => {
	console.log('[' + new Date().toISOString() + '] Connected!');

	// Get a list of channels.
	var channelsOrdered = client.channels.array().slice(0);

	// Evaluate only voice channels.
	channelsOrdered = channelsOrdered.filter(function(channel) {
		return channel.type == 'voice' && channel.position !== 'undefined';
	});

	// Sort channels by their current position.
	channelsOrdered = channelsOrdered.sort(function(channelA, channelB) {
		return channelA.position - channelB.position;
	});

	// Re-sort channels to support auto-grouping and maximum voice quality.
	var currentPosition = 100;
	channelsOrdered.forEach(function(channel) {
		currentChannel = client.channels.get(channel.id);
		currentChannel.edit({bitrate: 96000, position: currentPosition})
			.then(editedChannel => {
				console.log('[' + new Date().toISOString() + '] Set ' + editedChannel.type + ' channel "' + editedChannel.name + '" (' + editedChannel.id + ') position to ' + editedChannel.position + ' with ' + editedChannel.bitrate / 1000 + 'kbps bitrate')
			})
			.catch(console.error);
		currentPosition += 100;
	});
});

// Trigger on VOICE_STATE_UPDATE events.
client.on('voiceStateUpdate', (oldMember, member) => {

	// Check if the user entered a new channel.
	if (member.voiceChannelID) {
		const newChannel = member.guild.channels.get(member.voiceChannelID);

		// If the user entered a game channel (prefixed with a game controller icon), group them into their own channel.
		if (newChannel.name.startsWith('🎮')) {
			member.guild.createChannel('Group', 'voice')
				.then(createdChannel => {
					createdChannel.edit({bitrate: 96000, position: newChannel.position + 1})
						.then(createdChannel => {
							member.setVoiceChannel(createdChannel)
								.then(console.log('[' + new Date().toISOString() + '] Moved user "' + member.user.username + '#' + member.user.discriminator + '" (' + member.user.id + ') to ' + createdChannel.type + ' channel "' + createdChannel.name + '" (' + createdChannel.id + ')'))
								.catch(console.error);
						})
						.catch(console.error);
				})
				.catch(console.error);
		}
	}

	// Check if the user came from another channel.
	if (oldMember.voiceChannelID) {
		const oldChannel = oldMember.guild.channels.get(oldMember.voiceChannelID);

		// Delete the user's now empty temporary channel, if applicable.
		if (oldChannel.name.includes('Group') && !oldChannel.members.array().length) {
			oldChannel.delete()
				.then(function() {
					console.log('[' + new Date().toISOString() + '] Deleted ' + oldChannel.type + ' channel "' + oldChannel.name + '" (' + oldChannel.id + ')');
				})
				.catch(console.error);
		}
	}
});

client.login('');
<commit_msg>Bug fixes<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();

// Connect and perform routine maintenance.
client.on('ready', () => {
	console.log('[' + new Date().toISOString() + '] Connected!');

	// Get a list of channels.
	var channelsOrdered = client.channels.array().slice(0);

	// Evaluate only voice channels.
	channelsOrdered = channelsOrdered.filter(function(channel) {
		return channel.type == 'voice' && typeof channel.position !== 'undefined';
	});

	// Sort channels by their current position.
	channelsOrdered = channelsOrdered.sort(function(channelA, channelB) {
		return channelA.position - channelB.position;
	});

	// Re-sort channels to support auto-grouping and maximum voice quality.
	var currentPosition = 100;
	channelsOrdered.forEach(function(channel) {
		currentChannel = client.channels.get(channel.id);
		currentChannel.edit({bitrate: 96000, position: currentPosition})
			.then(editedChannel => {
				console.log('[' + new Date().toISOString() + '] Set ' + editedChannel.type + ' channel "' + editedChannel.name + '" (' + editedChannel.id + ') position to ' + editedChannel.position + ' with ' + editedChannel.bitrate / 1000 + 'kbps bitrate')
			})
			.catch(console.error);
		currentPosition += 100;
	});
});

// Trigger on VOICE_STATE_UPDATE events.
client.on('voiceStateUpdate', (oldMember, member) => {

	// Check if the user entered a new channel.
	if (member.voiceChannelID) {
		const newChannel = member.guild.channels.get(member.voiceChannelID);

		// If the user entered a game channel (prefixed with a game controller icon), group them into their own channel.
		if (newChannel.name.startsWith('🎮')) {
			member.guild.createChannel('Group', 'voice')
				.then(createdChannel => {
					createdChannel.edit({bitrate: 96000, position: newChannel.position + 50})
						.then(createdChannel => {
							member.setVoiceChannel(createdChannel)
								.then(console.log('[' + new Date().toISOString() + '] Moved user "' + member.user.username + '#' + member.user.discriminator + '" (' + member.user.id + ') to ' + createdChannel.type + ' channel "' + createdChannel.name + '" (' + createdChannel.id + ')'))
								.catch(console.error);
						})
						.catch(console.error);
				})
				.catch(console.error);
		}
	}

	// Check if the user came from another channel.
	if (oldMember.voiceChannelID) {
		const oldChannel = oldMember.guild.channels.get(oldMember.voiceChannelID);

		// Delete the user's now empty temporary channel, if applicable.
		if (oldChannel.name.includes('Group') && !oldChannel.members.array().length) {
			oldChannel.delete()
				.then(function() {
					console.log('[' + new Date().toISOString() + '] Deleted ' + oldChannel.type + ' channel "' + oldChannel.name + '" (' + oldChannel.id + ')');
				})
				.catch(console.error);
		}
	}
});

client.login('');
<|endoftext|>


<commit_before>//Option 3
(function() {
  "use strict";
  var CustomersController = function CustomersController() {
    this.sortBy = "name";
    this.reverse = false;
    this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
    this.doSort = function(propName) {
      this.sortBy = propName;
      this.reverse = !this.reverse
    }
  }
  CustomersController.$inject = [ "$scope" ];
  angular.module("customersApp")
  .controller("CustomersController", CustomersController);
}());

//Option 2
// (function() {
//   "use strict";
//   angular.module("customersApp")
//   .controller("CustomersController", function CustomersController() {
//     this.sortBy = "name";
//     this.reverse = false;
//     this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
//     this.doSort = function(propName) {
//       this.sortBy = propName;
//       this.reverse = !this.reverse
//     }
//   });
// }());

//Option 1
// app.controller("CustomersController", function CustomersController() {
//   this.sortBy = "name";
//   this.reverse = false;
//   this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
//   this.doSort = function(propName) {
//     this.sortBy = propName;
//     this.reverse = !this.reverse
//   }
// });
<commit_msg>Even Better minification syntax for readability<commit_after>//Option 3
(function() {
  "use strict";
  CustomersController.$inject = [ "$scope" ];
  function CustomersController($scope) {
    this.sortBy = "name";
    this.reverse = false;
    this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
    this.doSort = function(propName) {
      this.sortBy = propName;
      this.reverse = !this.reverse
    }
  }
  angular.module("customersApp")
  .controller("CustomersController", CustomersController);
}());

//Option 2
// (function() {
//   "use strict";
//   angular.module("customersApp")
//   .controller("CustomersController", function CustomersController() {
//     this.sortBy = "name";
//     this.reverse = false;
//     this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
//     this.doSort = function(propName) {
//       this.sortBy = propName;
//       this.reverse = !this.reverse
//     }
//   });
// }());

//Option 1
// app.controller("CustomersController", function CustomersController() {
//   this.sortBy = "name";
//   this.reverse = false;
//   this.customers = [ { name: "John", city:"Nashville", joined: "2012/01/15", orderTotal: 9.998 }, { name:"Gerald", city:"Heaven", joined: "1989/08/07", orderTotal: 7.00 }, { name: "Joe", city:"Dirte", joined: "2012/01/23", orderTotal: 14.23 } ];
//   this.doSort = function(propName) {
//     this.sortBy = propName;
//     this.reverse = !this.reverse
//   }
// });
<|endoftext|>