<commit_before>// @flow
/* eslint react/no-unescaped-entities: 0 */

import React from 'react';
import { compose, withState } from 'recompose';
import { connect } from 'react-redux';
import urlJoin from 'url-join';

import { authPartitionFiles } from '@ncigdc/utils/auth';
import DownloadButton from '@ncigdc/components/DownloadButton';
import BaseModal from '@ncigdc/components/Modals/BaseModal';
import CheckBoxModal from '@ncigdc/components/Modals/CheckBoxModal';
import LoginButton from '@ncigdc/components/LoginButton';

import DownCaretIcon from 'react-icons/lib/fa/caret-down';

import { setModal } from '@ncigdc/dux/modal';

import Dropdown from '@ncigdc/uikit/Dropdown';
import Button from '@ncigdc/uikit/Button';
import { Column, Row } from '@ncigdc/uikit/Flex';
import { ExternalLink } from '@ncigdc/uikit/Links';

import { withTheme } from '@ncigdc/theme';
import DownloadIcon from '@ncigdc/theme/icons/Download';
import Spinner from '@ncigdc/theme/icons/Spinner';

import download from '@ncigdc/utils/download';
import { AUTH_API } from '@ncigdc/utils/constants';
/*----------------------------------------------------------------------------*/

const styles = {
  common: theme => ({
    backgroundColor: 'transparent',
    color: theme.greyScale2,
    justifyContent: 'flex-start',
    ':hover': {
      backgroundColor: theme.greyScale6,
    },
  }),
  button: theme => ({
    borderRadius: '0px',
    marginLeft: '0px',
    ...styles.common(theme),
    '[disabled]': styles.common(theme),
  }),
  iconSpacing: {
    marginRight: '0.6rem',
  },
};

const downloadCart = ({
  user,
  files,
  dispatch,
  disableAgreement = false,
  setState,
}: {
  user: Object,
  files: Array<Object>,
  dispatch: Function,
  disableAgreement: boolean,
  setState: Function,
}) => {
  const { authorized, unauthorized } = authPartitionFiles({ user, files });

  const dbGapList = Array.from(
    new Set(
      authorized.files
        .concat(unauthorized.files)
        .reduce((acc, f) => acc.concat(f.acl), [])
        .filter(f => f !== 'open')
    )
  );
  if (disableAgreement || dbGapList.length === 0) {
    dispatch(setModal(null));
    setState(s => ({ ...s, cartDownloading: true }));
    download({
      url: urlJoin(AUTH_API, 'data'),
      params: {
        ids: files.map(file => file.file_id),
        annotations: true,
        related_files: true,
      },
      method: 'POST',
      altMessage: true,
    })(() => {}, () => setState(s => ({ ...s, cartDownloading: false })));
  } else if (
    authorized.files.reduce((sum, x) => sum + x.file_size, 0) >
    5 * 10e8
  ) {
    dispatch(
      setModal(
        <BaseModal title="Cart size limit">

Your cart contains more than 5GBs of data.

            Please select the "Download > Manifest" option and use the
            <ExternalLink
              hasExternalIcon={false}
              title="GDC Data Transfer Tool"
              href="https://gdc.cancer.gov/access-data/gdc-data-transfer-tool"
            >
              Data Transfer Tool
            </ExternalLink>{' '}
            Tool to continue.

        </BaseModal>
      )
    );
  } else if (unauthorized.doc_count > 0) {
    dispatch(
      setModal(
        <CheckBoxModal
          dbGapList={dbGapList}
          CustomButton={agreed => (
            <Button
              disabled={!authorized.doc_count || (!!user && !agreed)}
              onClick={() =>
                downloadCart({
                  user,
                  files: authorized.files,
                  disableAgreement: true,
                  dispatch,
                  setState,
                })}
              style={{ margin: '0 10px' }}
            >
              Download {authorized.doc_count} Authorized Files
            </Button>
          )}
          hidden={!user || authorized.doc_count === 0}
          closeText="Cancel"
          dispatch={dispatch}
        >

              You are attempting to download files that you are not authorized
              to access.

                {authorized.doc_count}
              {' '}
              files that you are authorized to download.

                {unauthorized.doc_count}
              {' '}
              files that you are not authorized to download.

          {user ? (

              Please request dbGaP Access to the project (
                click here for more information
              ).

          ) : (

              Please <LoginButton />

          )}
        </CheckBoxModal>
      )
    );
  } else {
    dispatch(
      setModal(
        <CheckBoxModal
          dbGapList={dbGapList}
          CustomButton={agreed => (
            <Button
              disabled={!agreed}
              onClick={() => {
                setState(s => ({ ...s, cartDownloading: true }));
                download({
                  url: urlJoin(AUTH_API, 'data'),
                  params: {
                    ids: files.map(file => file.file_id),
                    annotations: true,
                    related_files: true,
                  },
                  method: 'POST',
                  altMessage: true,
                })(
                  () => {},
                  () => setState(s => ({ ...s, cartDownloading: false }))
                );
              }}
              style={{ margin: '0 10px' }}
            >
              Download {authorized.doc_count} Authorized Files
            </Button>
          )}
          dispatch={dispatch}
        />
      )
    );
  }
};

const CartDownloadDropdown = ({
  user,
  files,
  theme,
  disabled = false,
  state,
  setState,
  dispatch,
}) => (
  <Row>
    <Dropdown
      className="test-cart-download-dropdown"
      dropdownStyle={{
        marginTop: '2px',
        borderRadius: '4px',
      }}
      dropdownItemClass={false}
      button={
        <Button
          style={{ marginLeft: '1em' }}
          leftIcon={
            state.manifestDownloading || state.cartDownloading ? (
              <Spinner />
            ) : (
              <DownloadIcon />
            )
          }
          rightIcon={<DownCaretIcon />}
        >
          Download
        </Button>
      }
    >
      <Column>
        <DownloadButton
          size={files.length}
          className="test-download-manifest"
          style={styles.button(theme)}
          endpoint="manifest"
          activeText="Manifest"
          inactiveText="Manifest"
          altMessage={false}
          setParentState={currentState =>
            setState(s => ({ ...s, manifestDownloading: currentState }))}
          active={state.manifestDownloading}
          extraParams={{
            ids: files.map(file => file.file_id),
          }}
        />
        <Button
          className="test-download-cart"
          style={styles.button(theme)}
          disabled={state.cartDownloading}
          onClick={() =>
            downloadCart({
              user,
              files,
              dispatch,
              disableAgreement: false,
              setState,
            })}
          leftIcon={state.cartDownloading ? <Spinner /> : <DownloadIcon />}
        >
          Cart
        </Button>
      </Column>
    </Dropdown>
  </Row>
);

