<commit_before>// ==UserScript==
// @include http://habrahabr.ru/*
// @include http://*.habrahabr.ru/*
// @include https://*.habrahabr.ru/*
// ==/UserScript==

(function() {
	var loaded = 0, // scripts loaded
	needed = 2, // scripts to load
	checkReady = function() {
		this.onload = null;
		loaded++;
		if (loaded !== needed) {
			return;
		}

		window
				.$(function() {

					document.onkeydown = function(e) {

						e = e || window.event;
						if (e.ctrlKey && e.keyCode == 13) {
							var authors = window.$('.author');
							if (authors.length == 1) {
								var author_name = window.$('.author a').text();
								var author_url = window.$('.author a').attr(
										'href');

								window.$('#dialog').remove();

								window
										.$('body')
										.append('
<form>

Кому: 	<input style="width:300px;" id="habracorrector_recipient" name="recipient" value="'
														+ author_name
														+ '"/>

Тема сообщения:	<input style="width:300px;" id="habracorrector_title" name="theme" value="Ошибка в статье '
														+ window.history.current
														+ '"/>

Текст сообщения:	 <textarea id="habracorrector_text" cols="40" rows="7" name="text">Здравствуйте, '
														+ author_name
														+ '. В вашей статье: '
														+ window.history.current
														+ ' допущена ошибка в этих строках:\n'
														+ window.getSelection()
																.toString()
														+ '\nЯ предлагаю такой правильный вариант:</textarea>

</form>
');

								window.$('#dialog')
										.dialog(
												{
													minWidth : 450,
													buttons : {
														"Отправить" : function() {
															var title = window
																	.$('#habracorrector_title')
																	.attr('value');
															var text = window
																	.$('#habracorrector_text')
																	.html();
															var recipient = window
																	.$('#habracorrector_recipient')
																	.attr('value');
															window.$
																	.post("http://habrahabr.ru/ajax/messages/add/",
																			{
																				'message[recipients]' : recipient,
																				'message[title]' : title,
																				'message[text]' : text
																			},
																			function(
																					data) {
																				window.$
																						.jGrowl(
																								'Сообщение об ошибке отправлено',
																								{});

																			});

															window
																	.$(this)
																	.dialog("close");
														}
													}
												});
							}
						}
						return true;
					}

				});
	}

	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.id = 'myjQuery';
	newScript.onload = checkReady;
	newScript.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js';
	headID.appendChild(newScript);

	newScript = document.createElement('link');
	newScript.rel = 'stylesheet';
	newScript.type = 'text/css';
	newScript.onload = checkReady;
	newScript.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css';
	headID.appendChild(newScript);

})();
<commit_msg>format code<commit_after>// ==UserScript==
// @include http://habrahabr.ru/*
// @include http://*.habrahabr.ru/*
// @include https://*.habrahabr.ru/*
// ==/UserScript==
(function() {
    var loaded = 0,
        // scripts loaded
        needed = 2,
        // scripts to load
        checkReady = function() {
            this.onload = null;
            loaded++;
            if (loaded !== needed) {
                return;
            }

            window.$(function() {

                document.onkeydown = function(e) {

                    e = e || window.event;
                    if (e.ctrlKey && e.keyCode == 13) {
                        var authors = window.$('.author');
                        if (authors.length == 1) {
                            var author_name = window.$('.author a').text();
                            var author_url = window.$('.author a').attr('href');

                            window.$('#dialog').remove();

                            window.$('body').append('
<form>

Кому: 	<input style="width:300px;" id="habracorrector_recipient" name="recipient" value="' + author_name + '"/>

Тема сообщения:	<input style="width:300px;" id="habracorrector_title" name="theme" value="Ошибка в статье ' + window.history.current + '"/>

Текст сообщения:	 <textarea id="habracorrector_text" cols="40" rows="7" name="text">Здравствуйте, ' + author_name + '. В вашей статье: ' + window.history.current + ' допущена ошибка в этих строках:\n' + window.getSelection().toString() + '\nЯ предлагаю такой правильный вариант:</textarea>

</form>
');

                            window.$('#dialog').dialog({
                                minWidth: 450,
                                buttons: {
                                    "Отправить": function() {
                                        var title = window.$('#habracorrector_title').attr('value');
                                        var text = window.$('#habracorrector_text').html();
                                        var recipient = window.$('#habracorrector_recipient').attr('value');
                                        window.$.post("http://habrahabr.ru/ajax/messages/add/", {
                                            'message[recipients]': recipient,
                                            'message[title]': title,
                                            'message[text]': text
                                        }, function(
                                        data) {
                                            window.$.jGrowl('Сообщение об ошибке отправлено', {});

                                        });

                                        window.$(this).dialog("close");
                                    }
                                }
                            });
                        }
                    }
                    return true;
                }

            });
        }

        var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.id = 'myjQuery';
    newScript.onload = checkReady;
    newScript.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js';
    headID.appendChild(newScript);

    newScript = document.createElement('link');
    newScript.rel = 'stylesheet';
    newScript.type = 'text/css';
    newScript.onload = checkReady;
    newScript.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css';
    headID.appendChild(newScript);

})();;
})();
<|endoftext|>


<commit_before>import gulp from 'gulp'
import del from 'del'
import sourcemaps from 'gulp-sourcemaps'
import suitcss from 'gulp-suitcss'
import nunjucks from 'gulp-nunjucks'
import plumber from 'gulp-plumber'
import webpackStream from 'webpack-stream'
import webpack from 'webpack'
import styleLintConfig from '../stylelint.config'
import projectConfig from '../config'

export const EXTRAS_GLOB = 'src/**/*.{txt,json,xml,ico,jpeg,jpg,png,gif,svg,ttf,otf,eot,woff,woff2,mp3,mp4,ogv,ogg,webm}'

gulp.task('clean', () => del('public/'))

gulp.task('remove-help', () => del('public/help'))

gulp.task('webpack', () =>
  webpackStream(require('../webpack.config.js'), webpack)
  .pipe(gulp.dest('public/static/js/')))

