<commit_before>'use strict';

const RSVP = require('rsvp');

const lookupCommand = require('./lookup-command');
const getOptionArgs = require('../utilities/get-option-args');
let logger = require('heimdalljs-logger')('ember-cli:cli');
let loggerTesting = require('heimdalljs-logger')('ember-cli:testing');
const heimdall = require('heimdalljs');

const Promise = RSVP.Promise;
// Disabled until e2e and serve command can be evaluated/corrected -- require('../utilities/will-interrupt-process');
const onProcessInterrupt = { addHandler: (_handler) => { }, removeHandler: (_handler) => { } };

class CLI {
  /**
   * @private
   * @class CLI
   * @constructor
   * @param options
   */
  constructor(options) {
    /**
     * @private
     * @property name
     */
    this.name = options.name;

    /**
     * @private
     * @property ui
     * @type UI
     */
    this.ui = options.ui;

    /**
     * @private
     * @property analytics
     */
    this.analytics = options.analytics;

    /**
     * @private
     * @property testing
     * @type Boolean
     */
    this.testing = options.testing;

    /**
     * @private
     * @property disableDependencyChecker
     * @type Boolean
     */
    this.disableDependencyChecker = options.disableDependencyChecker;

    /**
     * @private
     * @property root
     */
    this.root = options.root;

    /**
     * @private
     * @property npmPackage
     */
    this.npmPackage = options.npmPackage;

    /**
     * @private
     * @property instrumentation
     */
    this.instrumentation = {
      stopAndReport: (...args) => { },
      start: (...args) => { },
    };

    logger.info('testing %o', !!this.testing);
  }

  /**
   * @private
   * @method run
   * @param environment
   * @return {Promise}
   */
  run(environment) {
    let shutdownOnExit = null;

    return RSVP.hash(environment).then(environment => {
      let args = environment.cliArgs.slice();

      if (args.length === 0) {
        args[0] = 'help';
      }

      if (args[0] === '--help') {
        if (args.length === 1) {
          args[0] = 'help';
        } else {
          args.shift();
          args.push('--help');
        }
      }

      let commandName = args.shift();
      let commandArgs = args;
      let helpOptions;

      let commandLookupCreationtoken = heimdall.start('lookup-command');

      let CurrentCommand = lookupCommand(environment.commands, commandName, commandArgs, {
        project: environment.project,
        ui: this.ui,
      });

      let command = new CurrentCommand({
        ui: this.ui,
        analytics: this.analytics,
        commands: environment.commands,
        tasks: environment.tasks,
        project: environment.project,
        settings: environment.settings,
        testing: this.testing,
        cli: this,
      });

      commandLookupCreationtoken.stop();

      getOptionArgs('--verbose', commandArgs).forEach(arg => {
        process.env[`EMBER_VERBOSE_${arg.toUpperCase()}`] = 'true';
      });

      logger.info('command: %s', commandName);

      if (!this.testing) {
        process.chdir(environment.project.root);
        let skipInstallationCheck = commandArgs.indexOf('--skip-installation-check') !== -1;
        if (environment.project.isEmberCLIProject() && !skipInstallationCheck) {
          const InstallationChecker = require('../models/installation-checker');
          new InstallationChecker({ project: environment.project }).checkInstallations();
        }
      }

      let instrumentation = this.instrumentation;
      let onCommandInterrupt;

      let runPromise = Promise.resolve().then(() => {
        instrumentation.stopAndReport('init');
        instrumentation.start('command');

        loggerTesting.info('cli: command.beforeRun');
        onProcessInterrupt.addHandler(onCommandInterrupt);

        return command.beforeRun(commandArgs);
      }).then(() => {
        loggerTesting.info('cli: command.validateAndRun');

        return command.validateAndRun(commandArgs);
      }).then(result => {
        instrumentation.stopAndReport('command', commandName, commandArgs);

        onProcessInterrupt.removeHandler(onCommandInterrupt);

        return result;
      }).finally(() => {
        instrumentation.start('shutdown');
        shutdownOnExit = function() {
          instrumentation.stopAndReport('shutdown');
        };
      }).then(result => {
        // if the help option was passed, call the help command
        if (result === 'callHelp') {
          helpOptions = {
            environment,
            commandName,
            commandArgs,
          };

          return this.callHelp(helpOptions);
        }

        return result;
      }).then(exitCode => {
        loggerTesting.info(`cli: command run complete. exitCode: ${exitCode}`);
        // TODO: fix this
        // Possibly this issue: https://github.com/joyent/node/issues/8329
        // Wait to resolve promise when running on windows.
        // This ensures that stdout is flushed so acceptance tests get full output

        return new Promise(resolve => {
          if (process.platform === 'win32') {
            setTimeout(resolve, 250, exitCode);
          } else {
            resolve(exitCode);
          }
        });
      });

      onCommandInterrupt = () =>
        Promise.resolve(command.onInterrupt())
          .then(() => runPromise);

      return runPromise;
    })
    .finally(() => {
      if (shutdownOnExit) {
        shutdownOnExit();
      }
    })
    .catch(this.logError.bind(this));
  }

  /**
   * @private
   * @method callHelp
   * @param options
   * @return {Promise}
   */
  callHelp(options) {
    let environment = options.environment;
    let commandName = options.commandName;
    let commandArgs = options.commandArgs;
    let helpIndex = commandArgs.indexOf('--help');
    let hIndex = commandArgs.indexOf('-h');

    let HelpCommand = lookupCommand(environment.commands, 'help', commandArgs, {
      project: environment.project,
      ui: this.ui,
    });

    let help = new HelpCommand({
      ui: this.ui,
      analytics: this.analytics,
      commands: environment.commands,
      tasks: environment.tasks,
      project: environment.project,
      settings: environment.settings,
      testing: this.testing,
    });

    if (helpIndex > -1) {
      commandArgs.splice(helpIndex, 1);
    }

    if (hIndex > -1) {
      commandArgs.splice(hIndex, 1);
    }

    commandArgs.unshift(commandName);

    return help.validateAndRun(commandArgs);
  }

  /**
   * @private
   * @method logError
   * @param error
   * @return {number}
   */
  logError(error) {
    if (this.testing && error) {
      console.error(error.message);
      if (error.stack) {
        console.error(error.stack);
      }
      throw error;
    }
    this.ui.errorLog.push(error);
    this.ui.writeError(error);
    return 1;
  }
}

module.exports = CLI;
<commit_msg>fix(@angular/cli): fix directory issue<commit_after>'use strict';

const RSVP = require('rsvp');

const lookupCommand = require('./lookup-command');
const getOptionArgs = require('../utilities/get-option-args');
let logger = require('heimdalljs-logger')('ember-cli:cli');
let loggerTesting = require('heimdalljs-logger')('ember-cli:testing');
const heimdall = require('heimdalljs');

const Promise = RSVP.Promise;
// Disabled until e2e and serve command can be evaluated/corrected -- require('../utilities/will-interrupt-process');
const onProcessInterrupt = { addHandler: (_handler) => { }, removeHandler: (_handler) => { } };

class CLI {
  /**
   * @private
   * @class CLI
   * @constructor
   * @param options
   */
  constructor(options) {
    /**
     * @private
     * @property name
     */
    this.name = options.name;

    /**
     * @private
     * @property ui
     * @type UI
     */
    this.ui = options.ui;

    /**
     * @private
     * @property analytics
     */
    this.analytics = options.analytics;

    /**
     * @private
     * @property testing
     * @type Boolean
     */
    this.testing = options.testing;

    /**
     * @private
     * @property disableDependencyChecker
     * @type Boolean
     */
    this.disableDependencyChecker = options.disableDependencyChecker;

    /**
     * @private
     * @property root
     */
    this.root = options.root;

    /**
     * @private
     * @property npmPackage
     */
    this.npmPackage = options.npmPackage;

    /**
     * @private
     * @property instrumentation
     */
    this.instrumentation = {
      stopAndReport: (...args) => { },
      start: (...args) => { },
    };

    logger.info('testing %o', !!this.testing);
  }

  /**
   * @private
   * @method run
   * @param environment
   * @return {Promise}
   */
  run(environment) {
    let shutdownOnExit = null;

    return RSVP.hash(environment).then(environment => {
      let args = environment.cliArgs.slice();

      if (args.length === 0) {
        args[0] = 'help';
      }

      if (args[0] === '--help') {
        if (args.length === 1) {
          args[0] = 'help';
        } else {
          args.shift();
          args.push('--help');
        }
      }

      let commandName = args.shift();
      let commandArgs = args;
      let helpOptions;

      let commandLookupCreationtoken = heimdall.start('lookup-command');

      let CurrentCommand = lookupCommand(environment.commands, commandName, commandArgs, {
        project: environment.project,
        ui: this.ui,
      });

      let command = new CurrentCommand({
        ui: this.ui,
        analytics: this.analytics,
        commands: environment.commands,
        tasks: environment.tasks,
        project: environment.project,
        settings: environment.settings,
        testing: this.testing,
        cli: this,
      });

      commandLookupCreationtoken.stop();

      getOptionArgs('--verbose', commandArgs).forEach(arg => {
        process.env[`EMBER_VERBOSE_${arg.toUpperCase()}`] = 'true';
      });

      logger.info('command: %s', commandName);

      if (!this.testing) {
        let skipInstallationCheck = commandArgs.indexOf('--skip-installation-check') !== -1;
        if (environment.project.isEmberCLIProject() && !skipInstallationCheck) {
          const InstallationChecker = require('../models/installation-checker');
          new InstallationChecker({ project: environment.project }).checkInstallations();
        }
      }

      let instrumentation = this.instrumentation;
      let onCommandInterrupt;

      let runPromise = Promise.resolve().then(() => {
        instrumentation.stopAndReport('init');
        instrumentation.start('command');

        loggerTesting.info('cli: command.beforeRun');
        onProcessInterrupt.addHandler(onCommandInterrupt);

        return command.beforeRun(commandArgs);
      }).then(() => {
        loggerTesting.info('cli: command.validateAndRun');

        return command.validateAndRun(commandArgs);
      }).then(result => {
        instrumentation.stopAndReport('command', commandName, commandArgs);

        onProcessInterrupt.removeHandler(onCommandInterrupt);

        return result;
      }).finally(() => {
        instrumentation.start('shutdown');
        shutdownOnExit = function() {
          instrumentation.stopAndReport('shutdown');
        };
      }).then(result => {
        // if the help option was passed, call the help command
        if (result === 'callHelp') {
          helpOptions = {
            environment,
            commandName,
            commandArgs,
          };

          return this.callHelp(helpOptions);
        }

        return result;
      }).then(exitCode => {
        loggerTesting.info(`cli: command run complete. exitCode: ${exitCode}`);
        // TODO: fix this
        // Possibly this issue: https://github.com/joyent/node/issues/8329
        // Wait to resolve promise when running on windows.
        // This ensures that stdout is flushed so acceptance tests get full output

        return new Promise(resolve => {
          if (process.platform === 'win32') {
            setTimeout(resolve, 250, exitCode);
          } else {
            resolve(exitCode);
          }
        });
      });

      onCommandInterrupt = () =>
        Promise.resolve(command.onInterrupt())
          .then(() => runPromise);

      return runPromise;
    })
    .finally(() => {
      if (shutdownOnExit) {
        shutdownOnExit();
      }
    })
    .catch(this.logError.bind(this));
  }

