<commit_before>"use strict";

var proxyTo = require('../common.js').proxyTo
  , _ = require('underscore')
  , logger = require('../../server/logger.js').get('appium')
  , exec = require('child_process').exec
  , spawn = require('child_process').spawn
  , async = require('async')
  , through = require('through')
  , isWindows = require('../../helpers.js').isWindows()
  , isLinux = require('../../helpers.js').isLinux()
  , path = require('path')
  , fs = require('fs');

var Chromedriver = function (args, onDie) {
  this.proxyHost = '127.0.0.1';
  this.proxyPort = args.port || 9515;
  this.deviceId = args.deviceId;
  this.enablePerformanceLogging = args.enablePerformanceLogging;
  this.proc = null;
  this.onChromedriverStart = null;
  this.onDie = onDie;
  this.exitCb = null;
  this.shuttingDown = false;

  this.initChromedriverPath(args);
};

Chromedriver.prototype.initChromedriverPath = function (args) {
  if (args.executable) {
    this.chromedriver = args.executable;
  } else {
    var executable = isWindows ? "chromedriver.exe" : "chromedriver";
    var platform = "mac";
    if (isWindows) {
      platform = "windows";
    } else if (isLinux) {
      platform = "linux";
    }
    this.chromedriver = path.resolve(__dirname, "..", "..", "..", "build", "chromedriver", platform, executable);
  }
};

Chromedriver.prototype.ensureChromedriverExists = function (cb) {
  logger.debug("Ensuring Chromedriver exists");
  fs.exists(this.chromedriver, function (exists) {
    if (!exists) return cb(new Error("Could not find chromedriver. Need to run reset script?"));
    cb();
  });
};

Chromedriver.prototype.killOldChromedrivers = function (cb) {
  var cmd;
  if (isWindows) {
    cmd = "FOR /F \"usebackq tokens=5\" %%a in (`netstat -nao ^| findstr /R /C:\"" + this.proxyPort + " \"`) do (" +
            "FOR /F \"usebackq\" %%b in (`TASKLIST /FI \"PID eq %%a\" ^| findstr /I chromedriver.exe`) do (" +
              "IF NOT %%b==\"\" TASKKILL /F /PID %%b" +
            ")" +
          ")";
  } else {
    cmd = "ps -e | grep " + this.chromedriver + " | grep -v grep |" +
      "grep -e '--port=" + this.proxyPort + "$' | awk '{ print $1 }' | " +
      "xargs kill -15";
  }
  logger.debug("Killing any old chromedrivers, running: " + cmd);
  exec(cmd, function (err) {
    if (err) {
      logger.debug("No old chromedrivers seemed to exist");
    } else {
      logger.debug("Successfully cleaned up old chromedrivers");
    }
    cb();
  });
};

Chromedriver.prototype.start = function (cb) {
  this.onChromedriverStart = cb;
  logger.debug("Spawning chromedriver with: " + this.chromedriver);
  var alreadyReturned = false;
  var args = ["--url-base=wd/hub", "--port=" + this.proxyPort];
  this.proc = spawn(this.chromedriver, args);
  this.proc.stdout.setEncoding('utf8');
  this.proc.stderr.setEncoding('utf8');

  this.proc.on('error', function (err) {
    logger.error('Chromedriver process failed with error: ' + err.message);
    alreadyReturned = true;
    this.shuttingDown = true;
    logger.error('Killing chromedriver');
    this.proc.kill();
    this.onDie();
  }.bind(this));

  this.proc.stdout.pipe(through(function (data) {
    logger.debug('[CHROMEDRIVER] ' + data.trim());
    if (!alreadyReturned && data.indexOf('Starting ') === 0) {
      this.chromedriverStarted = true;
      alreadyReturned = true;
      return cb();
    }
  }.bind(this)));

  this.proc.stderr.pipe(through(function (data) {
    logger.debug('[CHROMEDRIVER STDERR] ' + data.trim());
  }));

  this.proc.on('exit', this.onClose.bind(this));
  this.proc.on('close', this.onClose.bind(this));
};

Chromedriver.prototype.onClose = function (code, signal) {
  if (!this.shuttingDown) {
    this.shuttingDown = true;
    logger.debug("Chromedriver exited with code " + code);
    if (signal) {
      logger.debug("(killed by signal " + signal + ")");
    }
    if (!this.chromedriverStarted) {
      return this.onChromedriverStart(
          new Error("Chromedriver quit before it was available"));
    }
    if (this.exitCb !== null) {
      return this.exitCb();
    }
    this.onDie();
  }
};

Chromedriver.prototype.createSession = function (caps, cb) {
  logger.debug("Creating Chrome session");
  caps.chromeOptions.androidDeviceSerial = this.deviceId;
  if (this.enablePerformanceLogging) {
    caps.loggingPrefs = {performance: 'ALL'};
  }
  var data = {
    sessionId: null,
    desiredCapabilities: caps
  };
  async.waterfall([
    this.ensureChromedriverExists.bind(this),
    this.killOldChromedrivers.bind(this),
    this.start.bind(this),
    _.partial(this.proxyNewSession.bind(this), data)
  ], cb);
};

Chromedriver.prototype.proxyNewSession = function (data, cb) {
  var maxRetries = 5;
  var curRetry = 0;
  var retryInt = 500;
  var doProxy = function (alreadyRestarted) {
    this.proxyTo('/wd/hub/session', 'POST', data, function (err, res, body) {
      if (err) {
        if (/ECONNREFUSED/.test(err.message) && curRetry < maxRetries) {
          logger.debug("Could not connect yet; retrying");
          curRetry++;
          setTimeout(doProxy, retryInt);
          return;
        }
        return cb(err);
      }

      // first checking if we get a well formed success response
      this.chromeSessionId = null;
      try {
        if (body.status === 0 && body.sessionId) {
          logger.debug("Successfully started chrome session");
          this.chromeSessionId = body.sessionId;
        }
      } catch (ignore) {}
      if (this.chromeSessionId) return cb(null, this.chromeSessionId);

      // then check redirect success case
      try {
        if (res.statusCode === 303 && res.headers.location) {
          logger.debug("Successfully started chrome session");
          var loc = res.headers.location;
          this.chromeSessionId = /\/([^\/]+)$/.exec(loc)[1];
        }
      } catch (ignore) {}
      if (this.chromeSessionId) return cb(null, this.chromeSessionId);

      // those are error cases
      if (typeof body !== "undefined" &&
                 typeof body.value !== "undefined" &&
                 typeof body.value.message !== "undefined" &&
                 body.value.message.indexOf("Failed to run adb command") !== -1) {
        logger.error("Chromedriver had trouble running adb");
        if (!alreadyRestarted) {
          logger.error("Restarting adb for chromedriver");
          return this.adb.restartAdb(function () {
            this.adb.getConnectedDevices(function () {
              doProxy(true);
            }.bind(this));
          }.bind(this));
        } else {
          cb(new Error("Chromedriver wasn't able to use adb. Is the server up?"));
        }
      } else {
        logger.error("Chromedriver create session did not work. Status was " +
                     res.statusCode + " and body was " +
                     JSON.stringify(body));
        cb(new Error("Did not get session redirect from Chromedriver"));
      }
    }.bind(this));
  }.bind(this);

  doProxy();
};

Chromedriver.prototype.deleteSession = function (cb) {
  logger.debug("Deleting Chrome session");
  var url = '/wd/hub/session/' + this.chromeSessionId;
  this.proxyTo(url, 'DELETE', null, function (err, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb(new Error("Status was not 200"));
    cb();
  }.bind(this));
};

Chromedriver.prototype.stop = function (cb) {
  logger.debug('Killing chromedriver');
  this.exitCb = cb;
  this.proc.kill();
};

Chromedriver.prototype.proxyTo = proxyTo;

module.exports = Chromedriver;
<commit_msg>ps in kill chromedriver added -f switch and moved awk to  since pid will be second for linux and mac<commit_after>"use strict";

var proxyTo = require('../common.js').proxyTo
  , _ = require('underscore')
  , logger = require('../../server/logger.js').get('appium')
  , exec = require('child_process').exec
  , spawn = require('child_process').spawn
  , async = require('async')
  , through = require('through')
  , isWindows = require('../../helpers.js').isWindows()
  , isLinux = require('../../helpers.js').isLinux()
  , path = require('path')
  , fs = require('fs');

var Chromedriver = function (args, onDie) {
  this.proxyHost = '127.0.0.1';
  this.proxyPort = args.port || 9515;
  this.deviceId = args.deviceId;
  this.enablePerformanceLogging = args.enablePerformanceLogging;
  this.proc = null;
  this.onChromedriverStart = null;
  this.onDie = onDie;
  this.exitCb = null;
  this.shuttingDown = false;

  this.initChromedriverPath(args);
};

Chromedriver.prototype.initChromedriverPath = function (args) {
  if (args.executable) {
    this.chromedriver = args.executable;
  } else {
    var executable = isWindows ? "chromedriver.exe" : "chromedriver";
    var platform = "mac";
    if (isWindows) {
      platform = "windows";
    } else if (isLinux) {
      platform = "linux";
    }
    this.chromedriver = path.resolve(__dirname, "..", "..", "..", "build", "chromedriver", platform, executable);
  }
};

Chromedriver.prototype.ensureChromedriverExists = function (cb) {
  logger.debug("Ensuring Chromedriver exists");
  fs.exists(this.chromedriver, function (exists) {
    if (!exists) return cb(new Error("Could not find chromedriver. Need to run reset script?"));
    cb();
  });
};