gulp.task('css', () =>
  gulp.src('src/static/css/app.css')
    .pipe(sourcemaps.init())
    .pipe(suitcss({
      stylelint: styleLintConfig
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('public/static/css/'))
)

gulp.task('nunjucks', () =>
  gulp.src(['src/templates/**/*.html', '!**/_*'])
    .pipe(plumber())
    .pipe(nunjucks.compile(projectConfig.getProperties(), {
      throwOnUndefined: true,
    }))
    .pipe(plumber.stop())
    .pipe(gulp.dest('public/')))

gulp.task('extras', () =>
  gulp.src(EXTRAS_GLOB)
    .pipe(gulp.dest('public/')))
<commit_msg>Nesting was broken<commit_after>import gulp from 'gulp'
import del from 'del'
import sourcemaps from 'gulp-sourcemaps'
import suitcss from 'gulp-suitcss'
import nunjucks from 'gulp-nunjucks'
import plumber from 'gulp-plumber'
import webpackStream from 'webpack-stream'
import webpack from 'webpack'
import styleLintConfig from '../stylelint.config'
import projectConfig from '../config'

export const EXTRAS_GLOB = 'src/**/*.{txt,json,xml,ico,jpeg,jpg,png,gif,svg,ttf,otf,eot,woff,woff2,mp3,mp4,ogv,ogg,webm}'

gulp.task('clean', () => del('public/'))

gulp.task('remove-help', () => del('public/help'))

gulp.task('webpack', () =>
  webpackStream(require('../webpack.config.js'), webpack)
  .pipe(gulp.dest('public/static/js/')))

gulp.task('css', () =>
  gulp.src('src/static/css/app.css')
    .pipe(sourcemaps.init())
    .pipe(suitcss({
      stylelint: styleLintConfig,
      use: [ 'postcss-nested' ]
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('public/static/css/'))
)

gulp.task('nunjucks', () =>
  gulp.src(['src/templates/**/*.html', '!**/_*'])
    .pipe(plumber())
    .pipe(nunjucks.compile(projectConfig.getProperties(), {
      throwOnUndefined: true,
    }))
    .pipe(plumber.stop())
    .pipe(gulp.dest('public/')))

gulp.task('extras', () =>
  gulp.src(EXTRAS_GLOB)
    .pipe(gulp.dest('public/')))
<|endoftext|>


<commit_before>/*!
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 *
 * classie.has( elem, 'my-class' ) -> true/false
 * classie.add( elem, 'my-new-class' )
 * classie.remove( elem, 'my-unwanted-class' )
 * classie.toggle( elem, 'my-class' )
 */

/*jshint browser: true, strict: true, undef: true */
/*global define: false */

( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

var classie = {
  // full names
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  // short names
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else {
  // browser global
  window.classie = classie;
}

})( window );
<commit_msg>Deleted file<commit_after><|endoftext|>


<commit_before>// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import RenderPermissions from './lib/RenderPermissions';

const propTypes = {
  data: PropTypes.shape({
    userPermissions: PropTypes.arrayOf(PropTypes.object),
    availablePermissions: PropTypes.arrayOf(PropTypes.object),
  }).isRequired,
  mutator: PropTypes.shape({
    userPermissions: PropTypes.shape({
      POST: PropTypes.func.isRequired,
      DELETE: PropTypes.func.isRequired,
    }),
  }),
  viewUserProps: PropTypes.shape({
  }),
};

class UserPermissions extends React.Component {
  static manifest = Object.freeze({
    availablePermissions: {
      type: 'okapi',
      records: 'permissions',
      path: 'perms/permissions?length=100',
    },
    userPermissions: {
      type: 'okapi',
      records: 'permissionNames',
      DELETE: {
        pk: 'permissionName',
        path: 'perms/users/:{username}/permissions',
      },
      GET: {
        path: 'perms/users/:{username}/permissions?full=true',
      },
      path: 'perms/users/:{username}/permissions',
    },
  });

  constructor(props) {
    super(props);

    this.addPermission = this.addPermission.bind(this);
    this.removePermission = this.removePermission.bind(this);
  }

  addPermission(perm) {
    this.props.mutator.userPermissions.POST(perm, this.props.viewUserProps);
  }

  removePermission(perm) {
    this.props.mutator.userPermissions.DELETE(perm, this.props.viewUserProps, perm.permissionName);
  }

  render() {
    const { availablePermissions, userPermissions } = this.props.data;

    return (<RenderPermissions
      {...this.props}
      heading="User Permissions"
      addPermission={this.addPermission}
      removePermission={this.removePermission}
      availablePermissions={availablePermissions}
      listedPermissions={userPermissions}
    />);
  }
}

UserPermissions.propTypes = propTypes;

export default UserPermissions;
<commit_msg>Do not pass perm.permissionName into the DELETE mutator<commit_after>// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes } from 'react';
import RenderPermissions from './lib/RenderPermissions';

const propTypes = {
  data: PropTypes.shape({
    userPermissions: PropTypes.arrayOf(PropTypes.object),
    availablePermissions: PropTypes.arrayOf(PropTypes.object),
  }).isRequired,
  mutator: PropTypes.shape({
    userPermissions: PropTypes.shape({
      POST: PropTypes.func.isRequired,
      DELETE: PropTypes.func.isRequired,
    }),
  }),
  viewUserProps: PropTypes.shape({
  }),
};

class UserPermissions extends React.Component {
  static manifest = Object.freeze({
    availablePermissions: {
      type: 'okapi',
      records: 'permissions',
      path: 'perms/permissions?length=100',
    },
    userPermissions: {
      type: 'okapi',
      records: 'permissionNames',
      DELETE: {
        pk: 'permissionName',
        path: 'perms/users/:{username}/permissions',
      },
      GET: {
        path: 'perms/users/:{username}/permissions?full=true',
      },
      path: 'perms/users/:{username}/permissions',
    },
  });

  constructor(props) {
    super(props);

    this.addPermission = this.addPermission.bind(this);
    this.removePermission = this.removePermission.bind(this);
  }

  addPermission(perm) {
    this.props.mutator.userPermissions.POST(perm, this.props.viewUserProps);
  }

  removePermission(perm) {
    this.props.mutator.userPermissions.DELETE(perm, this.props.viewUserProps);
  }

  render() {
    const { availablePermissions, userPermissions } = this.props.data;

    return (<RenderPermissions
      {...this.props}
      heading="User Permissions"
      addPermission={this.addPermission}
      removePermission={this.removePermission}
      availablePermissions={availablePermissions}
      listedPermissions={userPermissions}
    />);
  }
}

UserPermissions.propTypes = propTypes;

export default UserPermissions;
<|endoftext|>


<commit_before>const { rollup } = require('rollup');
const buble = require('rollup-plugin-buble');
const uglify = require('uglify-js');
const fs = require('fs');
const path = require('path');
const mkdirpNode = require('mkdirp');
const { promisify } = require('util');
const chalk = require('chalk');
const { paths, uglifyOptions } = require('./config');

const localesDir = path.join(__dirname, '..', 'locale');
const files = fs.readdirSync(localesDir);
let cache;

const mkdirp = promisify(mkdirpNode);

async function build () {
  await mkdirp(path.join(paths.dist, 'locale'));
  console.log(chalk.cyan('Building locales...'));

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    process.stdout.write(`${chalk.green(`Output File ${i}/${files.length}: `)} ${file}`);

    // ignore utils file.
    if (/utils/.test(file)) continue;

    const input = path.join(__dirname, '..', 'locale', file);
    const output = path.join(paths.dist, 'locale', file);

    const bundle = await rollup({
      cache,
      input,
      external: ['VeeValidate'],
      plugins: [ buble() ],
    });
    const { code } = await bundle.generate({
      format: 'umd',
      name: `__vee_validate_locale__${file}`,
    });

    fs.writeFileSync(output, uglify.minify(code, uglifyOptions).code);
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
  }
}

build();
<commit_msg>fix: pl locale plurals resolving<commit_after>const { rollup } = require('rollup');
const buble = require('rollup-plugin-buble');
const uglify = require('uglify-js');
const fs = require('fs');
const path = require('path');
const mkdirpNode = require('mkdirp');
const { promisify } = require('util');
const chalk = require('chalk');
const resolve = require('rollup-plugin-node-resolve');
const { paths, uglifyOptions } = require('./config');

const localesDir = path.join(__dirname, '..', 'locale');
const files = fs.readdirSync(localesDir);
let cache;

const mkdirp = promisify(mkdirpNode);

async function build () {
  await mkdirp(path.join(paths.dist, 'locale'));
  console.log(chalk.cyan('Building locales...'));

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    process.stdout.write(`${chalk.green(`Output File ${i}/${files.length}: `)} ${file}`);

    // ignore utils file.
    if (/utils/.test(file)) continue;

    const input = path.join(__dirname, '..', 'locale', file);
    const output = path.join(paths.dist, 'locale', file);

    const bundle = await rollup({
      cache,
      input,
      external: ['VeeValidate'],
      plugins: [buble(), resolve()],
    });
    const { code } = await bundle.generate({
      format: 'umd',
      name: `__vee_validate_locale__${file}`,
    });

    fs.writeFileSync(output, uglify.minify(code, uglifyOptions).code);
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
  }
}

build();
<|endoftext|>


<commit_before>FBL.ns(function() { with (FBL) {

  Firebug.FireFrameModel = extend(Firebug.Module,
  {
    onSelectFrame: function(context) {
        alert("hi");
    }
  });

  Firebug.registerModule(Firebug.FireFrameModel);

}});
<commit_msg>Add basic selector functionality.<commit_after>FBL.ns(function() { with (FBL) {

  Firebug.FireFrameModel = extend(Firebug.Module, {
    onSelectFrame: function(context) {
        var panel = context.getPanel('console');
        panel.inspectable = true;
        Firebug.Inspector.startInspecting(context);
        panel.inspectable = false;
    }
  });

  Firebug.ConsolePanel.prototype.startInspecting = function() {

  }

  Firebug.ConsolePanel.prototype.inspectNode = function(node) {
    return false;
  }

  Firebug.ConsolePanel.prototype.stopInspecting = function(node, canceled) {
    if (canceled === true)
      return;

    alert('Node selected.  Need to walk iframe stack and target it.');
  }

  Firebug.ConsolePanel.prototype.supportsObject = function(object, type) {
    var tagName = object.tagName.toLowerCase();
    return (tagName == "iframe") ? 1 : 0;
  }

  Firebug.ConsolePanel.prototype.inspectHighlightColor = "green";

  Firebug.registerModule(Firebug.FireFrameModel);

}});
<|endoftext|>


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

const plib = require('path');
const fs = require('fs-extra');
const Handlebars = require('handlebars');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const merge = require('webpack-merge');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin;
const baseConfig = require('@jupyterlab/buildutils/lib/webpack.config.base');
const { ModuleFederationPlugin } = webpack.container;

const Build = require('@jupyterlab/buildutils').Build;
const WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
const package_data = require('./package.json');

// Handle the extensions.
const jlab = package_data.jupyterlab;
const extensions = jlab.extensions;
const mimeExtensions = jlab.mimeExtensions;
const { externalExtensions } = jlab;
const packageNames = Object.keys(mimeExtensions).concat(
  Object.keys(extensions),
  Object.keys(externalExtensions)
);

// go throught each external extension
// add to mapping of extension and mime extensions, of package name
// to path of the extension.
for (const key in externalExtensions) {
  const {
    jupyterlab: { extension, mimeExtension }
  } = require(`${key}/package.json`);
  if (extension !== undefined) {
    extensions[key] = extension === true ? '' : extension;
  }
  if (mimeExtension !== undefined) {
    mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  }
}

// Ensure a clear build directory.
const buildDir = plib.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
  fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);

const outputDir = plib.resolve(jlab.outputDir);

// Build the assets
const extraConfig = Build.ensureAssets({
  packageNames: packageNames,
  output: outputDir
});

// Build up singleton metadata for module federation.
const singletons = {};

package_data.jupyterlab.singletonPackages.forEach(element => {
  singletons[element] = { singleton: true };
});

// Go through each external extension
// add to mapping of extension and mime extensions, of package name
// to path of the extension.
for (const key in externalExtensions) {
  const {
    jupyterlab: { extension, mimeExtension }
  } = require(`${key}/package.json`);
  if (extension !== undefined) {
    extensions[key] = extension === true ? '' : extension;
  }
  if (mimeExtension !== undefined) {
    mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  }
}

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

fs.writeFileSync(plib.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
if (outputDir !== buildDir) {
  fs.copySync(
    plib.join(outputDir, 'imports.css'),
    plib.join(buildDir, 'imports.css')
  );
}

// Make a bootstrap entrypoint
const entryPoint = plib.join(buildDir, 'bootstrap.js');
const bootstrap = 'import("./index.out.js");';
fs.writeFileSync(entryPoint, bootstrap);

// Set up variables for the watch mode ignore plugins
const watched = {};
const ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function(name) {
  if (name in watched) {
    return;
  }
  const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  watched[name] = plib.dirname(localPkgPath);
});

// Set up source-map-loader to look in watched lib dirs
const sourceMapRes = Object.values(watched).reduce((res, name) => {
  res.push(new RegExp(name + '/lib'));
  return res;
}, []);

/**
 * Sync a local path to a linked package path if they are files and differ.
 * This is used by `jupyter lab --watch` to synchronize linked packages
 * and has no effect in `jupyter lab --dev-mode --watch`.
 */
function maybeSync(localPath, name, rest) {
  const stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  if (source === fs.realpathSync(localPath)) {
    return;
  }
  fs.watchFile(source, { interval: 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

/**
 * A filter function set up to exclude all files that are not
 * in a package contained by the Jupyterlab repo. Used to ignore
 * files during a `--watch` build.
 */
function ignored(path) {
  path = plib.resolve(path);
  if (path in ignoreCache) {
    // Bail if already found.
    return ignoreCache[path];
  }

  // Limit the watched files to those in our local linked package dirs.
  let ignore = true;
  Object.keys(watched).some(name => {
    const rootPath = watched[name];
    const contained = path.indexOf(rootPath + plib.sep) !== -1;
    if (path !== rootPath && !contained) {
      return false;
    }
    const rest = path.slice(rootPath.length);
    if (rest.indexOf('node_modules') === -1) {
      ignore = false;
      maybeSync(path, name, rest);
    }
    return true;
  });
  ignoreCache[path] = ignore;
  return ignore;
}

const plugins = [
  new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
    verbose: true,
    exclude(instance) {
      // ignore known duplicates
      return ['domelementtype', 'hash-base', 'inherits'].includes(
        instance.name
      );
    }
  }),
  new HtmlWebpackPlugin({
    chunksSortMode: 'none',
    template: plib.join(__dirname, 'templates', 'template.html'),
    title: jlab.name || 'JupyterLab'
  }),
  new webpack.ids.HashedModuleIdsPlugin(),
  // custom plugin for ignoring files during a `--watch` build
  new WPPlugin.FilterWatchIgnorePlugin(ignored),
  // custom plugin that copies the assets to the static directory
  new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  new ModuleFederationPlugin({
    library: {
      type: 'var',
      name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
    },
    name: 'CORE_FEDERATION',
    shared: {
      ...package_data.resolutions,
      ...singletons
    }
  })
];

if (process.argv.includes('--analyze')) {
  plugins.push(new BundleAnalyzerPlugin());
}

module.exports = [
  merge(baseConfig, {
    mode: 'development',
    entry: {
      main: ['whatwg-fetch', entryPoint]
    },
    output: {
      path: plib.resolve(buildDir),
      publicPath: 'static/lab/',
      filename: '[name].[chunkhash].js'
    },
    optimization: {
      splitChunks: {
        chunks: 'all'
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          include: sourceMapRes,
          use: ['source-map-loader'],
          enforce: 'pre'
        }
      ]
    },
    devtool: 'inline-source-map',
    externals: ['node-fetch', 'ws'],
    plugins
  })
].concat(extraConfig);

const logPath = plib.join(buildDir, 'build_log.json');
fs.writeFileSync(logPath, JSON.stringify(module.exports, null, '  '));
<commit_msg>Add slash to publicPath<commit_after>/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/

const plib = require('path');
const fs = require('fs-extra');
const Handlebars = require('handlebars');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const merge = require('webpack-merge');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin;
const baseConfig = require('@jupyterlab/buildutils/lib/webpack.config.base');
const { ModuleFederationPlugin } = webpack.container;

const Build = require('@jupyterlab/buildutils').Build;
const WPPlugin = require('@jupyterlab/buildutils').WPPlugin;
const package_data = require('./package.json');

// Handle the extensions.
const jlab = package_data.jupyterlab;
const extensions = jlab.extensions;
const mimeExtensions = jlab.mimeExtensions;
const { externalExtensions } = jlab;
const packageNames = Object.keys(mimeExtensions).concat(
  Object.keys(extensions),
  Object.keys(externalExtensions)
);

// go throught each external extension
// add to mapping of extension and mime extensions, of package name
// to path of the extension.
for (const key in externalExtensions) {
  const {
    jupyterlab: { extension, mimeExtension }
  } = require(`${key}/package.json`);
  if (extension !== undefined) {
    extensions[key] = extension === true ? '' : extension;
  }
  if (mimeExtension !== undefined) {
    mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  }
}

// Ensure a clear build directory.
const buildDir = plib.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
  fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);