  /**
   * @private
   * @method callHelp
   * @param options
   * @return {Promise}
   */
  callHelp(options) {
    let environment = options.environment;
    let commandName = options.commandName;
    let commandArgs = options.commandArgs;
    let helpIndex = commandArgs.indexOf('--help');
    let hIndex = commandArgs.indexOf('-h');

    let HelpCommand = lookupCommand(environment.commands, 'help', commandArgs, {
      project: environment.project,
      ui: this.ui,
    });

    let help = new HelpCommand({
      ui: this.ui,
      analytics: this.analytics,
      commands: environment.commands,
      tasks: environment.tasks,
      project: environment.project,
      settings: environment.settings,
      testing: this.testing,
    });

    if (helpIndex > -1) {
      commandArgs.splice(helpIndex, 1);
    }

    if (hIndex > -1) {
      commandArgs.splice(hIndex, 1);
    }

    commandArgs.unshift(commandName);

    return help.validateAndRun(commandArgs);
  }

  /**
   * @private
   * @method logError
   * @param error
   * @return {number}
   */
  logError(error) {
    if (this.testing && error) {
      console.error(error.message);
      if (error.stack) {
        console.error(error.stack);
      }
      throw error;
    }
    this.ui.errorLog.push(error);
    this.ui.writeError(error);
    return 1;
  }
}

module.exports = CLI;
<|endoftext|>


<commit_before>module.exports = Eris => {
	Eris.Channel.prototype.createCode = function(code, lang) {
		const client = this.guild ? this.guild.shard.client : this._client;
		return client.createCode(this.id, code, lang);
	};
};

module.exports.deps = ["Client.createCode"];
<commit_msg>Update createCode.js<commit_after>module.exports = Eris => {
	Eris.Channel.prototype.createCode = function(code, lang) {
		const client = this.guild ? this.guild.shard.client : this.client;
		return client.createCode(this.id, code, lang);
	};
};

module.exports.deps = ["Client.createCode"];
<|endoftext|>


<commit_before>Sis.ApplicationRoute = Ember.Route.extend({
  model: function () {
    console.log("Model: app route");
    currentUser = this.get('auth.currentUser');
    if (currentUser != null) {
      if (currentUser.get('isAuthenticated') && currentUser.get('isTeacher')) {
        return this.get('store').find('semester');
      }
    }

  },

  beforeModel: function () {
    console.log("Before Model: app route");
  }
});<commit_msg>Alters application route, fixes login issues<commit_after>Sis.ApplicationRoute = Ember.Route.extend({
  model: function () {
    console.log("Model: app route");
    currentUser = this.get('auth.currentUser');
    if (currentUser != null) {
      console.log("Model: Returns find semesters");
      return this.get('store').find('semester');
    }

  },

  beforeModel: function () {
    console.log("Before Model: app route");
  }
});<|endoftext|>


<commit_before>

var express = require('express');
var router = express.Router();
var sequelize = require('sequelize');
var models = require("../models");

router.post("/create", function(req, res){
    var deadline = req.body.deadline;
    if(!!deadline.userId){
        models.User.findOne({
            where: {
                id: deadline.userId
            }
        }).then(function(user){
            if(!!user){
                models.Deadline.create(deadline).then(function(){
                    res.sendStatus(201);
                });
            }else{
                res.sendStatus(400);
            }
        })

    }else{
        res.sendStatus(400);
    }

});

/* Get Deadlines given a list of module codes */
router.get("/getDeadlines", function(req, res) {
	var modules = [];
	for (i in req.query) {
		modules.push(req.query[i]);
	}

	models.sequelize.Promise.all([
        models.Deadline.findAll({
            where: {
                module: modules,
            },
            include: [models.User]
        }),
    ]).spread(function(allDeadlines) {
        var deadlineArray = [];
        var convertDate = function(date){
            var d = new Date(date);
            return d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear() + " " +d.getHours() + ":" +
            ((d.getMinutes() > 9 ) ? d.getMinutes() : d.getMinutes()+"0");
        }
        for (var deadline of allDeadlines) {
            deadlineArray.push({
                id: deadline.id,
                title: deadline.title,
                des: deadline.description,
                module: deadline.module,
                date: convertDate(deadline.due),
                contributor: deadline.User.name
            });
        }
		res.send({
			deadlineArray: deadlineArray
		});
	});
});

module.exports = router;
<commit_msg>added ordering of deadlines<commit_after>

var express = require('express');
var router = express.Router();
var sequelize = require('sequelize');
var models = require("../models");

router.post("/create", function(req, res){
    var deadline = req.body.deadline;
    if(!!deadline.userId){
        models.User.findOne({
            where: {
                id: deadline.userId
            }
        }).then(function(user){
            if(!!user){
                models.Deadline.create(deadline).then(function(){
                    res.sendStatus(201);
                });
            }else{
                res.sendStatus(400);
            }
        })

    }else{
        res.sendStatus(400);
    }

});

/* Get Deadlines given a list of module codes */
router.get("/getDeadlines", function(req, res) {
	var modules = [];
	for (i in req.query) {
		modules.push(req.query[i]);
	}

	models.sequelize.Promise.all([
        models.Deadline.findAll({
            order:  [['due', 'ASC']],
            where: {
                module: modules,
            },
            include: [models.User]
        }),
    ]).spread(function(allDeadlines) {
        var deadlineArray = [];
        var convertDate = function(date){
            var d = new Date(date);
            return d.getDate()+'/'+d.getMonth()+'/'+d.getFullYear() + " " +d.getHours() + ":" +
            ((d.getMinutes() > 9 ) ? d.getMinutes() : d.getMinutes()+"0");
        }
        for (var deadline of allDeadlines) {
            console.log(deadline.due);
            deadlineArray.push({
                id: deadline.id,
                title: deadline.title,
                des: deadline.description,
                module: deadline.module,
                date: convertDate(deadline.due),
                contributor: deadline.User.name
            });
        }
		res.send({
			deadlineArray: deadlineArray
		});
	});
});

module.exports = router;
<|endoftext|>


<commit_before>import webpack from "webpack"
import path from "path"
import ServiceWorkerWebpackPlugin from "serviceworker-webpack-plugin"
import _ from "ramda"
import HtmlWebpackPlugin from "html-webpack-plugin"

const nodeENV = process.env.NODE_ENV
console.log(`webpack: process.env.NODE_ENV: "${nodeENV}"`)

const envList = ["development", "production"]
if (!_.contains(nodeENV)(envList)) {
    console.error("webpack: Error process.env.NODE_ENV invalid", nodeENV)
    process.exit(1)
}

const isDevEnv = nodeENV === "development"
console.log("webpack: isDevEnv: ", isDevEnv)

const outputDir = isDevEnv ? "dev" : "app"

export default {
    resolve: {
        alias: {elm: path.resolve(__dirname, 'src/elm/')}
    },
    // devtool: isDevEnv ? "inline" : 'source-map',
    // devtool: isDevEnv? "": "source-map",
    // devtool: 'source-map', // not much useful for elm, and slows down dev-server
    entry: {
        common: ["./src/web/common-require.js"],
        app: ["./src/web/app.js"]
    },

    output: {
        path: path.resolve(__dirname , outputDir),
        filename: '[name].js',
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: 'static/index.template.html',
            filename:"index.html"
        }),
        new HtmlWebpackPlugin({
            template: 'static/index.template.html',
            filename:"app/index.html"
        }),
        new webpack["ProvidePlugin"]({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery"
        }),
        new webpack.DefinePlugin({
            'IS_DEVELOPMENT_ENV': isDevEnv,
            "process.env": JSON.stringify(process.env)
        }),
        new ServiceWorkerWebpackPlugin({
            entry: './src/web/notification-sw.js',
            filename: "notification-sw.js",
            template: function () {
                return Promise.resolve(serviceWorkerTemplate)
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "common",
            minChunks: 2
        })
    ],

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: function (fileName) {
                    return !_.test(/crypto-random-string/, fileName)
                           && _.test(/(node_modules|bower_components)/, fileName)
                },
                use: 'babel-loader',
            },
            {
                test: /\.elm$/,
                exclude: [/elm-stuff/, /node_modules/],
                // use: ["elm-hot-loader","elm-webpack-loader?verbose=true&warn=true"],
                use: ["elm-hot-loader", "elm-webpack-loader?verbose=true"],
                // use: ["elm-hot-loader","elm-webpack-loader?debug=true"],
                // use: ["elm-hot-loader", "elm-webpack-loader"],
            },
            {
                test: /\.(pcss|css)$/,
                use: [
                    'style-loader',
                    {loader: 'css-loader', options: {importLoaders: 1}},
                    'postcss-loader'
                ]
            },
            {
                test: /\.scss$/,
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"},
                    {loader: "sass-loader"}
                ]
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'url-loader?name=[name].[ext]&outputPath=/assets&useRelativePath=true&limit=10000&mimetype=application/font-woff',
            },
            {
                test: /\.(ttf|eot|svg|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'file-loader',
            },
        ],

        noParse: [/\.elm$/],
    },

    devServer: {
        // stats: {colors: false, "errors-only":true},
        stats: "minimal",
        port: 8020,
        // open:true,
        // inline: false,
        contentBase: ["src/web/", "static/",],
        host: "0.0.0.0",
    },

};

const serviceWorkerTemplate =
    `
        const isDevEnv = ${isDevEnv};

    `
<commit_msg>* landing page<commit_after>import webpack from "webpack"
import path from "path"
import ServiceWorkerWebpackPlugin from "serviceworker-webpack-plugin"
import _ from "ramda"
import HtmlWebpackPlugin from "html-webpack-plugin"