Chromedriver.prototype.killOldChromedrivers = function (cb) {
  var cmd;
  if (isWindows) {
    cmd = "FOR /F \"usebackq tokens=5\" %%a in (`netstat -nao ^| findstr /R /C:\"" + this.proxyPort + " \"`) do (" +
            "FOR /F \"usebackq\" %%b in (`TASKLIST /FI \"PID eq %%a\" ^| findstr /I chromedriver.exe`) do (" +
              "IF NOT %%b==\"\" TASKKILL /F /PID %%b" +
            ")" +
          ")";
  } else {
    cmd = "ps -ef | grep " + this.chromedriver + " | grep -v grep |" +
      "grep -e '--port=" + this.proxyPort + "$' | awk '{ print $2 }' | " +
      "xargs kill -15";
  }
  logger.debug("Killing any old chromedrivers, running: " + cmd);
  exec(cmd, function (err) {
    if (err) {
      logger.debug("No old chromedrivers seemed to exist");
    } else {
      logger.debug("Successfully cleaned up old chromedrivers");
    }
    cb();
  });
};

Chromedriver.prototype.start = function (cb) {
  this.onChromedriverStart = cb;
  logger.debug("Spawning chromedriver with: " + this.chromedriver);
  var alreadyReturned = false;
  var args = ["--url-base=wd/hub", "--port=" + this.proxyPort];
  this.proc = spawn(this.chromedriver, args);
  this.proc.stdout.setEncoding('utf8');
  this.proc.stderr.setEncoding('utf8');

  this.proc.on('error', function (err) {
    logger.error('Chromedriver process failed with error: ' + err.message);
    alreadyReturned = true;
    this.shuttingDown = true;
    logger.error('Killing chromedriver');
    this.proc.kill();
    this.onDie();
  }.bind(this));

  this.proc.stdout.pipe(through(function (data) {
    logger.debug('[CHROMEDRIVER] ' + data.trim());
    if (!alreadyReturned && data.indexOf('Starting ') === 0) {
      this.chromedriverStarted = true;
      alreadyReturned = true;
      return cb();
    }
  }.bind(this)));

  this.proc.stderr.pipe(through(function (data) {
    logger.debug('[CHROMEDRIVER STDERR] ' + data.trim());
  }));

  this.proc.on('exit', this.onClose.bind(this));
  this.proc.on('close', this.onClose.bind(this));
};

Chromedriver.prototype.onClose = function (code, signal) {
  if (!this.shuttingDown) {
    this.shuttingDown = true;
    logger.debug("Chromedriver exited with code " + code);
    if (signal) {
      logger.debug("(killed by signal " + signal + ")");
    }
    if (!this.chromedriverStarted) {
      return this.onChromedriverStart(
          new Error("Chromedriver quit before it was available"));
    }
    if (this.exitCb !== null) {
      return this.exitCb();
    }
    this.onDie();
  }
};

Chromedriver.prototype.createSession = function (caps, cb) {
  logger.debug("Creating Chrome session");
  caps.chromeOptions.androidDeviceSerial = this.deviceId;
  if (this.enablePerformanceLogging) {
    caps.loggingPrefs = {performance: 'ALL'};
  }
  var data = {
    sessionId: null,
    desiredCapabilities: caps
  };
  async.waterfall([
    this.ensureChromedriverExists.bind(this),
    this.killOldChromedrivers.bind(this),
    this.start.bind(this),
    _.partial(this.proxyNewSession.bind(this), data)
  ], cb);
};

Chromedriver.prototype.proxyNewSession = function (data, cb) {
  var maxRetries = 5;
  var curRetry = 0;
  var retryInt = 500;
  var doProxy = function (alreadyRestarted) {
    this.proxyTo('/wd/hub/session', 'POST', data, function (err, res, body) {
      if (err) {
        if (/ECONNREFUSED/.test(err.message) && curRetry < maxRetries) {
          logger.debug("Could not connect yet; retrying");
          curRetry++;
          setTimeout(doProxy, retryInt);
          return;
        }
        return cb(err);
      }

      // first checking if we get a well formed success response
      this.chromeSessionId = null;
      try {
        if (body.status === 0 && body.sessionId) {
          logger.debug("Successfully started chrome session");
          this.chromeSessionId = body.sessionId;
        }
      } catch (ignore) {}
      if (this.chromeSessionId) return cb(null, this.chromeSessionId);

      // then check redirect success case
      try {
        if (res.statusCode === 303 && res.headers.location) {
          logger.debug("Successfully started chrome session");
          var loc = res.headers.location;
          this.chromeSessionId = /\/([^\/]+)$/.exec(loc)[1];
        }
      } catch (ignore) {}
      if (this.chromeSessionId) return cb(null, this.chromeSessionId);

      // those are error cases
      if (typeof body !== "undefined" &&
                 typeof body.value !== "undefined" &&
                 typeof body.value.message !== "undefined" &&
                 body.value.message.indexOf("Failed to run adb command") !== -1) {
        logger.error("Chromedriver had trouble running adb");
        if (!alreadyRestarted) {
          logger.error("Restarting adb for chromedriver");
          return this.adb.restartAdb(function () {
            this.adb.getConnectedDevices(function () {
              doProxy(true);
            }.bind(this));
          }.bind(this));
        } else {
          cb(new Error("Chromedriver wasn't able to use adb. Is the server up?"));
        }
      } else {
        logger.error("Chromedriver create session did not work. Status was " +
                     res.statusCode + " and body was " +
                     JSON.stringify(body));
        cb(new Error("Did not get session redirect from Chromedriver"));
      }
    }.bind(this));
  }.bind(this);

  doProxy();
};

Chromedriver.prototype.deleteSession = function (cb) {
  logger.debug("Deleting Chrome session");
  var url = '/wd/hub/session/' + this.chromeSessionId;
  this.proxyTo(url, 'DELETE', null, function (err, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb(new Error("Status was not 200"));
    cb();
  }.bind(this));
};

Chromedriver.prototype.stop = function (cb) {
  logger.debug('Killing chromedriver');
  this.exitCb = cb;
  this.proc.kill();
};

Chromedriver.prototype.proxyTo = proxyTo;

module.exports = Chromedriver;
<|endoftext|>


<commit_before>(function() {
    "use strict";

    var config = require("../server/config.js");
    var request = require("request");
    var assert = require("assert");

    function assertStatusIsGood(contents) {
        checkStatus(contents, (/Database status:(.*)/mi), "connected (" + config.get("database_hostname") + ")");
    }

    function checkStatus(contents, expectedPattern, expectedStatus) {
        var match = expectedPattern.exec(contents);

        assert.ok(match !== null, "Did not find " + expectedPattern.toString());

        if (match !== null) {
            assert.equal(match[1].trim(), expectedStatus);
        }
    }

    exports["should report if /status page looks good"] = function(test) {

        var target = config.urlFor("/status");
        console.log("requesting status page at", target);

        request(target, function(err, response, body) {
            if (err !== null) {
                test.ok(false, err.toString());
            } else if (response.statusCode != 200) {
                test.ok(false, "Expected 200 status code, actually was " + response.statusCode);
            } else {
                assertStatusIsGood(body);
            }
            test.done();
        });
    };
})();<commit_msg>smoke test doesn't care where database is hosted<commit_after>(function() {
    "use strict";

    var config = require("../server/config.js");
    var request = require("request");
    var assert = require("assert");

    function assertStatusIsGood(contents) {
        checkStatus(contents, (/Database status:(.*)/mi), "connected (");
    }

    function checkStatus(contents, expectedPattern, expectedStatus) {
        var match = expectedPattern.exec(contents);

        assert.ok(match !== null, "Did not find " + expectedPattern.toString());

        if (match !== null) {
            assert.equal(match[1].trim().slice(0, expectedStatus.length), expectedStatus);
        }
    }

    exports["should report if /status page looks good"] = function(test) {

        var target = config.urlFor("/status");
        console.log("requesting status page at", target);

        request(target, function(err, response, body) {
            if (err !== null) {
                test.ok(false, err.toString());
            } else if (response.statusCode != 200) {
                test.ok(false, "Expected 200 status code, actually was " + response.statusCode);
            } else {
                assertStatusIsGood(body);
            }
            test.done();
        });
    };
})();<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var Mix = require('laravel-mix').config;
var plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                },

                postcss: [
                    require('autoprefixer')
                ]
            }
        },

        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.(png|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]'
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: 'fonts/[name].[ext]?[hash]',
                publicPath: '/'
            }
        }
    ]
};

if (Mix.cssPreprocessor) {
    Mix[Mix.cssPreprocessor].forEach(toCompile => {
        let extractPlugin = new plugins.ExtractTextPlugin(
            Mix.cssOutput(toCompile)
        );

        module.exports.module.rules.push({
            test: new RegExp(toCompile.src.fileWithDir.replace(/\\/g, '\\\\') + '$'),
            loader: extractPlugin.extract({
                fallbackLoader: 'style-loader',
                loader: [
                    'css-loader',
                    'postcss-loader',
                    'resolve-url-loader',
                    (Mix.cssPreprocessor == 'sass') ? 'sass-loader?sourceMap&precision=8' : 'less-loader'
                ]
            })
        });

        module.exports.plugins = (module.exports.plugins || []).concat(extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    historyApiFallback: true,
    noInfo: true,
    compress: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: "mix-manifest.json",
        transform: Mix.manifest.transform,
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: [
                require('autoprefixer')
            ],
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

if (Mix.versioning) {
    Mix.versioning.record();

    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.versioning.prune(Mix.publicPath);
        })
    );
}

if (Mix.combine || Mix.minify) {
    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.concatenateAll().minifyAll();
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.js.vendor) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: [Mix.js.base + '/vendor', Mix.js.base + '/' + 'manifest'],
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins = module.exports.plugins.concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]);
}

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<commit_msg>Replace double quotes with single quotes<commit_after>var path = require('path');
var webpack = require('webpack');
var Mix = require('laravel-mix').config;
var plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                },

                postcss: [
                    require('autoprefixer')
                ]
            }
        },

        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.(png|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]'
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: 'fonts/[name].[ext]?[hash]',
                publicPath: '/'
            }
        }
    ]
};