export default compose(
  connect(),
  withTheme,
  withState('state', 'setState', {
    manifestDownloading: false,
    cartDownloading: false,
  })
)(CartDownloadDropdown);
<commit_msg>[PRTL-2429] close download popup (#2682)<commit_after>// @flow
/* eslint react/no-unescaped-entities: 0 */

import React from 'react';
import { compose, withState } from 'recompose';
import { connect } from 'react-redux';
import urlJoin from 'url-join';

import { authPartitionFiles } from '@ncigdc/utils/auth';
import DownloadButton from '@ncigdc/components/DownloadButton';
import BaseModal from '@ncigdc/components/Modals/BaseModal';
import CheckBoxModal from '@ncigdc/components/Modals/CheckBoxModal';
import LoginButton from '@ncigdc/components/LoginButton';

import DownCaretIcon from 'react-icons/lib/fa/caret-down';

import { setModal } from '@ncigdc/dux/modal';

import Dropdown from '@ncigdc/uikit/Dropdown';
import Button from '@ncigdc/uikit/Button';
import { Column, Row } from '@ncigdc/uikit/Flex';
import { ExternalLink } from '@ncigdc/uikit/Links';

import { withTheme } from '@ncigdc/theme';
import DownloadIcon from '@ncigdc/theme/icons/Download';
import Spinner from '@ncigdc/theme/icons/Spinner';

import download from '@ncigdc/utils/download';
import { AUTH_API } from '@ncigdc/utils/constants';
/*----------------------------------------------------------------------------*/

const styles = {
  common: theme => ({
    backgroundColor: 'transparent',
    color: theme.greyScale2,
    justifyContent: 'flex-start',
    ':hover': {
      backgroundColor: theme.greyScale6,
    },
  }),
  button: theme => ({
    borderRadius: '0px',
    marginLeft: '0px',
    ...styles.common(theme),
    '[disabled]': styles.common(theme),
  }),
  iconSpacing: {
    marginRight: '0.6rem',
  },
};

const downloadCart = ({
  user,
  files,
  dispatch,
  disableAgreement = false,
  setState,
}: {
  user: Object,
  files: Array<Object>,
  dispatch: Function,
  disableAgreement: boolean,
  setState: Function,
}) => {
  const { authorized, unauthorized } = authPartitionFiles({ user, files });

  const dbGapList = Array.from(
    new Set(
      authorized.files
        .concat(unauthorized.files)
        .reduce((acc, f) => acc.concat(f.acl), [])
        .filter(f => f !== 'open')
    )
  );
  if (disableAgreement || dbGapList.length === 0) {
    dispatch(setModal(null));
    setState(s => ({ ...s, cartDownloading: true }));
    download({
      url: urlJoin(AUTH_API, 'data'),
      params: {
        ids: files.map(file => file.file_id),
        annotations: true,
        related_files: true,
      },
      method: 'POST',
      altMessage: true,
    })(() => {}, () => setState(s => ({ ...s, cartDownloading: false })));
  } else if (
    authorized.files.reduce((sum, x) => sum + x.file_size, 0) >
    5 * 10e8
  ) {
    dispatch(
      setModal(
        <BaseModal title="Cart size limit">

Your cart contains more than 5GBs of data.

            Please select the "Download > Manifest" option and use the
            <ExternalLink
              hasExternalIcon={false}
              title="GDC Data Transfer Tool"
              href="https://gdc.cancer.gov/access-data/gdc-data-transfer-tool"
            >
              Data Transfer Tool
            </ExternalLink>{' '}
            Tool to continue.

        </BaseModal>
      )
    );
  } else if (unauthorized.doc_count > 0) {
    dispatch(
      setModal(
        <CheckBoxModal
          dbGapList={dbGapList}
          CustomButton={agreed => (
            <Button
              disabled={!authorized.doc_count || (!!user && !agreed)}
              onClick={() => {
                downloadCart({
                  user,
                  files: authorized.files,
                  disableAgreement: true,
                  dispatch,
                  setState,
                })
                dispatch(setModal(null));
              }}
              style={{ margin: '0 10px' }}
            >
              Download {authorized.doc_count} Authorized Files
            </Button>
          )}
          hidden={!user || authorized.doc_count === 0}
          closeText="Cancel"
          dispatch={dispatch}
        >

              You are attempting to download files that you are not authorized
              to access.

                {authorized.doc_count}
              {' '}
              files that you are authorized to download.

                {unauthorized.doc_count}
              {' '}
              files that you are not authorized to download.

          {user ? (

              Please request dbGaP Access to the project (
                click here for more information
              ).

          ) : (

              Please <LoginButton />

          )}
        </CheckBoxModal>
      )
    );
  } else {
    dispatch(
      setModal(
        <CheckBoxModal
          dbGapList={dbGapList}
          CustomButton={agreed => (
            <Button
              disabled={!agreed}
              onClick={() => {
                setState(s => ({ ...s, cartDownloading: true }));
                download({
                  url: urlJoin(AUTH_API, 'data'),
                  params: {
                    ids: files.map(file => file.file_id),
                    annotations: true,
                    related_files: true,
                  },
                  method: 'POST',
                  altMessage: true,
                })(() => {},() => {});
                dispatch(setModal(null));
                setState(s => ({ ...s, cartDownloading: false }));
              }}
              style={{ margin: '0 10px' }}
            >
              Download {authorized.doc_count} Authorized Files
            </Button>
          )}
          dispatch={dispatch}
        />
      )
    );
  }
};

const CartDownloadDropdown = ({
  user,
  files,
  theme,
  disabled = false,
  state,
  setState,
  dispatch,
}) => (
  <Row>
    <Dropdown
      className="test-cart-download-dropdown"
      dropdownStyle={{
        marginTop: '2px',
        borderRadius: '4px',
      }}
      dropdownItemClass={false}
      button={
        <Button
          style={{ marginLeft: '1em' }}
          leftIcon={
            state.manifestDownloading || state.cartDownloading ? (
              <Spinner />
            ) : (
              <DownloadIcon />
            )
          }
          rightIcon={<DownCaretIcon />}
        >
          Download
        </Button>
      }
    >
      <Column>
        <DownloadButton
          size={files.length}
          className="test-download-manifest"
          style={styles.button(theme)}
          endpoint="manifest"
          activeText="Manifest"
          inactiveText="Manifest"
          altMessage={false}
          setParentState={currentState =>
            setState(s => ({ ...s, manifestDownloading: currentState }))}
          active={state.manifestDownloading}
          extraParams={{
            ids: files.map(file => file.file_id),
          }}
        />
        <Button
          className="test-download-cart"
          style={styles.button(theme)}
          disabled={state.cartDownloading}
          onClick={() =>
            downloadCart({
              user,
              files,
              dispatch,
              disableAgreement: false,
              setState,
            })}
          leftIcon={state.cartDownloading ? <Spinner /> : <DownloadIcon />}
        >
          Cart
        </Button>
      </Column>
    </Dropdown>
  </Row>
);

export default compose(
  connect(),
  withTheme,
  withState('state', 'setState', {
    manifestDownloading: false,
    cartDownloading: false,
  })
)(CartDownloadDropdown);
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Dec 10 2015 00:03:13 GMT+0000 (GMT)

module.exports = function(config) {
  var configuration = ({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      {pattern: 'test-build/spec/courtroom/*.js', included: false},
      {pattern: 'test-build/spec/courtroom/**/*.js', included: false},
      {pattern: 'test-build/src/courtroom/*.spec.js', included: false},
      {pattern: 'test-build/src/courtroom/courtroom/juries/*.spec.js', included: false}
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'build/*.js': ['coverage'],
      'build/juries/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec', 'coverage'],

    coverageReporter: {
		reporters: [{type: 'lcov'}, {type: 'text'}],
		dir: "coverage/"
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  });

  if(process.env.TRAVIS){
    configuration.browsers = ['PhantomJS'];
    configuration.reporters.push('coveralls');
    configuration.singleRun = true;
  }

  config.set(configuration);
}
<commit_msg>Correct karma conf paths<commit_after>// Karma configuration
// Generated on Thu Dec 10 2015 00:03:13 GMT+0000 (GMT)

module.exports = function(config) {
  var configuration = ({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      {pattern: 'test-build/src/courtroom/*.js', included: false},
      {pattern: 'test-build/src/courtroom/juries/*.js', included: false},
      {pattern: 'test-build/spec/courtroom/*.spec.js', included: false},
      {pattern: 'test-build/spec/courtroom/courtroom/juries/*.spec.js', included: false}
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'build/*.js': ['coverage'],
      'build/juries/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec', 'coverage'],

    coverageReporter: {
		reporters: [{type: 'lcov'}, {type: 'text'}],
		dir: "coverage/"
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  });

  if(process.env.TRAVIS){
    configuration.browsers = ['PhantomJS'];
    configuration.reporters.push('coveralls');
    configuration.singleRun = true;
  }

  config.set(configuration);
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Tabs from 'react-responsive-tabs';
import Iframe from 'react-iframe'
import 'react-responsive-tabs/styles.css'
import ContentPageContainer from '../../../components/content-page-container/ContentPageContainer'

class BirthSpacing extends Component {
  render() {
    return (
      <ContentPageContainer
        filePath='/Content/birth-spacing.json'
        />
    )
  }
}
export default BirthSpacing
<commit_msg>removed unnecessary imports<commit_after>import React, { Component } from 'react';
import ContentPageContainer from '../../../components/content-page-container/ContentPageContainer'

class BirthSpacing extends Component {
  render() {
    return (
      <ContentPageContainer
        filePath='/Content/birth-spacing.json'
        />
    )
  }
}
export default BirthSpacing
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Feb 17 2016 15:48:21 GMT+0000 (GMT)

/*eslint-env node*/
/*eslint no-var: 0*/
module.exports = function(config) {

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {
    /*
    // Currently disabled as chunked-transfer responses appear to fail on *all*
    // SauceLabs MacOS platforms?
    'SL_Safari': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    */
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'linux'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'linux'
    },
    'SL_IE10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    }
  };

  var reporters = ['dots'];
  var browsers = [];
  var singlerun = false;
  var concurrency = Infinity;

  if (process.env.SAUCE_USERNAME) {
    reporters.push('saucelabs');
    Array.prototype.push.apply(browsers, Object.keys(customLaunchers));
    singlerun = true;
    concurrency = 1;
  }

  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    sauceLabs: {
      recordScreenshots: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },

    // list of files / patterns to load in the browser
    files: [
      'build/integration-tests.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    proxies: {
      '/chunked-response': 'http://localhost:2001/chunked-response',
      '/split-chunked-response': 'http://localhost:2001/split-chunked-response',
      '/error-response': 'http://localhost:2001/error-response',
      '/echo-response': 'http://localhost:2001/echo-response',
      '/unknown-host': 'http://unknown-host.com'
    },

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: reporters,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    browsers: browsers,
    captureTimeout: 120000,
    customLaunchers: customLaunchers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: singlerun,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: concurrency
  })
};
<commit_msg>Use a 'real' unknown address, address was actually known<commit_after>// Karma configuration
// Generated on Wed Feb 17 2016 15:48:21 GMT+0000 (GMT)

/*eslint-env node*/
/*eslint no-var: 0*/
module.exports = function(config) {

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {
    /*
    // Currently disabled as chunked-transfer responses appear to fail on *all*
    // SauceLabs MacOS platforms?
    'SL_Safari': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    */
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'linux'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'linux'
    },
    'SL_IE10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    }
  };

  var reporters = ['dots'];
  var browsers = [];
  var singlerun = false;
  var concurrency = Infinity;

  if (process.env.SAUCE_USERNAME) {
    reporters.push('saucelabs');
    Array.prototype.push.apply(browsers, Object.keys(customLaunchers));
    singlerun = true;
    concurrency = 1;
  }

  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    sauceLabs: {
      recordScreenshots: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },

    // list of files / patterns to load in the browser
    files: [
      'build/integration-tests.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    proxies: {
      '/chunked-response': 'http://localhost:2001/chunked-response',
      '/split-chunked-response': 'http://localhost:2001/split-chunked-response',
      '/error-response': 'http://localhost:2001/error-response',
      '/echo-response': 'http://localhost:2001/echo-response',
      '/unknown-host': 'http://localhost:5678'
    },

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: reporters,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    browsers: browsers,
    captureTimeout: 120000,
    customLaunchers: customLaunchers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: singlerun,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: concurrency
  })
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Apr 13 2013 02:25:04 GMT+0800 (CST)