const nodeENV = process.env.NODE_ENV
console.log(`webpack: process.env.NODE_ENV: "${nodeENV}"`)

const envList = ["development", "production"]
if (!_.contains(nodeENV)(envList)) {
    console.error("webpack: Error process.env.NODE_ENV invalid", nodeENV)
    process.exit(1)
}

const isDevEnv = nodeENV === "development"
console.log("webpack: isDevEnv: ", isDevEnv)

const outputDir = isDevEnv ? "dev" : "app"

export default {
    resolve: {
        alias: {elm: path.resolve(__dirname, 'src/elm/')}
    },
    // devtool: isDevEnv ? "inline" : 'source-map',
    // devtool: isDevEnv? "": "source-map",
    // devtool: 'source-map', // not much useful for elm, and slows down dev-server
    entry: {
        common: ["./src/web/common-require.js"],
        app: ["./src/web/app.js"],
        "start-app": ["./src/web/start-app.js"]
    },

    output: {
        path: path.resolve(__dirname , outputDir),
        filename: '[name].js',
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: 'static/index.template.html',
            filename:"index.html"
        }),
        new HtmlWebpackPlugin({
            template: 'static/index.template.html',
            filename:"app/index.html"
        }),
        new webpack["ProvidePlugin"]({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery"
        }),
        new webpack.DefinePlugin({
            'IS_DEVELOPMENT_ENV': isDevEnv,
            "process.env": JSON.stringify(process.env)
        }),
        new ServiceWorkerWebpackPlugin({
            entry: './src/web/notification-sw.js',
            filename: "notification-sw.js",
            template: function () {
                return Promise.resolve(serviceWorkerTemplate)
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "common",
            minChunks: 2
        })
    ],

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: function (fileName) {
                    return !_.test(/crypto-random-string/, fileName)
                           && _.test(/(node_modules|bower_components)/, fileName)
                },
                use: 'babel-loader',
            },
            {
                test: /\.elm$/,
                exclude: [/elm-stuff/, /node_modules/],
                // use: ["elm-hot-loader","elm-webpack-loader?verbose=true&warn=true"],
                use: ["elm-hot-loader", "elm-webpack-loader?verbose=true"],
                // use: ["elm-hot-loader","elm-webpack-loader?debug=true"],
                // use: ["elm-hot-loader", "elm-webpack-loader"],
            },
            {
                test: /\.(pcss|css)$/,
                use: [
                    'style-loader',
                    {loader: 'css-loader', options: {importLoaders: 1}},
                    'postcss-loader'
                ]
            },
            {
                test: /\.scss$/,
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"},
                    {loader: "sass-loader"}
                ]
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'url-loader?name=[name].[ext]&outputPath=/assets&useRelativePath=true&limit=10000&mimetype=application/font-woff',
            },
            {
                test: /\.(ttf|eot|svg|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'file-loader',
            },
        ],

        noParse: [/\.elm$/],
    },

    devServer: {
        // stats: {colors: false, "errors-only":true},
        stats: "minimal",
        port: 8020,
        // open:true,
        // inline: false,
        contentBase: ["src/web/", "static/",],
        host: "0.0.0.0",
    },

};

const serviceWorkerTemplate =
    `
        const isDevEnv = ${isDevEnv};

    `
<|endoftext|>


<commit_before>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var blockData;
var ledData;
var imageData;
var imageTime;
var frameData;
var current_frame=0;

var frameTimer;

function frameTimerFunc()
{
  if (current_frame < imageData.length) {
    current_frame = current_frame + 1;
    getVideo(imageData[current_frame]);
    draw(frameData);
  }else{
    frameTimerStop();
  }
}

function frameTimerStop() {  clearInterval(frameTimer);  }

(function() {
  'use strict';

  //var blockdata = [];
  //var qs = new Querystring();
  //var block_id = qs.get("myBlock");

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('/replay/#postdata', function(data){
  	blockData = [];
	ledData = [];
	blockData.push(data[0]); // time
	blockData.push(data[1]); // owner
	blockData.push(data[2]); // experiment id
	blockData.push(data[3]); // pattern id

	// image dir = 171.65.102.132:3001/blockid/

	for (var i=0;i<data[4].length/2;i++)
	{
	  //ledData.push(data[4][i*2]);
	  //ledTime.push(Math.round(parseInt(data[4][i*2+1])));

	  var led = new Object();
	  led.id = i;
	  led.time = parseInt(data[4][i*2+1]);
	  led.arrow = data[4][i*2];

	  ledData.push(led);
	}
	//console.dir(ledData);

	var info_p = document.createElement("p");
	var info_node_0 = document.createTextNode("Block ID: "+block_id);
	var info_node_1 = document.createTextNode("Block Start Time: "+data[0]);
	var info_node_2 = document.createTextNode("Owner : "+data[1]);
	var info_node_3 = document.createTextNode("Experiment : experiment id "+data[2]);
	var info_node_4 = document.createTextNode("Pattern : "+ (data[3] == 0 ? "Freeform Experiment" : "pattern id "+data[3]));
	info_p.appendChild(info_node_0);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_1);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_2);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_3);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_4);

	var info_box_div = document.getElementById('info_box');
	info_box_div.appendChild(info_p);

	//console.log(ledData);
	//console.log(ledData.length);
	//console.log(ledTime);
	//console.log(ledTime.length);

	socket.emit('/replay/#callimglist', { targetBlock: block_id});
  });

  socket.on('/replay/#postimglist', function(data){
	imageData = [];
	imageTime = [];
	data.forEach(function(filename){
	    var res = filename.split(".");
	    imageTime.push(Math.round(parseInt(res[0])/100)*100);
	    imageData.push(filename);
	});

	//console.log(imageData);
	//console.log(imageData.length);
	//console.log(imageTime);
	//console.log(imageTime.length);

	setupCanvas();
	getVideo(imageData[current_frame]);
	datavis_width = imageData.length * 5+20;

	frameData = [];
	for (var i=0;i<=imageData.length;i++){
		var frame = new Object();
		frame.id = i;
		frame.msec = imageTime[i];

		var d = new Date(0);
		d.setTime(imageTime[i]);
		frame.time = d;

		frame.ledarray = [];
		if (i<imageData.length) {
		    frame.ledarray = ledData.filter(function (el) {
			  return el.time >= imageTime[i] &&
			  el.time < imageTime[i+1];
		    });
		}
		frameData.push(frame);
	}
	console.dir(frameData);
	draw(frameData);
	//var path = '../../Dropbox/live-gallery/'+targetBlock;
  });

  socket.on('/replay/#newUser', function(user) {
      myname = user;
      console.log('>>> DB connected' + block_id);
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/replay/' + this.get('block_id') +'/';
    }
  });

  app.MovieView = Backbone.View.extend({
    el: '#playback_nav',
    template: _.template( $('#tmpl-movie_nav').html() ),
    events: {
      'click .btn-play': 'reqPlay',
      'click .btn-stop': 'reqStop',
      'click .btn-first': 'reqFirstFrame'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqPlay: function() {
      frameTimer=setInterval(function(){frameTimerFunc()},200);
    },
    reqStop: function() {
      frameTimerStop();
    },
    reqFirstFrame: function() {
      frameTimerStop();
      current_frame = 0;
      getVideo(imageData[current_frame]);
      draw(frameData);
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/replay/': 'default',
      'account/replay/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      socket.emit('/replay/#callblock', { targetBlock: block});
    }
  });

  $(document).ready(function() {
    app.movieView = new app.MovieView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var 	shape_bg,
	shape_stage,
	g_ledL,
	g_ledR,
	g_ledU,
	g_ledD,
	led_L,
	led_R,
	led_U,
	led_D,
	vid_canvas,
	svg_led,
	vid_context,
	svg_data_vis;

var 	vid_width = 640,
	vid_height = 480,
	m = 20,
	degrees = 180 / Math.PI,
	datavis_width = 1600,
	datavis_height = 100;

function setupCanvas() { // called in init
	vid_canvas = d3.select("#canvasArea").append("canvas")
		.attr("class", "display-canvas")
		.attr("width", vid_width+40)
		.attr("height", vid_height+40)
		.style("position", "absolute")
		.style("top", 0)
		.style("left", 0);

	svg_led = d3.select("#canvasArea").append("svg:svg")
		.attr("width", vid_width+40)
		.attr("height", vid_height+40)
		.style("position", "absolute")
		.style("top", 0)
		.style("left", 0);

	vid_context = vid_canvas.node().getContext("2d");

	led_L = svg_led.append("svg:g").
		append("svg:polygon")
		.attr("points", "26,230 66,260 26,290")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_R = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "654,230 654,290 614,260")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_U = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "310,26 370,26 340,66")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_D = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "310,494 340,454 370,494")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	//window.setInterval(getVideo, 1000/10);

	/*d3.timer(function(){
		joystick_draw();
		drawObjects();
	});*/
}

function resetCanvas(e) { // on resize events
    max_val = (document.getElementById("joystickArea").offsetWidth-100)/2;
    console.log('max_val :' + max_val);

    // resize the canvas - this clears the canvas
    control_canvas.width = document.getElementById("joystickArea").offsetWidth-20;
    control_canvas.height = control_canvas.width;
    halfWidth = (control_canvas.width)/2;
    halfHeight = (control_canvas.height)/2;

    rect_joy = control_canvas.getBoundingClientRect();

    // make sure we scroll to the top left.
    window.scrollTo(0, 0);
}

function drawObjects(){
	led_U.style("opacity",arrow.int1);
	led_L.style("opacity",arrow.int2);
	led_D.style("opacity",arrow.int3);
	led_R.style("opacity",arrow.int4);
}

