<commit_before>import fs from 'fs';
import chalk from 'chalk';
import gulp from 'gulp';
import babel from 'gulp-babel';
import rename from 'gulp-rename';
import clean from 'gulp-rimraf';
import minify from 'gulp-minifier';
import jeditor from "gulp-json-editor";
import runSequence from 'run-sequence';
import config from './src/config';

const dist = './dist';
const dist_server = `${dist}/server`;
const dist_swagger = `${dist_server}/core/swagger/api-docs`;
const dist_client = `${dist}/client`;
const pm2_simple = `simple.config.js`;
const pm2_cluster = `cluster.config.js`;

gulp.task('build', () => {
  runSequence('build-clean', 'build-babel', 'build-replace');
});

gulp.task('build-clean', () => {
  // Remove files dist, but ignore assets
  return gulp.src([
    `${dist_server}/*`, `!${dist_server}/assets`
  ], { read: false }).pipe(clean({ force: true }));
});

gulp.task('build-babel', () => {
  // Babel transform, ignore config and swagger api-docs
  return gulp.src(['src/**/*.js', '!src/config/*.js', '!src/core/swagger/api-docs/*']).pipe(babel()).pipe(gulp.dest(dist_server));
});

gulp.task('build-replace', () => {
  // Copy config production
  gulp.src(["src/config/production.js"]).pipe(babel()).pipe(rename('index.js')).pipe(gulp.dest(`${dist_server}/config`));
  // Copy views
  gulp.src(['src/views/**/*.{html,css}']).pipe(minify({ minify: true, collapseWhitespace: true, conservativeCollapse: true, minifyJS: true, minifyCSS: true })).pipe(gulp.dest(`${dist_server}/views`));
  // Copy assets
  gulp.src(['src/assets/**/*']).pipe(gulp.dest(`${dist_server}/assets`));
  // Copy *.yaml
  gulp.src(['src/**/*.yaml']).pipe(gulp.dest(dist_server));
  // Copy swagger/api-docs
  gulp.src([`src/core/swagger/api-docs/*`]).pipe(gulp.dest(dist_swagger));
  // package.json
  gulp.src("package.json").pipe(jeditor((json) => {
    delete json.devDependencies;
    json.scripts = {
      "start": `npm run redis && node server/app.js`,
      "simple": `npm run redis && npm stop && pm2 startOrRestart ${pm2_simple}`,
      "cluster": `npm run redis && npm stop && pm2 startOrRestart ${pm2_cluster}`,
      "dev-simple": `npm run simple && pm2 monit`,
      "dev-cluster": `npm run cluster && pm2 monit`,
      "redis": `redis-cli config set notify-keyspace-events KEA`,
      "stop": `pm2 delete ${pm2_simple} ${pm2_cluster}`
    };
    return json;
  })).pipe(gulp.dest(dist));
  // Copy pm2 files
  gulp.src([pm2_simple, pm2_cluster]).pipe(gulp.dest(dist));
  // If not exits client folder, then copy current client
  if (!fs.existsSync(`${dist}/client`)) {
    gulp.src(['client/*','!**/*.js']).pipe(minify({ minify: true, collapseWhitespace: true, conservativeCollapse: true, minifyCSS: true })).pipe(gulp.dest(dist_client));
    gulp.src(['client/**/*.js']).pipe(babel()).pipe(gulp.dest(dist_client));
  }
  // Success
  setTimeout(() => console.log(chalk.greenBright('\n---------\nBuild success!\n---------\n')), 500);
});
<commit_msg>updated build<commit_after>import fs from 'fs';
import chalk from 'chalk';
import gulp from 'gulp';
import babel from 'gulp-babel';
import rename from 'gulp-rename';
import clean from 'gulp-rimraf';
import minify from 'gulp-minifier';
import jeditor from "gulp-json-editor";
import runSequence from 'run-sequence';
import config from './src/config';

const dist = './dist';
const dist_server = `${dist}/server`;
const dist_swagger = `${dist_server}/core/swagger/api-docs`;
const dist_client = `${dist}/client`;
const pm2_simple = `simple.config.js`;
const pm2_cluster = `cluster.config.js`;

gulp.task('build', () => {

  runSequence('build-clean', 'build-babel', 'build-replace');
});

gulp.task('build-clean', () => {
  // Remove files dist, but ignore assets
  return gulp.src([
    `${dist_server}/*`, `!${dist_server}/assets`
  ], { read: false }).pipe(clean({ force: true }));
});

gulp.task('build-babel', () => {
  // Babel transform, ignore config and swagger api-docs
  return gulp.src(['src/**/*.js', '!src/config/*.js', '!src/core/swagger/api-docs/*']).pipe(babel()).pipe(gulp.dest(dist_server));
});

gulp.task('build-replace', () => {
  // Copy file config dev or production
  const conf = process.argv[3] ? 'index' : 'production';
  // Copy config production
  gulp.src([`src/config/${conf}.js`]).pipe(babel()).pipe(rename('index.js')).pipe(gulp.dest(`${dist_server}/config`));
  // Copy views
  gulp.src(['src/views/**/*.{html,css}']).pipe(minify({ minify: true, collapseWhitespace: true, conservativeCollapse: true, minifyJS: true, minifyCSS: true })).pipe(gulp.dest(`${dist_server}/views`));
  // Copy assets
  gulp.src(['src/assets/**/*']).pipe(gulp.dest(`${dist_server}/assets`));
  // Copy *.yaml
  gulp.src(['src/**/*.yaml']).pipe(gulp.dest(dist_server));
  // Copy swagger/api-docs
  gulp.src([`src/core/swagger/api-docs/*`]).pipe(gulp.dest(dist_swagger));
  // package.json
  gulp.src("package.json").pipe(jeditor((json) => {
    delete json.devDependencies;
    json.scripts = {
      "start": `npm run redis && node server/app.js`,
      "simple": `npm run redis && npm stop && pm2 startOrRestart ${pm2_simple}`,
      "cluster": `npm run redis && npm stop && pm2 startOrRestart ${pm2_cluster}`,
      "redis": `redis-cli config set notify-keyspace-events KEA`,
      "stop": `pm2 delete ${pm2_simple} ${pm2_cluster}`
    };
    return json;
  })).pipe(gulp.dest(dist));
  // Copy pm2 files
  gulp.src([pm2_simple, pm2_cluster]).pipe(gulp.dest(dist));
  // If not exits client folder, then copy current client
  if (!fs.existsSync(`${dist}/client`)) {
    gulp.src(['client/*','!**/*.js']).pipe(minify({ minify: true, collapseWhitespace: true, conservativeCollapse: true, minifyCSS: true })).pipe(gulp.dest(dist_client));
    gulp.src(['client/**/*.js']).pipe(babel()).pipe(gulp.dest(dist_client));
  }
  // Success
  setTimeout(() => console.log(chalk.greenBright('\n---------\nBuild success!\n---------\n')), 500);
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs-extra');
var mode = require('stat-mode');
var Ware = require('ware');

/**
 * Initialize Imagemin
 *
 * @api public
 */

function Imagemin() {
    this.ware = new Ware();
}

/**
 * Add a plugin to the middleware stack
 *
 * @param {Function} plugin
 * @api public
 */

Imagemin.prototype.use = function (plugin) {
    this.ware.use(plugin);
    return this;
};

/**
 * Get or set the source file
 *
 * @param {String|Buffer} file
 * @api public
 */

Imagemin.prototype.src = function (file) {
    if (!arguments.length) {
        return this._src;
    }

    this._src = file;
    return this;
};

/**
 * Get or set the destination file
 *
 * @param {String} file
 * @api public
 */

Imagemin.prototype.dest = function (file) {
    if (!arguments.length) {
        return this._dest;
    }

    this._dest = file;
    return this;
};

/**
 * Optimize file
 *
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.optimize = function (cb) {
    cb = cb || function () {};
    var self = this;

    this.read(function (err, file) {
        self.run(file, function (err, file) {
            if (err) {
                return cb(err);
            }

            self.write(file, function (err) {
                cb(err, file);
            });
        });
    });
};

/**
 * Run a file through the middleware
 *
 * @param {Array} file
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.run = function (file, cb) {
    this.ware.run(file, this, cb);
};

/**
 * Read the source file
 *
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.read = function (cb) {
    var file = {};
    var src = this.src();

    if (Buffer.isBuffer(src)) {
        file.contents = src;
        file.origSize = src.length;

        return cb(null, file);
    }

    fs.stat(src, function (err, stats) {
        if (err) {
            return cb(err);
        }

        fs.readFile(src, function (err, buf) {
            if (err) {
                return cb(err);
            }

            file.contents = buf;
            file.mode = mode(stats).toOctal();
            file.origSize = buf.length;

            cb(null, file);
        });
    });
};

/**
 * Write file to destination
 *
 * @param {Object} file
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.write = function (file, cb) {
    var dest = this.dest();

    file.destSize = file.contents.length;

    if (!dest) {
        return cb();
    }

    fs.outputFile(dest, file.contents, function (err) {
        cb(err);
    });
};

/**
 * Module exports
 */

module.exports = Imagemin;
module.exports.gifsicle = require('./plugins/gifsicle');
module.exports.jpegtran = require('./plugins/jpegtran');
module.exports.optipng = require('./plugins/optipng');
module.exports.pngquant = require('./plugins/pngquant');
<commit_msg>Read file before stating<commit_after>'use strict';

var fs = require('fs-extra');
var mode = require('stat-mode');
var Ware = require('ware');

/**
 * Initialize Imagemin
 *
 * @api public
 */

function Imagemin() {
    this.ware = new Ware();
}

/**
 * Add a plugin to the middleware stack
 *
 * @param {Function} plugin
 * @api public
 */

Imagemin.prototype.use = function (plugin) {
    this.ware.use(plugin);
    return this;
};

/**
 * Get or set the source file
 *
 * @param {String|Buffer} file
 * @api public
 */

Imagemin.prototype.src = function (file) {
    if (!arguments.length) {
        return this._src;
    }

    this._src = file;
    return this;
};

/**
 * Get or set the destination file
 *
 * @param {String} file
 * @api public
 */

Imagemin.prototype.dest = function (file) {
    if (!arguments.length) {
        return this._dest;
    }

    this._dest = file;
    return this;
};

/**
 * Optimize file
 *
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.optimize = function (cb) {
    cb = cb || function () {};
    var self = this;

    this.read(function (err, file) {
        self.run(file, function (err, file) {
            if (err) {
                return cb(err);
            }

            self.write(file, function (err) {
                cb(err, file);
            });
        });
    });
};

/**
 * Run a file through the middleware
 *
 * @param {Array} file
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.run = function (file, cb) {
    this.ware.run(file, this, cb);
};

/**
 * Read the source file
 *
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.read = function (cb) {
    var file = {};
    var src = this.src();

    if (Buffer.isBuffer(src)) {
        file.contents = src;
        file.origSize = src.length;

        return cb(null, file);
    }

    fs.readFile(src, function (err, buf) {
        if (err) {
            return cb(err);
        }

        fs.stat(src, function (err, stats) {
            if (err) {
                return cb(err);
            }

            file.contents = buf;
            file.mode = mode(stats).toOctal();
            file.origSize = buf.length;

            cb(null, file);
        });
    });

};

/**
 * Write file to destination
 *
 * @param {Object} file
 * @param {Function} cb
 * @api public
 */

Imagemin.prototype.write = function (file, cb) {
    var dest = this.dest();

    file.destSize = file.contents.length;

    if (!dest) {
        return cb();
    }

    fs.outputFile(dest, file.contents, function (err) {
        cb(err);
    });
};

/**
 * Module exports
 */

module.exports = Imagemin;
module.exports.gifsicle = require('./plugins/gifsicle');
module.exports.jpegtran = require('./plugins/jpegtran');
module.exports.optipng = require('./plugins/optipng');
module.exports.pngquant = require('./plugins/pngquant');
<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// Support for Node 0.10
// See https://github.com/webpack/css-loader/issues/144
require('es6-promise').polyfill();

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

console.log('Generating bundles...');

function JupyterLabPlugin(options) {}

JupyterLabPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    var sources = [];

    // Explore each chunk (build output):
    compilation.chunks.forEach(function(chunk) {
      // Explore each module within the chunk (built inputs):
      chunk.modules.forEach(function(module) {
        var deps = [];
        if (module.getAllModuleDependencies) {
          deps = module.getAllModuleDependencies();
        }
        if (!module.request) {
          console.log('skipped module', module.request);
          return;
        }
        // TODO: handle context dependencies
        var source = module.source().source();
        for (var dep of deps) {
          var id = dep.id;
          var request = dep.request;
          if (!request || request.indexOf('!') !== -1) {
            console.log('skipped', request);
            continue;
          }
          request = 'require("jupyterlab!' + findImport(request, dep.issuer) + '")';
          source = source.replace('__webpack_require__(' + id + ')', request);
        }
        var header = 'define("' + findName(module.request);
        header += '", function (require, exports, module) {\n'
        source = header + source + '\n}),\n';
        sources.push(source);
      });
    });

    // Insert this list into the Webpack build as a new file asset:
    compilation.assets['custom.bundle.js'] = {
      source: function() {
        return sources.join('\n\n');
      },
      size: function() {
        return sources.join('\n\n').length;
      }
    };

    callback();
  });
};