if (Mix.cssPreprocessor) {
    Mix[Mix.cssPreprocessor].forEach(toCompile => {
        let extractPlugin = new plugins.ExtractTextPlugin(
            Mix.cssOutput(toCompile)
        );

        module.exports.module.rules.push({
            test: new RegExp(toCompile.src.fileWithDir.replace(/\\/g, '\\\\') + '$'),
            loader: extractPlugin.extract({
                fallbackLoader: 'style-loader',
                loader: [
                    'css-loader',
                    'postcss-loader',
                    'resolve-url-loader',
                    (Mix.cssPreprocessor == 'sass') ? 'sass-loader?sourceMap&precision=8' : 'less-loader'
                ]
            })
        });

        module.exports.plugins = (module.exports.plugins || []).concat(extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    historyApiFallback: true,
    noInfo: true,
    compress: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: 'mix-manifest.json',
        transform: Mix.manifest.transform,
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: [
                require('autoprefixer')
            ],
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

if (Mix.versioning) {
    Mix.versioning.record();

    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.versioning.prune(Mix.publicPath);
        })
    );
}

if (Mix.combine || Mix.minify) {
    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.concatenateAll().minifyAll();
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.js.vendor) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: [Mix.js.base + '/vendor', Mix.js.base + '/' + 'manifest'],
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins = module.exports.plugins.concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]);
}

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<|endoftext|>


<commit_before>import butterchurnPresets from 'butterchurn-presets'
import {
  PLAYER_MEDIA_ELEMENT_CHANGE,
  PLAYER_NEXT,
  PLAYER_VISUALIZER,
  PLAYER_VISUALIZER_PRESET,
} from 'shared/actionTypes'

const presetKeys = Object.keys(butterchurnPresets.getPresets())

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [PLAYER_MEDIA_ELEMENT_CHANGE]: (state, { payload }) => ({
    ...state,
    isSupported: payload.isAlphaSupported,
  }),
  [PLAYER_NEXT]: (state, { payload }) => ({
    ...state,
    ...getPresetKeyAndName(getRandomIntInclusive(0, presetKeys.length - 1)),
  }),
  [PLAYER_VISUALIZER]: (state, { payload }) => ({
    ...state,
    ...payload,
  }),
  [PLAYER_VISUALIZER_PRESET]: (state, { payload }) => {
    const { mode } = payload

    if (mode === 'rand') {
      return {
        ...state,
        ...getPresetKeyAndName(getRandomIntInclusive(0, presetKeys.length - 1)),
      }
    }

    const curIdx = presetKeys.indexOf(state.presetKey)
    const nextIdx = curIdx === presetKeys.length - 1 ? 0 : curIdx + 1 // wrap around
    const prevIdx = curIdx === 0 ? presetKeys.length - 1 : curIdx - 1 // wrap around

    return {
      ...state,
      ...getPresetKeyAndName(mode === 'prev' ? prevIdx : nextIdx),
    }
  },
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  isEnabled: true,
  isSupported: false,
  presetKey: null,
  presetName: '',
  sensitivity: 1,
}

export default function playerVisualizer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}

function getPresetKeyAndName (i) {
  return {
    presetKey: presetKeys[i],
    presetName: `[${i + 1}/${presetKeys.length}] ` + presetKeys[i],
  }
}

function getRandomIntInclusive (min, max) {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min + 1)) + min
}
<commit_msg>Fix player visualizer randomization on first load<commit_after>import butterchurnPresets from 'butterchurn-presets'
import {
  PLAYER_MEDIA_ELEMENT_CHANGE,
  PLAYER_NEXT,
  PLAYER_VISUALIZER,
  PLAYER_VISUALIZER_PRESET,
} from 'shared/actionTypes'

const presetKeys = Object.keys(butterchurnPresets.getPresets())

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [PLAYER_MEDIA_ELEMENT_CHANGE]: (state, { payload }) => ({
    ...state,
    isSupported: payload.isAlphaSupported,
  }),
  [PLAYER_NEXT]: (state, { payload }) => ({
    ...state,
    ...getRandomPreset(),
  }),
  [PLAYER_VISUALIZER]: (state, { payload }) => ({
    ...state,
    ...payload,
  }),
  [PLAYER_VISUALIZER_PRESET]: (state, { payload }) => {
    const { mode } = payload

    if (mode === 'rand') {
      return {
        ...state,
        ...getRandomPreset(),
      }
    }

    const curIdx = presetKeys.indexOf(state.presetKey)
    const nextIdx = curIdx === presetKeys.length - 1 ? 0 : curIdx + 1 // wrap around
    const prevIdx = curIdx === 0 ? presetKeys.length - 1 : curIdx - 1 // wrap around

    return {
      ...state,
      ...getPresetKeyAndName(mode === 'prev' ? prevIdx : nextIdx),
    }
  },
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  isEnabled: true,
  isSupported: false,
  ...getRandomPreset(),
  sensitivity: 1,
}

export default function playerVisualizer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}

function getPresetKeyAndName (i) {
  return {
    presetKey: presetKeys[i],
    presetName: `[${i + 1}/${presetKeys.length}] ` + presetKeys[i],
  }
}

function getRandomPreset () {
  return getPresetKeyAndName(Math.floor(Math.random() * (presetKeys.length - 1)))
}
<|endoftext|>


<commit_before>const req = require.context(".", true, /\.test\.js$/);
const files = req.keys();
const globals = require("shims/_utils/globals");
const {overrideGlobals, overrideConsoleError} = require("test/test-utils");

// This exposes sinon assertions to chai.assert
sinon.assert.expose(assert, {prefix: ""});

describe("ActivtyStreams", () => {
  let restores;
  before(() => {
    restores = [
      overrideConsoleError(message => {throw new Error(message);}),
      overrideGlobals(globals)
    ];
  });
  after(() => {
    restores.forEach(fn => fn());
  });

  files.forEach(file => req(file));
  // In order to target specific files, comment out the above line and uncomment/edit the following:
  // require("./addon/PrefsProvider.test.js");
});
<commit_msg>fix(tests): #1823 Only run tests after before in content-test/index.js<commit_after>const req = require.context(".", true, /\.test\.js$/);
const files = req.keys();
const globals = require("shims/_utils/globals");
const {overrideGlobals, overrideConsoleError} = require("test/test-utils");

// This exposes sinon assertions to chai.assert
sinon.assert.expose(assert, {prefix: ""});

describe("ActivtyStreams", () => {
  let restores;
  before(() => {
    restores = [
      overrideConsoleError(message => {throw new Error(message);}),
      overrideGlobals(globals)
    ];
  });
  after(() => {
    restores.forEach(fn => fn());
  });

  it("should run the tests", () => {
    files.forEach(file => req(file));
    // In order to target specific files, comment out the above line and uncomment/edit the following:
    // require("./addon/PrefsProvider.test.js");
  });
});
<|endoftext|>


<commit_before>'use strict';

const apiResult = require('../../../helpers/apiResult');

exports.get = async (request, extensions, config) => {
	return apiResult(501, 'not implemented');
};

exports.post = async (request, extensions, config) => {
	return apiResult(501, 'not implemented');
};
<commit_msg>implement GET/POST applications/:id/application_key<commit_after>'use strict';

const apiResult = require('../../../helpers/apiResult');
const applicationsAsync = require('../../../helpers/collections').applications;

exports.get = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうかをチェック
	if (applicationDoc.document.creatorId !== request.user.id)
		return apiResult(400, 'you do not own this application');

	if (applicationDoc.document['key_code'] == null)
		return apiResult(400, 'application_key has not been generated yet');

	const key = await applicationDoc.getApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};