var draw = function(d3data){
    d3.select("svg")
	.remove();

    /*var tip = d3.tip()
	.attr('class', 'd3-tip')
	.direction('e')
	.offset([0,10])
	.html(function(d) {
		return "time: "+d.time;
	});*/

    svg_data_vis = d3.select("#data_vis_box").append("svg")
	    .attr("width", datavis_width)
	    .attr("height", datavis_height)
	    .append("g");
	    //.attr("transform", "translate(4, 4)");

    //svg.call(tip);

    var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = i*5;
		    var dy = 20;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 2)
	    .attr("height", 5);
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);

    /*block.append("text")
	    .attr("class", function (d)
	    {
		    var class_name;
		    if (d.username==myname){
			    class_name="my-block-name";
		    }else{
			    class_name="not-my-block-name";
		    }
		    return class_name;
	    })
	    .attr("x",10)
	    .attr("y",14)
	    .attr("dy", ".3em")
	    .text(function(d) {
		    var h = d.time.getHours();
		    var ampm = (h<12 ? "a":"p");
		    //h=("0" + h%12).slice(-2);
		    h=(h%12);
		    if(h==0){h="12";}
		    var m = d.time.getMinutes();
		    m=("0" + m).slice(-2);
		    return h+":"+m+ampm;
	    })
	    .on('mouseover', tip.show)
	    .on('mouseout', tip.hide);*/

    /*block.append('text')
	    .attr("class", function (d){
		    var class_name;
		    if (d.username==myname){
			    class_name="my-block-name";
		    }else{
			    class_name="not-my-block-name";
		    }
		    return class_name;})
	    .attr('font-family', 'FontAwesome')
	    .style('font-size', '150%' )
	    .attr("x",22)
	    .attr("y",44)
	    .text(function(d) { return '\uf023' })
	    .style("display", function(d) {
		    return d.lock == true ? null : "none";
	    });*/
  }

function getVideo(frame_img_name){
	getVidFrame("http://171.65.102.132:3001/" + block_id +"/"+ frame_img_name, function(image) {
		vid_context.clearRect(20, 20, vid_width+20, vid_height+20);
		vid_context.drawImage(image, 20, 20, vid_width, vid_height);
	});
}

function getVidFrame(path, callback) {
	var image = new Image;
	image.src = path;
	image.onload = function() {
		callback(image);
	    //console.log(new Date().getTime());
	};
}
<commit_msg>scroll to element<commit_after>/* global app:true, io:false */

var socket;
var myname;
var block_id;
var blockData;
var ledData;
var imageData;
var imageTime;
var frameData;
var current_frame=0;

var frameTimer;

function frameTimerFunc()
{
  if (current_frame < imageData.length) {
    current_frame = current_frame + 1;
    getVideo(imageData[current_frame]);
    draw(frameData);
  }else{
    frameTimerStop();
  }
}

function frameTimerStop() {  clearInterval(frameTimer);  }

(function() {
  'use strict';

  //var blockdata = [];
  //var qs = new Querystring();
  //var block_id = qs.get("myBlock");

  socket = io.connect();
  socket.on('connect', function(){
  	socket.emit('/replay/#join');
  });

  socket.on('/replay/#postdata', function(data){
  	blockData = [];
	ledData = [];
	blockData.push(data[0]); // time
	blockData.push(data[1]); // owner
	blockData.push(data[2]); // experiment id
	blockData.push(data[3]); // pattern id

	// image dir = 171.65.102.132:3001/blockid/

	for (var i=0;i<data[4].length/2;i++)
	{
	  //ledData.push(data[4][i*2]);
	  //ledTime.push(Math.round(parseInt(data[4][i*2+1])));

	  var led = new Object();
	  led.id = i;
	  led.time = parseInt(data[4][i*2+1]);
	  led.arrow = data[4][i*2];

	  ledData.push(led);
	}
	//console.dir(ledData);

	var info_p = document.createElement("p");
	var info_node_0 = document.createTextNode("Block ID: "+block_id);
	var info_node_1 = document.createTextNode("Block Start Time: "+data[0]);
	var info_node_2 = document.createTextNode("Owner : "+data[1]);
	var info_node_3 = document.createTextNode("Experiment : experiment id "+data[2]);
	var info_node_4 = document.createTextNode("Pattern : "+ (data[3] == 0 ? "Freeform Experiment" : "pattern id "+data[3]));
	info_p.appendChild(info_node_0);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_1);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_2);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_3);
	info_p.appendChild(document.createElement("br"));
	info_p.appendChild(info_node_4);

	var info_box_div = document.getElementById('info_box');
	info_box_div.appendChild(info_p);

	//console.log(ledData);
	//console.log(ledData.length);
	//console.log(ledTime);
	//console.log(ledTime.length);

	socket.emit('/replay/#callimglist', { targetBlock: block_id});
  });

  socket.on('/replay/#postimglist', function(data){
	imageData = [];
	imageTime = [];
	data.forEach(function(filename){
	    var res = filename.split(".");
	    imageTime.push(Math.round(parseInt(res[0])/100)*100);
	    imageData.push(filename);
	});

	//console.log(imageData);
	//console.log(imageData.length);
	//console.log(imageTime);
	//console.log(imageTime.length);

	setupCanvas();
	getVideo(imageData[current_frame]);
	datavis_width = imageData.length * 5+20;

	frameData = [];
	for (var i=0;i<=imageData.length;i++){
		var frame = new Object();
		frame.id = i;
		frame.msec = imageTime[i];

		var d = new Date(0);
		d.setTime(imageTime[i]);
		frame.time = d;

		frame.ledarray = [];
		if (i<imageData.length) {
		    frame.ledarray = ledData.filter(function (el) {
			  return el.time >= imageTime[i] &&
			  el.time < imageTime[i+1];
		    });
		}
		frameData.push(frame);
	}
	console.dir(frameData);
	draw(frameData);
	//var path = '../../Dropbox/live-gallery/'+targetBlock;
  });

  socket.on('/replay/#newUser', function(user) {
      myname = user;
      console.log('>>> DB connected' + block_id);
  });

  socket.on('message', function (message) {
      console.log(message);
  });

  socket.on('disconnect', function() {
      console.log('>>> DB disconnected');
  });

  app = app || {};

  app.Reset = Backbone.Model.extend({
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      blockid: undefined,
      confitm: ''
    },
    url: function(){
      return '/account/replay/' + this.get('block_id') +'/';
    }
  });

  app.MovieView = Backbone.View.extend({
    el: '#playback_nav',
    template: _.template( $('#tmpl-movie_nav').html() ),
    events: {
      'click .btn-play': 'reqPlay',
      'click .btn-stop': 'reqStop',
      'click .btn-first': 'reqFirstFrame'
    },
    initialize: function() {
      //this.model = new app.Blocks();
      //this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template);
    },
    reqPlay: function() {
      frameTimer=setInterval(function(){frameTimerFunc()},200);
    },
    reqStop: function() {
      frameTimerStop();
    },
    reqFirstFrame: function() {
      frameTimerStop();
      current_frame = 0;
      getVideo(imageData[current_frame]);
      draw(frameData);
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      'account/replay/': 'default',
      'account/replay/load/:block/': 'load'
    },
    default: function(){
      console.log(" >>default view, nothing loaded");
    },
    load: function(block) {
      console.log(">> loading block "+block);
      block_id = block;
      socket.emit('/replay/#callblock', { targetBlock: block});
    }
  });

  $(document).ready(function() {
    app.movieView = new app.MovieView();
    app.router = new app.Router();
    Backbone.history.start({ pushState: true });
  });
}());

/////////////////////////////
// Canvas setup functions
/////////////////////////////

var 	shape_bg,
	shape_stage,
	g_ledL,
	g_ledR,
	g_ledU,
	g_ledD,
	led_L,
	led_R,
	led_U,
	led_D,
	vid_canvas,
	svg_led,
	vid_context,
	svg_data_vis;

var 	vid_width = 640,
	vid_height = 480,
	m = 20,
	degrees = 180 / Math.PI,
	datavis_width = 1600,
	datavis_height = 100;

function setupCanvas() { // called in init
	vid_canvas = d3.select("#canvasArea").append("canvas")
		.attr("class", "display-canvas")
		.attr("width", vid_width+40)
		.attr("height", vid_height+40)
		.style("position", "absolute")
		.style("top", 0)
		.style("left", 0);

	svg_led = d3.select("#canvasArea").append("svg:svg")
		.attr("width", vid_width+40)
		.attr("height", vid_height+40)
		.style("position", "absolute")
		.style("top", 0)
		.style("left", 0);

	vid_context = vid_canvas.node().getContext("2d");

	led_L = svg_led.append("svg:g").
		append("svg:polygon")
		.attr("points", "26,230 66,260 26,290")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_R = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "654,230 654,290 614,260")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_U = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "310,26 370,26 340,66")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	led_D = svg_led.append("svg:g")
		.append("svg:polygon")
		.attr("points", "310,494 340,454 370,494")
		.style("fill", "#ffffff")
		.style("opacity", "0");

	//window.setInterval(getVideo, 1000/10);

	/*d3.timer(function(){
		joystick_draw();
		drawObjects();
	});*/
}

function resetCanvas(e) { // on resize events
    max_val = (document.getElementById("joystickArea").offsetWidth-100)/2;
    console.log('max_val :' + max_val);

    // resize the canvas - this clears the canvas
    control_canvas.width = document.getElementById("joystickArea").offsetWidth-20;
    control_canvas.height = control_canvas.width;
    halfWidth = (control_canvas.width)/2;
    halfHeight = (control_canvas.height)/2;

    rect_joy = control_canvas.getBoundingClientRect();

    // make sure we scroll to the top left.
    window.scrollTo(0, 0);
}

function drawObjects(){
	led_U.style("opacity",arrow.int1);
	led_L.style("opacity",arrow.int2);
	led_D.style("opacity",arrow.int3);
	led_R.style("opacity",arrow.int4);
}