const outputDir = plib.resolve(jlab.outputDir);

// Build the assets
const extraConfig = Build.ensureAssets({
  packageNames: packageNames,
  output: outputDir
});

// Build up singleton metadata for module federation.
const singletons = {};

package_data.jupyterlab.singletonPackages.forEach(element => {
  singletons[element] = { singleton: true };
});

// Go through each external extension
// add to mapping of extension and mime extensions, of package name
// to path of the extension.
for (const key in externalExtensions) {
  const {
    jupyterlab: { extension, mimeExtension }
  } = require(`${key}/package.json`);
  if (extension !== undefined) {
    extensions[key] = extension === true ? '' : extension;
  }
  if (mimeExtension !== undefined) {
    mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension;
  }
}

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

fs.writeFileSync(plib.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', plib.join(buildDir, 'package.json'));
if (outputDir !== buildDir) {
  fs.copySync(
    plib.join(outputDir, 'imports.css'),
    plib.join(buildDir, 'imports.css')
  );
}

// Make a bootstrap entrypoint
const entryPoint = plib.join(buildDir, 'bootstrap.js');
const bootstrap = 'import("./index.out.js");';
fs.writeFileSync(entryPoint, bootstrap);

// Set up variables for the watch mode ignore plugins
const watched = {};
const ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function(name) {
  if (name in watched) {
    return;
  }
  const localPkgPath = require.resolve(plib.join(name, 'package.json'));
  watched[name] = plib.dirname(localPkgPath);
});

// Set up source-map-loader to look in watched lib dirs
const sourceMapRes = Object.values(watched).reduce((res, name) => {
  res.push(new RegExp(name + '/lib'));
  return res;
}, []);