exports.post = async (request, extensions, config) => {
	const applications = await applicationsAsync(config);

	const applicationDoc = await applications.findIdAsync(request.params.id);

	if (applicationDoc == null)
		return apiResult(400, 'application is not found');

	// 対象アプリケーションの所有者かどうかをチェック
	if (applicationDoc.document.creatorId !== request.user.id)
		return apiResult(400, 'you do not own this application');

	const key = await applicationDoc.generateApplicationKeyAsync();

	return apiResult(200, 'success', {'application_key': key});
};
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.mvc.JSView.
sap.ui.define([
	'jquery.sap.global',
	'./View',
	'./JSViewRenderer',
	'sap/base/util/merge',
	'sap/ui/base/ManagedObject',
	'sap/ui/core/library',
	"sap/base/Log"
],
	function(jQuery, View, JSViewRenderer, merge, ManagedObject, library, Log) {
	"use strict";

	/**
	 * Constructor for a new mvc/JSView.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A View defined/constructed by JavaScript code.
	 * @extends sap.ui.core.mvc.View
	 * @version ${version}
	 *
	 * @public
	 * @alias sap.ui.core.mvc.JSView
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var JSView = View.extend("sap.ui.core.mvc.JSView", /** @lends sap.ui.core.mvc.JSView.prototype */ { metadata : {

		library : "sap.ui.core"
	}});

	/**
	 * Map of already registered JavaScript views (pseudo classes), keyed by their name.
	 *
	 * When a new JSView definition is registered for some name, the definition object
	 * is stored in this map, keyed by that name.
	 *
	 * When a new instance of JSView is created for an already registered view name (class),
	 * then all properties from the corresponding definition object in this map are copied to
	 * the new instance of JSView.
	 *
	 * There's currently no API to remove view definitions from this map.
	 *
	 * @type Object.<string,Object>
	 * @private
	 */
	var mRegistry = {};

	/**
	 * Flag for feature detection of asynchronous loading/rendering
	 * @public
	 * @since 1.30
	 */
	JSView.asyncSupport = true;

	// shortcut for enum(s)
	var ViewType = library.mvc.ViewType;

	/**
	 * Creates an instance of the view with the given name (and id).
	 *
	 * @param {map} mOptions A map containing the view configuration options.
	 * @param {string} [mOptions.id] Specifies an ID for the View instance. If no ID is given, an ID will be generated.
	 * @param {string} [mOptions.viewName] Name of the view. The view must be defined using sap.ui.core.mvc.JSView.extend.
	 * @param {sap.ui.core.mvc.Controller} [mOptions.controller] Controller instance to be used for this view.
	 * The given controller instance overrides the controller defined in the view definition. Sharing a controller instance
	 * between multiple views is not supported.
	 * @public
	 * @static
	 * @since 1.56.0
	 * @return {Promise} A Promise that resolves with the view instance
	 */
	JSView.create = function(mOptions) {
		var mParameters = merge({}, mOptions);
		//remove unsupported options:
		for (var sOption in mParameters) {
			if (sOption === 'definition' || sOption === 'preprocessors') {
				delete mParameters[sOption];
				Log.warning("JSView.create does not support the options definition or preprocessor!");
			}
		}
		mParameters.type = ViewType.JS;
		return View.create(mParameters);
	};

	/**
	 * Defines or creates an instance of a JavaScript view.
	 *
	 * The behavior of this method depends on the signature of the call and on the current context.
	 *
	 *
View Definition

	 *

	 *   sap.ui.jsview(sId, vView);
	 *

	 * Defines a view of the given name with the given implementation. sId must be the view's name,
	 * vView must be an object and can contain implementations for any of the hooks provided by JSView.
	 *
	 *
View Instantiation

	 *

	 *   var oView = sap.ui.jsview(vView);
	 *   var oView = sap.ui.jsview(vView, bASync);
	 *   var oView = sap.ui.jsview(sId, vView);
	 *   var oView = sap.ui.jsview(sId, vView, bAsync);
	 *

	 * Creates an instance of the view with the given name (and id). If no view implementation has been defined
	 * for that view name, a JavaScript module with the same qualified name and with suffix .view.js
	 * will be loaded (required) and executed. The module should register a view definition on execution
	 * (1st. variant above).
	 *
	 * If sId is omitted, an ID will be created automatically.
	 *
	 * When bAsync has a truthy value, the view definition will be read asynchronously, if needed,
	 * but the (incomplete) view instance will be returned immediately.
	 *
	 * Note: Any other call signature will lead to a runtime error.
	 *
	 * @param {string} [sId] id of the newly created view, only allowed for instance creation
	 * @param {string | object} vView name or implementation of the view.
	 * @param {boolean} [bAsync] defines how the view source is loaded and rendered later on
	 *   (only relevant for instantiation, ignored for everything else)
	 * @public
	 * @static
	 * @deprecated Since 1.56, use {@link #.create JSView.create} or {@link #.extend JSView.extend} instead.
	 * @return {sap.ui.core.mvc.JSView | undefined} the created JSView instance in the creation case, otherwise undefined
	 */
	sap.ui.jsview = function(sId, vView, bAsync) {
		if (vView && vView.async) {
			Log.info("Do not use deprecated factory function 'sap.ui.jsview' for view instance creation. Use 'JSView.create' instead.");
		} else {
			Log.warning("Do not use synchronous view creation! Use the new asynchronous factory 'JSView.create' for view instance creation instead.");
		}
		return viewFactory.apply(this, arguments);
	};

	/*
	 * The old view factory implementation
	 */
	function viewFactory(sId, vView, bAsync) {
		var mSettings = {}, oView;

		if (vView && typeof (vView) == "string") { // instantiation sap.ui.jsview("id","name", [async])
			mSettings.viewName = vView;
			if (typeof arguments[2] == "boolean") {
				mSettings.async = bAsync;
			} else if (typeof arguments[2] == "object") { // arguments[2] is somehow a controller
				mSettings.controller = arguments[2];
				mSettings.async = !!arguments[3]; // optional
			}
			oView = new JSView(sId, mSettings);
			return oView;

		} else if (vView && typeof (vView) == "object") { // definition sap.ui.jsview("name",definitionObject)
			// sId is not given, but contains the desired value of sViewName
			mRegistry[sId] = vView;
			//TODO: global jquery call found
			jQuery.sap.declare({modName:sId,type:"view"}, false);
			Log.info("For defining views use JSView.extend instead.");
		} else if (arguments.length == 1 && typeof sId == "string" ||
			arguments.length == 2 && typeof arguments[0] == "string" && typeof arguments[1] == "boolean") { // instantiation sap.ui.jsview("name", [async])
			mSettings.viewName = arguments[0];
			mSettings.async = !!arguments[1]; // optional
			/*** STEP 1: create View ***/
			oView = mSettings.id ? new JSView(mSettings.id, mSettings) : new JSView(mSettings);
			/*** Step 3B and 4B (create and connect controller) happen in View ***/
			return oView;

		} else {
			throw new Error("Wrong arguments ('" + sId + "', '" + vView + "')! Either call sap.ui.jsview([sId,] sViewName) to instantiate a View or sap.ui.jsview(sViewName, oViewImpl) to define a View type.");
		}
	}

	JSView.prototype.initViewSettings = function (mSettings) {
		var oPromise;

		// require view definition if not yet done...
		if (!mRegistry[mSettings.viewName]) {
			//TODO: global jquery call found
			var sModuleName = jQuery.sap.getResourceName(mSettings.viewName, ".view");
			if ( mSettings.async ) {
				oPromise = new Promise(function(resolve) {
					sap.ui.require([sModuleName], resolve);
				});
			} else {
				sap.ui.requireSync(sModuleName);
			}
		}

		// extend 'this' with view from registry which should now or then be available
		if (mSettings.async) {
			return Promise.resolve(oPromise).then(function() {
				jQuery.extend(this, mRegistry[mSettings.viewName]);
			}.bind(this));
		}
		jQuery.extend(this, mRegistry[mSettings.viewName]);
	};

	JSView.prototype.onControllerConnected = function(oController) {
		// temporarily replace any preprocessors, e.g. from an enclosing JSON view
		ManagedObject.runWithPreprocessors(function() {
			this.applySettings({
				content : this.createContent(oController)
			});
		}, {
			// when auto prefixing is enabled, we add the prefix
			id: this.getAutoPrefixId() ? this.createId.bind(this) : undefined,
			settings: this._fnSettingsPreprocessor
		}, this);
	};

	/**
	 * A method to be implemented by JSViews, returning the flag whether to prefix
	 * the IDs of controls automatically or not if the controls are created inside
	 * the {@link sap.ui.core.mvc.JSView#createContent} function. By default this
	 * feature is not activated.
	 *
	 * You can overwrite this function and return true to activate the automatic
	 * prefixing.
	 *
	 * @since 1.15.1
	 * @return {boolean} true, if the controls IDs should be prefixed automatically
	 * @protected
	 */
	JSView.prototype.getAutoPrefixId = function() {
		return false;
	};

	/**
	 * A method to be implemented by JSViews, returning the View UI.
	 * While for declarative View types like XMLView or JSONView the user interface definition is declared in a separate file,
	 * JSViews programmatically construct the UI. This happens in the createContent method which every JSView needs to implement.
	 * The View implementation can construct the complete UI in this method - or only return the root control and create the rest of the UI lazily later on.
	 *
	 * @return {sap.ui.core.Control} a control or (typically) tree of controls representing the View user interface
	 * @public
	 * @name sap.ui.core.mvc.JSView#createContent
	 * @function
	 */

	return JSView;

});<commit_msg>[INTERNAL] mvc.JSView: partially revert deprecation of sap.ui.jsview<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.mvc.JSView.
sap.ui.define([
	'jquery.sap.global',
	'./View',
	'./JSViewRenderer',
	'sap/base/util/merge',
	'sap/ui/base/ManagedObject',
	'sap/ui/core/library',
	"sap/base/Log"
],
	function(jQuery, View, JSViewRenderer, merge, ManagedObject, library, Log) {
	"use strict";

	/**
	 * Constructor for a new mvc/JSView.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A View defined/constructed by JavaScript code.
	 * @extends sap.ui.core.mvc.View
	 * @version ${version}
	 *
	 * @public
	 * @alias sap.ui.core.mvc.JSView
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var JSView = View.extend("sap.ui.core.mvc.JSView", /** @lends sap.ui.core.mvc.JSView.prototype */ { metadata : {

		library : "sap.ui.core"
	}});

	/**
	 * Map of already registered JavaScript views (pseudo classes), keyed by their name.
	 *
	 * When a new JSView definition is registered for some name, the definition object
	 * is stored in this map, keyed by that name.
	 *
	 * When a new instance of JSView is created for an already registered view name (class),
	 * then all properties from the corresponding definition object in this map are copied to
	 * the new instance of JSView.
	 *
	 * There's currently no API to remove view definitions from this map.
	 *
	 * @type Object.<string,Object>
	 * @private
	 */
	var mRegistry = {};

	/**
	 * Flag for feature detection of asynchronous loading/rendering
	 * @public
	 * @since 1.30
	 */
	JSView.asyncSupport = true;

	// shortcut for enum(s)
	var ViewType = library.mvc.ViewType;

	/**
	 * Creates an instance of the view with the given name (and id).
	 *
	 * @param {map} mOptions A map containing the view configuration options.
	 * @param {string} [mOptions.id] Specifies an ID for the View instance. If no ID is given, an ID will be generated.
	 * @param {string} [mOptions.viewName] Name of the view. The view must be defined using sap.ui.core.mvc.JSView.extend.
	 * @param {sap.ui.core.mvc.Controller} [mOptions.controller] Controller instance to be used for this view.
	 * The given controller instance overrides the controller defined in the view definition. Sharing a controller instance
	 * between multiple views is not supported.
	 * @public
	 * @static
	 * @since 1.56.0
	 * @return {Promise} A Promise that resolves with the view instance
	 */
	JSView.create = function(mOptions) {
		var mParameters = merge({}, mOptions);
		//remove unsupported options:
		for (var sOption in mParameters) {
			if (sOption === 'definition' || sOption === 'preprocessors') {
				delete mParameters[sOption];
				Log.warning("JSView.create does not support the options definition or preprocessor!");
			}
		}
		mParameters.type = ViewType.JS;
		return View.create(mParameters);
	};

	/**
	 * Defines or creates an instance of a JavaScript view.
	 *
	 * The behavior of this method depends on the signature of the call and on the current context.
	 *
	 *
View Definition

	 *

	 *   sap.ui.jsview(sId, vView);
	 *

	 * Defines a view of the given name with the given implementation. sId must be the view's name,
	 * vView must be an object and can contain implementations for any of the hooks provided by JSView.
	 *
	 *
View Instantiation (deprecated)

	 *

	 *   var oView = sap.ui.jsview(vView);
	 *   var oView = sap.ui.jsview(vView, bASync);
	 *   var oView = sap.ui.jsview(sId, vView);
	 *   var oView = sap.ui.jsview(sId, vView, bAsync);
	 *

	 * Creates an instance of the view with the given name (and id). If no view implementation has been defined
	 * for that view name, a JavaScript module with the same qualified name and with suffix .view.js
	 * will be loaded (required) and executed. The module should register a view definition on execution
	 * (1st. variant above).
	 *
	 * If sId is omitted, an ID will be created automatically.
	 *
	 * When bAsync has a truthy value, the view definition will be read asynchronously, if needed,
	 * but the (incomplete) view instance will be returned immediately.
	 *
	 * Note: Using sap.ui.jsview for creating view instances has been deprecated, use
	 * {@link sap.ui.core.mvc.JSView.create JSView.create} instead. JSView.create enforces
	 * asynchronous loading and can be used via an AMD reference, it doesn't rely on a global name.
	 *
	 * Note: Any other call signature will lead to a runtime error.
	 *
	 * @param {string} [sId] id of the newly created view, only allowed for instance creation
	 * @param {string | object} vView name or implementation of the view.
	 * @param {boolean} [bAsync] defines how the view source is loaded and rendered later on
	 *   (only relevant for instantiation, ignored for everything else)
	 * @public
	 * @static
	 * @deprecated Since 1.56, use {@link #.create JSView.create} to create view instances;
	 *   for defining JavaScript views, there's no substitute yet and sap.ui.jsview still has to be used
	 * @return {sap.ui.core.mvc.JSView | undefined} the created JSView instance in the creation case, otherwise undefined
	 */
	sap.ui.jsview = function(sId, vView, bAsync) {
		if (vView && vView.async) {
			Log.info("Do not use deprecated factory function 'sap.ui.jsview' for view instance creation. Use 'JSView.create' instead.");
		} else {
			Log.warning("Do not use synchronous view creation! Use the new asynchronous factory 'JSView.create' for view instance creation instead.");
		}
		return viewFactory.apply(this, arguments);
	};

	/*
	 * The old view factory implementation
	 */
	function viewFactory(sId, vView, bAsync) {
		var mSettings = {}, oView;

		if (vView && typeof (vView) == "string") { // instantiation sap.ui.jsview("id","name", [async])
			mSettings.viewName = vView;
			if (typeof arguments[2] == "boolean") {
				mSettings.async = bAsync;
			} else if (typeof arguments[2] == "object") { // arguments[2] is somehow a controller
				mSettings.controller = arguments[2];
				mSettings.async = !!arguments[3]; // optional
			}
			oView = new JSView(sId, mSettings);
			return oView;

		} else if (vView && typeof (vView) == "object") { // definition sap.ui.jsview("name",definitionObject)
			// sId is not given, but contains the desired value of sViewName
			mRegistry[sId] = vView;
			//TODO: global jquery call found
			jQuery.sap.declare({modName:sId,type:"view"}, false);
			Log.info("For defining views use JSView.extend instead.");
		} else if (arguments.length == 1 && typeof sId == "string" ||
			arguments.length == 2 && typeof arguments[0] == "string" && typeof arguments[1] == "boolean") { // instantiation sap.ui.jsview("name", [async])
			mSettings.viewName = arguments[0];
			mSettings.async = !!arguments[1]; // optional
			/*** STEP 1: create View ***/
			oView = mSettings.id ? new JSView(mSettings.id, mSettings) : new JSView(mSettings);
			/*** Step 3B and 4B (create and connect controller) happen in View ***/
			return oView;

		} else {
			throw new Error("Wrong arguments ('" + sId + "', '" + vView + "')! Either call sap.ui.jsview([sId,] sViewName) to instantiate a View or sap.ui.jsview(sViewName, oViewImpl) to define a View type.");
		}
	}

	JSView.prototype.initViewSettings = function (mSettings) {
		var oPromise;

		// require view definition if not yet done...
		if (!mRegistry[mSettings.viewName]) {
			//TODO: global jquery call found
			var sModuleName = jQuery.sap.getResourceName(mSettings.viewName, ".view");
			if ( mSettings.async ) {
				oPromise = new Promise(function(resolve) {
					sap.ui.require([sModuleName], resolve);
				});
			} else {
				sap.ui.requireSync(sModuleName);
			}
		}

		// extend 'this' with view from registry which should now or then be available
		if (mSettings.async) {
			return Promise.resolve(oPromise).then(function() {
				jQuery.extend(this, mRegistry[mSettings.viewName]);
			}.bind(this));
		}
		jQuery.extend(this, mRegistry[mSettings.viewName]);
	};

	JSView.prototype.onControllerConnected = function(oController) {
		// temporarily replace any preprocessors, e.g. from an enclosing JSON view
		ManagedObject.runWithPreprocessors(function() {
			this.applySettings({
				content : this.createContent(oController)
			});
		}, {
			// when auto prefixing is enabled, we add the prefix
			id: this.getAutoPrefixId() ? this.createId.bind(this) : undefined,
			settings: this._fnSettingsPreprocessor
		}, this);
	};

	/**
	 * A method to be implemented by JSViews, returning the flag whether to prefix
	 * the IDs of controls automatically or not if the controls are created inside
	 * the {@link sap.ui.core.mvc.JSView#createContent} function. By default this
	 * feature is not activated.
	 *
	 * You can overwrite this function and return true to activate the automatic
	 * prefixing.
	 *
	 * @since 1.15.1
	 * @return {boolean} true, if the controls IDs should be prefixed automatically
	 * @protected
	 */
	JSView.prototype.getAutoPrefixId = function() {
		return false;
	};

	/**
	 * A method to be implemented by JSViews, returning the View UI.
	 * While for declarative View types like XMLView or JSONView the user interface definition is declared in a separate file,
	 * JSViews programmatically construct the UI. This happens in the createContent method which every JSView needs to implement.
	 * The View implementation can construct the complete UI in this method - or only return the root control and create the rest of the UI lazily later on.
	 *
	 * @return {sap.ui.core.Control} a control or (typically) tree of controls representing the View user interface
	 * @public
	 * @name sap.ui.core.mvc.JSView#createContent
	 * @function
	 */

	return JSView;

});<|endoftext|>