// From a request - find its package root.
function findRoot(request) {
  while (true) {
    request = path.dirname(request);
    try {
      require.resolve(path.join(request, 'package.json'));
      return request;
    } catch (err) {
      // no-op
    }
  }
}

// From a request - find a version-mangled define name.
function findName(request) {
  var rootPath = findRoot(request);
  var package = require(path.join(rootPath, 'package.json'));
  var modPath = request.slice(rootPath.length + 1);
  var name = package.name;
  if (modPath) {
    return name + '@' + package.version + '/' + modPath;
  }
  return name + '@' + package.version;
}

// From a request - find its semver-mangled import path.
function findImport(request, issuer) {
  // Walk up to look for an explicit version, then look in the issuer
  var rootPath = findRoot(request);
  var rootPackage = require(path.join(rootPath, 'package.json'));
  var issuerPath = findRoot(issuer);
  var issuerPackage = require(path.join(issuerPath, 'package.json'));
  var modPath = request.slice(rootPath.length + 1);
  var name = rootPackage.name;
  try {
    var semver = issuerPackage.dependencies[name]
    if (modPath) {
      return name + semver + '/' + modPath;
    }
    return name + semver;
  } catch (err) {
    return name;
  }
}

module.exports = {
  entry: {
    jupyterlab: './index.js'
  },
  output: {
    path: __dirname + '/build',
    filename: '[name].bundle.js',
    publicPath: './lab/'
  },
  node: {
    fs: 'empty'
  },
  debug: true,
  bail: true,
  devtool: 'source-map',
  module: {
    loaders: [
      { test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader", {
          publicPath: './'
        })
      },
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.html$/, loader: 'file-loader' },
      // jquery-ui loads some images
      { test: /\.(jpg|png|gif)$/, loader: 'file-loader' },
      // required to load font-awesome
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].css'),
    new JupyterLabPlugin()
  ]
}
<commit_msg>cleanup<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// Support for Node 0.10
// See https://github.com/webpack/css-loader/issues/144
require('es6-promise').polyfill();

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

console.log('Generating bundles...');

function JupyterLabPlugin(options) {}

JupyterLabPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    var sources = [];

    // Explore each chunk (build output):
    compilation.chunks.forEach(function(chunk) {
      // Explore each module within the chunk (built inputs):
      chunk.modules.forEach(function(module) {
        var deps = [];
        if (module.getAllModuleDependencies) {
          deps = module.getAllModuleDependencies();
        }
        if (!module.request) {
          console.log('skipped module', module.request);
          return;
        }
        // TODO: handle context dependencies
        var source = module.source().source();
        for (var dep of deps) {
          var id = dep.id;
          var request = dep.request;
          if (!request || request.indexOf('!') !== -1) {
            console.log('skipped dep', request);
            continue;
          }
          request = 'require("jupyterlab!' + findImport(request, dep.issuer) + '")';
          source = source.replace('__webpack_require__(' + id + ')', request);
        }
        var header = 'define("' + findName(module.request);
        header += '", function (require, exports, module) {\n'
        source = header + source + '\n}),\n';
        sources.push(source);
      });
    });

    // Insert this list into the Webpack build as a new file asset:
    compilation.assets['custom.bundle.js'] = {
      source: function() {
        return sources.join('\n\n');
      },
      size: function() {
        return sources.join('\n\n').length;
      }
    };

    callback();
  });
};

// From a request - find its package root.
function findRoot(request) {
  while (true) {
    request = path.dirname(request);
    try {
      require.resolve(path.join(request, 'package.json'));
      return request;
    } catch (err) {
      // no-op
    }
  }
}

// From a request - find a version-mangled define name.
function findName(request) {
  var rootPath = findRoot(request);
  var package = require(path.join(rootPath, 'package.json'));
  var modPath = request.slice(rootPath.length + 1);
  var name = package.name + ':' + package.version;
  if (modPath) {
    name += '/' + modPath;
  }
  return name;
}

// From a request - find its semver-mangled import path.
function findImport(request, issuer) {
  var rootPath = findRoot(request);
  var rootPackage = require(path.join(rootPath, 'package.json'));
  var issuerPath = findRoot(issuer);
  var issuerPackage = require(path.join(issuerPath, 'package.json'));
  var modPath = request.slice(rootPath.length + 1);
  var name = rootPackage.name;
  var semver = issuerPackage.dependencies[name] || rootPackage.version;
  if (semver.indexOf('file:') === 0) {
    var sourcePath = path.resolve(issuerPath, semver.slice('file:'.length));
    var sourcePackage = require(path.join(sourcePath, 'package.json'));
    semver = sourcePackage.version;
  }
  name += ':' + semver;
  if (modPath) {
    name += '/' + modPath;
  }
  return name;
}

module.exports = {
  entry: {
    jupyterlab: './index.js'
  },
  output: {
    path: __dirname + '/build',
    filename: '[name].bundle.js',
    publicPath: './lab/'
  },
  node: {
    fs: 'empty'
  },
  debug: true,
  bail: true,
  devtool: 'source-map',
  module: {
    loaders: [
      { test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader", {
          publicPath: './'
        })
      },
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.html$/, loader: 'file-loader' },
      // jquery-ui loads some images
      { test: /\.(jpg|png|gif)$/, loader: 'file-loader' },
      // required to load font-awesome
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].css'),
    new JupyterLabPlugin()
  ]
}
<|endoftext|>