// base path, that will be used to resolve files and exclude
basePath = './';

// list of files / patterns to load in the browser
files = [
  JASMINE,
  JASMINE_ADAPTER,

  // lib
  'public/js/lib/angular.js',
  'public/js/lib/angular-resource.js',
  'public/js/lib/ui-bootstrap-tpls-0.2.0.js',

  // test lib
  'test/lib/angular/angular-mocks.js',

  // app
  'public/js/*.js',

  // test
  'test/unit/*.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
<commit_msg>Add coverage in karma<commit_after>// Karma configuration
// Generated on Sat Apr 13 2013 02:25:04 GMT+0800 (CST)

// base path, that will be used to resolve files and exclude
basePath = './';

preprocessors = {
  // app
  'public/js/*.js': 'coverage'
};

// list of files / patterns to load in the browser
files = [
  JASMINE,
  JASMINE_ADAPTER,

  // lib
  'public/js/lib/angular.js',
  'public/js/lib/angular-resource.js',
  'public/js/lib/ui-bootstrap-tpls-0.2.0.js',

  // test lib
  'test/lib/angular/angular-mocks.js',

  // app
  'public/js/*.js',

  // test
  'test/unit/*.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['coverage', 'progress'];

coverageReporter = {
    type: 'html',
    dir: 'coverage/',
}

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
<|endoftext|>


<commit_before>// Karma configuration file
var karma = require("karma");
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
var DEFAULT_NG_VERSION = "1.6";

/**
 * This returns a Karma 'files configuration'.
 * http://karma-runner.github.io/0.8/config/files.html
 *
 * Specifies which files can be served by the Karma web server
 *
 * included: true -- files that are always served to the browser (like <script> tag)
 * included: false -- files *available to be served* by karma, for instance via require()
 */
function karmaServedFiles(ngVersion) {
  // Returns necessary files for a specific version of angular
  function angular(version) {
    console.log('Using Angular ' + ngVersion + ' from test/angular/' + version + '/angular.js');

    return [
      'test/angular/' + version + '/angular.js',
      'test/angular/' + version + '/angular-mocks.js',
      'test/angular/' + version + '/angular-animate.js',
    ];
  }

  var angularFiles = angular(ngVersion).map(function (pattern) {
    return { watched: false, included: true, nocache: true, pattern: pattern };
  });

  return angularFiles.concat('test/index.js');
}

var webpackConfig = module.exports = {
  mode: 'development',
  resolve: {
    modules: ['node_modules'],
    extensions: ['.js', '.jsx', '.ts', '.tsx']
  },

  devtool: 'inline-source-map',

  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader', options: { transpileOnly: true } }
    ]
  },

  stats: false,

  plugins: [
    new ForkTsCheckerWebpackPlugin(),
  ],

  externals: [ 'angular' ]
};

module.exports = function(config) {
  var ngVersion = config.ngversion || DEFAULT_NG_VERSION;

  config.set({
    singleRun: true,
    autoWatch: false,
    autoWatchInterval: 0,

    // level of logging
    // possible values: LOG_DISABLE, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG
    logLevel: "warn",
    // possible values: 'dots', 'progress'
    reporters: 'dots',
    colors: true,

    port: 8080,

    // base path, that will be used to resolve files and exclude
    basePath: '.',

    // Start these browsers, currently available:
    // Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
    browsers: ['ChromeHeadless'],

    frameworks: ['jasmine'],

    plugins: [
      require('karma-webpack'),
      require('karma-sourcemap-loader'),
      require('karma-jasmine'),
      require('karma-chrome-launcher')
    ],

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: { chunks: false },
    },

    /* Files *available to be served* by karma, i.e., anything that will be require()'d */
    files: karmaServedFiles(ngVersion),

    preprocessors: {
      'test/index.js': ['webpack', 'sourcemap'],
      '../src/ng1': ['webpack', 'sourcemap'],
    },

  });
};
<commit_msg>test(*): update karma chrome headless config https://github.com/travis-ci/docs-travis-ci-com/pull/1671<commit_after>// Karma configuration file
var karma = require("karma");
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
var DEFAULT_NG_VERSION = "1.6";

/**
 * This returns a Karma 'files configuration'.
 * http://karma-runner.github.io/0.8/config/files.html
 *
 * Specifies which files can be served by the Karma web server
 *
 * included: true -- files that are always served to the browser (like <script> tag)
 * included: false -- files *available to be served* by karma, for instance via require()
 */
function karmaServedFiles(ngVersion) {
  // Returns necessary files for a specific version of angular
  function angular(version) {
    console.log('Using Angular ' + ngVersion + ' from test/angular/' + version + '/angular.js');

    return [
      'test/angular/' + version + '/angular.js',
      'test/angular/' + version + '/angular-mocks.js',
      'test/angular/' + version + '/angular-animate.js',
    ];
  }

  var angularFiles = angular(ngVersion).map(function (pattern) {
    return { watched: false, included: true, nocache: true, pattern: pattern };
  });

  return angularFiles.concat('test/index.js');
}

var webpackConfig = module.exports = {
  mode: 'development',
  resolve: {
    modules: ['node_modules'],
    extensions: ['.js', '.jsx', '.ts', '.tsx']
  },

  devtool: 'inline-source-map',

  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader', options: { transpileOnly: true } }
    ]
  },

  stats: false,

  plugins: [
    new ForkTsCheckerWebpackPlugin(),
  ],

  externals: [ 'angular' ]
};

module.exports = function(config) {
  var ngVersion = config.ngversion || DEFAULT_NG_VERSION;

  config.set({
    singleRun: true,
    autoWatch: false,
    autoWatchInterval: 0,

    // level of logging
    // possible values: LOG_DISABLE, LOG_ERROR, LOG_WARN, LOG_INFO, LOG_DEBUG
    logLevel: "warn",
    // possible values: 'dots', 'progress'
    reporters: 'dots',
    colors: true,

    port: 8080,

    // base path, that will be used to resolve files and exclude
    basePath: '.',

    // Start these browsers, currently available:
    // Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }
    },

    frameworks: ['jasmine'],

    plugins: [
      require('karma-webpack'),
      require('karma-sourcemap-loader'),
      require('karma-jasmine'),
      require('karma-chrome-launcher')
    ],

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: { chunks: false },
    },

    /* Files *available to be served* by karma, i.e., anything that will be require()'d */
    files: karmaServedFiles(ngVersion),

    preprocessors: {
      'test/index.js': ['webpack', 'sourcemap'],
      '../src/ng1': ['webpack', 'sourcemap'],
    },

  });
};
<|endoftext|>


<commit_before>
// chrome.storage.sync.clear()
// chrome.permissions.getAll((p) => chrome.permissions.remove({origins: p.origins}))

var match = '\\.(?:markdown|mdown|mkdn|md|mkd|mdwn|mdtxt|mdtext|text)(?:#.*|\\?.*)?$'

var defaults = {
  theme: 'github',
  compiler: 'marked',
  content: {
    emoji: false,
    scroll: true,
    toc: false,
    mathjax: false,
  },
  raw: false,
  header: true,
  match,
  origins: {
    'file://': match
  }
}
Object.keys(md).forEach((compiler) => {
  defaults[compiler] = md[compiler].defaults
})

var state

function set (options) {
  chrome.storage.sync.set(options)
  Object.assign(state, options)
}

chrome.storage.sync.get((res) => {
  var options = !Object.keys(res).length ? defaults : res

  // v2.2 -> v2.3
  if (!options.match || !options.origins) {
    options.match = match
    options.origins = {
      'file://': match
    }
  }
  // v2.3 -> v2.4
  else if (!options.origins['file://']) {
    options.origins['file://'] = match
  }
  // v2.4 -> v2.5
  if (!options.compiler) {
    options.compiler = options.options
  }
  if (!options.content) {
    options.content = defaults.content
  }
  // v2.7 -> v2.8
  if (!options.marked) {
    options.compiler = 'marked'
    options.marked = md.marked.defaults
  }
  // v2.8 -> v2.9
  if (!options.remark) {
    options.remark = md.remark.defaults
  }
  // v2.9 -> v3.0
  if (options.content.emoji === undefined) {
    options.content.emoji = false
  }
  // v3.0 -> v3.1
  if (options.header === undefined) {
    options.header = true
  }
  // v3.1 -> v3.2
  if (options.remark && options.remark.yaml) {
    delete options.remark.yaml
  }
  if (options.content.mathjax === undefined) {
    options.content.mathjax = false
  }

  Object.keys(md).forEach((compiler) => {
    if (!options[compiler]) {
      options[compiler] = md[compiler].defaults
    }
  })

  chrome.storage.sync.set(options)
  state = JSON.parse(JSON.stringify(options))
})

function inject (id) {
  chrome.tabs.executeScript(id, {
    code: [
      'document.querySelector("pre").style.visibility = "hidden"',
      'var theme = "' + state.theme + '"',
      'var raw = ' + state.raw,
      'var content = ' + JSON.stringify(state.content),
      'var compiler = "' + state.compiler + '"'
    ].join(';'), runAt: 'document_start'})

  chrome.tabs.insertCSS(id, {file: 'css/content.css', runAt: 'document_start'})
  chrome.tabs.insertCSS(id, {file: 'vendor/prism.css', runAt: 'document_start'})

  chrome.tabs.executeScript(id, {file: 'vendor/mithril.min.js', runAt: 'document_start'})
  chrome.tabs.executeScript(id, {file: 'vendor/prism.js', runAt: 'document_start'})
  if (state.content.emoji) {
    chrome.tabs.executeScript(id, {file: 'content/emoji.js', runAt: 'document_start'})
  }
  chrome.tabs.executeScript(id, {file: 'content/content.js', runAt: 'document_start'})
}