<commit_before>var TapReporter = require('testem/lib/reporters/tap_reporter');

function FailureOnlyReporter() {
  TapReporter.apply(this, arguments);
  this._reportCount = 0;
}

FailureOnlyReporter.prototype = Object.create(TapReporter.prototype);
FailureOnlyReporter.prototype.constructor = FailureOnlyReporter;

FailureOnlyReporter.prototype.display = function(prefix, result) {
  this._reportCount++;

  if (!result.passed) {
    TapReporter.prototype.display.apply(this, arguments);
  }

  if (this._reportCount > 100) {
    this.out.write('pass count: ' + this.pass);
    this._reportCount = 0;
  }
};

module.exports = FailureOnlyReporter;
<commit_msg>FailureOnlyReporter: Convert to ES6 class<commit_after>var TapReporter = require('testem/lib/reporters/tap_reporter');

class FailureOnlyReporter extends TapReporter {
  constructor(...args) {
    super(...args);
    this._reportCount = 0;
  }

  display(prefix, result) {
    this._reportCount++;

    if (!result.passed) {
      super.display(prefix, result);
    }

    if (this._reportCount > 100) {
      this.out.write('pass count: ' + this.pass);
      this._reportCount = 0;
    }
  }
}

module.exports = FailureOnlyReporter;
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { reset, setX } from './actions';
import canUseDOM from 'can-use-dom';
import debounce from 'lodash.debounce';
import getFocusPanel from '../panels/get-focus-panel';
import getViewportWidth from './get-viewport-width';
import MoveLeft from './move-left';
import Panels from '../panels/component';
import React, { Component } from 'react';
import shallowEqual from '../utils/shallow-equal';
import snap from './snap';

const DEBOUNCE = 50;