<commit_before>'use strict';

var nconf = require('nconf');
//nconf.argv().env();

var chai = require('chai');
var expect = require('chai').expect;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var vendSdk = require('./../vend')({
    debugRequests: false
});
var _ = require('underscore');

var getConnectionInfo = function() {
    return {
        domainPrefix: nconf.get('domain_prefix'),
        accessToken: nconf.get('access_token'),
        refreshToken: nconf.get('refresh_token'), // oauth.json
        vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
        vendClientId: nconf.get('vend:client_id'), // config/<env>.json
        vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
    };
};

describe('vend-nodejs-sdk', function() {/*jshint expr: true*/

    describe('requires proper configuration to run tests', function() {
        it('NODE_ENV must be set', function() {
            expect(process.env.NODE_ENV).to.exist;
            expect(process.env.NODE_ENV).to.be.a('string');
            expect(process.env.NODE_ENV).to.not.be.empty;
        });
        it('a file with client data must be available', function() {
            nconf.file('config', { file: 'config/' + process.env.NODE_ENV + '.json' });

            expect(nconf.get('vend:token_service')).to.exist;
            expect(nconf.get('vend:token_service')).to.be.a('string');
            expect(nconf.get('vend:token_service')).to.not.be.empty;

            expect(nconf.get('vend:client_id')).to.exist;
            expect(nconf.get('vend:client_id')).to.be.a('string');
            expect(nconf.get('vend:client_id')).to.not.be.empty;

            expect(nconf.get('vend:client_secret')).to.exist;
            expect(nconf.get('vend:client_secret')).to.be.a('string');
            expect(nconf.get('vend:client_secret')).to.not.be.empty;
        });
        it('a file with oauth data must be available', function() {
            nconf.file('oauth', { file: 'config/oauth.json' });

            expect(nconf.get('domain_prefix')).to.exist;
            expect(nconf.get('domain_prefix')).to.be.a('string');
            expect(nconf.get('domain_prefix')).to.not.be.empty;

            expect(nconf.get('refresh_token')).to.exist;
            expect(nconf.get('refresh_token')).to.be.a('string');
            expect(nconf.get('refresh_token')).to.not.be.empty;
        });
    });

    describe('when refreshToken is unavailable', function() {

        it('should fail when accessToken is missing', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix')
            };

            /* short hand for testing */
            //var unresolvedPromise = vendSdk.products.fetch(args, connectionInfo);
            //return expect(unresolvedPromise).to.be.rejectedWith('missing required arguments for sendRequest()');

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(function(error){
                    expect(error).to.be.a('string');
                    expect(error).to.equal('missing required arguments for sendRequest()');
                });
        });

        it('should fail when given an incorrect or outdated accessToken', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: nconf.get('access_token') || 'junk'
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(function(error){
                    expect(error).to.be.a('string');
                    expect(error).to.equal('missing required arguments for retryWhenAuthNFails()');
                });
        });

    });

    describe('when a refreshToken is available', function() {

        this.timeout(30000);

        it('but invalid - API calls should fail', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK',
                refreshToken: 'JUNK',
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return expect( vendSdk.products.fetch(args, connectionInfo) ).to.be.rejectedWith(TypeError);

        });

        it('and valid - can regenerate an accessToken for use in API calls', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK', //nconf.get('access_token'),
                refreshToken: nconf.get('refresh_token'), // oauth.json
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(TypeError, function(error){
                    expect(error).to.equal(
                        undefined,
                        'the refresh token might be invalid' +
                        ' \n\t\t look inside vend-nodejs-sdk.log file to confirm' +
                        ' \n\t\t or turn on console logging by using `NODE_ENV=testing ./node_modules/.bin/mocha`' +
                        ' \n\t\t to run the tests and confirm' +
                        ' \n\t\t'
                    );
                });

        });

        it('can fetch products', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK', //nconf.get('access_token'),
                refreshToken: nconf.get('refresh_token'), // oauth.json
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .then(function(response){
                    expect(response).to.exist;
                    expect(response.products).to.exist;
                    expect(response.products).to.be.instanceof(Array);
                    expect(response.products).to.have.length.of.at.least(1);
                    expect(response.products).to.have.length.of.at.most(5);
                    if(response.pagination) {/*jshint camelcase: false */
                        expect(response.pagination.results).to.exist;
                        expect(response.pagination.results).to.be.above(0);
                        expect(response.pagination.page).to.exist;
                        expect(response.pagination.page).to.be.equal(1);
                        expect(response.pagination.page_size).to.exist;
                        expect(response.pagination.page_size).to.be.equal(args.pageSize.value);
                        expect(response.pagination.pages).to.exist;
                        expect(response.pagination.pages).to.be.above(0);
                    }
                })
                .catch(TypeError, function(error){
                    expect(error).to.equal(
                        undefined,
                        'the refresh token might be invalid' +
                        ' \n\t\t look inside vend-nodejs-sdk.log file to confirm' +
                        ' \n\t\t or turn on console logging by using `NODE_ENV=testing ./node_modules/.bin/mocha`' +
                        ' \n\t\t to run the tests and confirm' +
                        ' \n\t\t'
                    );
                });

        });

        it('can fetch a product by ID', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = getConnectionInfo();

            // get one of any product
            return vendSdk.products.fetch(args, connectionInfo)
              .then(function(response){
                  expect(response).to.exist;
                  expect(response.products).to.exist;
                  expect(response.products).to.be.instanceof(Array);
                  expect(response.products).to.have.length.of.at.least(1);

                  // fetch a product by ID
                  var args = vendSdk.args.products.fetchById();
                  args.apiId.value = _.last(response.products).id;
                  return vendSdk.products.fetchById(args, connectionInfo)
                    .then(function(response){
                        expect(response).to.exist;
                        expect(response.products).to.exist;
                        expect(response.products).to.be.instanceof(Array);
                        expect(response.products.length).to.equal(1);
                        expect(response.products[0].id).to.equal(_.last(response.products).id); // IDs should match
                    });
              });
        });

        it('can create a customer', function() {
            // create a dummy customer
            var customer = {
                'first_name': 'boy',
                'last_name': 'blue',
                'email': 'boy'+Date.now()+'@blue.com'
            };
            var connectionInfo = getConnectionInfo();
            return vendSdk.customers.create(customer, connectionInfo);
        });

        it('can create a product', function() {
            // TODO: implement it
        });

        it('can fetch a product that was just created', function() {
            // TODO: implement it
        });

        it('can upload product image', function() {
            // TODO: implement it
        });

        it('can fetch registers', function() {
            var args = vendSdk.args.registers.fetch();
            return vendSdk.registers.fetch(args, getConnectionInfo())
              .then(function(response){
                  //console.log(response);
                  expect(response).to.exist;
                  expect(response.registers).to.exist;
                  expect(response.registers).to.be.instanceof(Array);
              });
        });

        it('cannot paginate when fetching registers - it is not supported by vend in 0.x', function() {
            var args = vendSdk.args.registers.fetch();
            args.page.value = 1;
            args.pageSize.value = 1;
            return vendSdk.registers.fetch(args, getConnectionInfo())
              .then(function(response){
                  //console.log(response);
                  expect(response).to.exist;
                  expect(response.registers).to.exist;
                  expect(response.registers).to.be.instanceof(Array);
                  expect(response.registers).to.have.length.above(1); // TODO: what if no more than 1 registers exist?
              });
        });

        it('can fetch a register by ID', function() {
            // TODO: implement it
        });

        xit('can fetch ALL registers', function() {
            // TODO: implement it
        });

        it('can fetch tags', function() {
            // TODO: implement it
        });

        it('can create a tag', function() {
            // TODO: implement it
        });

        xit('can fetch outlets', function() {
            // TODO: implement it
        });

        it('can fetch an outlet by ID', function() {
            // TODO: implement it
        });

        xit('can fetch ALL outlets', function() {
            // NOTE: no need for fetchAll since hardly any Vend customers have more than 200 outlets
        });

        it('can fetch product-types', function() {
            // TODO: implement it
        });

        it('can create a product-type', function() {
            // TODO: implement it
        });

        it('can fetch brands', function() {
            // TODO: implement it
        });

        it('can create a brand', function() {
            // TODO: implement it
        });

        it('can create a supplier', function() {
            // TODO: implement it
        });

        it('can create a tax', function() {
            // TODO: implement it
        });

    });

});
<commit_msg>demonstrate that pagination works for products<commit_after>'use strict';

var nconf = require('nconf');
//nconf.argv().env();

var chai = require('chai');
var expect = require('chai').expect;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

var vendSdk = require('./../vend')({
    debugRequests: false
});
var _ = require('underscore');

var getConnectionInfo = function() {
    return {
        domainPrefix: nconf.get('domain_prefix'),
        accessToken: nconf.get('access_token'),
        refreshToken: nconf.get('refresh_token'), // oauth.json
        vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
        vendClientId: nconf.get('vend:client_id'), // config/<env>.json
        vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
    };
};