chrome.tabs.onUpdated.addListener((id, info, tab) => {
  if (info.status === 'loading') {
    chrome.tabs.executeScript(id, {
      code: 'JSON.stringify({' +
        'location: window.location,' +
        'contentType: document.contentType,' +
        'loaded: !!window.state' +
      '})',
      runAt: 'document_start'
    }, (res) => {
      if (chrome.runtime.lastError) {
        // Origin not allowed
        return
      }

      try {
        var win = JSON.parse(res)
      }
      catch (err) {
        // JSON parse error
        return
      }

      if (win.loaded) {
        return
      }

      if (state.header && /text\/(?:x-)?markdown/i.test(win.contentType)) {
        inject(id)
      }
      else {
        var path =
          state.origins[win.location.origin] ||
          state.origins['*://' + win.location.host] ||
          state.origins['*://*']

        if (path && new RegExp(path).test(win.location.href)) {
          inject(id)
        }
      }
    })
  }
})

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  if (req.message === 'markdown') {
    var markdown = req.markdown

    if (state.content.mathjax) {
      var m = mathjax()
      markdown = m.tokenize(markdown)
    }

    var html = md[state.compiler].compile(markdown)

    if (state.content.mathjax) {
      html = m.detokenize(html)
    }

    sendResponse({message: 'html', html})
  }
  else if (req.message === 'settings') {
    sendResponse(Object.assign({}, state, {
      options: state[state.compiler],
      description: md[state.compiler].description,
      compilers: Object.keys(md)
    }))
  }
  else if (req.message === 'compiler.name') {
    set({compiler: req.compiler})
    sendResponse()
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'compiler.options') {
    set({[req.compiler]: req.options})
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'content') {
    set({content: req.content})
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'defaults') {
    set(defaults)
    sendResponse()
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'theme') {
    set({theme: req.theme})
    notifyContent({message: 'theme', theme: req.theme})
  }
  else if (req.message === 'raw') {
    set({raw: req.raw})
    notifyContent({message: 'raw', raw: req.raw})
  }
  else if (req.message === 'advanced') {
    chrome.management.getSelf((extension) => {
      chrome.tabs.create({url: extension.optionsUrl})
    })
  }
  else if (req.message === 'origins') {
    sendResponse({origins: state.origins, header: state.header})
  }
  else if (req.message === 'header') {
    set({header: req.header})
  }
  else if (req.message === 'add') {
    state.origins[req.origin] = match
    set({origins: state.origins})
    sendResponse()
  }
  else if (req.message === 'remove') {
    delete state.origins[req.origin]
    set({origins: state.origins})
    sendResponse()
  }
  else if (req.message === 'update') {
    state.origins[req.origin] = req.match
    set({origins: state.origins})
  }
  return true
})

function notifyContent (req, res) {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, req, res)
  })
}
<commit_msg>Use string literals for injected code<commit_after>
// chrome.storage.sync.clear()
// chrome.permissions.getAll((p) => chrome.permissions.remove({origins: p.origins}))

var match = '\\.(?:markdown|mdown|mkdn|md|mkd|mdwn|mdtxt|mdtext|text)(?:#.*|\\?.*)?$'

var defaults = {
  theme: 'github',
  compiler: 'marked',
  content: {
    emoji: false,
    scroll: true,
    toc: false,
    mathjax: false,
  },
  raw: false,
  header: true,
  match,
  origins: {
    'file://': match
  }
}
Object.keys(md).forEach((compiler) => {
  defaults[compiler] = md[compiler].defaults
})

var state

function set (options) {
  chrome.storage.sync.set(options)
  Object.assign(state, options)
}

chrome.storage.sync.get((res) => {
  var options = !Object.keys(res).length ? defaults : res

  // v2.2 -> v2.3
  if (!options.match || !options.origins) {
    options.match = match
    options.origins = {
      'file://': match
    }
  }
  // v2.3 -> v2.4
  else if (!options.origins['file://']) {
    options.origins['file://'] = match
  }
  // v2.4 -> v2.5
  if (!options.compiler) {
    options.compiler = options.options
  }
  if (!options.content) {
    options.content = defaults.content
  }
  // v2.7 -> v2.8
  if (!options.marked) {
    options.compiler = 'marked'
    options.marked = md.marked.defaults
  }
  // v2.8 -> v2.9
  if (!options.remark) {
    options.remark = md.remark.defaults
  }
  // v2.9 -> v3.0
  if (options.content.emoji === undefined) {
    options.content.emoji = false
  }
  // v3.0 -> v3.1
  if (options.header === undefined) {
    options.header = true
  }
  // v3.1 -> v3.2
  if (options.remark && options.remark.yaml) {
    delete options.remark.yaml
  }
  if (options.content.mathjax === undefined) {
    options.content.mathjax = false
  }

  Object.keys(md).forEach((compiler) => {
    if (!options[compiler]) {
      options[compiler] = md[compiler].defaults
    }
  })

  chrome.storage.sync.set(options)
  state = JSON.parse(JSON.stringify(options))
})

function inject (id) {
  chrome.tabs.executeScript(id, {
    code: `
      document.querySelector('pre').style.visibility = 'hidden'
      var theme = '${state.theme}'
      var raw = ${state.raw}
      var content = ${JSON.stringify(state.content)}
      var compiler = '${state.compiler}'
    `,
    runAt: 'document_start'
  })

  chrome.tabs.insertCSS(id, {file: 'css/content.css', runAt: 'document_start'})
  chrome.tabs.insertCSS(id, {file: 'vendor/prism.css', runAt: 'document_start'})

  chrome.tabs.executeScript(id, {file: 'vendor/mithril.min.js', runAt: 'document_start'})
  chrome.tabs.executeScript(id, {file: 'vendor/prism.js', runAt: 'document_start'})
  if (state.content.emoji) {
    chrome.tabs.executeScript(id, {file: 'content/emoji.js', runAt: 'document_start'})
  }
  chrome.tabs.executeScript(id, {file: 'content/content.js', runAt: 'document_start'})
}

chrome.tabs.onUpdated.addListener((id, info, tab) => {
  if (info.status === 'loading') {
    chrome.tabs.executeScript(id, {
      code: `
        JSON.stringify({
          location: window.location,
          contentType: document.contentType,
          loaded: !!window.state
        })
      `,
      runAt: 'document_start'
    }, (res) => {
      if (chrome.runtime.lastError) {
        // origin not allowed
        return
      }

      try {
        var win = JSON.parse(res)
      }
      catch (err) {
        // JSON parse error
        return
      }

      if (win.loaded) {
        // anchor
        return
      }

      if (state.header && /text\/(?:x-)?markdown/i.test(win.contentType)) {
        inject(id)
      }
      else {
        var path =
          state.origins[win.location.origin] ||
          state.origins['*://' + win.location.host] ||
          state.origins['*://*']

        if (path && new RegExp(path).test(win.location.href)) {
          inject(id)
        }
      }
    })
  }
})

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  if (req.message === 'markdown') {
    var markdown = req.markdown

    if (state.content.mathjax) {
      var m = mathjax()
      markdown = m.tokenize(markdown)
    }

    var html = md[state.compiler].compile(markdown)

    if (state.content.mathjax) {
      html = m.detokenize(html)
    }

    sendResponse({message: 'html', html})
  }
  else if (req.message === 'settings') {
    sendResponse(Object.assign({}, state, {
      options: state[state.compiler],
      description: md[state.compiler].description,
      compilers: Object.keys(md)
    }))
  }
  else if (req.message === 'compiler.name') {
    set({compiler: req.compiler})
    sendResponse()
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'compiler.options') {
    set({[req.compiler]: req.options})
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'content') {
    set({content: req.content})
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'defaults') {
    set(defaults)
    sendResponse()
    notifyContent({message: 'reload'})
  }
  else if (req.message === 'theme') {
    set({theme: req.theme})
    notifyContent({message: 'theme', theme: req.theme})
  }
  else if (req.message === 'raw') {
    set({raw: req.raw})
    notifyContent({message: 'raw', raw: req.raw})
  }
  else if (req.message === 'advanced') {
    chrome.management.getSelf((extension) => {
      chrome.tabs.create({url: extension.optionsUrl})
    })
  }
  else if (req.message === 'origins') {
    sendResponse({origins: state.origins, header: state.header})
  }
  else if (req.message === 'header') {
    set({header: req.header})
  }
  else if (req.message === 'add') {
    state.origins[req.origin] = match
    set({origins: state.origins})
    sendResponse()
  }
  else if (req.message === 'remove') {
    delete state.origins[req.origin]
    set({origins: state.origins})
    sendResponse()
  }
  else if (req.message === 'update') {
    state.origins[req.origin] = req.match
    set({origins: state.origins})
  }
  return true
})

function notifyContent (req, res) {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, req, res)
  })
}
<|endoftext|>


<commit_before>"use strict";

let warmRepositories = [],
    currentNotifications = [],
    intervalID,
    currentRefresh;

chrome.notifications.onButtonClicked.addListener(
    function(notifId, btnIdx) {
        chrome.tabs.create(
            {
                url: 'http://github.com' + notifId.split(':')[3]
            }
        );
    }
);