/**
 * Sync a local path to a linked package path if they are files and differ.
 * This is used by `jupyter lab --watch` to synchronize linked packages
 * and has no effect in `jupyter lab --dev-mode --watch`.
 */
function maybeSync(localPath, name, rest) {
  const stats = fs.statSync(localPath);
  if (!stats.isFile(localPath)) {
    return;
  }
  const source = fs.realpathSync(plib.join(jlab.linkedPackages[name], rest));
  if (source === fs.realpathSync(localPath)) {
    return;
  }
  fs.watchFile(source, { interval: 500 }, function(curr) {
    if (!curr || curr.nlink === 0) {
      return;
    }
    try {
      fs.copySync(source, localPath);
    } catch (err) {
      console.error(err);
    }
  });
}

/**
 * A filter function set up to exclude all files that are not
 * in a package contained by the Jupyterlab repo. Used to ignore
 * files during a `--watch` build.
 */
function ignored(path) {
  path = plib.resolve(path);
  if (path in ignoreCache) {
    // Bail if already found.
    return ignoreCache[path];
  }

  // Limit the watched files to those in our local linked package dirs.
  let ignore = true;
  Object.keys(watched).some(name => {
    const rootPath = watched[name];
    const contained = path.indexOf(rootPath + plib.sep) !== -1;
    if (path !== rootPath && !contained) {
      return false;
    }
    const rest = path.slice(rootPath.length);
    if (rest.indexOf('node_modules') === -1) {
      ignore = false;
      maybeSync(path, name, rest);
    }
    return true;
  });
  ignoreCache[path] = ignore;
  return ignore;
}

const plugins = [
  new WPPlugin.NowatchDuplicatePackageCheckerPlugin({
    verbose: true,
    exclude(instance) {
      // ignore known duplicates
      return ['domelementtype', 'hash-base', 'inherits'].includes(
        instance.name
      );
    }
  }),
  new HtmlWebpackPlugin({
    chunksSortMode: 'none',
    template: plib.join(__dirname, 'templates', 'template.html'),
    title: jlab.name || 'JupyterLab'
  }),
  new webpack.ids.HashedModuleIdsPlugin(),
  // custom plugin for ignoring files during a `--watch` build
  new WPPlugin.FilterWatchIgnorePlugin(ignored),
  // custom plugin that copies the assets to the static directory
  new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),
  new ModuleFederationPlugin({
    library: {
      type: 'var',
      name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION']
    },
    name: 'CORE_FEDERATION',
    shared: {
      ...package_data.resolutions,
      ...singletons
    }
  })
];

if (process.argv.includes('--analyze')) {
  plugins.push(new BundleAnalyzerPlugin());
}

module.exports = [
  merge(baseConfig, {
    mode: 'development',
    entry: {
      main: ['whatwg-fetch', entryPoint]
    },
    output: {
      path: plib.resolve(buildDir),
      publicPath: '/static/lab/',
      filename: '[name].[chunkhash].js'
    },
    optimization: {
      splitChunks: {
        chunks: 'all'
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          include: sourceMapRes,
          use: ['source-map-loader'],
          enforce: 'pre'
        }
      ]
    },
    devtool: 'inline-source-map',
    externals: ['node-fetch', 'ws'],
    plugins
  })
].concat(extraConfig);

const logPath = plib.join(buildDir, 'build_log.json');
fs.writeFileSync(logPath, JSON.stringify(module.exports, null, '  '));
<|endoftext|>


<commit_before>var net = require('net');
var helper = require(__dirname+'/../test-helper');

var authConnect = function(username, database, callback) {
  if(typeof username === 'function') {
    callback = username;
    username = helper.args.user;
    database = helper.args.database;
  }
  var connection = new Connection({stream: new net.Stream()});
  connection.connect('5432','localhost');
  connection.once('connect', function() {
    connection.startup({
      user: username,
      database: database
    });
    callback(connection);
  });
};

var connect = function(callback) {
  authConnect(function(con) {
    con.once('readyForQuery', function() {
      con.query('create temp table ids(id integer)');
      con.once('readyForQuery', function() {
        con.query('insert into ids(id) values(1); insert into ids(id) values(2);');
        con.once('readyForQuery', function() {
          callback(con);
        });
      });
    });
  });
};

module.exports = {
  authConnect: authConnect,
  connect: connect
};
<commit_msg>automatically handle connection password from cli args<commit_after>var net = require('net');
var helper = require(__dirname+'/../test-helper');

var authConnect = function(username, database, callback) {
  if(typeof username === 'function') {
    callback = username;
    username = helper.args.user;
    database = helper.args.database;
  }
  var connection = new Connection({stream: new net.Stream()});
  connection.on('error', function(error){
    console.log(error);
    throw new Error("Connection error");
  });
  connection.connect('5432','localhost');
  connection.once('connect', function() {
    connection.startup({
      user: username,
      database: database
    });
    connection.once('authenticationCleartextPassword', function(){
      connection.password(helper.args.password);
    });
    connection.once('authenticationMD5Password', function(msg){
      var inner = Client.md5(helper.args.password+helper.args.user);
      var outer = Client.md5(inner + msg.salt.toString('binary'));
      connection.password("md5"+outer);
    });
    callback(connection);
  });
};

var connect = function(callback) {
  authConnect(function(con) {
    con.once('readyForQuery', function() {
      con.query('create temp table ids(id integer)');
      con.once('readyForQuery', function() {
        con.query('insert into ids(id) values(1); insert into ids(id) values(2);');
        con.once('readyForQuery', function() {
          callback(con);
        });
      });
    });
  });
};

module.exports = {
  authConnect: authConnect,
  connect: connect
};
<|endoftext|>