describe('vend-nodejs-sdk', function() {/*jshint expr: true*/

    describe('requires proper configuration to run tests', function() {
        it('NODE_ENV must be set', function() {
            expect(process.env.NODE_ENV).to.exist;
            expect(process.env.NODE_ENV).to.be.a('string');
            expect(process.env.NODE_ENV).to.not.be.empty;
        });
        it('a file with client data must be available', function() {
            nconf.file('config', { file: 'config/' + process.env.NODE_ENV + '.json' });

            expect(nconf.get('vend:token_service')).to.exist;
            expect(nconf.get('vend:token_service')).to.be.a('string');
            expect(nconf.get('vend:token_service')).to.not.be.empty;

            expect(nconf.get('vend:client_id')).to.exist;
            expect(nconf.get('vend:client_id')).to.be.a('string');
            expect(nconf.get('vend:client_id')).to.not.be.empty;

            expect(nconf.get('vend:client_secret')).to.exist;
            expect(nconf.get('vend:client_secret')).to.be.a('string');
            expect(nconf.get('vend:client_secret')).to.not.be.empty;
        });
        it('a file with oauth data must be available', function() {
            nconf.file('oauth', { file: 'config/oauth.json' });

            expect(nconf.get('domain_prefix')).to.exist;
            expect(nconf.get('domain_prefix')).to.be.a('string');
            expect(nconf.get('domain_prefix')).to.not.be.empty;

            expect(nconf.get('refresh_token')).to.exist;
            expect(nconf.get('refresh_token')).to.be.a('string');
            expect(nconf.get('refresh_token')).to.not.be.empty;
        });
    });

    describe('when refreshToken is unavailable', function() {

        it('should fail when accessToken is missing', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix')
            };

            /* short hand for testing */
            //var unresolvedPromise = vendSdk.products.fetch(args, connectionInfo);
            //return expect(unresolvedPromise).to.be.rejectedWith('missing required arguments for sendRequest()');

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(function(error){
                    expect(error).to.be.a('string');
                    expect(error).to.equal('missing required arguments for sendRequest()');
                });
        });

        it('should fail when given an incorrect or outdated accessToken', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: nconf.get('access_token') || 'junk'
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(function(error){
                    expect(error).to.be.a('string');
                    expect(error).to.equal('missing required arguments for retryWhenAuthNFails()');
                });
        });

    });

    describe('when a refreshToken is available', function() {

        this.timeout(30000);

        it('but invalid - API calls should fail', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK',
                refreshToken: 'JUNK',
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return expect( vendSdk.products.fetch(args, connectionInfo) ).to.be.rejectedWith(TypeError);

        });

        it('and valid - can regenerate an accessToken for use in API calls', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK', //nconf.get('access_token'),
                refreshToken: nconf.get('refresh_token'), // oauth.json
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .catch(TypeError, function(error){
                    expect(error).to.equal(
                        undefined,
                        'the refresh token might be invalid' +
                        ' \n\t\t look inside vend-nodejs-sdk.log file to confirm' +
                        ' \n\t\t or turn on console logging by using `NODE_ENV=testing ./node_modules/.bin/mocha`' +
                        ' \n\t\t to run the tests and confirm' +
                        ' \n\t\t'
                    );
                });

        });

        it('can fetch products', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 5;
            args.active.value = true;

            var connectionInfo = {
                domainPrefix: nconf.get('domain_prefix'),
                accessToken: 'JUNK', //nconf.get('access_token'),
                refreshToken: nconf.get('refresh_token'), // oauth.json
                vendTokenService: nconf.get('vend:token_service'), // config/<env>.json
                vendClientId: nconf.get('vend:client_id'), // config/<env>.json
                vendClientSecret: nconf.get('vend:client_secret') // config/<env>.json
            };

            return vendSdk.products.fetch(args, connectionInfo)
                .then(function(response){
                    expect(response).to.exist;
                    expect(response.products).to.exist;
                    expect(response.products).to.be.instanceof(Array);
                    expect(response.products).to.have.length.of.at.least(1);
                    expect(response.products).to.have.length.of.at.most(5);
                    if(response.pagination) {/*jshint camelcase: false */
                        expect(response.pagination.results).to.exist;
                        expect(response.pagination.results).to.be.above(0);
                        expect(response.pagination.page).to.exist;
                        expect(response.pagination.page).to.be.equal(1);
                        expect(response.pagination.page_size).to.exist;
                        expect(response.pagination.page_size).to.be.equal(args.pageSize.value);
                        expect(response.pagination.pages).to.exist;
                        expect(response.pagination.pages).to.be.above(0);
                    }
                })
                .catch(TypeError, function(error){
                    expect(error).to.equal(
                        undefined,
                        'the refresh token might be invalid' +
                        ' \n\t\t look inside vend-nodejs-sdk.log file to confirm' +
                        ' \n\t\t or turn on console logging by using `NODE_ENV=testing ./node_modules/.bin/mocha`' +
                        ' \n\t\t to run the tests and confirm' +
                        ' \n\t\t'
                    );
                });

        });

        it('can paginate when fetching products', function() {
            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;
            return vendSdk.products.fetch(args, getConnectionInfo())
              .then(function(response){
                  expect(response).to.exist;
                  expect(response.products).to.exist;
                  expect(response.products).to.be.instanceof(Array);
                  expect(response.products.length).to.equal(1);
              });
        });

        it('can fetch a product by ID', function() {

            var args = vendSdk.args.products.fetch();
            args.orderBy.value = 'id';
            args.page.value = 1;
            args.pageSize.value = 1;
            args.active.value = true;

            var connectionInfo = getConnectionInfo();

            // get one of any product
            return vendSdk.products.fetch(args, connectionInfo)
              .then(function(response){
                  expect(response).to.exist;
                  expect(response.products).to.exist;
                  expect(response.products).to.be.instanceof(Array);
                  expect(response.products).to.have.length.of.at.least(1);

                  // fetch a product by ID
                  var args = vendSdk.args.products.fetchById();
                  args.apiId.value = _.last(response.products).id;
                  return vendSdk.products.fetchById(args, connectionInfo)
                    .then(function(response){
                        expect(response).to.exist;
                        expect(response.products).to.exist;
                        expect(response.products).to.be.instanceof(Array);
                        expect(response.products.length).to.equal(1);
                        expect(response.products[0].id).to.equal(_.last(response.products).id); // IDs should match
                    });
              });
        });

        it('can create a customer', function() {
            // create a dummy customer
            var customer = {
                'first_name': 'boy',
                'last_name': 'blue',
                'email': 'boy'+Date.now()+'@blue.com'
            };
            var connectionInfo = getConnectionInfo();
            return vendSdk.customers.create(customer, connectionInfo);
        });

        it('can create a product', function() {
            // TODO: implement it
        });

        it('can fetch a product that was just created', function() {
            // TODO: implement it
        });

        it('can upload product image', function() {
            // TODO: implement it
        });

        it('can fetch registers', function() {
            var args = vendSdk.args.registers.fetch();
            return vendSdk.registers.fetch(args, getConnectionInfo())
              .then(function(response){
                  //console.log(response);
                  expect(response).to.exist;
                  expect(response.registers).to.exist;
                  expect(response.registers).to.be.instanceof(Array);
              });
        });

        it('cannot paginate when fetching registers - it is not supported by vend in 0.x', function() {
            var args = vendSdk.args.registers.fetch();
            args.page.value = 1;
            args.pageSize.value = 1;
            return vendSdk.registers.fetch(args, getConnectionInfo())
              .then(function(response){
                  //console.log(response);
                  expect(response).to.exist;
                  expect(response.registers).to.exist;
                  expect(response.registers).to.be.instanceof(Array);
                  expect(response.registers).to.have.length.above(1); // TODO: what if no more than 1 registers exist?
              });
        });

        it('can fetch a register by ID', function() {
            // TODO: implement it
        });

        xit('can fetch ALL registers', function() {
            // TODO: implement it
        });

        it('can fetch tags', function() {
            // TODO: implement it
        });

        it('can create a tag', function() {
            // TODO: implement it
        });

        xit('can fetch outlets', function() {
            // TODO: implement it
        });

        it('can fetch an outlet by ID', function() {
            // TODO: implement it
        });

        xit('can fetch ALL outlets', function() {
            // NOTE: no need for fetchAll since hardly any Vend customers have more than 200 outlets
        });

        it('can fetch product-types', function() {
            // TODO: implement it
        });

        it('can create a product-type', function() {
            // TODO: implement it
        });

        it('can fetch brands', function() {
            // TODO: implement it
        });

        it('can create a brand', function() {
            // TODO: implement it
        });

        it('can create a supplier', function() {
            // TODO: implement it
        });

        it('can create a tax', function() {
            // TODO: implement it
        });

    });

});
<|endoftext|>


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

var koa =require('koa');
var path = require('path');
var tracer = require('tracer');
var mount = require('koa-mount');
var morgan = require('koa-morgan');
var koaStatic = require('koa-static');

// Config
var argv = require('optimist')
  .usage([
    'USAGE: $0 [-p <port>] [-d <directory>]']
  )
  .option('port', {
    alias: 'p',
    'default': 5000,
    description: 'Server Port'
  })
  .option('directory', {
    alias: 'd',
    description: 'Root Files Directory'
  })
  .option('version', {
    alias: 'v',
    description: 'Server　Version'
  })
  .option('help', {
    alias: 'h',
    description: "Display This Help Message"
  })
  .argv;

if (argv.help) {
  require('optimist').showHelp(console.log);
  process.exit(0);
}

if (argv.version) {
  console.log('FileManager', require('./package.json').version);
  process.exit(0);
}