function XHRGetRequest(url){
    return new Promise(function(resolve, reject){
        let request = new XMLHttpRequest();

        request.open('GET', url, true);

        // Set GitHub user agent (good web citizen)
        request.setRequestHeader('X-GH-UserAgent', 'github-notifier-v1.11.1');

        request.onload = function() {
            if (this.status >= 200 && this.status < 400) {
                resolve(this.response);
            }

            reject(this)
        }

        request.send();
    });
}

function displayNotification(id, title, message, buttons){
    chrome.notifications.create(
        id,
        {
            type: "basic",
            title: title,
            message: message,
            iconUrl: "../icons/512.png",
            buttons: buttons
        },
        function() {}
    );
}

function getData(initialRun){
    chrome.storage.sync.get("data", (obj) => {
        obj.data.forEach((project) => {
            setTimeout(function () {
                let organisation = project.org,
                    repository = project.repo,
                    githubProjectUrl = 'http://github.com/' + organisation + '/' + repository,
                    isCold = warmRepositories.indexOf(organisation + ":" + repository) === -1;

                if(isCold){
                    initialRun = true;
                    warmRepositories.push(organisation + ":" + repository);
                }

                if(organisation !== undefined && repository !== undefined){
                    XHRGetRequest(githubProjectUrl + '/pulls').then((data) => {
                        parseData(data, organisation, repository, initialRun, 'pull');
                        return XHRGetRequest(githubProjectUrl + '/issues');
                    }).then((data) => {
                        parseData(data, organisation, repository, initialRun, 'issue');
                        return XHRGetRequest(githubProjectUrl + '/releases');
                    }).then((data) => {
                        parseData(data, organisation, repository, initialRun, 'release');
                    }).catch((e) => {
                        console.error('There was an issue fetching ' + e.responseURL + ' from Github. Error: ', e);
                    });
                };
            }, 60000)
        });
    });
}

function parseData(resp, org, repo, initialRun, type){
    let container = document.implementation.createHTMLDocument().documentElement,
        selectors;

    container.innerHTML = resp;

    switch(type){
        case 'pull':
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'pull request'
            break;
        case 'issue':
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'issue'
            break;
        case 'release':
            selectors = '.release-timeline .release-header .release-title a',
            type = 'release'
            break;
        default:
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'pull request'
            break;
    };

    let notificationNodeList = container.querySelectorAll(selectors),
        notificationMetadataNodeList = container.querySelectorAll('.table-list-issues .js-issue-row  .tooltipped-s'),
        notificationReleaseMetadataNodeList = container.querySelectorAll('.release-timeline .release-authorship a');

    [].forEach.call(notificationNodeList, (notification, i) => {
        if(currentNotifications.indexOf(notification.text.trim()) === -1){
            if(!initialRun){
                let notificationAuthor = notificationMetadataNodeList[i].text.trim(),
                    notificationTitle = notification.text.trim(),
                    notificationLink = notification.attributes['href'].value;

                if (type === 'release') {
                    notificationAuthor = notificationReleaseMetadataNodeList[i].text.trim();
                }

                displayNotification(
                    org + ':' + repo  + ':' + notificationTitle.replace(':', '') + ':' + notificationLink,
                    org + '/' + repo + " - " + type,
                    notificationTitle + '\n\nAuthor: ' + notificationAuthor,
                    [{ title: "View " + type }]
                );
            }

            currentNotifications.push(notification.text.trim());
        };
    });

    chrome.storage.sync.get("refresh", (obj) => {
        if(currentRefresh !== obj.refresh){
            clearInterval(intervalID);

            if(obj.refresh <= 180000){
                obj.refresh = 180000;
            };

            currentRefresh = obj.refresh;

            intervalID = setInterval(() => getData(false), currentRefresh);
        }
    });
}

// Initial run to prevent notification flooding
getData(true);

// Poll for new notifications every x seconds
chrome.storage.sync.get("refresh", (obj) => {
    if(obj.refresh === undefined || obj.refresh <= 180000){
        obj.refresh = 180000;
    }

    currentRefresh = obj.refresh;
    intervalID = setInterval(() => getData(false), currentRefresh);
});
<commit_msg>Bump UA<commit_after>"use strict";

let warmRepositories = [],
    currentNotifications = [],
    intervalID,
    currentRefresh;

chrome.notifications.onButtonClicked.addListener(
    function(notifId, btnIdx) {
        chrome.tabs.create(
            {
                url: 'http://github.com' + notifId.split(':')[3]
            }
        );
    }
);

function XHRGetRequest(url){
    return new Promise(function(resolve, reject){
        let request = new XMLHttpRequest();

        request.open('GET', url, true);

        // Set GitHub user agent (good web citizen)
        request.setRequestHeader('X-GH-UserAgent', 'github-notifier-v1.11.2');

        request.onload = function() {
            if (this.status >= 200 && this.status < 400) {
                resolve(this.response);
            }

            reject(this)
        }

        request.send();
    });
}

function displayNotification(id, title, message, buttons){
    chrome.notifications.create(
        id,
        {
            type: "basic",
            title: title,
            message: message,
            iconUrl: "../icons/512.png",
            buttons: buttons
        },
        function() {}
    );
}

function getData(initialRun){
    chrome.storage.sync.get("data", (obj) => {
        obj.data.forEach((project) => {
            setTimeout(function () {
                let organisation = project.org,
                    repository = project.repo,
                    githubProjectUrl = 'http://github.com/' + organisation + '/' + repository,
                    isCold = warmRepositories.indexOf(organisation + ":" + repository) === -1;

                if(isCold){
                    initialRun = true;
                    warmRepositories.push(organisation + ":" + repository);
                }

                if(organisation !== undefined && repository !== undefined){
                    XHRGetRequest(githubProjectUrl + '/pulls').then((data) => {
                        parseData(data, organisation, repository, initialRun, 'pull');
                        return XHRGetRequest(githubProjectUrl + '/issues');
                    }).then((data) => {
                        parseData(data, organisation, repository, initialRun, 'issue');
                        return XHRGetRequest(githubProjectUrl + '/releases');
                    }).then((data) => {
                        parseData(data, organisation, repository, initialRun, 'release');
                    }).catch((e) => {
                        console.error('There was an issue fetching ' + e.responseURL + ' from Github. Error: ', e);
                    });
                };
            }, 60000)
        });
    });
}

function parseData(resp, org, repo, initialRun, type){
    let container = document.implementation.createHTMLDocument().documentElement,
        selectors;

    container.innerHTML = resp;

    switch(type){
        case 'pull':
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'pull request'
            break;
        case 'issue':
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'issue'
            break;
        case 'release':
            selectors = '.release-timeline .release-header .release-title a',
            type = 'release'
            break;
        default:
            selectors = '.table-list-issues .js-issue-row .issue-title-link',
            type = 'pull request'
            break;
    };

    let notificationNodeList = container.querySelectorAll(selectors),
        notificationMetadataNodeList = container.querySelectorAll('.table-list-issues .js-issue-row  .tooltipped-s'),
        notificationReleaseMetadataNodeList = container.querySelectorAll('.release-timeline .release-authorship a');

    [].forEach.call(notificationNodeList, (notification, i) => {
        if(currentNotifications.indexOf(notification.text.trim()) === -1){
            if(!initialRun){
                let notificationAuthor = notificationMetadataNodeList[i].text.trim(),
                    notificationTitle = notification.text.trim(),
                    notificationLink = notification.attributes['href'].value;

                if (type === 'release') {
                    notificationAuthor = notificationReleaseMetadataNodeList[i].text.trim();
                }

                displayNotification(
                    org + ':' + repo  + ':' + notificationTitle.replace(':', '') + ':' + notificationLink,
                    org + '/' + repo + " - " + type,
                    notificationTitle + '\n\nAuthor: ' + notificationAuthor,
                    [{ title: "View " + type }]
                );
            }

            currentNotifications.push(notification.text.trim());
        };
    });

    chrome.storage.sync.get("refresh", (obj) => {
        if(currentRefresh !== obj.refresh){
            clearInterval(intervalID);

            if(obj.refresh <= 180000){
                obj.refresh = 180000;
            };

            currentRefresh = obj.refresh;

            intervalID = setInterval(() => getData(false), currentRefresh);
        }
    });
}

// Initial run to prevent notification flooding
getData(true);

// Poll for new notifications every x seconds
chrome.storage.sync.get("refresh", (obj) => {
    if(obj.refresh === undefined || obj.refresh <= 180000){
        obj.refresh = 180000;
    }

    currentRefresh = obj.refresh;
    intervalID = setInterval(() => getData(false), currentRefresh);
});
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var config = require('./config');

// create api object
process.mono = new EventEmitter();
process.mono.config = config;
process.mono.error = require(config.paths.LIB_ROOT + 'error');
process.mono.cache = require(config.paths.LIB_ROOT + 'cache')();

// TEST new store factory
var setupStoreFactory = require(config.paths.LIB_ROOT + 'stores/factory');
var storeType = 'mongodb';
var serverStoreConfig = {
    host: config.dbHost,
    port: config.dbPort,
    name: 'mono',
    user: 'server',
    pass: config.dbPwd
};

// TODO make application model configurable
process.mono.config.applicationModel = 'm_applications';

setupStoreFactory(storeType, serverStoreConfig, function (err, store) {
    process.mono.emit('ready');
});
<commit_msg>added todo<commit_after>var EventEmitter = require('events').EventEmitter;
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var config = require('./config');