export class Runtime extends Component {
  componentDidMount() {
    if (canUseDOM) {
      this.setXDebounced = debounce(this.setX.bind(this), DEBOUNCE);
      this.refs.runtime.addEventListener('scroll', this.setXDebounced, false);

      this.setViewportWidthDebounced = debounce(this.setViewportWidth.bind(this), DEBOUNCE);
      window.addEventListener('resize', this.setViewportWidthDebounced, false);
      window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);

      this.setViewportWidth();
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.x !== prevProps.x) {
      snap(this.refs.runtime, this.props.x);
    }

    if (!shallowEqual(this.props.panels, prevProps.panels)) {
      this.props.dispatch(reset(this.props.preferredSnapPoint, undefined, this.props.isExpanded));
    }

    if (!shallowEqual(this.props.routes, prevProps.routes)) {
      this.props.dispatch(reset(this.props.preferredSnapPoint));
    }

    if (this.props.title !== prevProps.title) {
      window.document.title = this.props.title;
    }
  }

  componentWillUnmount() {
    if (canUseDOM) {
      this.refs.runtime.removeEventListener('scroll', this.setXDebounced);
      window.removeEventListener('resize', this.setViewportWidthDebounced, false);
      window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
    }
  }

  render() {
    const { props } = this;

    const backgroundStyle = {};
    if (props.background) {
      if (props.background.image) {
        backgroundStyle.backgroundImage = `url(${props.background.image})`;

        if (props.background.size) {
          backgroundStyle.backgroundSize = props.background.size;
        }
      }

      if (props.background.color) {
        backgroundStyle.backgroundColor = props.background.color;
      }
    }

    return (

        {!props.shouldGoMobile && props.x > 0 && <MoveLeft {...props} />}
        <Panels />

    );
  }

  setViewportWidth() {
    this.props.dispatch(reset(this.props.preferredSnapPoint, getViewportWidth()));
  }

  setX() {
    this.props.dispatch(setX(this.refs.runtime.scrollLeft));
  }
}

const style = {
  overflowX: 'auto',
  overflowY: 'hidden',
  width: '100vw'
};

function mapStateToProps(state, props) {
  const focusPanel = getFocusPanel(state.router.routes, state.panels);
  let isExpanded = false;
  const panels = Object.keys(state.panels).map(k => {
    const panel = state.panels[k];
    isExpanded = isExpanded || panel.isExpanded;
    return panel.isExpanded ? panel.maxWidth : panel.width;
  });

  return {
    background: focusPanel.background,
    isExpanded,
    panels,
    routes: state.router.routes,
    snapPoint: state.runtime.snapPoint,
    shouldGoMobile: state.runtime.shouldGoMobile,
    title: focusPanel.title,
    x: state.runtime.x
  };
}
export default connect(mapStateToProps)(Runtime);
<commit_msg>fix: set height 100vh to prevent runtime from overflowing<commit_after>import { connect } from 'react-redux';
import { reset, setX } from './actions';
import canUseDOM from 'can-use-dom';
import debounce from 'lodash.debounce';
import getFocusPanel from '../panels/get-focus-panel';
import getViewportWidth from './get-viewport-width';
import MoveLeft from './move-left';
import Panels from '../panels/component';
import React, { Component } from 'react';
import shallowEqual from '../utils/shallow-equal';
import snap from './snap';

const DEBOUNCE = 50;

export class Runtime extends Component {
  componentDidMount() {
    if (canUseDOM) {
      this.setXDebounced = debounce(this.setX.bind(this), DEBOUNCE);
      this.refs.runtime.addEventListener('scroll', this.setXDebounced, false);

      this.setViewportWidthDebounced = debounce(this.setViewportWidth.bind(this), DEBOUNCE);
      window.addEventListener('resize', this.setViewportWidthDebounced, false);
      window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);

      this.setViewportWidth();
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.x !== prevProps.x) {
      snap(this.refs.runtime, this.props.x);
    }

    if (!shallowEqual(this.props.panels, prevProps.panels)) {
      this.props.dispatch(reset(this.props.preferredSnapPoint, undefined, this.props.isExpanded));
    }

    if (!shallowEqual(this.props.routes, prevProps.routes)) {
      this.props.dispatch(reset(this.props.preferredSnapPoint));
    }

    if (this.props.title !== prevProps.title) {
      window.document.title = this.props.title;
    }
  }

  componentWillUnmount() {
    if (canUseDOM) {
      this.refs.runtime.removeEventListener('scroll', this.setXDebounced);
      window.removeEventListener('resize', this.setViewportWidthDebounced, false);
      window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
    }
  }

  render() {
    const { props } = this;

    const backgroundStyle = {};
    if (props.background) {
      if (props.background.image) {
        backgroundStyle.backgroundImage = `url(${props.background.image})`;

        if (props.background.size) {
          backgroundStyle.backgroundSize = props.background.size;
        }
      }

      if (props.background.color) {
        backgroundStyle.backgroundColor = props.background.color;
      }
    }

    return (

        {!props.shouldGoMobile && props.x > 0 && <MoveLeft {...props} />}
        <Panels />

    );
  }

  setViewportWidth() {
    this.props.dispatch(reset(this.props.preferredSnapPoint, getViewportWidth()));
  }

  setX() {
    this.props.dispatch(setX(this.refs.runtime.scrollLeft));
  }
}

const style = {
  height: '100vh',
  overflowX: 'auto',
  overflowY: 'hidden',
  width: '100vw'
};

function mapStateToProps(state, props) {
  const focusPanel = getFocusPanel(state.router.routes, state.panels);
  let isExpanded = false;
  const panels = Object.keys(state.panels).map(k => {
    const panel = state.panels[k];
    isExpanded = isExpanded || panel.isExpanded;
    return panel.isExpanded ? panel.maxWidth : panel.width;
  });

  return {
    background: focusPanel.background,
    isExpanded,
    panels,
    routes: state.router.routes,
    snapPoint: state.runtime.snapPoint,
    shouldGoMobile: state.runtime.shouldGoMobile,
    title: focusPanel.title,
    x: state.runtime.x
  };
}
export default connect(mapStateToProps)(Runtime);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import StarsBackground from '../../../../components/StarsBackground';
import eltcoinLogo from './images/logo.png';
import idexLogo from './images/idex.png';
import mercatoxLogo from './images/mercatox.png';
import decentrexLogo from './images/decentrex.png';
import etherdeltaLogo from './images/etherdelta.png';
import coinexchangeLogo from './images/coinexchange.png';

const EXCHANGES = [
  {
    link: 'https://idex.market/eth/eltcoin',
    logo: idexLogo,
  },
  {
    link: 'https://mercatox.com/exchange/ELTCOIN/ETH',
    logo: mercatoxLogo,
  },
  {
    link: 'https://decentrex.com/#ELTCOIN-ETH',
    logo: decentrexLogo,
  },
  {
    link: 'https://etherdelta.com/#ELTCOIN-ETH',
    logo: etherdeltaLogo,
  },
  {
    link: 'https://www.coinexchange.io/market/ELT/ETH',
    logo: coinexchangeLogo,
  },
];

export default class Exchanges extends Component {
  state = {
    btcPrice: 0,
    isTextBold: false,
    marketCap: 0,
    percentChange24h: 0,
    rank: 0,
    usdPrice: 0,
    volumeUsd24h: 0,
  };

  componentDidMount() {
    this.fetchData();
    this.initializeAnimation();
  }

  getPriceChangeClassName = () => {
    if (this.state.percentChange24h >= 0) {
      return 'has-text-success';
    }

    return 'has-text-danger';
  };

  initializeAnimation = () => {
    setInterval(() => {
      this.setState({
        btcPrice: this.state.btcPrice - 0.00000001,
        isTextBold: true,
        percentChange24h: this.state.percentChange24h - 0.01,
        usdPrice: this.state.usdPrice - 0.0001,
      });

      setTimeout(() => {
        this.setState({
          isTextBold: false,
        });
      }, 2000);
    }, 10000);

    setTimeout(() => {
      setInterval(() => {
        this.setState({
          btcPrice: this.state.btcPrice + 0.00000001,
          isTextBold: true,
          percentChange24h: this.state.percentChange24h + 0.01,
          usdPrice: this.state.usdPrice + 0.0001,
        });

        setTimeout(() => {
          this.setState({
            isTextBold: false,
          });
        }, 2000);
      }, 10000);
    }, 5000);
  };

  fetchData = async () => {
    const eltcoinData = await fetch(
      'https://api.coinmarketcap.com/v1/ticker/eltcoin/?ref=widget&convert=USD',
    )
      .then(data => data.json())
      .then(data => data[0]);

    this.setState({
      btcPrice: +eltcoinData.price_btc,
      marketCap: eltcoinData.market_cap_usd,
      percentChange24h: +eltcoinData.percent_change_24h,
      rank: eltcoinData.rank,
      usdPrice: +eltcoinData.price_usd,
      volumeUsd24h: eltcoinData['24h_volume_usd'],
    });
  };

  render() {
    return (

        <StarsBackground />

          Exchanges

          {EXCHANGES.map(exchange => (

                Status: LISTED

          ))}

                  {this.state.usdPrice} USD
                {' '}

                  ({this.state.percentChange24h}%)

                  {this.state.btcPrice.toFixed(8)} BTC

                  Rank

{this.state.rank}

                  Market cap.

{Math.round(this.state.marketCap / 1000, 2)}K USD

                  Volume (24H)

{Math.round(this.state.volumeUsd24h / 1000, 2)}K USD

    );
  }
}
<commit_msg>Fix prices animation<commit_after>import React, { Component } from 'react';
import StarsBackground from '../../../../components/StarsBackground';
import eltcoinLogo from './images/logo.png';
import idexLogo from './images/idex.png';
import mercatoxLogo from './images/mercatox.png';
import decentrexLogo from './images/decentrex.png';
import etherdeltaLogo from './images/etherdelta.png';
import coinexchangeLogo from './images/coinexchange.png';