global.C = {
  data: {
    root: argv.directory || path.dirname('.')
  },
  logger: require('tracer').console({level: 'info'}),
  morganFormat: ':date[iso] :remote-addr :method :url :status :res[content-length] :response-time ms'
};

// Start Server
var Tools = require('./tools');

var startServer = function (app, port) {
  app.listen(port);
  C.logger.info('listening on *.' + port);
};

var app = koa();
app.proxy = true;
app.use(Tools.handelError);
app.use(Tools.realIp);
app.use(morgan.middleware(C.morganFormat));

var IndexRouter = require('./routes');
app.use(mount('/', IndexRouter));
app.use(koaStatic('./public/'));

startServer(app, +argv.port);

<commit_msg>fix:js file not found in view template<commit_after>#!/usr/bin/env node

var koa =require('koa');
var path = require('path');
var tracer = require('tracer');
var mount = require('koa-mount');
var morgan = require('koa-morgan');
var koaStatic = require('koa-static');

// Config
var argv = require('optimist')
  .usage([
    'USAGE: $0 [-p <port>] [-d <directory>]']
  )
  .option('port', {
    alias: 'p',
    'default': 5000,
    description: 'Server Port'
  })
  .option('directory', {
    alias: 'd',
    description: 'Root Files Directory'
  })
  .option('version', {
    alias: 'v',
    description: 'Server　Version'
  })
  .option('help', {
    alias: 'h',
    description: "Display This Help Message"
  })
  .argv;

if (argv.help) {
  require('optimist').showHelp(console.log);
  process.exit(0);
}

if (argv.version) {
  console.log('FileManager', require('./package.json').version);
  process.exit(0);
}

global.C = {
  data: {
    root: argv.directory || path.dirname('.')
  },
  logger: require('tracer').console({level: 'info'}),
  morganFormat: ':date[iso] :remote-addr :method :url :status :res[content-length] :response-time ms'
};

// Start Server
var Tools = require('./tools');

var startServer = function (app, port) {
  app.listen(port);
  C.logger.info('listening on *.' + port);
};

var app = koa();
app.proxy = true;
app.use(Tools.handelError);
app.use(Tools.realIp);
app.use(morgan.middleware(C.morganFormat));

var IndexRouter = require('./routes');
app.use(mount('/', IndexRouter));
app.use(koaStatic(path.join(__dirname,'./public/')));

startServer(app, +argv.port);

<|endoftext|>


<commit_before>import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import path from 'path';
import del from 'del';
import runSequence from 'run-sequence';

const plugins = gulpLoadPlugins();

const paths = {
  js: ['./**/*.js', '!dist/**', '!node_modules/**', '!coverage/**'],
  nonJs: ['./package.json', './.gitignore', './.env'],
  tests: './server/tests/*.js'
};

// Clean up dist and coverage directory
gulp.task('clean', () =>
  del.sync(['dist/**', 'dist/.*', 'coverage/**', '!dist', '!coverage'])
);

// Copy non-js files to dist
gulp.task('copy', () =>
  gulp.src(paths.nonJs)
    .pipe(plugins.newer('dist'))
    .pipe(gulp.dest('dist'))
);

// Compile ES6 to ES5 and copy to dist
gulp.task('babel', () =>
  gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' })
    .pipe(plugins.newer('dist'))
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.babel())
    .pipe(plugins.sourcemaps.write('.', {
      includeContent: false,
      sourceRoot(file) {
        return path.relative(file.path, __dirname);
      }
    }))
    .pipe(gulp.dest('dist'))
);

// Start server with restart on file changes
gulp.task('nodemon', ['copy', 'babel'], () =>
  plugins.nodemon({
    script: path.join('dist', 'index.js'),
    ext: 'js',
    ignore: ['node_modules/**/*.js', 'dist/**/*.js'],
    tasks: ['copy', 'babel']
  })
);

// gulp serve for development
gulp.task('serve', ['clean'], () => runSequence('nodemon'));

// default task: clean dist, compile js files and copy non-js files.
gulp.task('default', ['clean'], () => {
  runSequence(
    ['copy', 'babel']
  );
});
<commit_msg>modify build nonJS files<commit_after>import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import path from 'path';
import del from 'del';
import runSequence from 'run-sequence';

const plugins = gulpLoadPlugins();

const paths = {
  js: ['./**/*.js', '!dist/**', '!node_modules/**', '!coverage/**'],
  nonJs: ['./package.json', './.gitignore', './.env', './publicKey.pub', './privateKey.pem'],
  tests: './server/tests/*.js'
};

// Clean up dist and coverage directory
gulp.task('clean', () =>
  del.sync(['dist/**', 'dist/.*', 'coverage/**', '!dist', '!coverage'])
);

// Copy non-js files to dist
gulp.task('copy', () =>
  gulp.src(paths.nonJs)
    .pipe(plugins.newer('dist'))
    .pipe(gulp.dest('dist'))
);

gulp.task('copyDocs', () =>
  gulp.src(['./server/docs/api_docs.yml'])
    .pipe(plugins.newer('dist'))
    .pipe(gulp.dest('dist/server/docs'))
);

// Compile ES6 to ES5 and copy to dist
gulp.task('babel', () =>
  gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' })
    .pipe(plugins.newer('dist'))
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.babel())
    .pipe(plugins.sourcemaps.write('.', {
      includeContent: false,
      sourceRoot(file) {
        return path.relative(file.path, __dirname);
      }
    }))
    .pipe(gulp.dest('dist'))
);

// Start server with restart on file changes
gulp.task('nodemon', ['copy', 'babel'], () =>
  plugins.nodemon({
    script: path.join('dist', 'index.js'),
    ext: 'js',
    ignore: ['node_modules/**/*.js', 'dist/**/*.js'],
    tasks: ['copy', 'babel', 'copyDocs']
  })
);

// gulp serve for development
gulp.task('serve', ['clean'], () => runSequence('nodemon'));

// default task: clean dist, compile js files and copy non-js files.
gulp.task('default', ['clean'], () => {
  runSequence(
    ['copy', 'babel', 'copyDocs']
  );
});
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var crypto = require('crypto');
var package_data = require('./package.json');
var Build = require('@jupyterlab/buildutils').Build;

// Ensure a clear build directory.
var buildDir = './build';
if (fs.existsSync(buildDir)) {
  fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);