// create api object
process.mono = new EventEmitter();
process.mono.config = config;
process.mono.error = require(config.paths.LIB_ROOT + 'error');
process.mono.cache = require(config.paths.LIB_ROOT + 'cache')();

// TODO make main store config configurable in application
var setupStoreFactory = require(config.paths.LIB_ROOT + 'stores/factory');
var storeType = 'mongodb';
var serverStoreConfig = {
    host: config.dbHost,
    port: config.dbPort,
    name: 'mono',
    user: 'server',
    pass: config.dbPwd
};

// TODO make application model configurable
process.mono.config.applicationModel = 'm_applications';

setupStoreFactory(storeType, serverStoreConfig, function (err, store) {
    process.mono.emit('ready');
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         moneything-filter
// @namespace    https://github.com/moogman/p2p-userscripts/scripts/moneything
// @version      0.1.2
// @description  Filter out various things on the MoneyThing website.
// @author       moogman
// @match        https://www.moneything.com/p2p/index.php/loan
// @match        https://www.moneything.com/p2p/index.php/Loan
// @match        https://www.moneything.com/p2p/index.php/Loan.html
// @match        https://www.moneything.com/p2p/index.php/Center/invest/mid/live.html
// @match        https://www.moneything.com/p2p/index.php/Loan/invest/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_addStyle
// @require      ../../includes/p2p-common.user.js
// XX@require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js        // Disable as MT already uses jQuery
// XX@require      https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js  // Disable as MT already uses jQueryUI
// ==/UserScript==

/* ### DO NOT EDIT ANYTHING HERE - IT WILL BE OVERWRITTEN ON UPDATE ###
Please log a feature request through the forum.
*/

set_defaults(false);
var target_upper_spread = 1.1;  //  Investment target + this value is the upper target, whereby any investments >= this level will be highlighted in red.
var initial_wait_timer = 0.5;  // Wait this amount of seconds before decorating the loan table (Because the loan table is loaded after page load, via ajax).

// Row IDs.
var description_row = 0;
var rate_row = 4;
var biddingstart_row = 5;
var enddate_row = 6;
var available_row = 7;
var invested_row = 8;
var drawdown_row = 9;
var renew_row = 10;

function decorate_available_page() {
    // Expand the main table.
    $(_x("/html/body/div[1]/div[2]/div")).removeClass("container").addClass("container-fluid");
    // Reduce the padding on the table headings, to compress things more.
    // .fixed-table-container thead th .sortable  -> padding-right: 15px;
    // .fixed-table-container tbody td .th-inner, .fixed-table-container thead th .th-inner  -> padding: 2px;
    GM_addStyle(`
    .fixed-table-container tbody td .th-inner, .fixed-table-container thead th .th-inner {
        /* Make that able heading padding smaller */
        padding: 0px;
    }
    .fixed-table-container thead th .sortable {
        /* Make the table heading right padding smaller */
        padding-right: 10px;
    }
    .th-inner {
        /* Make the table heading text smaller */
        font-size: 10px;
    }
    .fixed-table-container thead th .sortable {
        /* Shift the sortable icon to the right a bit. */
        background-position: 115%;
    }
    `);

    // Hide out some loans that don't meet our requirements.
    var each_tr = "//*[@id='table1']/*/tr[*]";
    $(_x(each_tr)).each(function () {
        var tr = this;

        for (var child of tr.children) {
            child.style.padding = '2px';
        }

        var is_available_page = true;
        var invested_td = this.children[invested_row];
        var invested = str_to_pounds(invested_td.textContent) || 0;
        var available = -1;
        if (is_available_page) {
            var available_td = tr.children[available_row];
            //available = str_to_pounds(available_td.textContent);
             if (available_td.textContent != '0.00%') {
                 available = 1;
             }
        }

        // Hide any at target investment level.
        var target_lower = parseFloat(GM_getValue('investment_target'));
        var target_upper = target_lower * target_upper_spread;
        if (is_available_page && available < 1) {
            tr.dataset.target = 'hit';
            //tr.style.display = 'none';
        } else if (invested > target_upper) {
            // heavy -> make red
            invested_td.style["background-color"] = '#ffdddd';
            tr.dataset.target = 'above';
        } else if (invested > target_lower) {
            // light -> make orange
            invested_td.style["background-color"] = '#fff6db';
            tr.dataset.target = 'hit';
        } else if (invested < target_lower) {
            // light -> make green
            invested_td.style["background-color"] = '#ddffdd';
            tr.dataset.target = 'below';
        } else {
            tr.dataset.target = 'hit';
        }

        // Hide any loans with IR < 12%.
        if (parseFloat(this.children[rate_row].textContent) < parseFloat(GM_getValue('min_interest_rate'))) {
            this.children[rate_row].style["background-color"] = '#ffdddd';
            tr.dataset.target = 'hit';
        }

        // Hide any "IMMINENT REPAYMENT" or "EXPECTED REPAYMENT".
        if (this.children[description_row].textContent.includes("IMMINENT REPAYMENT") || this.children[description_row].textContent.includes("EXPECTED REPAYMENT")) {
            this.children[description_row].style["background-color"] = '#ffdddd';
            tr.dataset.target = 'hit';
        }

        // Hide some columns: Bidding start, Draw Down, Renew.
        this.children[biddingstart_row].style.display = 'none';
        this.children[drawdown_row].style.display = 'none';
        if (GM_getValue('show_renew_column') === false) {
            this.children[renew_row].style.display = 'none';
        }

    });

    setup_target_toggler_checkbox('//*[@id="content"]/div[2]', each_tr);
}

function decorate_loan_page() {
    var details_pane = _x('//*[@id="details"]')[0];
    var invest_pane = _x('//*[@id="invest-now"]')[0];

    // Make the invest pane also active, and shuffle the panes so that it's at the top of the page.
    $(invest_pane).addClass('active');
    invest_pane.parentElement.insertBefore(invest_pane, details_pane);

    // Calculate existing investment.
    var existing_investment = 0;
    var existing_investment_div = _x('//*[@id="invest-now"]/div/div/form/dl/dd[1]/div');
    if (existing_investment_div.length > 0) {
        var investment_txt = existing_investment_div[0].innerText;
        if (investment_txt.startsWith("My existing investment: £")) {
            existing_investment = str_to_pounds(investment_txt.replace("My existing investment: ", ""));
        }
    }

    // Populate investment suggestion.
    var my_funds_div = _x('//*[@id="invest-now"]/div/div/form/dl/dd[2]/span[@class="invest_price"]')[0];
    var my_funds = str_to_pounds(my_funds_div.innerText);

    // Calculate investment suggestion.
    var target_lower = parseFloat(GM_getValue('investment_target'));
    var suggested_investment = Math.max(0, target_lower - existing_investment);
    suggested_investment = Math.min(Math.floor(my_funds), suggested_investment);

    var invest_box = _x('//*[@id="price"]')[0];
    invest_box.value = suggested_investment;

    // Focus the price box.
    $("#price").focus(function() { $(this).select(); } );  // On focus, select all the text.
    $('#price').focus();
}

(function() {
    'use strict';

    if (window.location.href.search('[lL]oan\(\|.html\)$') > -1) {
        /* Loans available page */
        console.log('loans/available page');
        var reloader_timeout = setTimeout(decorate_available_page, initial_wait_timer*1000);

    } else if (window.location.href.search('Center/invest/mid/live.html') > -1) {
        /* My Loans page */
        console.log('my loans page');

    } else if (window.location.href.match('Loan/invest/[0-9]+.html') !== null) {
        /* A loan page */
        console.log('a loan page');
        decorate_loan_page();
    }

})();
<commit_msg>Bump version for bugfix (0.1.3)<commit_after>// ==UserScript==
// @name         moneything-filter
// @namespace    https://github.com/moogman/p2p-userscripts/scripts/moneything
// @version      0.1.3
// @description  Filter out various things on the MoneyThing website.
// @author       moogman
// @match        https://www.moneything.com/p2p/index.php/loan
// @match        https://www.moneything.com/p2p/index.php/Loan
// @match        https://www.moneything.com/p2p/index.php/Loan.html
// @match        https://www.moneything.com/p2p/index.php/Center/invest/mid/live.html
// @match        https://www.moneything.com/p2p/index.php/Loan/invest/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_addStyle
// @require      ../../includes/p2p-common.user.js
// XX@require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js        // Disable as MT already uses jQuery
// XX@require      https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js  // Disable as MT already uses jQueryUI
// ==/UserScript==

/* ### DO NOT EDIT ANYTHING HERE - IT WILL BE OVERWRITTEN ON UPDATE ###
Please log a feature request through the forum.
*/

set_defaults(false);
var target_upper_spread = 1.1;  //  Investment target + this value is the upper target, whereby any investments >= this level will be highlighted in red.
var initial_wait_timer = 0.5;  // Wait this amount of seconds before decorating the loan table (Because the loan table is loaded after page load, via ajax).

// Row IDs.
var description_row = 0;
var rate_row = 4;
var biddingstart_row = 5;
var enddate_row = 6;
var available_row = 7;
var invested_row = 8;
var drawdown_row = 9;
var renew_row = 10;

function decorate_available_page() {
    // Expand the main table.
    $(_x("/html/body/div[1]/div[2]/div")).removeClass("container").addClass("container-fluid");
    // Reduce the padding on the table headings, to compress things more.
    // .fixed-table-container thead th .sortable  -> padding-right: 15px;
    // .fixed-table-container tbody td .th-inner, .fixed-table-container thead th .th-inner  -> padding: 2px;
    GM_addStyle(`
    .fixed-table-container tbody td .th-inner, .fixed-table-container thead th .th-inner {
        /* Make that able heading padding smaller */
        padding: 0px;
    }
    .fixed-table-container thead th .sortable {
        /* Make the table heading right padding smaller */
        padding-right: 10px;
    }
    .th-inner {
        /* Make the table heading text smaller */
        font-size: 10px;
    }
    .fixed-table-container thead th .sortable {
        /* Shift the sortable icon to the right a bit. */
        background-position: 115%;
    }
    `);

    // Hide out some loans that don't meet our requirements.
    var each_tr = "//*[@id='table1']/*/tr[*]";
    $(_x(each_tr)).each(function () {
        var tr = this;

        for (var child of tr.children) {
            child.style.padding = '2px';
        }

        var is_available_page = true;
        var invested_td = this.children[invested_row];
        var invested = str_to_pounds(invested_td.textContent) || 0;
        var available = -1;
        if (is_available_page) {
            var available_td = tr.children[available_row];
            //available = str_to_pounds(available_td.textContent);
             if (available_td.textContent != '0.00%') {
                 available = 1;
             }
        }

        // Hide any at target investment level.
        var target_lower = parseFloat(GM_getValue('investment_target'));
        var target_upper = target_lower * target_upper_spread;
        if (is_available_page && available < 1) {
            tr.dataset.target = 'hit';
            //tr.style.display = 'none';
        } else if (invested > target_upper) {
            // heavy -> make red
            invested_td.style["background-color"] = '#ffdddd';
            tr.dataset.target = 'above';
        } else if (invested > target_lower) {
            // light -> make orange
            invested_td.style["background-color"] = '#fff6db';
            tr.dataset.target = 'hit';
        } else if (invested < target_lower) {
            // light -> make green
            invested_td.style["background-color"] = '#ddffdd';
            tr.dataset.target = 'below';
        } else {
            tr.dataset.target = 'hit';
        }

        // Hide any loans with IR < 12%.
        if (parseFloat(this.children[rate_row].textContent) < parseFloat(GM_getValue('min_interest_rate'))) {
            this.children[rate_row].style["background-color"] = '#ffdddd';
            tr.dataset.target = 'hit';
        }

        // Hide any "IMMINENT REPAYMENT" or "EXPECTED REPAYMENT".
        if (this.children[description_row].textContent.includes("IMMINENT REPAYMENT") || this.children[description_row].textContent.includes("EXPECTED REPAYMENT")) {
            this.children[description_row].style["background-color"] = '#ffdddd';
            tr.dataset.target = 'hit';
        }

        // Hide some columns: Bidding start, Draw Down, Renew.
        this.children[biddingstart_row].style.display = 'none';
        this.children[drawdown_row].style.display = 'none';
        if (GM_getValue('show_renew_column') === false) {
            this.children[renew_row].style.display = 'none';
        }

    });

    setup_target_toggler_checkbox('//*[@id="content"]/div[2]', each_tr);
}

function decorate_loan_page() {
    var details_pane = _x('//*[@id="details"]')[0];
    var invest_pane = _x('//*[@id="invest-now"]')[0];

    // Make the invest pane also active, and shuffle the panes so that it's at the top of the page.
    $(invest_pane).addClass('active');
    invest_pane.parentElement.insertBefore(invest_pane, details_pane);

    // Calculate existing investment.
    var existing_investment = 0;
    var existing_investment_div = _x('//*[@id="invest-now"]/div/div/form/dl/dd[1]/div');
    if (existing_investment_div.length > 0) {
        var investment_txt = existing_investment_div[0].innerText;
        if (investment_txt.startsWith("My existing investment: £")) {
            existing_investment = str_to_pounds(investment_txt.replace("My existing investment: ", ""));
        }
    }

    // Populate investment suggestion.
    var my_funds_div = _x('//*[@id="invest-now"]/div/div/form/dl/dd[2]/span[@class="invest_price"]')[0];
    var my_funds = str_to_pounds(my_funds_div.innerText);

    // Calculate investment suggestion.
    var target_lower = parseFloat(GM_getValue('investment_target'));
    var suggested_investment = Math.max(0, target_lower - existing_investment);
    suggested_investment = Math.min(Math.floor(my_funds), suggested_investment);

    var invest_box = _x('//*[@id="price"]')[0];
    invest_box.value = suggested_investment;

    // Focus the price box.
    $("#price").focus(function() { $(this).select(); } );  // On focus, select all the text.
    $('#price').focus();
}

(function() {
    'use strict';

    if (window.location.href.search('[lL]oan\(\|.html\)$') > -1) {
        /* Loans available page */
        console.log('loans/available page');
        var reloader_timeout = setTimeout(decorate_available_page, initial_wait_timer*1000);

    } else if (window.location.href.search('Center/invest/mid/live.html') > -1) {
        /* My Loans page */
        console.log('my loans page');

    } else if (window.location.href.match('Loan/invest/[0-9]+.html') !== null) {
        /* A loan page */
        console.log('a loan page');
        decorate_loan_page();
    }

})();
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SingletonFactory = undefined;

var _keyfunc2 = require('keyfunc');

var _keyfunc3 = _interopRequireDefault(_keyfunc2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var getKeyFunc = function getKeyFunc(defaultKeyfunc) {
  var keyfunc = defaultKeyfunc;

  if (typeof keyfunc !== 'function') {
    if (Array.isArray(keyfunc)) {
      keyfunc = _keyfunc3.default.apply(undefined, _toConsumableArray(keyfunc));
    } else {
      throw new TypeError('Initializing keyFunc argument should be a function generating unique\nkeys from arguments, or an array of hints');
    }
  }

  return keyfunc;
};

var idFunc = function idFunc(args) {
  return args;
};

var SingletonFactory = exports.SingletonFactory = function SingletonFactory(Type) {
  var defaultKeyfunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (obj) {
    return obj.toString();
  };
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    preprocess: idFunc,
    postprocess: idFunc
  };

  var madeSingleton = function (_Type, _keyfunc, _options) {
    var preprocess = _options.preprocess || idFunc;
    var postprocess = _options.postprocess || idFunc;

    var instances = new Map();
    var keySymb = Symbol();
    var Singleton = function Singleton() {
      for (var _len = arguments.length, _args = Array(_len), _key2 = 0; _key2 < _len; _key2++) {
        _args[_key2] = arguments[_key2];
      }

      var args = preprocess(_args);

      var key = Singleton.key.apply(Singleton, _toConsumableArray(args));
      var instance = instances.get(key);

      if (instance) {
        return postprocess(instance, args);
      }

      instance = new (Function.prototype.bind.apply(_Type, [null].concat(_toConsumableArray(args))))();
      instance[keySymb] = key;
      instances.set(key, instance);

      return postprocess(instance, args);
    };

    Singleton.key = function (arg0) {
      for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
        args[_key3 - 1] = arguments[_key3];
      }

      if (arg0[keySymb]) {
        return arg0[keySymb];
      }

      return _keyfunc.apply(undefined, [arg0].concat(args));
    };
    Singleton.singleton = function (_key) {
      return instances.get(_key);
    };
    Singleton.get = function () {
      return instances.get(Singleton.key.apply(Singleton, arguments));
    };

    return Singleton;
  }(Type, getKeyFunc(defaultKeyfunc), options);

  return madeSingleton;
};<commit_msg>Prepublish<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SingletonFactory = undefined;

var _keyfunc2 = require('keyfunc');

var _keyfunc3 = _interopRequireDefault(_keyfunc2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var getKeyFunc = function getKeyFunc(defaultKeyfunc) {
  var keyfunc = defaultKeyfunc;

  if (typeof keyfunc !== 'function') {
    if (Array.isArray(keyfunc)) {
      keyfunc = _keyfunc3.default.apply(undefined, _toConsumableArray(keyfunc));
    } else {
      throw new TypeError('Initializing keyFunc argument should be a function generating unique\nkeys from arguments, or an array of hints');
    }
  }

  return keyfunc;
};

var idFunc = function idFunc(args) {
  return args;
};

var SingletonFactory = exports.SingletonFactory = function SingletonFactory(Type) {
  var defaultKeyfunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (obj) {
    return obj.toString();
  };
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    preprocess: idFunc,
    postprocess: idFunc
  };

  var madeSingleton = function (_Type, _keyfunc, _options) {
    var preprocess = _options.preprocess || idFunc;
    var postprocess = _options.postprocess || idFunc;
    var customArgs = _options.customArgs && new Map(_options.customArgs);

    var reduceableTypes = customArgs ? new Set(Array.from(customArgs.keys()).filter(function (key) {
      return customArgs.get(key).reduce;
    })) : null;

    var instances = new Map();
    var keySymb = Symbol();
    var Singleton = function Singleton() {
      var extractedArgs = void 0;
      var convertedArgs = void 0;
      var unreduceableArgs = void 0;

      for (var _len = arguments.length, _args = Array(_len), _key2 = 0; _key2 < _len; _key2++) {
        _args[_key2] = arguments[_key2];
      }

      if (customArgs) {
        extractedArgs = _args.filter(function (arg) {
          return customArgs.has(Object.getPrototypeOf(arg).constructor);
        });

        convertedArgs = _args.map(function (arg) {
          var type = Object.getPrototypeOf(arg).constructor;

          if (customArgs.has(type)) {
            var _customArgs$get = customArgs.get(type),
                convert = _customArgs$get.convert;

            return convert ? convert(arg) : null;
          }

          return arg;
        }).filter(function (arg) {
          return arg !== null;
        });

        unreduceableArgs = extractedArgs.filter(function (arg) {
          var type = Object.getPrototypeOf(arg).constructor;
          return !reduceableTypes.has(type);
        });
      }

      var args = preprocess(convertedArgs || _args);

      var key = Singleton.key.apply(Singleton, _toConsumableArray(args));
      var instance = instances.get(key);

      if (!instance) {
        instance = new (Function.prototype.bind.apply(_Type, [null].concat(_toConsumableArray(args))))();
        instance[keySymb] = key;
        instances.set(key, instance);
      }

      if (customArgs) {
        reduceableTypes.forEach(function (type) {
          var _customArgs$get2 = customArgs.get(type),
              reduce = _customArgs$get2.reduce,
              postprocess = _customArgs$get2.postprocess;

          postprocess.call(instance, reduce(extractedArgs.filter(function (arg) {
            return arg instanceof type;
          })));
        });

        unreduceableArgs.forEach(function (arg) {
          var type = Object.getPrototypeOf(arg).constructor;

          var _customArgs$get3 = customArgs.get(type),
              postprocess = _customArgs$get3.postprocess;

          if (postprocess) {
            postprocess.call(instance, arg);
          }
        });
      }

      postprocess.call(instance, args);

      return instance;
    };

    Singleton.key = function (arg0) {
      for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
        args[_key3 - 1] = arguments[_key3];
      }

      if (arg0[keySymb]) {
        return arg0[keySymb];
      }

      return _keyfunc.apply(undefined, [arg0].concat(args));
    };
    Singleton.singleton = function (_key) {
      return instances.get(_key);
    };
    Singleton.get = function () {
      return instances.get(Singleton.key.apply(Singleton, arguments));
    };

    return Singleton;
  }(Type, getKeyFunc(defaultKeyfunc), options);

  return madeSingleton;
};<|endoftext|>