var draw = function(d3data){
    d3.select("svg")
	.remove();

    /*var tip = d3.tip()
	.attr('class', 'd3-tip')
	.direction('e')
	.offset([0,10])
	.html(function(d) {
		return "time: "+d.time;
	});*/

    svg_data_vis = d3.select("#data_vis_box").append("svg")
	    .attr("width", datavis_width)
	    .attr("height", datavis_height)
	    .append("g");
	    //.attr("transform", "translate(4, 4)");

    //svg.call(tip);

    var frame = svg_data_vis.selectAll(".frame")
	    .data(d3data)
    .enter().append("g")
	    .attr("class", "block")
	    .attr("transform", function (d,i)
	    {
		    var dx = i*5;
		    var dy = 20;
		    return "translate(" + dx + ","+ dy + ")";
	    });
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide);

    frame.append("rect")
	    .attr("class", function (d,i)
	    {
		    var class_name;
		    if(i==current_frame){
		      class_name="current-frame";
		    }
		    else{
		      if (d.ledarray.length>0){
			    class_name="frame-with-led";
		      }else{
			    class_name="frame-no-led";
		      }

		    }
		    return class_name;
	    })
	    .attr("width", 2)
	    .attr("height", 5);
	    /*.attr("led", function (d){
		    if (d.ledarray.length>0){
			    return true;
		    }else{
			    return false
		    }
	    });*/
	    //.on('mouseover', tip.show)
	    //.on('mouseout', tip.hide)
	    //.on('click', mouseclick);

    /*block.append("text")
	    .attr("class", function (d)
	    {
		    var class_name;
		    if (d.username==myname){
			    class_name="my-block-name";
		    }else{
			    class_name="not-my-block-name";
		    }
		    return class_name;
	    })
	    .attr("x",10)
	    .attr("y",14)
	    .attr("dy", ".3em")
	    .text(function(d) {
		    var h = d.time.getHours();
		    var ampm = (h<12 ? "a":"p");
		    //h=("0" + h%12).slice(-2);
		    h=(h%12);
		    if(h==0){h="12";}
		    var m = d.time.getMinutes();
		    m=("0" + m).slice(-2);
		    return h+":"+m+ampm;
	    })
	    .on('mouseover', tip.show)
	    .on('mouseout', tip.hide);*/

    /*block.append('text')
	    .attr("class", function (d){
		    var class_name;
		    if (d.username==myname){
			    class_name="my-block-name";
		    }else{
			    class_name="not-my-block-name";
		    }
		    return class_name;})
	    .attr('font-family', 'FontAwesome')
	    .style('font-size', '150%' )
	    .attr("x",22)
	    .attr("y",44)
	    .text(function(d) { return '\uf023' })
	    .style("display", function(d) {
		    return d.lock == true ? null : "none";
	    });*/
    var currentframe_g = document.getElementByClass("current-frame");
    currentframe_g.scrollIntoView(true);
  }

function getVideo(frame_img_name){
	getVidFrame("http://171.65.102.132:3001/" + block_id +"/"+ frame_img_name, function(image) {
		vid_context.clearRect(20, 20, vid_width+20, vid_height+20);
		vid_context.drawImage(image, 20, 20, vid_width, vid_height);
	});
}

function getVidFrame(path, callback) {
	var image = new Image;
	image.src = path;
	image.onload = function() {
		callback(image);
	    //console.log(new Date().getTime());
	};
}
<|endoftext|>


<commit_before>var Namespace = function() {
  var Namespace = this;

  // Global settings accessible to all objects.
  Namespace.global = {};
  // A helper function for adding multiple settings to the global namespace.
  // Example usage:
  //
  //  > var namespace = new Namespace();
  //  > namespace.updateGlobal({
  //  >   name: 'Peter',
  //  >   age: 19,
  //  >   useful: true})
  //
  //  settings: an object of key => value to set on namespace.global.
  //
  //  overrideProtect: if truthy, will throw an exeption if setting
  //  a key that has already been set.
  Namespace.updateGlobal = function(settings, overrideProtect) {
    var overrideProtect = !!overrideProtect;
    for (var key in settings) {
      if (Object.hasOwnProperty.call(settings, key)) {
        var value = settings[key];
        if (overrideProtect && Namespace.global[key] !== undefined) {
          throw "Already defined: " + key + " => " + Namespace.global[key];
        }
        Namespace.global[key] = value;
      }
    }
  };

  // A helper function for resolving a dotted name, useful for checking
  // properties on nested namespaces or modules. Example usage:
  //
  //  > var namespace = new Namespace();
  //  > if (namespace.get('Math.Trigonometry') {
  //  >   namespace.Math.Trigonomety.cos(2 * Math.PI);
  //  > }
  //
  //  dottedName: a string of dotted paths to resolve.
  //
  //  defaultValue: the value returned if the full resolution fails at any
  //  point. Defaults to undefined.
  Namespace.get = function(dottedName, defaultValue) {
    var names = dottedName.split('.');
    var current = this;
    try {
      for (var i = 0; i < names.length; i++) {
        current = current[names[i]];
        if (current === undefined) {
          return defaultValue;
        }
      }
      return current;
    } catch (exception) {
      return defaultValue;
    }
  };

  // A helper function for determining whether or not a dotted name has been
  // defined. Example usage:
  //
  //  > var namespace = new Namespace();
  //  > namespace.global
  //  {}
  //  > namespace.global.age = 12;
  //  12
  //  > namespace.exists('global.age')
  //  true
  //  > namespace.exists('TestModule')
  //  false
  //  > namespace.define([], 'TestModule', function() {})
  //  > namespace.exists('TestModule')
  //  true
  //
  //  dottedName: a string of dotted paths to resolve.
  Namespace.exists = function(dottedName) {
    return Namespace.get(dottedName, undefined) !== undefined;
  };

  Namespace.require = function(dottedName) {
    var value = Namespace.get(dottedName, undefined);
    if (value === undefined) {
      throw "required value ('" + dottedName + "') not defined";
    }
    return value;
  }

  // A helper function to add modules to the current namespace. For example,
  //
  //  > var namespace = new Namespace();
  //  > namespace.define('Widget.Core', myfunc{...}, [arg1val, arg2val]);
  //
  // will set namespace.Widget.Core to {} if it doesn't exist and run
  //
  //  > myfunc.apply(namespace.Widget.Core, [namespace, arg1val, arg2val]):
  //
  // moduleDefinition: must be a Function. It must not set any attributes on
  // the Namespace object. The first argument to the definition will be this
  // global Namespace object.
  //
  // moduleArguments: must either be an Array or a falsy value or omitted.
  //
  // dottedName: must not begin or end with a '.', and the first part of the
  // must not be 'global', 'updateGlobal', 'require', 'exists', 'define', or
  // 'get'.
  Namespace.define = function(
      dottedName, dependencyNames, moduleDefinition, moduleArguments) {
    // Resolve dependencies before doing any sort of definition. If any of the
    // dependencies is undefined, throw an error instead of defining the
    // module.
    var dependencies = [];
    dependencyNames = dependencyNames || [];
    for (var i = 0; i < dependencyNames.length; i++) {
      var dependencyName = dependencyNames[i];
      var dependency = Namespace.get(dependencyName, undefined);
      if (dependency === undefined) {
        throw "Dependencies not met: '" + dependencyName + "' not defined";
      }
      dependencies.push(dependency);
    }

    var names = dottedName.split('.');
    // The module name is the last part of the dotted name.
    var moduleName = names.pop();
    // The first argument to every module definition is the global Namespace
    // object. This is followed by any dependencies, then any module arguments.
    moduleArguments = dependencies.concat(moduleArguments || []);
    moduleArguments.unshift(Namespace);
    // Define the module in the correct namespace, traversing the dotted names
    // until there are no more.
    var namespace = this;
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      namespace = namespace[name] = namespace[name] || {};
    };
    if (namespace[moduleName]) {
      throw "Cannot define '" + dottedName + "' (already exists)";
    }
    var module = namespace[moduleName] = {};
    moduleDefinition.apply(module, moduleArguments);
  };
};

var exports;
if (exports) {
  exports.Namespace = Namespace;
}

var ns = new Namespace();
if (ns.exists('global.age')) throw "Broken exists";

ns.updateGlobal({
  name: 'Peter',
  age: 19
})
if (!(ns.exists('global.age'))) throw "Broken exists";
if (!(ns.get('global.name') === 'Peter')) throw "Broken get";
if (!(ns.get('global.undefined', 'default') === 'default')) throw "Broken get";
ns.define('TestModule', [], function() {this.Helpers = true;});
var outer_ns = ns;
ns.define('PeterModule', ['TestModule.Helpers'], function(ns, Helpers) {
  if (ns !== outer_ns) throw "Broken define";
  if (Helpers !== outer_ns.TestModule.Helpers) throw "Broken define";
  console.log('arguments:', arguments);
  var x = 12;
  this.getX = function() {
    return x;
  }
});

if (!ns.get('PeterModule').getX() === 12) throw "Broken define/get";
console.log("All tests pass.");

var namespace = new Namespace();
namespace.define('LibA', [], function(namespace) {
  this.sayHello = function(name) {
    return 'Hello ' + name;
  };
});

// This call fails because LibB is not defined.
try {
  namespace.define('PetersModule', ['LibA', 'LibB'], function(namespace, LibA, LibB) {
    // This function depends on both LibA and LibB
    this.sayHelloToObject = function(object) {
      return LibA.sayHello(LibB.getObjectName(object, 'Anonymous'));
    };
  });
} catch (exception) {
  console.log('caught expected exception');
  console.log(exception);
}

namespace.define('LibB', [], function(namespace) {
  this.getObjectName = function(object, _default) {
    return object.name || _default;
  };
});

// This call succeeds because both LibA and LibB are defined
namespace.define('PetersModule', ['LibA', 'LibB'], function(namespace, LibA, LibB) {
  // This function depends on both LibA and LibB
  this.sayHelloToObject = function(object) {
    return LibA.sayHello(LibB.getObjectName(object, 'Anonymous'));
  };
});

console.log(namespace.PetersModule.sayHelloToObject({name : 'Peter'}))