const EXCHANGES = [
  {
    link: 'https://idex.market/eth/eltcoin',
    logo: idexLogo,
  },
  {
    link: 'https://mercatox.com/exchange/ELTCOIN/ETH',
    logo: mercatoxLogo,
  },
  {
    link: 'https://decentrex.com/#ELTCOIN-ETH',
    logo: decentrexLogo,
  },
  {
    link: 'https://etherdelta.com/#ELTCOIN-ETH',
    logo: etherdeltaLogo,
  },
  {
    link: 'https://www.coinexchange.io/market/ELT/ETH',
    logo: coinexchangeLogo,
  },
];

export default class Exchanges extends Component {
  state = {
    btcPrice: 0,
    isTextBold: false,
    marketCap: 0,
    percentChange24h: 0,
    rank: 0,
    usdPrice: 0,
    volumeUsd24h: 0,
  };

  componentDidMount() {
    this.fetchData();
    this.initializeAnimation();
  }

  getPriceChangeClassName = () => {
    if (this.state.percentChange24h >= 0) {
      return 'has-text-success';
    }

    return 'has-text-danger';
  };

  initializeAnimation = () => {
    setInterval(() => {
      this.setState({
        btcPrice: this.state.btcPrice - 0.00000001,
        isTextBold: true,
        percentChange24h: this.state.percentChange24h - 0.01,
        usdPrice: this.state.usdPrice - 0.0001,
      });

      setTimeout(() => {
        this.setState({
          isTextBold: false,
        });
      }, 2000);
    }, 10000);

    setTimeout(() => {
      setInterval(() => {
        this.setState({
          btcPrice: this.state.btcPrice + 0.00000001,
          isTextBold: true,
          percentChange24h: this.state.percentChange24h + 0.01,
          usdPrice: this.state.usdPrice + 0.0001,
        });

        setTimeout(() => {
          this.setState({
            isTextBold: false,
          });
        }, 2000);
      }, 10000);
    }, 5000);
  };

  fetchData = async () => {
    const eltcoinData = await fetch(
      'https://api.coinmarketcap.com/v1/ticker/eltcoin/?ref=widget&convert=USD',
    )
      .then(data => data.json())
      .then(data => data[0]);

    this.setState({
      btcPrice: parseFloat(eltcoinData.price_btc),
      marketCap: eltcoinData.market_cap_usd,
      percentChange24h: parseFloat(eltcoinData.percent_change_24h),
      rank: eltcoinData.rank,
      usdPrice: parseFloat(eltcoinData.price_usd),
      volumeUsd24h: eltcoinData['24h_volume_usd'],
    });
  };

  render() {
    return (

        <StarsBackground />

          Exchanges

          {EXCHANGES.map(exchange => (

                Status: LISTED

          ))}

                  {this.state.usdPrice.toFixed(6)} USD
                {' '}

                  ({this.state.percentChange24h.toFixed(2)}%)

                  {this.state.btcPrice.toFixed(8)} BTC

                  Rank

{this.state.rank}

                  Market cap.

{Math.round(this.state.marketCap / 1000, 2)}K USD

                  Volume (24H)

{Math.round(this.state.volumeUsd24h / 1000, 2)}K USD

    );
  }
}
<|endoftext|>


<commit_before>//Because Browserify encapsulates every module, use strict won't apply to the global scope and break everything
'use strict';

/**
 * Movement System constructor
 *
 * @class Movement
 * @classdesc The movement system is responsible for handling collision between entities and moving them
 *
 * @param {Game} game - Reference to the currently running game
 */
var Movement = function(game) {

	/**
	 * @property {Game} game - Reference to the current game object
	 */
	this.game = game;

};

Movement.prototype = {

	/**
	 * Performs the needed operations for this specific system on one entity
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being processed by this system
	 * @param {Object} newPosition - The new x or y coordinates the entity is trying to move to
	 */
	handleSingleEntity: function(entity, newPosition) {

		//Check if the sprite needs to be flipped
		if(entity.hasComponent("sprite")) {

			this.changeDirection(entity, newPosition);

		}

		//Check if the new position is correct
		if(this.canMove(entity, newPosition)) {

			//Get components
			var positionComponent = entity.getComponent("position");

			//Get the tile to which the entity is trying to move
			var currentTile = this.game.map.tiles[positionComponent.position.x][positionComponent.position.y];
			var nextTile = this.game.map.tiles[newPosition.x][newPosition.y];

			//Remove the entity from the tile it's currently on
			currentTile.removeEntity(entity);

			//And add him to the next tile that he is going to be on
			nextTile.addEntity(entity);

			//Pop the new position from the "stack"
			positionComponent.position = newPosition;

		}

	},

	/**
	 * Changes the direction of a sprite based on it's new position
	 * This way a sprite can face left or right based on it's movement
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being processed by this system
	 * @param {Object} newPosition - The new x or y coordinates the entity is trying to move to
	 */
	changeDirection: function(entity, newPosition) {

		//Get components
		var positionComponent = entity.getComponent("position");
		var spriteComponent = entity.getComponent("sprite");

		//Check if the entity moved left or right
		if(newPosition.x > positionComponent.position.x) {

			//The entity moved right
			spriteComponent.direction = "right";

		}else if(newPosition.x < positionComponent.position.x) {

			//The entity moved left
			spriteComponent.direction = "left";

		}

	},

	/**
	 * Function that gets called when an entity wants to move
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being checked against the map
	 * @param {Object} newPosition - The new position the entity is trying to move to
	 *
	 * @return {Boolean} True when an entity can move to the new position, false when the entity is obstructed
	 */
	canMove: function(entity, newPosition) {

		//Get the tile to which the entity is trying to move
		var nextTile = this.game.map.tiles[newPosition.x][newPosition.y];

		//Check for collision on the map, walls etc
		if(nextTile.type !== 2) {

			return false;

		}

		//Check if there is one or more than one entity at the new location
		if(nextTile.entities.length !== 0) {

			//Define variables
			var canContinue = true;

			//Loop through the entities
			for(var i = 0; i < nextTile.entities.length; i++) {

				//Check if the entity has a collide component
				if(nextTile.entities[i].hasComponent("collide")) {

					//Get the collide component
					var collideComponent = nextTile.entities[i].getComponent("collide");

					//If collide is true, it means we can't walk to the next tile
					if(collideComponent.collide === true) {

						canContinue = false;

					}

				}

				//Loop through the components
				for(var key in nextTile.entities[i].components) {

					//Check if the entity still exists
					if(typeof nextTile.entities[i] === "undefined") {

						//The entity could have died in a previous bumpInto event
						//Thus we should abort the loop of the entity no longer exists
						break;

					}

					//Make sure that obj[key] belongs to the object and was not inherited
					if(nextTile.entities[i].components.hasOwnProperty(key)) {

						//Check if the component has an events parameter
						if(typeof nextTile.entities[i].components[key].events !== "undefined") {

							//Trigger the specified event
							nextTile.entities[i].components[key].events.trigger("bumpInto", entity, nextTile.entities[i]);

						}

					}

				}

			}

			//If there was even one entity that we couldn't collide with on the next tile
			//this will return false
			return canContinue;

		}

		//Function made it all the way down here, that means the entity is able to move to the new position
		return true;

	}

};

//Export the Browserify module
module.exports = Movement;
<commit_msg>Update the sprite's position when the position in the Position component changes.<commit_after>//Because Browserify encapsulates every module, use strict won't apply to the global scope and break everything
'use strict';

/**
 * Movement System constructor
 *
 * @class Movement
 * @classdesc The movement system is responsible for handling collision between entities and moving them
 *
 * @param {Game} game - Reference to the currently running game
 */
var Movement = function(game) {

	/**
	 * @property {Game} game - Reference to the current game object
	 */
	this.game = game;

};