<commit_before>/* eslint-env node */
/* eslint  @typescript-eslint/no-var-requires: "off" */
const path = require('path');
const webpack = require('webpack');

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CopyPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const PROD = process.env.NODE_ENV === 'production';
const PREPROD = process.env.NODE_ENV === 'pre-production';
const STATS = process.env.NODE_ENV === 'stats';

const isCI =
  typeof process.env.CI === 'string'
    ? process.env.CI.toLowerCase() === 'true'
    : false;

const plugins = [
  new webpack.ProvidePlugin({
    Buffer: ['buffer', 'Buffer'],
  }),
  new webpack.ProvidePlugin({
    process: 'process/browser',
  }),
  new ForkTsCheckerWebpackPlugin({
    typescript: { configFile: process.env.TS_NODE_PROJECT },
  }),
  new CopyPlugin({
    patterns: [{ from: 'src/**/*.less' }],
  }),
  new ESLintPlugin({
    context: './src',
    extensions: ['ts', 'tsx'],
    quiet: true,
    failOnError: PROD ? true : false,
  }),
];

if (!isCI && PREPROD) {
  plugins.push(new BundleAnalyzerPlugin());
}

const modules = {
  devtool: PROD || PREPROD ? 'source-map' : 'inline-source-map',
  optimization: {
    minimizer: [
      compiler => {
        const TerserPlugin = require('terser-webpack-plugin');
        new TerserPlugin({
          terserOptions: {
            mangle: {
              keep_classnames: true,
              keep_fnames: true,
            },
            compress: {
              passes: 2,
            },
          },
        }).apply(compiler);
      },
    ],
  },
  entry: {
    editor: ['./src/index.tsx'],
    player: ['./src/player.tsx'],
    host: ['./src/host.tsx'],
  },
  output: {
    path: path.join(__dirname, '../../../../target/Wegas/wegas-react/dist/'),
    publicPath: '../wegas-react/dist/',
  },
  resolve: {
    extensions: [
      '.ts',
      '.tsx',
      '.mjs',
      '.js',
      '.jsx',
      '.json',
      '.ttf',
      '.d.ts',
    ],
    mainFields: ['browser', 'module', 'main'],
  },
  plugins: plugins,
  module: {
    // https://github.com/ivan-aksamentov/reactlandia-bolerplate-lite/issues/5#issuecomment-413306341
    exprContextCritical: false,
    rules: [
      {
        // Include ts, tsx, js, and jsx files.
        test: /\.(ts)x?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jp(e*)g)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000, // Convert images < 8kb to base64 strings
              name: 'src/pictures/[hash]-[name].[ext]',
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
      {
        test: /\.(ttf)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000,
              name: 'src/fonts/[hash]-[name].[ext]',
            },
          },
        ],
      },
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
      {
        test: /\.less$/i,
        use: 'raw-loader',
      },
      {
        // https://github.com/foxglove/studio/pull/546/commits/8a60775ac428b25c8cf7bd4be7c5075f4b9bafdc
        // TypeScript uses dynamic requires()s when running in node. We can disable these when we
        // bundle it for the renderer.
        test: /[\\/]node_modules[\\/]typescript[\\/]lib[\\/]typescript\.js$/,
        loader: 'string-replace-loader',
        options: {
          multiple: [
            {
              search:
                'var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;',
              replace:
                "throw new Error('[perf_hooks] This module is not supported in the browser.');",
            },
          ],
        },
      },
    ],
  },
  devServer: {
    host: 'localhost',
    port: 3003,
    proxy: {
      '/Wegas': 'http://localhost:8080',
    },
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
    devMiddleware: {
      stats: 'errors-warnings',
      publicPath: '/Wegas/wegas-react/dist',
    },
  },
};