<commit_msg>Update 'test suite'.<commit_after>var Namespace = function() {
  var Namespace = this;

  // Global settings accessible to all objects.
  Namespace.global = {};
  // A helper function for adding multiple settings to the global namespace.
  // Example usage:
  //
  //  > var namespace = new Namespace();
  //  > namespace.updateGlobal({
  //  >   name: 'Peter',
  //  >   age: 19,
  //  >   useful: true})
  //
  //  settings: an object of key => value to set on namespace.global.
  //
  //  overrideProtect: if truthy, will throw an exeption if setting
  //  a key that has already been set.
  Namespace.updateGlobal = function(settings, overrideProtect) {
    var overrideProtect = !!overrideProtect;
    for (var key in settings) {
      if (Object.hasOwnProperty.call(settings, key)) {
        var value = settings[key];
        if (overrideProtect && Namespace.global[key] !== undefined) {
          throw "Already defined: " + key + " => " + Namespace.global[key];
        }
        Namespace.global[key] = value;
      }
    }
  };

  // A helper function for resolving a dotted name, useful for checking
  // properties on nested namespaces or modules. Example usage:
  //
  //  > var namespace = new Namespace();
  //  > if (namespace.get('Math.Trigonometry') {
  //  >   namespace.Math.Trigonomety.cos(2 * Math.PI);
  //  > }
  //
  //  dottedName: a string of dotted paths to resolve.
  //
  //  defaultValue: the value returned if the full resolution fails at any
  //  point. Defaults to undefined.
  Namespace.get = function(dottedName, defaultValue) {
    var names = dottedName.split('.');
    var current = this;
    try {
      for (var i = 0; i < names.length; i++) {
        current = current[names[i]];
        if (current === undefined) {
          return defaultValue;
        }
      }
      return current;
    } catch (exception) {
      return defaultValue;
    }
  };

  // A helper function for determining whether or not a dotted name has been
  // defined. Example usage:
  //
  //  > var namespace = new Namespace();
  //  > namespace.global
  //  {}
  //  > namespace.global.age = 12;
  //  12
  //  > namespace.exists('global.age')
  //  true
  //  > namespace.exists('TestModule')
  //  false
  //  > namespace.define([], 'TestModule', function() {})
  //  > namespace.exists('TestModule')
  //  true
  //
  //  dottedName: a string of dotted paths to resolve.
  Namespace.exists = function(dottedName) {
    return Namespace.get(dottedName, undefined) !== undefined;
  };

  Namespace.require = function(dottedName) {
    var value = Namespace.get(dottedName, undefined);
    if (value === undefined) {
      throw "required value ('" + dottedName + "') not defined";
    }
    return value;
  }

  // A helper function to add modules to the current namespace. For example,
  //
  //  > var namespace = new Namespace();
  //  > namespace.define('Widget.Core', myfunc{...}, [arg1val, arg2val]);
  //
  // will set namespace.Widget.Core to {} if it doesn't exist and run
  //
  //  > myfunc.apply(namespace.Widget.Core, [namespace, arg1val, arg2val]):
  //
  // moduleDefinition: must be a Function. It must not set any attributes on
  // the Namespace object. The first argument to the definition will be this
  // global Namespace object.
  //
  // moduleArguments: must either be an Array or a falsy value or omitted.
  //
  // dottedName: must not begin or end with a '.', and the first part of the
  // must not be 'global', 'updateGlobal', 'require', 'exists', 'define', or
  // 'get'.
  Namespace.define = function(
      dottedName, dependencyNames, moduleDefinition, moduleArguments) {
    // Resolve dependencies before doing any sort of definition. If any of the
    // dependencies is undefined, throw an error instead of defining the
    // module.
    var dependencies = [];
    dependencyNames = dependencyNames || [];
    for (var i = 0; i < dependencyNames.length; i++) {
      var dependencyName = dependencyNames[i];
      var dependency = Namespace.get(dependencyName, undefined);
      if (dependency === undefined) {
        throw "Dependencies not met: '" + dependencyName + "' not defined";
      }
      dependencies.push(dependency);
    }

    var names = dottedName.split('.');
    // The module name is the last part of the dotted name.
    var moduleName = names.pop();
    // The first argument to every module definition is the global Namespace
    // object. This is followed by any dependencies, then any module arguments.
    moduleArguments = dependencies.concat(moduleArguments || []);
    moduleArguments.unshift(Namespace);
    // Define the module in the correct namespace, traversing the dotted names
    // until there are no more.
    var namespace = this;
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      namespace = namespace[name] = namespace[name] || {};
    };
    if (namespace[moduleName]) {
      throw "Cannot define '" + dottedName + "' (already exists)";
    }
    var module = namespace[moduleName] = {};
    moduleDefinition.apply(module, moduleArguments);
  };
};

// A very hacky "test suite" -- run this file with node to see if these tests
// pass.

var exports;
if (exports) {
  exports.Namespace = Namespace;
}

var ns = new Namespace();
if (ns.exists('global.age')) throw "Broken exists";

ns.updateGlobal({
  name: 'Peter',
  age: 19
})
if (!(ns.exists('global.age'))) throw "Broken exists";
if (!(ns.get('global.name') === 'Peter')) throw "Broken get";
if (!(ns.get('global.undefined', 'default') === 'default')) throw "Broken get";

ns.define('TestModule', [], function() {this.Helpers = true;});
var outer_ns = ns;
ns.define('PeterModule', ['TestModule.Helpers'], function(ns, Helpers) {
  if (ns !== outer_ns) throw "Broken define";
  if (Helpers !== outer_ns.TestModule.Helpers) throw "Broken define";
  console.log('arguments:', arguments);
  var x = 12;
  this.getX = function() {
    return x;
  }
});

if (!ns.get('PeterModule').getX() === 12) throw "Broken define/get";

ns.define('LibA', [], function(namespace) {
  this.sayHello = function(name) {
    return 'Hello ' + name;
  };
});

// This call fails because LibB is not defined.
try {
  ns.define('PetersModule', ['LibA', 'LibB'], function(namespace, LibA, LibB) {
    // This function depends on both LibA and LibB
    this.sayHelloToObject = function(object) {
      return LibA.sayHello(LibB.getObjectName(object, 'Anonymous'));
    };
  });
} catch (exception) {
  console.log('caught expected exception:', exception);
}

ns.define('LibB', [], function(namespace) {
  this.getObjectName = function(object, _default) {
    return object.name || _default;
  };
});

// This call succeeds because both LibA and LibB are defined
ns.define('PetersModule', ['LibA', 'LibB'], function(namespace, LibA, LibB) {
  // This function depends on both LibA and LibB
  this.sayHelloToObject = function(object) {
    return LibA.sayHello(LibB.getObjectName(object, 'Anonymous'));
  };
});

console.log(ns.PetersModule.sayHelloToObject({name : 'Peter'}))

console.log("All tests pass.");

<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ['error', {'devDependencies': true}] */
import webpack from 'webpack';
import {getIfUtils, removeEmpty} from 'webpack-config-utils';
import AssetsPlugin from 'assets-webpack-plugin';
import Visualizer from 'webpack-visualizer-plugin';
import CleanPlugin from 'clean-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';

export default function (env) {
  const {ifDevelopment, ifProduction} = getIfUtils(env);
  const assetsPath = path.resolve(__dirname, './lib');
  const defaultChunks = ['vendor', 'manifest'];

  return {
    devtool: ifDevelopment('eval-source-map', 'source-map'),
    entry: {
      'example/index': './src/example',
      'component-library/index': './src/component-library',
      'continuous-deployment/index': './src/continuous-deployment',
      'continuous-deployment-dsmjs-june-2017/index': './src/continuous-deployment-dsmjs-june-2017',
      vendor: removeEmpty([
        // ifDevelopment('webpack-hot-middleware/client'),
        'react',
        'react-dom',
        'spectacle'
      ])
    },
    output: {
      path: assetsPath,
      filename: ifProduction('[name]-[chunkhash].js', '[name].js'),
      publicPath: '/'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            presets: [['es2015', {modules: false}], 'react'],
            plugins: removeEmpty([
              ifProduction('transform-react-remove-prop-types'),
              ifDevelopment('transform-react-jsx-source'),
              'transform-runtime'
            ]),
            comments: false,
            cacheDirectory: true
          }
        },
        {
          test: /\.example$/,
          use: 'raw-loader'
        },
        {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                limit: 8192,
                publicPath: '..//'
              }
            },
            {
              loader: 'img-loader',
              options: {
                progressive: true
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
        },
        {
          test: /\.mustache$/,
          loader: 'mustache-loader'
        }
      ]
    },
    plugins: removeEmpty([
      ifProduction(new CleanPlugin([assetsPath], {root: __dirname})),
      // ifDevelopment(new webpack.HotModuleReplacementPlugin()),
      ifDevelopment(new webpack.NamedModulesPlugin()),
      ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
      new AssetsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(env)
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: defaultChunks
      }),
      ifProduction(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      })),
      ifProduction(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true,
          warnings: false
        }
      })),
      ifProduction(new Visualizer()),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'example/index'],
        filename: 'example/index.html',
        template: 'src/index.mustache',
        title: 'Example'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'continuous-deployment/index'],
        filename: 'continuous-deployment/index.html',
        template: 'src/index.mustache',
        title: 'Continuous Deployment'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'continuous-deployment-dsmjs-june-2017/index'],
        filename: 'continuous-deployment-dsmjs-june-2017/index.html',
        template: 'src/index.mustache',
        title: 'Continuous Deployment'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'component-library/index'],
        filename: 'component-library/index.html',
        template: 'src/index.mustache',
        title: 'Component Library'
      })
    ])
  };
}
<commit_msg>feat(component-library): added the build config that actually deploys the pinned version<commit_after>/* eslint import/no-extraneous-dependencies: ['error', {'devDependencies': true}] */
import webpack from 'webpack';
import {getIfUtils, removeEmpty} from 'webpack-config-utils';
import AssetsPlugin from 'assets-webpack-plugin';
import Visualizer from 'webpack-visualizer-plugin';
import CleanPlugin from 'clean-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';

export default function (env) {
  const {ifDevelopment, ifProduction} = getIfUtils(env);
  const assetsPath = path.resolve(__dirname, './lib');
  const defaultChunks = ['vendor', 'manifest'];

  return {
    devtool: ifDevelopment('eval-source-map', 'source-map'),
    entry: {
      'example/index': './src/example',
      'component-library/index': './src/component-library',
      'component-library-dsmjs-july-2016/index': './src/component-library-dsmjs-july-2016',
      'continuous-deployment/index': './src/continuous-deployment',
      'continuous-deployment-dsmjs-june-2017/index': './src/continuous-deployment-dsmjs-june-2017',
      vendor: removeEmpty([
        // ifDevelopment('webpack-hot-middleware/client'),
        'react',
        'react-dom',
        'spectacle'
      ])
    },
    output: {
      path: assetsPath,
      filename: ifProduction('[name]-[chunkhash].js', '[name].js'),
      publicPath: '/'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            presets: [['es2015', {modules: false}], 'react'],
            plugins: removeEmpty([
              ifProduction('transform-react-remove-prop-types'),
              ifDevelopment('transform-react-jsx-source'),
              'transform-runtime'
            ]),
            comments: false,
            cacheDirectory: true
          }
        },
        {
          test: /\.example$/,
          use: 'raw-loader'
        },
        {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                limit: 8192,
                publicPath: '..//'
              }
            },
            {
              loader: 'img-loader',
              options: {
                progressive: true
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
        },
        {
          test: /\.mustache$/,
          loader: 'mustache-loader'
        }
      ]
    },
    plugins: removeEmpty([
      ifProduction(new CleanPlugin([assetsPath], {root: __dirname})),
      // ifDevelopment(new webpack.HotModuleReplacementPlugin()),
      ifDevelopment(new webpack.NamedModulesPlugin()),
      ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
      new AssetsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(env)
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: defaultChunks
      }),
      ifProduction(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      })),
      ifProduction(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true,
          warnings: false
        }
      })),
      ifProduction(new Visualizer()),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'example/index'],
        filename: 'example/index.html',
        template: 'src/index.mustache',
        title: 'Example'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'continuous-deployment/index'],
        filename: 'continuous-deployment/index.html',
        template: 'src/index.mustache',
        title: 'Continuous Deployment'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'continuous-deployment-dsmjs-june-2017/index'],
        filename: 'continuous-deployment-dsmjs-june-2017/index.html',
        template: 'src/index.mustache',
        title: 'Continuous Deployment'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'component-library/index'],
        filename: 'component-library/index.html',
        template: 'src/index.mustache',
        title: 'Component Library'
      }),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'component-library-dsmjs-july-2016/index'],
        filename: 'component-library-dsmjs-july-2016/index.html',
        template: 'src/index.mustache',
        title: 'Component Library'
      })
    ])
  };
}
<|endoftext|>