fs.copySync('./package.json', './build/package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

fs.writeFileSync(path.resolve(buildDir, 'index.out.js'), result);

// Set up variables for watch mode.
var localLinked = {};
var ignoreCache = new Map();
Object.keys(jlab.linkedPackages).forEach(function (name) {
  var localPath = require.resolve(path.join(name, 'package.json'));
  localLinked[name] = path.dirname(localPath);
});

/**
 * Sync a local path to a linked package path if they are files and differ.
 */
function maybeSync(localPath, name, rest) {
  var stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  var source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
  if (source === localPath) {
    return;
  }
  fs.watchFile(source, { 'interval': 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      console.log('updating', path.join(name, rest));
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

// Create the hash
var hash = crypto.createHash('md5');
hash.update(fs.readFileSync('./package.json'));
var digest = hash.digest('hex');
fs.writeFileSync(path.resolve(buildDir, 'hash.md5'), digest);

module.exports = {
  entry:  path.resolve(buildDir, 'index.out.js'),
  output: {
    path: path.resolve(buildDir),
    filename: '[name].bundle.js'
  },
  module: {
    rules: [
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.json$/, use: 'json-loader' },
      { test: /\.html$/, use: 'file-loader' },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        exclude: path.join(process.cwd(), 'node_modules')
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  watchOptions: {
    ignored: function(localPath) {
      if (ignoreCache.has(localPath)) {
        return ignoreCache.get(localPath);
      }
      // Limit the watched files to those in our local linked package dirs.
      var ignore = true;
      Object.keys(localLinked).some(function (name) {
        // Bail if already found.
        var rootPath = localLinked[name];
        var contained = localPath.indexOf(rootPath + path.sep) !== -1;
        if (localPath !== rootPath && !contained) {
          return false;
        }
        var rest = localPath.slice(rootPath.length);
        if (rest.indexOf('node_modules') === -1) {
          ignore = false;
          maybeSync(localPath, name, rest);
        }
        return true;
      });
      ignoreCache.set(localPath, ignore);
      return ignore;
    }
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'cheap-source-map'
}
<commit_msg>Do not remove build dir<commit_after>var webpack = require('webpack');
var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var crypto = require('crypto');
var package_data = require('./package.json');
var Build = require('@jupyterlab/buildutils').Build;

// Ensure a clear build directory.
var buildDir = './build';
fs.ensureDirSync(buildDir);

fs.copySync('./package.json', './build/package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

fs.writeFileSync(path.resolve(buildDir, 'index.out.js'), result);

// Set up variables for watch mode.
var localLinked = {};
var ignoreCache = new Map();
Object.keys(jlab.linkedPackages).forEach(function (name) {
  var localPath = require.resolve(path.join(name, 'package.json'));
  localLinked[name] = path.dirname(localPath);
});

/**
 * Sync a local path to a linked package path if they are files and differ.
 */
function maybeSync(localPath, name, rest) {
  var stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  var source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
  if (source === localPath) {
    return;
  }
  fs.watchFile(source, { 'interval': 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      console.log('updating', path.join(name, rest));
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

// Create the hash
var hash = crypto.createHash('md5');
hash.update(fs.readFileSync('./package.json'));
var digest = hash.digest('hex');
fs.writeFileSync(path.resolve(buildDir, 'hash.md5'), digest);

module.exports = {
  entry:  path.resolve(buildDir, 'index.out.js'),
  output: {
    path: path.resolve(buildDir),
    filename: '[name].bundle.js'
  },
  module: {
    rules: [
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.json$/, use: 'json-loader' },
      { test: /\.html$/, use: 'file-loader' },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        exclude: path.join(process.cwd(), 'node_modules')
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  watchOptions: {
    ignored: function(localPath) {
      if (ignoreCache.has(localPath)) {
        return ignoreCache.get(localPath);
      }
      // Limit the watched files to those in our local linked package dirs.
      var ignore = true;
      Object.keys(localLinked).some(function (name) {
        // Bail if already found.
        var rootPath = localLinked[name];
        var contained = localPath.indexOf(rootPath + path.sep) !== -1;
        if (localPath !== rootPath && !contained) {
          return false;
        }
        var rest = localPath.slice(rootPath.length);
        if (rest.indexOf('node_modules') === -1) {
          ignore = false;
          maybeSync(localPath, name, rest);
        }
        return true;
      });
      ignoreCache.set(localPath, ignore);
      return ignore;
    }
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'cheap-source-map'
}
<|endoftext|>


<commit_before>var expect = require('expect.js');
var racer = require('racer');
var plugin = require('../index');

describe('bundle', function() {

  it('adds a bundle method to stores', function() {
    var store = racer.createStore();
    expect(store.bundle).equal(undefined);
    racer.use(plugin);
    expect(store.bundle).to.be.a('function');
  });

});
<commit_msg>fix test<commit_after>var expect = require('expect.js');
var racer = require('racer');
var plugin = require('../index');

describe('bundle', function() {

  it('adds a bundle method to stores', function() {
    var backend = racer.createBackend();
    expect(backend.bundle).equal(undefined);
    racer.use(plugin);
    expect(backend.bundle).to.be.a('function');
  });

});
<|endoftext|>


<commit_before>'use strict';

var gutil = require('gulp-util');
var through2 = require('through2');
var minimatch = require('minimatch');
var async = require('async');
var _ = require('lodash');

var sharpVinyl = require('./sharp');
var prepareConfig = require('./config');

var PLUGIN_NAME = require('../package.json').name;

function gulpResponsive(config, options) {

  var statistics = {
    total: 0,
    matched: 0,
    created: 0,
    unmatched: 0,
    unmatchedBlocked: 0,
    unmatchedPassed: 0
  };

  options = _.defaults({}, options, {
    errorOnUnusedConfig: true,
    errorOnUnusedImage: true,
    errorOnEnlargement: true,
    passThroughUnused: false
  });

  config = prepareConfig(config || [], options);

  return through2.obj(function (file, enc, done) {
      var that = this;

      if (file.isNull()) {
        this.push(file);
        return done();
      }

      if (file.isStream()) {
        return done(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      }

      statistics.total++;
      var matched = config.filter(function(conf) {
        return minimatch(file.relative, conf.name);
      });

      if (matched.length === 0) {
        statistics.unmatched++;
        var message = 'File `' + file.relative + '`: Image does not match any config';
        if (options.errorOnUnusedImage) {
          return done(new gutil.PluginError(PLUGIN_NAME, message));
        } else if (options.passThroughUnused) {
          this.push(file);
          statistics.unmatchedPassed++;
          gutil.log(PLUGIN_NAME + ': (pass through without changes)', gutil.colors.magenta(message));
          return done();
        }
        statistics.unmatchedBlocked++;
        gutil.log(PLUGIN_NAME + ': (skip for processing)', gutil.colors.magenta(message));
        return done();
      }

      statistics.matched++;
      async.each(matched, function(conf, cb) {
        // config item matched (can be matched multiple times)
        conf.mathed = true;

        sharpVinyl(file, conf, options, function(err, newFile) {
          if (err) {
            return cb(err);
          }
          if (newFile) {
            that.push(newFile);
            statistics.created++;
          }
          cb();
        });
      }, done);
    }, function(cb) {
      var notMatched = config.filter(function(conf) {
        return !conf.mathed;
      });

      if (notMatched.length > 0) {
        var message = 'Available images do not match the following config:';
        notMatched.forEach(function(conf) {
          message += '\n  - `' + conf.name + '`';
        });
        if (options.errorOnUnusedConfig) {
          return cb(new gutil.PluginError(PLUGIN_NAME, message));
        } else {
          gutil.log(PLUGIN_NAME + ':', gutil.colors.magenta(message));
        }
      }
      cb();
    }
  );
}

module.exports = gulpResponsive;
<commit_msg>Add silence option (default: false to not change API)<commit_after>'use strict';

var gutil = require('gulp-util');
var through2 = require('through2');
var minimatch = require('minimatch');
var async = require('async');
var _ = require('lodash');

var sharpVinyl = require('./sharp');
var prepareConfig = require('./config');

var PLUGIN_NAME = require('../package.json').name;

function gulpResponsive(config, options) {

  var statistics = {
    total: 0,
    matched: 0,
    created: 0,
    unmatched: 0,
    unmatchedBlocked: 0,
    unmatchedPassed: 0
  };

  options = _.defaults({}, options, {
    errorOnUnusedConfig: true,
    errorOnUnusedImage: true,
    errorOnEnlargement: true,
    passThroughUnused: false,
    silent: false
  });

  config = prepareConfig(config || [], options);

  return through2.obj(function (file, enc, done) {
      var that = this;

      if (file.isNull()) {
        this.push(file);
        return done();
      }

      if (file.isStream()) {
        return done(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      }

      statistics.total++;
      var matched = config.filter(function(conf) {
        return minimatch(file.relative, conf.name);
      });

      if (matched.length === 0) {
        statistics.unmatched++;
        var message = 'File `' + file.relative + '`: Image does not match any config';
        if (options.errorOnUnusedImage) {
          return done(new gutil.PluginError(PLUGIN_NAME, message));
        } else if (options.passThroughUnused) {
          this.push(file);
          statistics.unmatchedPassed++;
          gutil.log(PLUGIN_NAME + ': (pass through without changes)', gutil.colors.magenta(message));
          return done();
        }
        statistics.unmatchedBlocked++;
        gutil.log(PLUGIN_NAME + ': (skip for processing)', gutil.colors.magenta(message));
        return done();
      }

      statistics.matched++;
      async.each(matched, function(conf, cb) {
        // config item matched (can be matched multiple times)
        conf.mathed = true;

        sharpVinyl(file, conf, options, function(err, newFile) {
          if (err) {
            return cb(err);
          }
          if (newFile) {
            that.push(newFile);
            statistics.created++;
          }
          cb();
        });
      }, done);
    }, function(cb) {
      var notMatched = config.filter(function(conf) {
        return !conf.mathed;
      });

      if (notMatched.length > 0) {
        var message = 'Available images do not match the following config:';
        notMatched.forEach(function(conf) {
          message += '\n  - `' + conf.name + '`';
        });
        if (options.errorOnUnusedConfig) {
          return cb(new gutil.PluginError(PLUGIN_NAME, message));
        } else {
          gutil.log(PLUGIN_NAME + ':', gutil.colors.magenta(message));
        }
      }
      cb();
    }
  );
}

module.exports = gulpResponsive;
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado

/**
 * CH3OH Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var AtomNode = require( 'NITROGLYCERIN/nodes/AtomNode' );
  var Element = require( 'NITROGLYCERIN/Element' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function CH3OHNode( options ) {

    options = _.extend( { atomOptions: {} }, options );

    Node.call( this );

    // atom nodes
    var leftNode = new AtomNode( Element.C, options.atomOptions );
    var smallTopNode = new AtomNode( Element.H, options.atomOptions );
    var smallBottomNode = new AtomNode( Element.H, options.atomOptions );
    var smallLeftNode = new AtomNode( Element.H, options.atomOptions );
    var rightNode = new AtomNode( Element.O, options.atomOptions );
    var smallRightNode = new AtomNode( Element.H, options.atomOptions );

    // rendering order
    var parentNode = new Node();
    this.addChild( parentNode );
    parentNode.addChild( smallBottomNode );
    parentNode.addChild( smallTopNode );
    parentNode.addChild( leftNode );
    parentNode.addChild( smallLeftNode );
    parentNode.addChild( smallRightNode );
    parentNode.addChild( rightNode );

    // layout
    var x = 0;
    var y = 0;
    leftNode.setTranslation( x, y );
    x = leftNode.right + ( 0.25 * rightNode.width );
    y = leftNode.y;
    rightNode.setTranslation( x, y );
    x = leftNode.x;
    y = leftNode.top;
    smallTopNode.setTranslation( x, y );
    x = smallTopNode.x;
    y = leftNode.bottom;
    smallBottomNode.setTranslation( x, y );
    x = leftNode.left;
    y = leftNode.y;
    smallLeftNode.setTranslation( x, y );
    x = rightNode.right;
    y = rightNode.y;
    smallRightNode.setTranslation( x, y );

    // move origin to geometric center
    parentNode.center = Vector2.ZERO;
  }

  return inherit( Node, CH3OHNode );
} );
<commit_msg>#4 rework CH3OH<commit_after>// Copyright 2002-2015, University of Colorado

/**
 * CH3OH Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var AtomNode = require( 'NITROGLYCERIN/nodes/AtomNode' );
  var Element = require( 'NITROGLYCERIN/Element' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function CH3OHNode( options ) {

    options = _.extend( { atomOptions: {} }, options );

    // atoms
    var leftNode = new AtomNode( Element.C, options.atomOptions );
    var smallTopNode = new AtomNode( Element.H, _.extend( {
      x: leftNode.x,
      y: leftNode.top
    }, options.atomOptions ) );
    var smallBottomNode = new AtomNode( Element.H, _.extend( {
      x: smallTopNode.x,
      y: leftNode.bottom
    }, options.atomOptions ) );
    var smallLeftNode = new AtomNode( Element.H, _.extend( {
      x: leftNode.left,
      y: leftNode.y
    }, options.atomOptions ) );
    var rightNode = new AtomNode( Element.O, _.extend( {
      x: leftNode.right + ( 0.25 * leftNode.width ),
      y: leftNode.y
    }, options.atomOptions ) );
    var smallRightNode = new AtomNode( Element.H, _.extend( {
      x: rightNode.right,
      y: rightNode.y
    }, options.atomOptions ) );

    options.children = [ new Node( {
      children: [ smallBottomNode, smallTopNode, leftNode, smallLeftNode, smallRightNode, rightNode ],
      center: Vector2.ZERO // origin at geometric center
    } ) ];
    Node.call( this, options );
  }

  return inherit( Node, CH3OHNode );
} );
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import TextField from 'material-ui/TextField'
import DatePicker from 'material-ui/DatePicker'
import Checkbox from 'material-ui/Checkbox'
import RaisedButton from '../components/MaterializeRaisedButton'
import { Link } from 'react-router-dom'
import '../styles/inputFile.css'

const styles = {
  block: {
    maxWidth: 250
  },
  checkbox: {
    marginBottom: 16
  },
  button: {
    margin: 12
  },
  exampleImageInput: {
    cursor: 'pointer',
    position: 'absolute',
    top: 0,
    bottom: 0,
    right: 0,
    left: 0,
    width: '100%',
    opacity: 0
  }
}

// https://github.com/Dogfalo/materialize/blob/master/js/forms.js#L192
class ServiceRequest extends Component {
  constructor (props) {
    super(props)
    this.state = {
      fileInput: null,
      name: '',
      email: '',
      phone: ''
    }
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  handleInputChange (event) {
    const target = event.target
    const value = target.type === 'checkbox' ? target.checked : target.value
    const name = target.name

    this.setState({
      [name]: value
    })
  }

  handleFilePath = () => {
    let file = document.getElementById('upload').files
    if (file.length === 0) {
      this.setState({
        fileInput: null
      })
    } else {
      let fileNames = ''
      for (let i = 0; i < file.length; i++) {
        fileNames = fileNames + file[i].name + ', '
      }
      this.setState({
        fileInput: fileNames
      })
    }
  }

  render () {
    let fileValue = this.state.fileInput || 'Select a file to upload'
    return (

Please use this form to request services.

            <TextField
              floatingLabelText='Name'
              name='name'
              value={this.state.name}
              onChange={this.handleInputChange}
              fullWidth
            />

            <TextField
              floatingLabelText='Email'
              name='email'
              onChange={this.handleInputChange}
              type='email'
              fullWidth
            />

            <TextField
              floatingLabelText='Phone'
              name='phone'
              onChange={this.handleInputChange}
              fullWidth
            />

            <TextField floatingLabelText='Department' fullWidth />

            <TextField
              floatingLabelText='Project Description'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Goal'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Budget'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Key Messages'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Primary Target Audience'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Secondary Target Audience'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Contact (if other than yourself)'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Comments'
              multiLine
              rows={2}
              fullWidth
            />

            <DatePicker hintText='Desired Completion Date' />

                Upload Files
                <input
                  id='upload'
                  type='file'
                  multiple
                  onChange={this.handleFilePath}
                />

                <input
                  value={fileValue}
                  className='file-path validate'
                  type='text'
                  readOnly
                />

            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />

            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />

            <RaisedButton label='Submit' primary />
            <Checkbox
              label={

                  I have read the{' '}
                  <Link to='/planning-guide' style={{ fontWeight: 500 }}>
                    Planning Guide
                  </Link>

              }
              style={styles.checkbox}
              inputStyle={{ width: '35px' }}
            />

    )
  }
}

export default ServiceRequest
<commit_msg>Change some let to const in ServiceRequest<commit_after>import React, { Component } from 'react'
import TextField from 'material-ui/TextField'
import DatePicker from 'material-ui/DatePicker'
import Checkbox from 'material-ui/Checkbox'
import RaisedButton from '../components/MaterializeRaisedButton'
import { Link } from 'react-router-dom'
import '../styles/inputFile.css'

const styles = {
  block: {
    maxWidth: 250
  },
  checkbox: {
    marginBottom: 16
  },
  button: {
    margin: 12
  },
  exampleImageInput: {
    cursor: 'pointer',
    position: 'absolute',
    top: 0,
    bottom: 0,
    right: 0,
    left: 0,
    width: '100%',
    opacity: 0
  }
}

// https://github.com/Dogfalo/materialize/blob/master/js/forms.js#L192
class ServiceRequest extends Component {
  constructor (props) {
    super(props)
    this.state = {
      fileInput: null,
      name: '',
      email: '',
      phone: ''
    }
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  handleInputChange (event) {
    const target = event.target
    const value = target.type === 'checkbox' ? target.checked : target.value
    const name = target.name

    this.setState({
      [name]: value
    })
  }

  handleFilePath = () => {
    // Array.from converts array-like to array (so that map works)
    const file = Array.from(document.getElementById('upload').files)
    if (file.length === 0) {
      this.setState({
        fileInput: null
      })
    } else {
      const fileNames = file.map(f => f.name).join(', ')
      this.setState({
        fileInput: fileNames
      })
    }
  }

  render () {
    const fileValue = this.state.fileInput || 'Select a file to upload'
    return (

Please use this form to request services.

            <TextField
              floatingLabelText='Name'
              name='name'
              value={this.state.name}
              onChange={this.handleInputChange}
              fullWidth
            />

            <TextField
              floatingLabelText='Email'
              name='email'
              onChange={this.handleInputChange}
              type='email'
              fullWidth
            />

            <TextField
              floatingLabelText='Phone'
              name='phone'
              onChange={this.handleInputChange}
              fullWidth
            />

            <TextField floatingLabelText='Department' fullWidth />

            <TextField
              floatingLabelText='Project Description'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Goal'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Budget'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Key Messages'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Primary Target Audience'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Secondary Target Audience'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Project Contact (if other than yourself)'
              multiLine
              rows={2}
              fullWidth
            />

            <TextField
              floatingLabelText='Comments'
              multiLine
              rows={2}
              fullWidth
            />

            <DatePicker hintText='Desired Completion Date' />

                Upload Files
                <input
                  id='upload'
                  type='file'
                  multiple
                  onChange={this.handleFilePath}
                />

                <input
                  value={fileValue}
                  className='file-path validate'
                  type='text'
                  readOnly
                />

            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />

            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />
            <Checkbox label='Simple' style={styles.checkbox} />

            <RaisedButton label='Submit' primary />
            <Checkbox
              label={

                  I have read the{' '}
                  <Link to='/planning-guide' style={{ fontWeight: 500 }}>
                    Planning Guide
                  </Link>

              }
              style={styles.checkbox}
              inputStyle={{ width: '35px' }}
            />

    )
  }
}

export default ServiceRequest
<|endoftext|>


<commit_before>import {promisifyAll} from "bluebird";
import {execSync} from "child_process";
import {createReadStream} from "fs";
import gulp from "gulp";
import babel from "gulp-babel";
import eslint from "gulp-eslint";
import mocha from "gulp-spawn-mocha";
import zip from "gulp-zip";
import proGulp from "pro-gulp";
import {Lambda, S3} from "aws-sdk";

promisifyAll(Lambda);
promisifyAll(S3);

function getOutput (command) {
    try {
        return execSync(command).toString("utf8").trim();
    } catch (ignore) {
        return null;
    }
}

var CURRENT_BRANCH = getOutput("git rev-parse --abbrev-ref HEAD");
var CURRENT_COMMIT = getOutput("git rev-parse --short HEAD");
var CURRENT_TAG = getOutput("git describe --abbrev=0 --tags");
var LAMBDA_HANDLER = "index.handler";
var LAMBDA_NAME = process.env.LAMBDA_NAME;
var LAMBDA_ROLE = process.env.LAMBDA_ROLE;
var S3_BUCKET = process.env.S3_BUCKET;

var BUNDLE_NAME = [
    LAMBDA_NAME,
    CURRENT_TAG && "_t_" + CURRENT_TAG,
    "_b_" + CURRENT_BRANCH,
    "_c_" + CURRENT_COMMIT,
    "bundle.zip"
].filter(e => !!e).join("-");

proGulp.task("compile", function () {
    return gulp.src("src/**/*.js")
        .pipe(babel())
        .pipe(gulp.dest("build/" + CURRENT_COMMIT + "/"));
});

proGulp.task("install", function () {
    execSync("cp package.json build/" + CURRENT_COMMIT + "/package.json");
    execSync("npm install --production", {
        cwd: "build/" + CURRENT_COMMIT + "/"
    });
});

proGulp.task("bundle", function () {
    return gulp.src("build/" + CURRENT_COMMIT + "/**/*")
        .pipe(zip(BUNDLE_NAME))
        .pipe(gulp.dest("build/"));
});

proGulp.task("uploadToS3", function () {
    var s3 = new S3({apiVersion: "2006-03-01"});
    var params = {
        Bucket: S3_BUCKET,
        Key: BUNDLE_NAME,
        Body: createReadStream("builds/" + BUNDLE_NAME)
    };
    return s3.uploadAsync(params);
});

proGulp.task("updateLambda", function () {
    var lambda = new Lambda({apiVersion: "2015-03-31"});
    var createParams = {
      Code: {
        S3Bucket: S3_BUCKET,
        S3Key: BUNDLE_NAME
      },
      FunctionName: LAMBDA_NAME + "_" + CURRENT_BRANCH,
      Handler: LAMBDA_HANDLER,
      Role: LAMBDA_ROLE,
      Runtime: "nodejs"
    };
    var updateParams = {
        FunctionName: LAMBDA_NAME + "_" + CURRENT_BRANCH,
        S3Bucket: S3_BUCKET,
        S3Key: BUNDLE_NAME
    };
    return lambda.createFunctionAsync(createParams)
        .catch(function () {
            return lambda.updateFunctionCodeAsync(updateParams);
        });
});

gulp.task("deploy", proGulp.sequence([
    "compile",
    "install",
    "bundle",
    "uploadToS3",
    "updateLambda"
]));

gulp.task("test", function () {
    return gulp.src(["test/**/*.js"])
        .pipe(mocha({
            compilers: "js:babel/register",
            env: {
                NODE_ENV: "test",
                NODE_PATH: "./src/"
            },
            istanbul: true
        }));
});

gulp.task("lint", function () {
    return gulp.src(["src/**/*.js"])
        .pipe(eslint())
        .pipe(eslint.format());
});

gulp.task("default", ["test", "lint"], function () {
    return gulp.watch(["src/**/*.js", "test/**/*.js"], ["test", "lint"]);
});
<commit_msg>Changed promisification suffix<commit_after>import {promisifyAll} from "bluebird";
import {execSync} from "child_process";
import {createReadStream} from "fs";
import gulp from "gulp";
import babel from "gulp-babel";
import eslint from "gulp-eslint";
import mocha from "gulp-spawn-mocha";
import zip from "gulp-zip";
import proGulp from "pro-gulp";
import {Lambda, S3} from "aws-sdk";

promisifyAll(Lambda, {suffix: "Promise"});
promisifyAll(S3, {suffix: "Promise"});

function getOutput (command) {
    try {
        return execSync(command).toString("utf8").trim();
    } catch (ignore) {
        return null;
    }
}

var CURRENT_BRANCH = getOutput("git rev-parse --abbrev-ref HEAD");
var CURRENT_COMMIT = getOutput("git rev-parse --short HEAD");
var CURRENT_TAG = getOutput("git describe --abbrev=0 --tags");
var LAMBDA_HANDLER = "index.handler";
var LAMBDA_NAME = process.env.LAMBDA_NAME;
var LAMBDA_ROLE = process.env.LAMBDA_ROLE;
var S3_BUCKET = process.env.S3_BUCKET;

var BUNDLE_NAME = [
    LAMBDA_NAME,
    CURRENT_TAG && "_t_" + CURRENT_TAG,
    "_b_" + CURRENT_BRANCH,
    "_c_" + CURRENT_COMMIT,
    "bundle.zip"
].filter(e => !!e).join("-");

proGulp.task("compile", function () {
    return gulp.src("src/**/*.js")
        .pipe(babel())
        .pipe(gulp.dest("build/" + CURRENT_COMMIT + "/"));
});

proGulp.task("install", function () {
    execSync("cp package.json build/" + CURRENT_COMMIT + "/package.json");
    execSync("npm install --production", {
        cwd: "build/" + CURRENT_COMMIT + "/"
    });
});

proGulp.task("bundle", function () {
    return gulp.src("build/" + CURRENT_COMMIT + "/**/*")
        .pipe(zip(BUNDLE_NAME))
        .pipe(gulp.dest("build/"));
});

proGulp.task("uploadToS3", function () {
    var s3 = new S3({apiVersion: "2006-03-01"});
    var params = {
        Bucket: S3_BUCKET,
        Key: BUNDLE_NAME,
        Body: createReadStream("builds/" + BUNDLE_NAME)
    };
    return s3.uploadPromise(params);
});

proGulp.task("updateLambda", function () {
    var lambda = new Lambda({apiVersion: "2015-03-31"});
    var createParams = {
      Code: {
        S3Bucket: S3_BUCKET,
        S3Key: BUNDLE_NAME
      },
      FunctionName: LAMBDA_NAME + "_" + CURRENT_BRANCH,
      Handler: LAMBDA_HANDLER,
      Role: LAMBDA_ROLE,
      Runtime: "nodejs"
    };
    var updateParams = {
        FunctionName: LAMBDA_NAME + "_" + CURRENT_BRANCH,
        S3Bucket: S3_BUCKET,
        S3Key: BUNDLE_NAME
    };
    return lambda.createFunctionPromise(createParams)
        .catch(function () {
            return lambda.updateFunctionCodePromise(updateParams);
        });
});

gulp.task("deploy", proGulp.sequence([
    "compile",
    "install",
    "bundle",
    "uploadToS3",
    "updateLambda"
]));

gulp.task("test", function () {
    return gulp.src(["test/**/*.js"])
        .pipe(mocha({
            compilers: "js:babel/register",
            env: {
                NODE_ENV: "test",
                NODE_PATH: "./src/"
            },
            istanbul: true
        }));
});

gulp.task("lint", function () {
    return gulp.src(["src/**/*.js"])
        .pipe(eslint())
        .pipe(eslint.format());
});

gulp.task("default", ["test", "lint"], function () {
    return gulp.watch(["src/**/*.js", "test/**/*.js"], ["test", "lint"]);
});
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var crypto = require('crypto');
var package_data = require('./package.json');
var Build = require('@jupyterlab/buildutils').Build;

// Ensure a clear build directory.
var buildDir = './build';
fs.ensureDirSync(buildDir);

fs.copySync('./package.json', './build/package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

fs.writeFileSync(path.resolve(buildDir, 'index.out.js'), result);

// Create the hash
var hash = crypto.createHash('md5');
hash.update(fs.readFileSync('./package.json'));
var digest = hash.digest('hex');
fs.writeFileSync(path.resolve(buildDir, 'hash.md5'), digest);

// Handle linked packages.
var linkedPackages = {};
Object.keys(jlab.linkedPackages).forEach(function (name) {
  linkedPackages[name] = fs.realpathSync(jlab.linkedPackages[name]);
});

module.exports = {
  entry:  path.resolve(buildDir, 'index.out.js'),
  output: {
    path: path.resolve(buildDir),
    filename: '[name].bundle.js'
  },
  module: {
    rules: [
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.json$/, use: 'json-loader' },
      { test: /\.html$/, use: 'file-loader' },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        exclude: path.join(process.cwd(), 'node_modules')
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  resolve: {
    alias: linkedPackages,
    modules: [path.resolve(__dirname, './node_modules'),
              path.resolve(__dirname, '../node_modules')]
  },
  watchOptions: {
    ignored: /node_modules/
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'cheap-source-map'
}
<commit_msg>Fix resolving of loaders<commit_after>var webpack = require('webpack');
var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var crypto = require('crypto');
var package_data = require('./package.json');
var Build = require('@jupyterlab/buildutils').Build;

// Ensure a clear build directory.
var buildDir = './build';
fs.ensureDirSync(buildDir);

fs.copySync('./package.json', './build/package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

fs.writeFileSync(path.resolve(buildDir, 'index.out.js'), result);

// Create the hash
var hash = crypto.createHash('md5');
hash.update(fs.readFileSync('./package.json'));
var digest = hash.digest('hex');
fs.writeFileSync(path.resolve(buildDir, 'hash.md5'), digest);

// Handle linked packages.
var linkedPackages = {};
Object.keys(jlab.linkedPackages).forEach(function (name) {
  linkedPackages[name] = fs.realpathSync(jlab.linkedPackages[name]);
});

// The valid module paths.
var modules = [
  path.resolve(__dirname, './node_modules'),
  path.resolve(__dirname, '../node_modules')
];

module.exports = {
  entry:  path.resolve(buildDir, 'index.out.js'),
  output: {
    path: path.resolve(buildDir),
    filename: '[name].bundle.js'
  },
  module: {
    rules: [
      { test: /\.css$/, use: ['style-loader', 'css-loader'] },
      { test: /\.json$/, use: 'json-loader' },
      { test: /\.html$/, use: 'file-loader' },
      { test: /\.md$/, use: 'raw-loader' },
      { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
        exclude: path.join(process.cwd(), 'node_modules')
      },
      { test: /\.(jpg|png|gif)$/, use: 'file-loader' },
      { test: /\.js.map$/, use: 'file-loader' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
    ],
  },
  resolve: {
    alias: linkedPackages,
    modules: modules
  },
  resolveLoader: {
    modules: modules
  },
  watchOptions: {
    ignored: /node_modules/
  },
  node: {
    fs: 'empty'
  },
  bail: true,
  devtool: 'cheap-source-map'
}
<|endoftext|>