module.exports = STATS ? smp.wrap(modules) : modules;
<commit_msg>Do not use inline-source-map event<commit_after>/* eslint-env node */
/* eslint  @typescript-eslint/no-var-requires: "off" */
const path = require('path');
const webpack = require('webpack');

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CopyPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const PROD = process.env.NODE_ENV === 'production';
const PREPROD = process.env.NODE_ENV === 'pre-production';
const STATS = process.env.NODE_ENV === 'stats';

const isCI =
  typeof process.env.CI === 'string'
    ? process.env.CI.toLowerCase() === 'true'
    : false;

const plugins = [
  new webpack.ProvidePlugin({
    Buffer: ['buffer', 'Buffer'],
  }),
  new webpack.ProvidePlugin({
    process: 'process/browser',
  }),
  new ForkTsCheckerWebpackPlugin({
    typescript: { configFile: process.env.TS_NODE_PROJECT },
  }),
  new CopyPlugin({
    patterns: [{ from: 'src/**/*.less' }],
  }),
  new ESLintPlugin({
    context: './src',
    extensions: ['ts', 'tsx'],
    quiet: true,
    failOnError: PROD ? true : false,
  }),
];

if (!isCI && PREPROD) {
  plugins.push(new BundleAnalyzerPlugin());
}

const modules = {
  devtool: PROD || PREPROD ? 'source-map' : 'source-map',
  optimization: {
    minimizer: [
      compiler => {
        const TerserPlugin = require('terser-webpack-plugin');
        new TerserPlugin({
          terserOptions: {
            mangle: {
              keep_classnames: true,
              keep_fnames: true,
            },
            compress: {
              passes: 2,
            },
          },
        }).apply(compiler);
      },
    ],
  },
  entry: {
    editor: ['./src/index.tsx'],
    player: ['./src/player.tsx'],
    host: ['./src/host.tsx'],
  },
  output: {
    path: path.join(__dirname, '../../../../target/Wegas/wegas-react/dist/'),
    publicPath: '../wegas-react/dist/',
  },
  resolve: {
    extensions: [
      '.ts',
      '.tsx',
      '.mjs',
      '.js',
      '.jsx',
      '.json',
      '.ttf',
      '.d.ts',
    ],
    mainFields: ['browser', 'module', 'main'],
  },
  plugins: plugins,
  module: {
    // https://github.com/ivan-aksamentov/reactlandia-bolerplate-lite/issues/5#issuecomment-413306341
    exprContextCritical: false,
    rules: [
      {
        // Include ts, tsx, js, and jsx files.
        test: /\.(ts)x?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jp(e*)g)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000, // Convert images < 8kb to base64 strings
              name: 'src/pictures/[hash]-[name].[ext]',
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
      {
        test: /\.(ttf)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8000,
              name: 'src/fonts/[hash]-[name].[ext]',
            },
          },
        ],
      },
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
      {
        test: /\.less$/i,
        use: 'raw-loader',
      },
      {
        // https://github.com/foxglove/studio/pull/546/commits/8a60775ac428b25c8cf7bd4be7c5075f4b9bafdc
        // TypeScript uses dynamic requires()s when running in node. We can disable these when we
        // bundle it for the renderer.
        test: /[\\/]node_modules[\\/]typescript[\\/]lib[\\/]typescript\.js$/,
        loader: 'string-replace-loader',
        options: {
          multiple: [
            {
              search:
                'var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;',
              replace:
                "throw new Error('[perf_hooks] This module is not supported in the browser.');",
            },
          ],
        },
      },
    ],
  },
  devServer: {
    host: 'localhost',
    port: 3003,
    proxy: {
      '/Wegas': 'http://localhost:8080',
    },
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
    devMiddleware: {
      stats: 'errors-warnings',
      publicPath: '/Wegas/wegas-react/dist',
    },
  },
};

module.exports = STATS ? smp.wrap(modules) : modules;
<|endoftext|>