<commit_before>'use strict';
// var app = angular.module('MobileAngularUiExamples');
angular.module('MobileAngularUiExamples').controller('login', function ($scope, $location) {
  $scope.signInGoogle = function ($location) {
    console.log('signin google');

    var google = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithPopup(google).then(function () {
      console.log('login : ' + firebase.auth().currentUser);
      // window.location.replace("/youyou/#/nickname");
      $location.path("nickname");
    });

  };
  $scope.signInFacebook = function ($location) {
    console.log('signin facebook');
    var facebook = new firebase.auth.FacebookAuthProvider();
    firebase.auth().signInWithPopup(facebook).then(function () {
      console.log('login : ' + firebase.auth().currentUser);
      // window.location.replace("/youyou/#/nickname");
      $location.path("nickname");
    });
  };
});

angular.module('MobileAngularUiExamples').controller('nickname', function ($scope, $location) {
});

<commit_msg>login 후 페이지 이동이 안되고 있던거 고침 apply 스코프 안에 넣어야 변경 바로 적용됨<commit_after>'use strict';
// var app = angular.module('MobileAngularUiExamples');
var app = angular.module('MobileAngularUiExamples');
app.controller('login', function ($scope, $location) {
  $scope.signInGoogle = function () {
    console.log('signin google');

    var google = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithPopup(google).then(function () {
      console.log('login : ' + firebase.auth().currentUser);
      // window.location.replace("/youyou/#/nickname");
      pageChange();
    });

  };
  $scope.signInFacebook = function () {
    console.log('signin facebook');
    var facebook = new firebase.auth.FacebookAuthProvider();
    firebase.auth().signInWithPopup(facebook).then(function () {
      console.log('login : ' + firebase.auth().currentUser);
      // window.location.replace("/youyou/#/nickname");
      pageChange()
    });
  };

  var pageChange = function () {
    $scope.$apply(function () {
      $location.path("nickname");
    });
  }
});

angular.module('MobileAngularUiExamples').controller('nickname', function ($scope, $location) {
});

<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const chalk = require('chalk');

/** @type {string[]} */
const blockMany = [
  'chrome',
  'chrome_android',
  'edge',
  'firefox',
  'firefox_android',
  'ie',
  'opera',
  'opera_android',
  'safari',
  'safari_ios',
  'webview_android'
];

/** @type {Record<string, string[]>} */
const blockList = {
  api: [],
  css: ['edge', 'firefox', 'firefox_android', 'ie'],
  html: [],
  http: [],
  svg: [],
  javascript: ['firefox', 'firefox_android'],
  mathml: blockMany,
  webdriver: blockMany.concat(['samsunginternet_android']),
  webextensions: [],
  xpath: [],
  xslt: []
};

/**
 * @param {SupportBlock} supportData
 * @param {string[]} blockList
 * @param {string} relPath
 * @param {{error:function(...unknown):void}} logger
 */
function checkRealValues(supportData, blockList, relPath, logger) {
  let hasErrors = false;
  for (const browser of blockList) {
    /** @type {SimpleSupportStatement[]} */
    const supportStatements = [];
    if (Array.isArray(supportData[browser])) {
      Array.prototype.push.apply(supportStatements, supportData[browser]);
    } else {
      supportStatements.push(supportData[browser]);
    }

    for (const statement of supportStatements) {
      if (statement === undefined) {
        logger.error(chalk`{red {bold ${browser}} must be defined for {bold ${relPath}}`);
          hasErrors = true;
      } else {
        if ([true, null].includes(statement.version_added)) {
          logger.error(chalk`{red {bold ${relPath}} - {bold ${browser}} no longer accepts {bold ${statement.version_added}} as a value}`);
          hasErrors = true;
        }
        if ([true, null].includes(statement.version_removed)) {
          logger.error(chalk`{red {bold ${relPath}} - {bold ${browser}} no longer accepts} {bold ${statement.version_removed}} as a value}`);
          hasErrors = true;
        }
      }
    }
  }

  return hasErrors;
}

/**
 * @param {string} filename
 */
function testRealValues(filename) {
  const relativePath = path.relative(path.resolve(__dirname, '..'), filename);
  const category = relativePath.includes(path.sep) && relativePath.split(path.sep)[0];
  /** @type {Identifier} */
  const data = require(filename);

  /** @type {string[]} */
  const errors = [];
  const logger = {
    /** @param {...unknown} message */
    error: (...message) => {
      errors.push(message.join(' '));
    },
  };

  /**
   * @param {Identifier} data
   * @param {string} relPath
   */
  function findSupport(data, relPath) {
    for (const prop in data) {
      if (prop === '__compat' && data[prop].support) {
        if (blockList[category] && blockList[category].length > 0) checkRealValues(data[prop].support, blockList[category], relPath, logger);
      }
      const sub = data[prop];
      if (typeof sub === 'object') {
        findSupport(sub, relPath ? `${relPath}.${prop}` : `${prop}`);
      }
    }
  }
  findSupport(data);

  if (errors.length) {
    console.error(chalk`{red   Real values – {bold ${errors.length}} ${errors.length === 1 ? 'error' : 'errors'}:}`);
    for (const error of errors) {
      console.error(`    ${error}`);
    }
    return true;
  }
  return false;
}

module.exports = testRealValues;
<commit_msg>test(real‑values): Fix broken chalk tagged template literal call (#4480)<commit_after>'use strict';
const path = require('path');
const chalk = require('chalk');

/** @type {string[]} */
const blockMany = [
  'chrome',
  'chrome_android',
  'edge',
  'firefox',
  'firefox_android',
  'ie',
  'opera',
  'opera_android',
  'safari',
  'safari_ios',
  'webview_android'
];

/** @type {Record<string, string[]>} */
const blockList = {
  api: [],
  css: ['edge', 'firefox', 'firefox_android', 'ie'],
  html: [],
  http: [],
  svg: [],
  javascript: ['firefox', 'firefox_android'],
  mathml: blockMany,
  webdriver: blockMany.concat(['samsunginternet_android']),
  webextensions: [],
  xpath: [],
  xslt: []
};

/**
 * @param {SupportBlock} supportData
 * @param {string[]} blockList
 * @param {string} relPath
 * @param {{error:function(...unknown):void}} logger
 */
function checkRealValues(supportData, blockList, relPath, logger) {
  let hasErrors = false;
  for (const browser of blockList) {
    /** @type {SimpleSupportStatement[]} */
    const supportStatements = [];
    if (Array.isArray(supportData[browser])) {
      Array.prototype.push.apply(supportStatements, supportData[browser]);
    } else {
      supportStatements.push(supportData[browser]);
    }

    for (const statement of supportStatements) {
      if (statement === undefined) {
        logger.error(chalk`{red {bold ${browser}} must be defined for {bold ${relPath}}}`);
          hasErrors = true;
      } else {
        if ([true, null].includes(statement.version_added)) {
          logger.error(chalk`{red {bold ${relPath}} - {bold ${browser}} no longer accepts {bold ${statement.version_added}} as a value}`);
          hasErrors = true;
        }
        if ([true, null].includes(statement.version_removed)) {
          logger.error(chalk`{red {bold ${relPath}} - {bold ${browser}} no longer accepts} {bold ${statement.version_removed}} as a value}`);
          hasErrors = true;
        }
      }
    }
  }

  return hasErrors;
}

/**
 * @param {string} filename
 */
function testRealValues(filename) {
  const relativePath = path.relative(path.resolve(__dirname, '..'), filename);
  const category = relativePath.includes(path.sep) && relativePath.split(path.sep)[0];
  /** @type {Identifier} */
  const data = require(filename);

  /** @type {string[]} */
  const errors = [];
  const logger = {
    /** @param {...unknown} message */
    error: (...message) => {
      errors.push(message.join(' '));
    },
  };

  /**
   * @param {Identifier} data
   * @param {string} relPath
   */
  function findSupport(data, relPath) {
    for (const prop in data) {
      if (prop === '__compat' && data[prop].support) {
        if (blockList[category] && blockList[category].length > 0) checkRealValues(data[prop].support, blockList[category], relPath, logger);
      }
      const sub = data[prop];
      if (typeof sub === 'object') {
        findSupport(sub, relPath ? `${relPath}.${prop}` : `${prop}`);
      }
    }
  }
  findSupport(data);

  if (errors.length) {
    console.error(chalk`{red   Real values – {bold ${errors.length}} ${errors.length === 1 ? 'error' : 'errors'}:}`);
    for (const error of errors) {
      console.error(`    ${error}`);
    }
    return true;
  }
  return false;
}

module.exports = testRealValues;
<|endoftext|>


<commit_before>import React from 'react';
import { PropTypes as T } from 'prop-types';
import styled from 'styled-components';
import LoadingMessage from '../../components/loading-message';
import Card from '../../components/card';
import Table from '../../components/table';
import { shortenLargeNumber } from '../../utils/format';

const initData = {
  pollutant: {
    values: [],
    formatHeader: v => v.toUpperCase(),
    style: {
      color: 'black',
      fontWeight: 700,
    },
  },
  avg: {
    values: [],
    formatHeader: v => v.toUpperCase(),
    formatCell: shortenLargeNumber,
    style: {
      textAlign: 'center',
    },
  },
  count: {
    values: [],
    formatHeader: v => v.toUpperCase(),
    formatCell: shortenLargeNumber,
    style: {
      textAlign: 'center',
    },
  },
};

const StyledLoading = styled(LoadingMessage)`
  grid-column: 1 / 7;
`;
const ErrorMessage = styled.div`
  grid-column: 1 / 7;
`;

// TODO This function currently just extracts the first data available for each pollutant
const prepareData = data => {
  const combinedData = data.reduce((accum, datum) => {
    const { parameter, measurement_count, average } = datum;
    if (!accum[parameter]) {
      accum[parameter] = {
        count: measurement_count,
        value: average,
      };
    }
    return accum;
  }, {});

  const preparedData = Object.entries(combinedData).reduce(
    (acc, [pollutant, stats]) => {
      acc = {
        pollutant: {
          ...acc.pollutant,
          values: [...acc.pollutant.values, pollutant],
        },
        avg: {
          ...acc.avg,
          values: [...acc.count.values, stats.value],
        },
        count: {
          ...acc.count,
          values: [...acc.count.values, stats.count],
        },
      };
      return acc;
    },
    initData
  );
  return preparedData;
};
export default function Averages({ measurements }) {
  const { fetched, fetching, error, data } = measurements;

  if (!fetched && !fetching) {
    return null;
  } else if (fetching) {
    return


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

function testErrorMessage(error, stdout, stderr, option) {
  stdout.should.be.exactly('');
  should.exist(error.message);
  if ( option === 'noOption') {
    error.message.should.be.exactly('Command failed: node index.js\nPlease enter searh terms. "googleit <terms>"\n');
  } else {
    error.message.should.be.exactly('Command failed: node index.js -' + option + '\nPlease enter searh terms. "googleit <terms>"\n');
  }
}

var exec = require('child_process').exec;
var cmd = 'node index.js';

exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'noOption');
})
<commit_msg>Add test for options<commit_after>var should = require('should');