<commit_before>/**
 * @fileOverview Requirejs module containing base class for device
 * modifiers for media playback
 *
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    "antie/devices/mediaplayer/mediaplayer",
    [
        "antie/class",
        "antie/callbackmanager",
        "antie/runtimecontext"
    ],
    function(Class, CallbackManager, RuntimeContext) {
        "use strict";

        /**
         * Base class for media playback device modifiers.
         * @name antie.devices.mediaplayer.MediaPlayer
         * @class
         * @abstract
         * @extends antie.Class
         */
        var MediaPlayer = Class.extend(/** @lends antie.devices.mediaplayer.MediaPlayer.prototype */ {
            /**
             * @constructor
             * @ignore
             */
            init: function() {
                this._callbackManager = new CallbackManager();
            },

            /**
             * Add an event callback to receive all media player events from now on.
             *
             * Note that failing to remove callbacks when you are finished with them can stop garbage collection
             * of objects/closures containing those callbacks and so create memory leaks in your application.
             * @param {Object} thisArg The object to use as "this" when calling the callback.
             * @param {Function} callback Function to which events are passed (e.g. to be bubbled up the component hierarchy).
             */
            addEventCallback: function(thisArg, callback) {
                this._callbackManager.addCallback(thisArg, callback);
            },

            /**
             * Stop receiving events with the specified callback.
             * @param {Object} thisArg The object specified to use as "this" when adding the callback.
             * @param {Function} callback Function to which events are no longer to be passed
             */
            removeEventCallback: function(thisArg, callback) {
                this._callbackManager.removeCallback(thisArg, callback);
            },

            /**
             * Stop receiving events to any callbacks.
             */
            removeAllEventCallbacks: function() {
                this._callbackManager.removeAllCallbacks();
            },

            /**
             * Protected method, for use by subclasses to emit events of any specified type, adding in the
             * standard payload used by all events.
             * @param {String} eventType The type of the event to be emitted.
             * @protected
             */
            _emitEvent: function(eventType) {

                var event = {
                    type: eventType,
                    currentTime: this.getCurrentTime(),
                    range: this.getRange(),
                    url: this.getSource(),
                    mimeType: this.getMimeType(),
                    state: this.getState()
                };

                this._callbackManager.callAll(event);
            },

            /**
             * @constant {Number}
             */
            CLAMP_OFFSET_FROM_END_OF_RANGE: 0.1,

            /**
             * Clamp a time value so it does not exceed the current range.
             * Clamps to near the end instead of the end itself to allow for devices that cannot seek to the very end of the media.
             * @param {Number} seconds The time value to clamp in seconds from the start of the media
             * @protected
             */
            _getClampedTime: function(seconds) {
                var range = this.getRange();
                var offsetFromEnd = this._getClampOffsetFromConfig();
                var nearToEnd = Math.max(range.end - offsetFromEnd, range.start);
                if (seconds < range.start) {
                    return range.start;
                } else if (seconds > nearToEnd) {
                    return nearToEnd;
                } else {
                    return seconds;
                }
            },

            /**
             * @constant {Number} Time (in seconds) compared to current time within which seeking has no effect.
             */
            CURRENT_TIME_TOLERANCE: 1,

            /**
             * Check whether a time value is near to the current media play time.
             * @param {Number} seconds The time value to test, in seconds from the start of the media
             * @protected
             */
            _isNearToCurrentTime: function(seconds) {
                var currentTime = this.getCurrentTime();
                var targetTime = this._getClampedTime(seconds);
                return Math.abs(currentTime - targetTime) <= this.CURRENT_TIME_TOLERANCE;
            },

            /**
             * Set the media resource to be played.
             * Calling this in any state other than EMPTY is an error.
             * @param {antie.devices.mediaplayer.MediaPlayer.TYPE} mediaType Value from the MediaPlayer.TYPE enum; audio or video.
             * @param {String} url location of the media resource to play
             * @param {String} mimeType type of media resource
             */
            setSource: function (mediaType, url, mimeType) {
                throw new Error("setSource method has not been implemented");
            },

            /**
             * Request that the media start playing from Time.
             * A media source must have been set with setSource before calling this.
             * This can be used to resume media after changing source.
             * This may transition to the buffering state if enough media data is not yet available to play.
             * If the media is buffering, call this to resume playback in a playing state once buffering ends.
             * Calling this in state EMPTY is an error.
             * Clamps the time to the seekable range of the media.
             * If trying to play at (or past) the very end of the media, this will actually begin playback just before the end.
             * This allows the media playback to complete normally.
             * @param {Number} seconds Time to play from in seconds from the start of the media
             */
            playFrom: function (seconds) {
                throw new Error("playFrom method has not been implemented");
            },

            /**
             * Begin playback of the media resource from wherever the device chooses.
             * For On Demand assets, this will normally be the start, for Live stream assets it should be the live point
             * but could be the start of the stream window on some devices.
             * This function can only be called from the STOPPED state; calling it from any other state is an error.
             * To begin playback from a specified time offset, use the playFrom function instead.
             */
            beginPlayback: function () {
                throw new Error("beginPlayback method has not been implemented");
            },

            /**
             * Request that the media be paused.
             * If the Media is playing, call this to pause it.
             * If the media is buffering, call this to resume playback in a paused state once buffering ends.
             * Calling this in state EMPTY or STOPPED is an error.
             */
            pause: function () {
                throw new Error("pause method has not been implemented");
            },

            /**
             * Request that the media resume playing after being paused.
             * If the Media is paused, call this to resume playing it.
             * If the media is buffering, call this to resume playback in a playing state once buffering ends.
             * Calling this in state EMPTY or STOPPED is an error.
             */
            resume: function () {
                throw new Error("resume method has not been implemented");
            },

            /**
             * Request that the media be stopped.
             * If the Media is playing, call this to stop the media.
             * Note that the source is still set after calling stop.
             * Call reset after stop to unset the source.
             * Calling this in state EMPTY is an error.
             */
            stop: function () {
                throw new Error("stop method has not been implemented");
            },

            /**
             * Reset the Media Player.
             * When the media is stopped, calling reset will reset the player to a clean state with no source set.
             * Calling this in any state other than STOPPED or ERROR is an error.
             */
            reset: function () {
                throw new Error("reset method has not been implemented");
            },

            /**
             * Get the source URL.
             * If no source is set (in state EMPTY for example), then this returns undefined.
             * @return {String} The URL
             */
            getSource: function () {
                throw new Error("getSource method has not been implemented");
            },

            /**
            * Get the source MIME type.
            * If no source is set (in state EMPTY for example), then this returns undefined.
            * @return {String} The MIME type
            */
            getMimeType: function () {
                throw new Error("getMimeType method has not been implemented");
            },

            /**
            * Get the current play time.
            * If no current time is available, then this returns undefined.
            * @return {Number} The current play time in seconds from the start of the media.
            */
            getCurrentTime: function () {
                throw new Error("getCurrentTime method has not been implemented");
            },

            /**
            * Get the available range of media.
            * Returns a range Object with 'start' and 'end' numeric properties, giving the start and end of the available media in seconds from the start of the media.
            * For VOD playback, 'start' is zero and 'end' is the media duration.
            * For Live playback, 'start' may be non-zero, reflecting the amount of 'live rewind' available before the current play position.
            * For live playback, 'end' is the current live time.
            * For live playback, both 'start' and 'end' may advance over time.
            * If no range is available, then this returns an object with 'start' and 'end' properties which both have the value undefined.
            * @return {Object} Object with 'start' and 'end' numeric properties.
            */
            getRange: function () {
                throw new Error("getRange method has not been implemented");
            },

            /**
            * Get the current state of the Media PLayer state machine.
            * @return {antie.devices.mediaplayer.MediaPlayer.STATE} The current state of the Media Player state machine.
            */
            getState: function () {
                throw new Error("getState method has not been implemented");
            },

            _getClampOffsetFromConfig: function() {
                var clampOffsetFromEndOfRange;
                var config = RuntimeContext.getDevice().getConfig();
                if (config && config.streaming && config.streaming.overrides) {
                    clampOffsetFromEndOfRange = config.streaming.overrides.clampOffsetFromEndOfRange;
                }

                if(clampOffsetFromEndOfRange !== undefined) {
                    return clampOffsetFromEndOfRange;
                } else {
                    return this.CLAMP_OFFSET_FROM_END_OF_RANGE;
                }
            }
        });

        /**
        * An enumeration of possible media player states.
        * @name antie.devices.mediaplayer.MediaPlayer.STATE
        * @enum {String}
        */
        MediaPlayer.STATE = {
            EMPTY:      "EMPTY",     // No source set
            STOPPED:    "STOPPED",   // Source set but no playback
            BUFFERING:  "BUFFERING", // Not enough data to play, waiting to download more
            PLAYING:    "PLAYING",   // Media is playing
            PAUSED:     "PAUSED",    // Media is paused
            COMPLETE:   "COMPLETE",  // Media has reached its end point
            ERROR:      "ERROR"      // An error occurred
        };

        /**
        * Media Player event names
        */
        MediaPlayer.EVENT = {
            STOPPED:   "stopped",   // Event fired when playback is stopped
            BUFFERING: "buffering", // Event fired when playback has to suspend due to buffering
            PLAYING:   "playing",   // Event fired when starting (or resuming) playing of the media
            PAUSED:    "paused",    // Event fired when media playback pauses
            COMPLETE:  "complete",  // Event fired when media playback has reached the end of the media
            ERROR:     "error",     // Event fired when an error condition occurs
            STATUS:    "status",    // Event fired regularly during play
            SENTINEL_ENTER_BUFFERING:  "sentinel-enter-buffering", // Event fired when a sentinel has to act because the device has started buffering but not reported it
            SENTINEL_EXIT_BUFFERING:   "sentinel-exit-buffering",  // Event fired when a sentinel has to act because the device has finished buffering but not reported it
            SENTINEL_PAUSE:            "sentinel-pause",           // Event fired when a sentinel has to act because the device has failed to pause when expected
            SENTINEL_PLAY:             "sentinel-play",            // Event fired when a sentinel has to act because the device has failed to play when expected
            SENTINEL_SEEK:             "sentinel-seek",            // Event fired when a sentinel has to act because the device has failed to seek to the correct location
            SENTINEL_COMPLETE:         "sentinel-complete"         // Event fired when a sentinel has to act because the device has completed the media but not reported it
        };

        /**
         * An enumeration of valid Media Types.
         * @name antie.devices.mediaplayer.MediaPlayer.TYPE
         * @enum {String}
         */
        MediaPlayer.TYPE = {
            VIDEO: "video",
            AUDIO: "audio"
        };

        return MediaPlayer;
    }
);
<commit_msg>Add stub for getDuration() and update relevant JsDoc<commit_after>/**
 * @fileOverview Requirejs module containing base class for device
 * modifiers for media playback
 *
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    "antie/devices/mediaplayer/mediaplayer",
    [
        "antie/class",
        "antie/callbackmanager",
        "antie/runtimecontext"
    ],
    function(Class, CallbackManager, RuntimeContext) {
        "use strict";

        /**
         * Base class for media playback device modifiers.
         * @name antie.devices.mediaplayer.MediaPlayer
         * @class
         * @abstract
         * @extends antie.Class
         */
        var MediaPlayer = Class.extend(/** @lends antie.devices.mediaplayer.MediaPlayer.prototype */ {
            /**
             * @constructor
             * @ignore
             */
            init: function() {
                this._callbackManager = new CallbackManager();
            },

            /**
             * Add an event callback to receive all media player events from now on.
             *
             * Note that failing to remove callbacks when you are finished with them can stop garbage collection
             * of objects/closures containing those callbacks and so create memory leaks in your application.
             * @param {Object} thisArg The object to use as "this" when calling the callback.
             * @param {Function} callback Function to which events are passed (e.g. to be bubbled up the component hierarchy).
             */
            addEventCallback: function(thisArg, callback) {
                this._callbackManager.addCallback(thisArg, callback);
            },

            /**
             * Stop receiving events with the specified callback.
             * @param {Object} thisArg The object specified to use as "this" when adding the callback.
             * @param {Function} callback Function to which events are no longer to be passed
             */
            removeEventCallback: function(thisArg, callback) {
                this._callbackManager.removeCallback(thisArg, callback);
            },

            /**
             * Stop receiving events to any callbacks.
             */
            removeAllEventCallbacks: function() {
                this._callbackManager.removeAllCallbacks();
            },

            /**
             * Protected method, for use by subclasses to emit events of any specified type, adding in the
             * standard payload used by all events.
             * @param {String} eventType The type of the event to be emitted.
             * @protected
             */
            _emitEvent: function(eventType) {

                var event = {
                    type: eventType,
                    currentTime: this.getCurrentTime(),
                    range: this.getRange(),
                    url: this.getSource(),
                    mimeType: this.getMimeType(),
                    state: this.getState()
                };

                this._callbackManager.callAll(event);
            },

            /**
             * @constant {Number}
             */
            CLAMP_OFFSET_FROM_END_OF_RANGE: 0.1,

            /**
             * Clamp a time value so it does not exceed the current range.
             * Clamps to near the end instead of the end itself to allow for devices that cannot seek to the very end of the media.
             * @param {Number} seconds The time value to clamp in seconds from the start of the media
             * @protected
             */
            _getClampedTime: function(seconds) {
                var range = this.getRange();
                var offsetFromEnd = this._getClampOffsetFromConfig();
                var nearToEnd = Math.max(range.end - offsetFromEnd, range.start);
                if (seconds < range.start) {
                    return range.start;
                } else if (seconds > nearToEnd) {
                    return nearToEnd;
                } else {
                    return seconds;
                }
            },

            /**
             * @constant {Number} Time (in seconds) compared to current time within which seeking has no effect.
             */
            CURRENT_TIME_TOLERANCE: 1,

            /**
             * Check whether a time value is near to the current media play time.
             * @param {Number} seconds The time value to test, in seconds from the start of the media
             * @protected
             */
            _isNearToCurrentTime: function(seconds) {
                var currentTime = this.getCurrentTime();
                var targetTime = this._getClampedTime(seconds);
                return Math.abs(currentTime - targetTime) <= this.CURRENT_TIME_TOLERANCE;
            },

            /**
             * Set the media resource to be played.
             * Calling this in any state other than EMPTY is an error.
             * @param {antie.devices.mediaplayer.MediaPlayer.TYPE} mediaType Value from the MediaPlayer.TYPE enum; audio or video.
             * @param {String} url location of the media resource to play
             * @param {String} mimeType type of media resource
             */
            setSource: function (mediaType, url, mimeType) {
                throw new Error("setSource method has not been implemented");
            },

            /**
             * Request that the media start playing from Time.
             * A media source must have been set with setSource before calling this.
             * This can be used to resume media after changing source.
             * This may transition to the buffering state if enough media data is not yet available to play.
             * If the media is buffering, call this to resume playback in a playing state once buffering ends.
             * Calling this in state EMPTY is an error.
             * Clamps the time to the seekable range of the media.
             * If trying to play at (or past) the very end of the media, this will actually begin playback just before the end.
             * This allows the media playback to complete normally.
             * @param {Number} seconds Time to play from in seconds from the start of the media
             */
            playFrom: function (seconds) {
                throw new Error("playFrom method has not been implemented");
            },

            /**
             * Begin playback of the media resource from wherever the device chooses.
             * For On Demand assets, this will normally be the start, for Live stream assets it should be the live point
             * but could be the start of the stream window on some devices.
             * This function can only be called from the STOPPED state; calling it from any other state is an error.
             * To begin playback from a specified time offset, use the playFrom function instead.
             */
            beginPlayback: function () {
                throw new Error("beginPlayback method has not been implemented");
            },

            /**
             * Request that the media be paused.
             * If the Media is playing, call this to pause it.
             * If the media is buffering, call this to resume playback in a paused state once buffering ends.
             * Calling this in state EMPTY or STOPPED is an error.
             */
            pause: function () {
                throw new Error("pause method has not been implemented");
            },

            /**
             * Request that the media resume playing after being paused.
             * If the Media is paused, call this to resume playing it.
             * If the media is buffering, call this to resume playback in a playing state once buffering ends.
             * Calling this in state EMPTY or STOPPED is an error.
             */
            resume: function () {
                throw new Error("resume method has not been implemented");
            },

            /**
             * Request that the media be stopped.
             * If the Media is playing, call this to stop the media.
             * Note that the source is still set after calling stop.
             * Call reset after stop to unset the source.
             * Calling this in state EMPTY is an error.
             */
            stop: function () {
                throw new Error("stop method has not been implemented");
            },

            /**
             * Reset the Media Player.
             * When the media is stopped, calling reset will reset the player to a clean state with no source set.
             * Calling this in any state other than STOPPED or ERROR is an error.
             */
            reset: function () {
                throw new Error("reset method has not been implemented");
            },

            /**
             * Get the source URL.
             * If no source is set (in state EMPTY for example), then this returns undefined.
             * @return {String} The URL
             */
            getSource: function () {
                throw new Error("getSource method has not been implemented");
            },

            /**
            * Get the source MIME type.
            * If no source is set (in state EMPTY for example), then this returns undefined.
            * @return {String} The MIME type
            */
            getMimeType: function () {
                throw new Error("getMimeType method has not been implemented");
            },

            /**
            * Get the current play time.
            * If no current time is available, then this returns undefined.
            * @return {Number} The current play time in seconds from the start of the media.
            */
            getCurrentTime: function () {
                throw new Error("getCurrentTime method has not been implemented");
            },

            /**
            * Get the available seekable range of media.
            * Returns a range Object with 'start' and 'end' numeric properties, giving the start and end of the available media in seconds from the start of the media.
            * For VOD playback, 'start' is zero and 'end' is the last possible seek time (in many cases equal to duration).
            * For Live playback, 'start' may be non-zero, reflecting the amount of 'live rewind' available before the current play position.
            * For live playback, 'end' is the current live time.
            * For live playback, both 'start' and 'end' may advance over time.
            * If no range is available, this returns undefined.
            * @return {Object} Object with 'start' and 'end' times in seconds, or undefined.
            */
            getRange: function () {
                throw new Error("getRange method has not been implemented");
            },

            /**
             * Get the duration of the media in seconds.
             * For VOD playback, this is the duration of the media.
             * For Live playback, this is positive Infinity.
             * If no duration is available, this returns undefined.
             * @return {Number} Duration of media in seconds, or Infinity, or undefined.
             */
            getDuration: function() {
                throw new Error("getDuration method has not been implemented");
            },

            /**
            * Get the current state of the Media PLayer state machine.
            * @return {antie.devices.mediaplayer.MediaPlayer.STATE} The current state of the Media Player state machine.
            */
            getState: function () {
                throw new Error("getState method has not been implemented");
            },

            _getClampOffsetFromConfig: function() {
                var clampOffsetFromEndOfRange;
                var config = RuntimeContext.getDevice().getConfig();
                if (config && config.streaming && config.streaming.overrides) {
                    clampOffsetFromEndOfRange = config.streaming.overrides.clampOffsetFromEndOfRange;
                }

                if(clampOffsetFromEndOfRange !== undefined) {
                    return clampOffsetFromEndOfRange;
                } else {
                    return this.CLAMP_OFFSET_FROM_END_OF_RANGE;
                }
            }
        });

        /**
        * An enumeration of possible media player states.
        * @name antie.devices.mediaplayer.MediaPlayer.STATE
        * @enum {String}
        */
        MediaPlayer.STATE = {
            EMPTY:      "EMPTY",     // No source set
            STOPPED:    "STOPPED",   // Source set but no playback
            BUFFERING:  "BUFFERING", // Not enough data to play, waiting to download more
            PLAYING:    "PLAYING",   // Media is playing
            PAUSED:     "PAUSED",    // Media is paused
            COMPLETE:   "COMPLETE",  // Media has reached its end point
            ERROR:      "ERROR"      // An error occurred
        };

        /**
        * Media Player event names
        */
        MediaPlayer.EVENT = {
            STOPPED:   "stopped",   // Event fired when playback is stopped
            BUFFERING: "buffering", // Event fired when playback has to suspend due to buffering
            PLAYING:   "playing",   // Event fired when starting (or resuming) playing of the media
            PAUSED:    "paused",    // Event fired when media playback pauses
            COMPLETE:  "complete",  // Event fired when media playback has reached the end of the media
            ERROR:     "error",     // Event fired when an error condition occurs
            STATUS:    "status",    // Event fired regularly during play
            SENTINEL_ENTER_BUFFERING:  "sentinel-enter-buffering", // Event fired when a sentinel has to act because the device has started buffering but not reported it
            SENTINEL_EXIT_BUFFERING:   "sentinel-exit-buffering",  // Event fired when a sentinel has to act because the device has finished buffering but not reported it
            SENTINEL_PAUSE:            "sentinel-pause",           // Event fired when a sentinel has to act because the device has failed to pause when expected
            SENTINEL_PLAY:             "sentinel-play",            // Event fired when a sentinel has to act because the device has failed to play when expected
            SENTINEL_SEEK:             "sentinel-seek",            // Event fired when a sentinel has to act because the device has failed to seek to the correct location
            SENTINEL_COMPLETE:         "sentinel-complete"         // Event fired when a sentinel has to act because the device has completed the media but not reported it
        };

        /**
         * An enumeration of valid Media Types.
         * @name antie.devices.mediaplayer.MediaPlayer.TYPE
         * @enum {String}
         */
        MediaPlayer.TYPE = {
            VIDEO: "video",
            AUDIO: "audio"
        };

        return MediaPlayer;
    }
);
<|endoftext|>