Movement.prototype = {

	/**
	 * Performs the needed operations for this specific system on one entity
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being processed by this system
	 * @param {Object} newPosition - The new x or y coordinates the entity is trying to move to
	 */
	handleSingleEntity: function(entity, newPosition) {

		//Check if the sprite needs to be flipped
		if(entity.hasComponent("sprite")) {

			this.changeDirection(entity, newPosition);

		}

		//Check if the new position is correct
		if(this.canMove(entity, newPosition)) {

			//Get components
			var positionComponent = entity.getComponent("position");

			//Get the tile to which the entity is trying to move
			var currentTile = this.game.map.tiles[positionComponent.position.x][positionComponent.position.y];
			var nextTile = this.game.map.tiles[newPosition.x][newPosition.y];

			//Remove the entity from the tile it's currently on
			currentTile.removeEntity(entity);

			//And add him to the next tile that he is going to be on
			nextTile.addEntity(entity);

			//Update the position of the sprite
			entity.sprite.position = new PIXI.Point(newPosition.x * this.game.settings.tileSize, newPosition.y * this.game.settings.tileSize);

			//Set the new position in the position component
			positionComponent.position = newPosition;

		}

	},

	/**
	 * Changes the direction of a sprite based on it's new position
	 * This way a sprite can face left or right based on it's movement
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being processed by this system
	 * @param {Object} newPosition - The new x or y coordinates the entity is trying to move to
	 */
	changeDirection: function(entity, newPosition) {

		//Get components
		var positionComponent = entity.getComponent("position");
		var spriteComponent = entity.getComponent("sprite");

		//Check if the entity moved left or right
		if(newPosition.x > positionComponent.position.x) {

			//The entity moved right
			spriteComponent.direction = "right";

		}else if(newPosition.x < positionComponent.position.x) {

			//The entity moved left
			spriteComponent.direction = "left";

		}

	},

	/**
	 * Function that gets called when an entity wants to move
	 * @protected
	 *
	 * @param {Entity} entity - The entity that is being checked against the map
	 * @param {Object} newPosition - The new position the entity is trying to move to
	 *
	 * @return {Boolean} True when an entity can move to the new position, false when the entity is obstructed
	 */
	canMove: function(entity, newPosition) {

		//Get the tile to which the entity is trying to move
		var nextTile = this.game.map.tiles[newPosition.x][newPosition.y];

		//Check for collision on the map, walls etc
		if(nextTile.type !== 2) {

			return false;

		}

		//Check if there is one or more than one entity at the new location
		if(nextTile.entities.length !== 0) {

			//Define variables
			var canContinue = true;

			//Loop through the entities
			for(var i = 0; i < nextTile.entities.length; i++) {

				//Check if the entity has a collide component
				if(nextTile.entities[i].hasComponent("collide")) {

					//Get the collide component
					var collideComponent = nextTile.entities[i].getComponent("collide");

					//If collide is true, it means we can't walk to the next tile
					if(collideComponent.collide === true) {

						canContinue = false;

					}

				}

				//Loop through the components
				for(var key in nextTile.entities[i].components) {

					//Check if the entity still exists
					if(typeof nextTile.entities[i] === "undefined") {

						//The entity could have died in a previous bumpInto event
						//Thus we should abort the loop of the entity no longer exists
						break;

					}

					//Make sure that obj[key] belongs to the object and was not inherited
					if(nextTile.entities[i].components.hasOwnProperty(key)) {

						//Check if the component has an events parameter
						if(typeof nextTile.entities[i].components[key].events !== "undefined") {

							//Trigger the specified event
							nextTile.entities[i].components[key].events.trigger("bumpInto", entity, nextTile.entities[i]);

						}

					}

				}

			}

			//If there was even one entity that we couldn't collide with on the next tile
			//this will return false
			return canContinue;

		}

		//Function made it all the way down here, that means the entity is able to move to the new position
		return true;

	}

};

//Export the Browserify module
module.exports = Movement;
<|endoftext|>


<commit_before>ace.define('ace/mode/wast_highlight_rules', function (acequire, exports, module) {
    "use strict";

    var oop = acequire("ace/lib/oop");
    var TextHighlightRules = acequire("ace/mode/text_highlight_rules").TextHighlightRules;

    var WastHighlightRules = function () {
        var keywords = ["global|local|type|memory|module|table|import|export|param|offset|start|code",
                        "data|segment|element|invoke|label"].join("|");

        var types    = "i32|i64|f32|f64|anyfunc|func|void";
        var operator = [
            "const|if|else|loop|block|br|br_if|br_table|drop|select|end|return|call|call_indirect|call_import",
            "current_memory|grow_memory|get_local|set_local|tee_local|get_global|set_global",
            "load|load8_s|load8_u|load16_s|load16_u|load32_s|load32_u|store|store8|store16|store32",
            "eqz|eq|ne|lt_s|lt_u|lt|gt_s|gt_u|gt|le_s|le_u|le|ge_s|ge_u|ge|clz|ctz|popcnt|add|sub",
            "mul|div_s|div_u|div|rem_s|rem_u|and|xor|or|shl|shr_s|shr_u|rotl|rotr|abs|neg|ceil|floor",
            "trunc|nearest|sqrt|min|max|copysign|wrap|trunc_s|trunc_u|extend_s|extend_u|convert_s",
            "convert_u|demote|promote|reinterpret|failure|switch|case|tableswitch|unreachable|nop|has_feature",
            "assert_invalid|assert_trap|assert_return_nan|assert_return"
        ].join("|");

        var keywordMapper = this.createKeywordMapper({
            "keyword.control":  keywords,
            "keyword.operator": operator,
            "support.function": types
        }, "identifier", true);

        this.$rules = {
            "start": [{
                token: "constant.numeric", // hex, float, octal, binary
                regex: /\\b(((\\+|-)?0(x|X)[0-9a-fA-F]+\\.?[0-9a-fA-F]*((p|P)(\\+|-)?[0-9]+)?)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)\\b/
            }, {
                token: "constant.numeric",
                regex: '\\b(\\+|-)?(?i:infinity|nan)\\b'
            }, {
                token: keywordMapper,
                regex: "\$[a-zA-Z_][a-zA-Z_0-9.]*\\b"
            }, {
                token: "lparen",
                regex: "[[({]"
            }, {
                token: "rparen",
                regex: "[\\])}]"
            }, {
                token: "text",
                regex: "\\s+"
            }]
        };
    };

    oop.inherits(WastHighlightRules, TextHighlightRules);
    exports.WastHighlightRules = WastHighlightRules;
});
<commit_msg>minor fix<commit_after>ace.define('ace/mode/wast_highlight_rules', function (acequire, exports, module) {
    "use strict";

    var oop = acequire("ace/lib/oop");
    var TextHighlightRules = acequire("ace/mode/text_highlight_rules").TextHighlightRules;

    var WastHighlightRules = function () {
        var keywords = ["global|local|type|memory|module|table|import|export|param|offset|start|code",
                        "data|segment|element|invoke|label"].join("|");

        var types    = "i32|i64|f32|f64|anyfunc|func|void";
        var operator = [
            "const|if|else|loop|block|br|br_if|br_table|drop|select|end|return|call|call_indirect|call_import",
            "current_memory|grow_memory|get_local|set_local|tee_local|get_global|set_global",
            "load|load8_s|load8_u|load16_s|load16_u|load32_s|load32_u|store|store8|store16|store32",
            "eqz|eq|ne|lt_s|lt_u|lt|gt_s|gt_u|gt|le_s|le_u|le|ge_s|ge_u|ge|clz|ctz|popcnt|add|sub",
            "mul|div_s|div_u|div|rem_s|rem_u|and|xor|or|shl|shr_s|shr_u|rotl|rotr|abs|neg|ceil|floor",
            "trunc|nearest|sqrt|min|max|copysign|wrap|trunc_s|trunc_u|extend_s|extend_u|convert_s",
            "convert_u|demote|promote|reinterpret|failure|switch|case|tableswitch|unreachable|nop|has_feature",
            "assert_invalid|assert_trap|assert_return_nan|assert_return"
        ].join("|");

        var keywordMapper = this.createKeywordMapper({
            "keyword.control":  keywords,
            "keyword.operator": operator,
            "support.function": types
        }, "identifier", true);

        this.$rules = {
            "start": [{
                token: "constant.numeric", // hex, float, octal, binary
                regex: /\\b(((\\+|-)?0(x|X)[0-9a-fA-F]+\\.?[0-9a-fA-F]*((p|P)(\\+|-)?[0-9]+)?)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)\\b/
            }, {
                token: "constant.numeric",
                regex: '\\b(\\+|-)?(?i:infinity|nan)\\b'
            }, {
                token: keywordMapper,
                regex: "[a-zA-Z_$][a-zA-Z_0-9.]*\\b"
            }, {
                token: "lparen",
                regex: "[[({]"
            }, {
                token: "rparen",
                regex: "[\\])}]"
            }, {
                token: "text",
                regex: "\\s+"
            }]
        };
    };

    oop.inherits(WastHighlightRules, TextHighlightRules);
    exports.WastHighlightRules = WastHighlightRules;
});
<|endoftext|>


<commit_before>app.models.Stream = Backbone.Collection.extend({
  initialize : function(){
    this.posts = new app.collections.Posts();
  },

  url : function(){
    return _.any(this.posts.models) ? this.timeFilteredPath() : this.basePath()
  },

  _fetching : false,

  fetch: function() {
    var self = this

    // we're fetching the collection... there is probably a better way to do this
    self._fetching = true;

    this.posts
      .fetch({
        add : true,
        url : self.url()
      })
      .done(
        function(resp){
          // we're done fetching... there is probably a better way to handle this
          self._fetching = false;

          self.trigger("fetched", self);

          // all loaded?
          if(resp.posts && (resp.posts.author || resp.posts.length == 0)) {
            self.trigger("allPostsLoaded", self);
          }
        }
      )
    return this;
  },

  basePath : function(){
    return document.location.pathname;
  },

  timeFilteredPath : function(){
   return this.basePath() + "?max_time=" + _.last(this.posts.models).createdAt();
  },

  add : function(models){
    this.posts.add(models)
  }
})
<commit_msg>fixed really nasty inf scroll bug (hotfix)<commit_after>app.models.Stream = Backbone.Collection.extend({
  initialize : function(){
    this.posts = new app.collections.Posts();
  },

  url : function(){
    return _.any(this.posts.models) ? this.timeFilteredPath() : this.basePath()
  },

  _fetching : false,

  fetch: function() {
    if(this._fetching) { console.log('no sir'); return false; }
    var self = this

    // we're fetching the collection... there is probably a better way to do this
    self._fetching = true;

    this.posts
      .fetch({
        add : true,
        url : self.url()
      })
      .done(
        function(resp){
          // we're done fetching... there is probably a better way to handle this
          self._fetching = false;

          self.trigger("fetched", self);

          // all loaded?
          if(resp.posts && (resp.posts.author || resp.posts.length == 0)) {
            self.trigger("allPostsLoaded", self);
          }
        }
      )
    return this;
  },

  basePath : function(){
    return document.location.pathname;
  },

  timeFilteredPath : function(){
   return this.basePath() + "?max_time=" + _.last(this.posts.models).createdAt();
  },

  add : function(models){
    this.posts.add(models)
  }
})
<|endoftext|>