function testErrorMessage(error, stdout, stderr, option) {
  stdout.should.be.exactly('');
  should.exist(error.message);
  if ( option === 'noOption') {
    error.message.should.be.exactly('Command failed: node index.js\nPlease enter searh terms. "googleit <terms>"\n');
  } else {
    error.message.should.be.exactly('Command failed: node index.js -' + option + '\nPlease enter searh terms. "googleit <terms>"\n');
  }
}

var exec = require('child_process').exec;
var cmd = 'node index.js';

exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'noOption');
})

// Test option provided but no argument
// Options
// program
//   .option('-i, --image', 'Search Image on Google')
//   .option('-n, --news', 'Search News on Google')
//   .option('-v, --video', 'Search Video on Google')
//   .option('-p, --patent', 'Search Patent on Google')
//   .option('-b, --book', 'Search Book on Google')
var cmd = 'node index.js -i';
exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'i');
})

var cmd = 'node index.js -n';
exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'n');
})

var cmd = 'node index.js -v';
exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'v');
})

var cmd = 'node index.js -p';
exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'p');
})

var cmd = 'node index.js -b';
exec(cmd, function(error, stdout, stderr) {
  testErrorMessage(error, stdout, stderr, 'b');
})
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';

const destDir = path.join(__dirname, 'admin', 'public', 'js');

const proxyLoader = {
	// Auto-chunk Fields for dynamic loading
	// We cannot chunk Filter due to .getDefaultValue()
	test: /fields(\/|\\).*(Field|Column)\.jsx?$/i,
	loader: 'react-proxy',
	exclude: [
		// The field decorator
		path.join(__dirname, 'fields', 'types', 'Field.js'),
		// Fields using the Array mixin (doesn't like proxy)
		/Array/,
	],
};
const babelLoader = {
	test: /\.jsx?$/,
	loader: 'babel',
	include: [__dirname],
	exclude: [
		path.join(__dirname, 'node_modules'),
		destDir,
	],
};

const getBase = ({ adminPath = '/keystone', entry } = {}) => {
	return {
		entry: entry || {
			admin: `${__dirname}/admin/client/App`,
			signin: `${__dirname}/admin/client/Signin`,
		},
		// https://webpack.github.io/docs/configuration.html#devtool
		devtool: 'eval',
		output: {
			path: destDir,
			publicPath: `${adminPath}/js/`,
			pathinfo: true,
			filename: '[name].js',
			chunkFilename: '[id].js',
			sourceMapFilename: '[file].map',
		},
		module: {
			loaders: [
				proxyLoader,
				babelLoader,
				{ test: /\.css$/, loaders: ['style', 'css'] },
				{ test: /\.json$/, loader: 'json' },
				{ test: /\.md$/, loader: 'raw' },
			],
		},
		// Externally loaded dependencies
		externals: {
			jquery: 'jQuery',
			tinymce: 'tinymce',
		},
		plugins: [
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(process.env.NODE_ENV),
				},
			}),
			// Only bundle locales we use with moment
			new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
			new webpack.optimize.CommonsChunkPlugin('common', 'common.js'),
			// Provide consistent build hashes
			new webpack.optimize.OccurenceOrderPlugin(),
		],
	};
};

export const getDev = (options) => getBase(options);

export const getProd = (options) => {
	const base = getBase(options);
	return {
		...base,
		// Not sure if useful, gets quite big
		// devtool: 'source-map',
		devtool: undefined,
		output: {
			...base.output,
			pathinfo: false,
		},
		plugins: [
			...base.plugins,
			// TODO doesn't do anything right now
			new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 14000 }),
			new webpack.optimize.UglifyJsPlugin({
				compress: {
					// Comment this if you want to verify the uglification
					warnings: false,
				},
				output: {
					screw_ie8: true,
					semicolons: false,
				},
			}),
			new webpack.optimize.DedupePlugin(),
		],
	};
};

export const getHot = (options = {}) => {
	const { adminPath = '/keystone' } = options;
	const hmrPath = `${adminPath}/__webpack_hmr`.replace('//', '/');
	const hotStuff = [
		'react-hot-loader/patch',
		`webpack-hot-middleware/client?path=${hmrPath}`,
	];
	const base = getBase(options);
	const entry = {};
	// Prepend hot entry code
	for (const name of Object.keys(base.entry)) {
		entry[name] = [...hotStuff, base.entry[name]];
	}
	// Strip off the react-proxy-loader and change the react loader
	const loaders = base.module.loaders
	.filter(l => l !== proxyLoader)
	.map(l => l === babelLoader ? ({
		...babelLoader,
		query: {
			plugins: 'react-hot-loader/babel',
		},
	}) : l)
	;
	return {
		...base,
		entry,
		module: {
			...base.module,
			loaders,
		},
		plugins: [
			...base.plugins,
			// hot-reload infrastructure
			new webpack.HotModuleReplacementPlugin(),
			// show names instead of module numbers
			new webpack.NamedModulesPlugin(),
		],
	};
};

const getConfig = (process.env.NODE_ENV === 'production') ? getProd : getDev;
export default getConfig();
<commit_msg>Webpack: merge small chunks<commit_after>import path from 'path';
import webpack from 'webpack';

const destDir = path.join(__dirname, 'admin', 'public', 'js');

const proxyLoader = {
	// Auto-chunk Fields for dynamic loading
	// We cannot chunk Filter due to .getDefaultValue()
	test: /fields(\/|\\).*(Field|Column)\.jsx?$/i,
	loader: 'react-proxy',
	exclude: [
		// The field decorator
		path.join(__dirname, 'fields', 'types', 'Field.js'),
		// Fields using the Array mixin (doesn't like proxy)
		/Array/,
	],
};
const babelLoader = {
	test: /\.jsx?$/,
	loader: 'babel',
	include: [__dirname],
	exclude: [
		path.join(__dirname, 'node_modules'),
		destDir,
	],
};

const getBase = ({ adminPath = '/keystone', entry } = {}) => {
	return {
		entry: entry || {
			admin: `${__dirname}/admin/client/App`,
			signin: `${__dirname}/admin/client/Signin`,
		},
		// https://webpack.github.io/docs/configuration.html#devtool
		devtool: 'eval',
		output: {
			path: destDir,
			publicPath: `${adminPath}/js/`,
			pathinfo: true,
			filename: '[name].js',
			chunkFilename: '[id].js',
			sourceMapFilename: '[file].map',
		},
		module: {
			loaders: [
				proxyLoader,
				babelLoader,
				{ test: /\.css$/, loaders: ['style', 'css'] },
				{ test: /\.json$/, loader: 'json' },
				{ test: /\.md$/, loader: 'raw' },
			],
		},
		// Externally loaded dependencies
		externals: {
			jquery: 'jQuery',
			tinymce: 'tinymce',
		},
		plugins: [
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(process.env.NODE_ENV),
				},
			}),
			// Only bundle locales we use with moment
			new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
			new webpack.optimize.CommonsChunkPlugin('common', 'common.js'),
			// Provide consistent build hashes
			new webpack.optimize.OccurenceOrderPlugin(),
		],
	};
};

export const getDev = (options) => getBase(options);

export const getProd = (options) => {
	const base = getBase(options);
	return {
		...base,
		// Not sure if useful, gets quite big
		// devtool: 'source-map',
		devtool: undefined,
		output: {
			...base.output,
			pathinfo: false,
		},
		plugins: [
			...base.plugins,
			new webpack.optimize.AggressiveMergingPlugin({ minSizeReduce: 1.8 }),
			new webpack.optimize.UglifyJsPlugin({
				compress: {
					// Comment this if you want to verify the uglification
					warnings: false,
				},
				output: {
					screw_ie8: true,
					semicolons: false,
				},
			}),
			new webpack.optimize.DedupePlugin(),
		],
	};
};

export const getHot = (options = {}) => {
	const { adminPath = '/keystone' } = options;
	const hmrPath = `${adminPath}/__webpack_hmr`.replace('//', '/');
	const hotStuff = [
		'react-hot-loader/patch',
		`webpack-hot-middleware/client?path=${hmrPath}`,
	];
	const base = getBase(options);
	const entry = {};
	// Prepend hot entry code
	for (const name of Object.keys(base.entry)) {
		entry[name] = [...hotStuff, base.entry[name]];
	}
	// Strip off the react-proxy-loader and change the react loader
	const loaders = base.module.loaders
	.filter(l => l !== proxyLoader)
	.map(l => l === babelLoader ? ({
		...babelLoader,
		query: {
			plugins: 'react-hot-loader/babel',
		},
	}) : l)
	;
	return {
		...base,
		entry,
		module: {
			...base.module,
			loaders,
		},
		plugins: [
			...base.plugins,
			// hot-reload infrastructure
			new webpack.HotModuleReplacementPlugin(),
			// show names instead of module numbers
			new webpack.NamedModulesPlugin(),
		],
	};
};

const getConfig = (process.env.NODE_ENV === 'production') ? getProd : getDev;
export default getConfig();
<|endoftext|>