<commit_before>const Context = require('../lib/context');
const { expect } = require('chai');
const sinon = require('sinon');

describe('Context', () => {
    describe('#startTimeout', () => {
        it('sets the execution timeout', (done) => {
            const ctx = new Context({});
            ctx.done = done;
            ctx.startTimeout();
            expect(ctx.timeout).to.not.be.equal(undefined);
            ctx.stop();
            done();
        });
    });
    describe('#start', () => {
        const ctx = new Context({});
        it('Starts a timeout', (done) => {
            ctx.done = done;
            const spy = sinon.spy(ctx, 'startTimeout');
            ctx.start((ctx, done) => {
                expect(spy.called).to.be.ok;
                ctx.stop();
                spy.restore();
                done();
            });
        });
        it('Execute sync job', (done) => {
            ctx.done = () => {
                ctx.stop();
                done();
            };
            ctx.start((ctx, done) => {
                done();
            });
        });
        it('Execute resolved job', (done) => {
            ctx.done = () => {
                ctx.stop();
                done();
            };
            ctx.start(async (ctx, done) => {
                return Promise.resolve(true);
            });
        });
        it('Execute rejected job', (end) => {
            ctx.done = (err, res) => {
                expect(err).to.exist;
                ctx.stop();
                end();
            };
            ctx.start((ctx, done) => {
                return Promise.reject(new Error('Rejected test'));
            });
        });
    });

    describe('#retryable', () => {
        it('Returns the date/time it is going to retry', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 2,
                retry: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.retryable()).to.be.equal('2020-12-20T12:14:25.864Z');
        });
        it('Returns false when it have reached retry limit', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 3,
                retry: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.retryable()).to.be.equal(false);
        });
        it('Returns false when retry is not defined', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 3
            });
            expect(ctx.retryable()).to.be.equal(false);
        });
    });

    describe('#repeatable', () => {
        it('Returns the date of next execution', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                repetitions: 2,
                repeat: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.repeatable()).to.be.equal('2020-12-20T12:14:25.864Z');
        });
        it('Returns false when have reached its recurrency cycle', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                repetitions: 3,
                repeat: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.repeatable()).to.be.equal(false);
        });
    });
    describe('#next', () => {
        let task = {};
        const job = (ctx, done) => {
            done();
        }
        beforeEach(() => {
            task = {
                id: '101020teste2010',
                date: '2018-12-20T12:14:25.864Z',
                job: 'compress',
                worker: 'manobi',
                retries: 0,
                data: {
                    src: 'https://images.dog.ceo/breeds/pointer-german/n02100236_1941.jpg',
                    level: 100
                }
            }
        });

        it('Increment the execution counter', () => {
            const incrementalTask = {
                ...task,
                executions: 1
            }
            const ctx = new Context(incrementalTask);
            ctx.done = () => {
                ctx.stop();
            }
            ctx.start(job);

            const next = {
                ...task,
                status: 'failed',
                error: {error: true},
                result: false,
                duration: ctx.duration,
                executions: 2,
                repetitions: 0
            };
            expect(ctx.next({error: true})).to.be.deep.equal(next);
        });

        describe('When error', () => {
            it('without retry the status is "failed"', () => {
                const ctx = new Context(task);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'failed',
                    error: {error: true},
                    result: false,
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next({error: true})).to.be.deep.equal(next);
            });

            it('with retry the status is retry and future date', () => {
                const retryableTask = {
                    ...task,
                    retries: 1,
                    retry: {
                        limit: 2,
                        interval: {
                            year: 1
                        }
                    }
                };
                const ctx = new Context(retryableTask);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...retryableTask,
                    date: '2019-12-20T12:14:25.864Z',
                    status: 'retry',
                    error: {error: true},
                    result: false,
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next({error: true})).to.be.deep.equal(next);
            });
        });

        describe('When success', () => {
            it('without repeat option', () => {
                const ctx = new Context(task);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'complete',
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });

            it('with retries reset attempts', () => {
                const ctx = new Context({
                    ...task,
                    retries: 3
                });
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'complete',
                    retries: 0,
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });

            it('with repeat status is done and future date', () => {
                const repeatableTask = {
                    ...task,
                    repetitions: 1,
                    repeat: {
                        limit: 2,
                        interval: {
                            year: 1
                        }
                    }
                };
                const ctx = new Context(repeatableTask);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...repeatableTask,
                    date: '2019-12-20T12:14:25.864Z',
                    status: 'done',
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    repetitions: 1,
                    executions: 1
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });
        });
    });
});<commit_msg>tests for ctx.cancel<commit_after>const Context = require('../lib/context');
const { expect } = require('chai');
const sinon = require('sinon');

describe('Context', () => {
    describe('#startTimeout', () => {
        it('sets the execution timeout', (done) => {
            const ctx = new Context({});
            ctx.done = done;
            ctx.startTimeout();
            expect(ctx.timeout).to.not.be.equal(undefined);
            ctx.stop();
            done();
        });
    });
    describe('#start', () => {
        const ctx = new Context({});
        it('Starts a timeout', (done) => {
            ctx.done = done;
            const spy = sinon.spy(ctx, 'startTimeout');
            ctx.start((ctx, done) => {
                expect(spy.called).to.be.ok;
                ctx.stop();
                spy.restore();
                done();
            });
        });
        it('Execute sync job', (done) => {
            ctx.done = () => {
                ctx.stop();
                done();
            };
            ctx.start((ctx, done) => {
                done();
            });
        });
        it('Execute resolved job', (done) => {
            ctx.done = () => {
                ctx.stop();
                done();
            };
            ctx.start(async (ctx, done) => {
                return Promise.resolve(true);
            });
        });
        it('Execute rejected job', (end) => {
            ctx.done = (err, res) => {
                expect(err).to.exist;
                ctx.stop();
                end();
            };
            ctx.start((ctx, done) => {
                return Promise.reject(new Error('Rejected test'));
            });
        });
    });

    describe('cancel', () => {
        const ctx = new Context({});
        it('aborts an execution', (done) => {
            let spy = sinon.spy();
            ctx.done = done;
            ctx.start((ctx, done) => {
                setTimeout(spy, 1000);
            });
            ctx.cancel();
            expect(spy).to.not.have.been.called;
            ctx.stop();
            done();
        });
        it('calls clearTimeout', (done) => {
            let spy = sinon.spy(global, 'clearTimeout');
            ctx.done = done;
            ctx.start((ctx, done) => {
                setTimeout(done, 1000);
            });
            ctx.cancel();
            expect(spy).to.have.been.called;
            ctx.stop();
            done();
        });
    });

    describe('#retryable', () => {
        it('Returns the date/time it is going to retry', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 2,
                retry: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.retryable()).to.be.equal('2020-12-20T12:14:25.864Z');
        });
        it('Returns false when it have reached retry limit', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 3,
                retry: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.retryable()).to.be.equal(false);
        });
        it('Returns false when retry is not defined', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                retries: 3
            });
            expect(ctx.retryable()).to.be.equal(false);
        });
    });

    describe('#repeatable', () => {
        it('Returns the date of next execution', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                repetitions: 2,
                repeat: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.repeatable()).to.be.equal('2020-12-20T12:14:25.864Z');
        });
        it('Returns false when have reached its recurrency cycle', () => {
            const ctx = new Context({
                date: '2018-12-20T12:14:25.864Z',
                repetitions: 3,
                repeat: {
                    limit: 3,
                    interval: {
                        year: 2
                    }
                }
            });
            expect(ctx.repeatable()).to.be.equal(false);
        });
    });

    describe('#next', () => {
        let task = {};
        const job = (ctx, done) => {
            done();
        }
        beforeEach(() => {
            task = {
                id: '101020teste2010',
                date: '2018-12-20T12:14:25.864Z',
                job: 'compress',
                worker: 'manobi',
                retries: 0,
                data: {
                    src: 'https://images.dog.ceo/breeds/pointer-german/n02100236_1941.jpg',
                    level: 100
                }
            }
        });

        it('Increment the execution counter', () => {
            const incrementalTask = {
                ...task,
                executions: 1
            }
            const ctx = new Context(incrementalTask);
            ctx.done = () => {
                ctx.stop();
            }
            ctx.start(job);

            const next = {
                ...task,
                status: 'failed',
                error: {error: true},
                result: false,
                duration: ctx.duration,
                executions: 2,
                repetitions: 0
            };
            expect(ctx.next({error: true})).to.be.deep.equal(next);
        });

        describe('When error', () => {
            it('without retry the status is "failed"', () => {
                const ctx = new Context(task);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'failed',
                    error: {error: true},
                    result: false,
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next({error: true})).to.be.deep.equal(next);
            });

            it('with retry the status is retry and future date', () => {
                const retryableTask = {
                    ...task,
                    retries: 1,
                    retry: {
                        limit: 2,
                        interval: {
                            year: 1
                        }
                    }
                };
                const ctx = new Context(retryableTask);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...retryableTask,
                    date: '2019-12-20T12:14:25.864Z',
                    status: 'retry',
                    error: {error: true},
                    result: false,
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next({error: true})).to.be.deep.equal(next);
            });
        });

        describe('When success', () => {
            it('without repeat option', () => {
                const ctx = new Context(task);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'complete',
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });

            it('with retries reset attempts', () => {
                const ctx = new Context({
                    ...task,
                    retries: 3
                });
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...task,
                    status: 'complete',
                    retries: 0,
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    executions: 1,
                    repetitions: 0
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });

            it('with repeat status is done and future date', () => {
                const repeatableTask = {
                    ...task,
                    repetitions: 1,
                    repeat: {
                        limit: 2,
                        interval: {
                            year: 1
                        }
                    }
                };
                const ctx = new Context(repeatableTask);
                ctx.done = () => {
                    ctx.stop();
                }
                ctx.start(job);
                const next = {
                    ...repeatableTask,
                    date: '2019-12-20T12:14:25.864Z',
                    status: 'done',
                    error: null,
                    result: {success: true},
                    duration: ctx.duration,
                    repetitions: 1,
                    executions: 1
                };
                expect(ctx.next(null, {success: true})).to.be.deep.equal(next);
            });
        });
    });
});<|endoftext|>


<commit_before>'use strict';
(function(app) {
	app.HTTPService = (function() {
		var HTTPService = function(http) {
			this.http = http;
		};
		HTTPService.parameters = [
			ng.http.Http
		];
		HTTPService.prototype.get = function(reqId, url, o, p) {
			return this.http
				.get(url + '?o=' + o + '&p=' + p, {
					"cache":   false,
					"headers": {
						"x-reqid": reqId
					}
				})
				.map(function(response) {
					var h_reqId   = response.headers.get('x-reqid'),
					    h_rtt     = response.headers.get('x-angular-time'),
					    is_cached = response.headers.get('x-cache-status' === 'HIT';
					return {
						"json":   response.json() || {},
						"reqId":  parseInt(h_reqId),
						"rtt":    parseInt(h_rtt),
						"tsn":    is_cached ? 0.5 : parseFloat(response.headers.get('x-nginx-time') * 1000.0) | 0,
						"exts":   is_cached ? 0 : parseFloat(response.headers.get('x-node-time')),
						"red":    is_cached ? 0 : parseFloat(response.headers.get('x-redis-time')),
						"cached": is_cached
					};
				})
				.catch();
		};
		HTTPService.prototype.post = function(url, body) {
			return this.http
				.post(url + '?time=' + Date.now(), body, {
					"cache":   false,
					"headers": {
						"Cache-Control":     'no-cache, no-store, must-revalidate',
						"If-Modified-Since": 'Mon, 26 Jul 1997 05:00:00 GMT',
						"Pragma":            'no-cache'
					}
				})
				.map(function(response) {
					return response.json() || {};
				})
				.catch();
		};
		return HTTPService;
	})();
})(window.app || (window.app = {}));
<commit_msg>V8 deoptimization prevention updates<commit_after>'use strict';
(function(app) {
	app.HTTPService = (function() {
		var HTTPService = function(http) {
			this.http = http;
		};
		HTTPService.parameters = [
			ng.http.Http
		];
		HTTPService.prototype.get = function(reqId, url, o, p) {
			return this.http
				.get(url + '?o=' + o + '&p=' + p, {
					"cache":   false,
					"headers": {
						"x-reqid": reqId
					}
				})
				.map(function(response) {
					var is_cached = response.headers.get('x-cache-status') === 'HIT';
					return {
						"json":   response.json() || {},
						"reqId":  parseInt(response.headers.get('x-reqid')),
						"rtt":    parseInt(response.headers.get('x-angular-time')),
						"tsn":    is_cached ? 0.5 : parseFloat(response.headers.get('x-nginx-time') * 1000.0) | 0,
						"exts":   is_cached ? 0 : parseFloat(response.headers.get('x-node-time')),
						"red":    is_cached ? 0 : parseFloat(response.headers.get('x-redis-time')),
						"cached": is_cached
					};
				})
				.catch();
		};
		HTTPService.prototype.post = function(url, body) {
			return this.http
				.post(url + '?time=' + Date.now(), body, {
					"cache":   false,
					"headers": {
						"Cache-Control":     'no-cache, no-store, must-revalidate',
						"If-Modified-Since": 'Mon, 26 Jul 1997 05:00:00 GMT',
						"Pragma":            'no-cache'
					}
				})
				.map(function(response) {
					return response.json() || {};
				})
				.catch();
		};
		return HTTPService;
	})();
})(window.app || (window.app = {}));
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import expect from 'unexpected';

import CardComponent from './CardComponent';

const shallowRenderer = TestUtils.createRenderer();

describe('CardComponent', () => {
  it('should render', () => {
    shallowRenderer.render(<CardComponent title="Title" />);
    expect(shallowRenderer.getRenderOutput(), 'to be defined');
  });
});<commit_msg>Add systemjs import for tests<commit_after>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import expect from 'unexpected';
import System from 'systemjs';

import CardComponent from './CardComponent';

const shallowRenderer = TestUtils.createRenderer();

describe('CardComponent', () => {
  it('should render', () => {
    shallowRenderer.render(<CardComponent title="Title" />);
    expect(shallowRenderer.getRenderOutput(), 'to be defined');
  });
});<|endoftext|>