<commit_before>app
.factory('localizedMessageService', ['$cookies', function($cookies) {
	var exposedAPI =
	{
		getDropdown: getDropdown,
		getLocalizedMessage: getLocalizedMessage
	}

	return exposedAPI;

	function getDropdown()
	{
		return [
			{text: 'English', click: 'setLangCode("en")'},
			{text: 'Polski', click: 'setLangCode("pl")'}
		  ];
	}

	function getLocalizedMessage(messageCode)
	{
		var langCode = $cookies.get('language');

		switch(langCode)
		{
			case "en":
				return getEnValue(messageCode);
				break;
			case "pl":
				return getPlValue(messageCode);
				break;
		}

		return "Localization service error";
	}

	function getEnValue(messageCode)
	{
		switch(messageCode)
		{
			case "settings.header":
				return "Settings";
			case "settings.selectLanguage":
				return "Select language";
			case "navbar.networks":
				return "Networks";
			case "navbar.workspace":
				return "Workspace";
			case "navbar.generate":
				return "Generate";
			case "navbar.export":
				return "Export";
			case "navbar.training":
				return "Training";
			case "navbar.settings":
				return "Settings";
			case "navbar.logout":
				return "Logout";
			case "login.signIn":
				return "Sign in";
			case "login.login":
				return "Login";
			case "login.password":
				return "Password";
			case "login.rememberMe":
				return "Remember me";
			case "login.createNewAccount":
				return "Create new account";
			case "login.alert.unableToSignIn.title":
				return "Unable to sign in: ";
			case "register.signUp":
				return "Sign up";
			case "register.email":
				return "Email";
			case "register.login":
				return "Login";
			case "register.password":
				return "Password";
			case "register.confirmPassword":
				return "Confiirm password";
			case "register.enterTheMessageForAdminHere":
				return "Enter the message for the admin here...";
			case "register.register":
				return "Register";
			case "register.backToTheLoginPrompt":
				return "Go back to the login prompt";
			case "register.alert.dataSubmitOK.title":
				return 'Data has been submitted successfully.';
			case "register.alert.dataSubmitOK.content":
				return 'We will look at your request';
			case "register.alert.dataSubmitNOK.title":
				return 'Cannot register: ';
			case "register.alert.errorMessagePasswordsDM":
				return "Passwords doesn't match!";
			case "navbar.dropdown.load":
				return "Load...";
			case "navbar.dropdown.save":
				return "Save";
			case "navbar.dropdown.saveas":
				return "Save as...";
			case "navbar.dropdown.delete":
				return "Delete";
			case "navbar.alert.deleteOK.title":
				return "Network deleted";
			case "navbar.alert.deleteOK.content":
				return "Network deleted successfully";
			case "navbar.alert.deleteNOK.title":
				return "Unable to delete network";
			case "load.loadViewHeader":
				return "Select network to load";
			case "load.createdIn":
				return "created in";
			case "load.alert.loadListNOK.title":
				return "Unable to load the list of networks";
		}

		return "Localization service error getting English value";
	}

	function getPlValue(messageCode)
	{
		switch(messageCode)
		{
			case "settings.header":
				return "Ustawienia";
			case "settings.selectLanguage":
				return "Wybierz język";
			case "navbar.networks":
				return "Sieci";
			case "navbar.workspace":
				return "Przestrzeń robocza";
			case "navbar.generate":
				return "Generuj";
			case "navbar.export":
				return "Eksport";
			case "navbar.training":
				return "Trening";
			case "navbar.settings":
				return "Ustawienia";
			case "navbar.logout":
				return "Wyloguj";
			case "login.signIn":
				return "Zaloguj";
			case "login.login":
				return "Login";
			case "login.password":
				return "Hasło";
			case "login.rememberMe":
				return "Zapamiętaj";
			case "login.createNewAccount":
				return "Stwórz nowe konto";
			case "login.alert.unableToSignIn.title":
				return "Bład logowania: ";
			case "register.signUp":
				return "Rejestracja nowego konta";
			case "register.email":
				return "Email";
			case "register.login":
				return "Login";
			case "register.password":
				return "Hasło";
			case "register.confirmPassword":
				return "Potwierdzenie hasła";
			case "register.enterTheMessageForAdminHere":
				return "Wpisz tutaj wiadomość dla administratora...";
			case "register.register":
				return "Zarejestruj";
			case "register.backToTheLoginPrompt":
				return "Wróć do ekranu logowania";
			case "register.alert.dataSubmitOK.title":
				return 'Dane zostały wysłane pomyślnie';
			case "register.alert.dataSubmitOK.content":
				return 'Podanie zostanie rozpatrzone';
			case "register.alert.dataSubmitNOK.title":
				return 'Nie można zarejestrować: ';
			case "register.alert.errorMessagePasswordsDM":
				return "Podane hasła nie zgadzają się";
		}

		return "Localization service error getting Polish value";
	}
}]);<commit_msg>Bugfix<commit_after>app
.factory('localizedMessageService', ['$cookies', function($cookies) {
	var exposedAPI =
	{
		getDropdown: getDropdown,
		getLocalizedMessage: getLocalizedMessage
	}

	return exposedAPI;

	function getDropdown()
	{
		return [
			{text: 'English', click: 'setLangCode("en")'},
			{text: 'Polski', click: 'setLangCode("pl")'}
		  ];
	}

	function getLocalizedMessage(messageCode)
	{
		var langCode = $cookies.get('language');

		switch(langCode)
		{
			case "en":
				return getEnValue(messageCode);
				break;
			case "pl":
				return getPlValue(messageCode);
				break;
		}

		return "Localization service error";
	}

	function getEnValue(messageCode)
	{
		switch(messageCode)
		{
			case "settings.header":
				return "Settings";
			case "settings.selectLanguage":
				return "Select language";
			case "navbar.networks":
				return "Networks";
			case "navbar.workspace":
				return "Workspace";
			case "navbar.generate":
				return "Generate";
			case "navbar.export":
				return "Export";
			case "navbar.training":
				return "Training";
			case "navbar.settings":
				return "Settings";
			case "navbar.logout":
				return "Logout";
			case "login.signIn":
				return "Sign in";
			case "login.login":
				return "Login";
			case "login.password":
				return "Password";
			case "login.rememberMe":
				return "Remember me";
			case "login.createNewAccount":
				return "Create new account";
			case "login.alert.unableToSignIn.title":
				return "Unable to sign in: ";
			case "register.signUp":
				return "Sign up";
			case "register.email":
				return "Email";
			case "register.login":
				return "Login";
			case "register.password":
				return "Password";
			case "register.confirmPassword":
				return "Confiirm password";
			case "register.enterTheMessageForAdminHere":
				return "Enter the message for the admin here...";
			case "register.register":
				return "Register";
			case "register.backToTheLoginPrompt":
				return "Go back to the login prompt";
			case "register.alert.dataSubmitOK.title":
				return 'Data has been submitted successfully.';
			case "register.alert.dataSubmitOK.content":
				return 'We will look at your request';
			case "register.alert.dataSubmitNOK.title":
				return 'Cannot register: ';
			case "register.alert.errorMessagePasswordsDM":
				return "Passwords doesn't match!";
			case "navbar.dropdown.load":
				return "Load...";
			case "navbar.dropdown.save":
				return "Save";
			case "navbar.dropdown.saveas":
				return "Save as...";
			case "navbar.dropdown.delete":
				return "Delete";
			case "navbar.alert.deleteOK.title":
				return "Network deleted";
			case "navbar.alert.deleteOK.content":
				return "Network deleted successfully";
			case "navbar.alert.deleteNOK.title":
				return "Unable to delete network";
			case "load.loadViewHeader":
				return "Select network to load";
			case "load.createdIn":
				return "created in";
			case "load.alert.loadListNOK.title":
				return "Unable to load the list of networks";
		}

		return "Localization service error getting English value";
	}

	function getPlValue(messageCode)
	{
		switch(messageCode)
		{
			case "settings.header":
				return "Ustawienia";
			case "settings.selectLanguage":
				return "Wybierz język";
			case "navbar.networks":
				return "Sieci";
			case "navbar.workspace":
				return "Przestrzeń robocza";
			case "navbar.generate":
				return "Generuj";
			case "navbar.export":
				return "Eksport";
			case "navbar.training":
				return "Trening";
			case "navbar.settings":
				return "Ustawienia";
			case "navbar.logout":
				return "Wyloguj";
			case "login.signIn":
				return "Zaloguj";
			case "login.login":
				return "Login";
			case "login.password":
				return "Hasło";
			case "login.rememberMe":
				return "Zapamiętaj";
			case "login.createNewAccount":
				return "Stwórz nowe konto";
			case "login.alert.unableToSignIn.title":
				return "Bład logowania: ";
			case "register.signUp":
				return "Rejestracja nowego konta";
			case "register.email":
				return "Email";
			case "register.login":
				return "Login";
			case "register.password":
				return "Hasło";
			case "register.confirmPassword":
				return "Potwierdzenie hasła";
			case "register.enterTheMessageForAdminHere":
				return "Wpisz tutaj wiadomość dla administratora...";
			case "register.register":
				return "Zarejestruj";
			case "register.backToTheLoginPrompt":
				return "Wróć do ekranu logowania";
			case "register.alert.dataSubmitOK.title":
				return 'Dane zostały wysłane pomyślnie';
			case "register.alert.dataSubmitOK.content":
				return 'Podanie zostanie rozpatrzone';
			case "register.alert.dataSubmitNOK.title":
				return 'Nie można zarejestrować: ';
			case "register.alert.errorMessagePasswordsDM":
				return "Podane hasła nie zgadzają się";
			case "navbar.dropdown.load":
				return "Ładuj...";
			case "navbar.dropdown.save":
				return "Zapisz";
			case "navbar.dropdown.saveas":
				return "Zapisz jako...";
			case "navbar.dropdown.delete":
				return "Usuń";
			case "navbar.alert.deleteOK.title":
				return "Usunięcie sieci";
			case "navbar.alert.deleteOK.content":
				return "Sieć została usunięta pomyślnie";
			case "navbar.alert.deleteNOK.title":
				return "Nie można usunąć sieci";
			case "load.loadViewHeader":
				return "Wybierz sieć";
			case "load.createdIn":
				return "utworzono";
			case "load.alert.loadListNOK.title":
				return "Nie można pobrać listy sieci";
		}

		return "Localization service error getting Polish value";
	}
}]);<|endoftext|>


<commit_before>import React, { useState } from 'react';
import Types from 'prop-types';
import { connect } from 'react-redux';
import { Link, Redirect } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import { Radio } from '../../../common';
import ThirdPillarPaymentsThisYear from '../../../account/statusBox/thirdPillarStatusBox/ThirdPillarYearToDateContribution';

export const ThirdPillarPayment2 = ({
  previousPath,
  nextPath,
  signedMandateId,
  pensionAccountNumber,
  isUserConverted,
}) => {
  const [paymentType, setPaymentType] = useState('SINGLE');
  const [paymentAmount, setPaymentAmount] = useState('');
  const [paymentBank, setPaymentBank] = useState('');

  const onPayment = (amount, bank) => {
    // console.log(amount, bank);
  };

  return (
    <>
      {false && !signedMandateId && !isUserConverted && <Redirect to={previousPath} />}

      Millist tüüpi makset soovid teha?

      <Radio
        name="payment-type"
        id="payment-type-single"
        className="mt-3 p-3"
        selected={paymentType === 'SINGLE'}
        onSelect={() => {
          setPaymentType('SINGLE');
        }}
      >

          <FormattedMessage id="thirdPillarPayment.singlePayment" />

      </Radio>

      <Radio
        name="payment-type"
        id="payment-type-recurring"
        className="mt-3"
        selected={paymentType === 'RECURRING'}
        onSelect={() => {
          setPaymentType('RECURRING');
        }}
      >

          <FormattedMessage id="thirdPillarPayment.recurringPayment" />

      </Radio>

      {paymentType === 'SINGLE' && (

            Kui suures summas soovid sissemakset teha?

          <ThirdPillarPaymentsThisYear />

                <input
                  id="monthly-contribution"
                  type="number"
                  placeholder="200"
                  className="form-control"
                  min="0"
                  value={paymentAmount}
                  onChange={(event) => setPaymentAmount(event.target.value)}
                  onWheel={(event) => event.currentTarget.blur()}
                />

                  €

            Vali pank, kust soovid makset teha:

            <label
              className={`btn btn-light ${paymentBank === 'SWEDBANK' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('SWEDBANK');
              }}
            >
              <input type="radio" name="banks" id="swedbank" checked={paymentBank === 'SWEDBANK'} />{' '}
              Swedbank

            <label
              className={`btn btn-light ${paymentBank === 'SEB' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('SEB');
              }}
            >
              <input type="radio" name="banks" id="seb" checked={paymentBank === 'SEB'} /> SEB

            <label
              className={`btn btn-light ${paymentBank === 'LHV' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('LHV');
              }}
            >
              <input type="radio" name="banks" id="lhv" checked={paymentBank === 'LHV'} /> LHV

            <label
              className={`btn btn-light ${paymentBank === 'LUMINOR' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('LUMINOR');
              }}
            >
              <input type="radio" name="banks" id="luminor" checked={paymentBank === 'LUMINOR'} />{' '}
              Luminor

            <label
              className={`btn btn-light ${paymentBank === 'OTHER' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('OTHER');
              }}
            >
              <input type="radio" name="banks" id="other" checked={paymentBank === 'OTHER'} />{' '}
              Muu pank

          {paymentBank !== 'OTHER' && paymentType === 'SINGLE' && (

              <button
                type="button"
                className="btn btn-primary"
                disabled={
                  !paymentBank || paymentBank === 'OTHER' || !paymentAmount || paymentAmount <= 0
                }
                onClick={() => {
                  onPayment(paymentAmount, paymentBank);
                }}
              >
                <FormattedMessage id="thirdPillarPayment.makePayment" />
              </button>

          )}

      )}

      {(paymentBank === 'OTHER' || paymentType === 'RECURRING') && (

            <FormattedMessage
              id="thirdPillarPayment.description"
              values={{ b: (chunks) => {chunks} }}
            />

                <FormattedMessage id="thirdPillarPayment.accountName" />:{' '}

                AS Pensionikeskus

                <FormattedMessage id="thirdPillarPayment.accountNumber" />:{' '}

                EE362200221067235244 - Swedbank

                EE141010220263146225 - SEB

                EE547700771002908125 - LHV

                EE961700017004379157 - Luminor

                <FormattedMessage id="thirdPillarPayment.details" />:{' '}

                30101119828

                <FormattedMessage id="thirdPillarPayment.reference" />:{' '}

                {pensionAccountNumber}

            <FormattedMessage id="thirdPillarPayment.paymentQuestion" />

          <Link to={nextPath}>
            <button type="button" className="btn btn-primary">
              <FormattedMessage id="thirdPillarPayment.paymentButton" />
            </button>
          </Link>

      )}
    </>
  );
};

ThirdPillarPayment2.propTypes = {
  previousPath: Types.string,
  nextPath: Types.string,

  signedMandateId: Types.number,
  pensionAccountNumber: Types.string,
  isUserConverted: Types.bool,
};

ThirdPillarPayment2.defaultProps = {
  previousPath: '',
  nextPath: '',

  signedMandateId: null,
  pensionAccountNumber: null,
  isUserConverted: false,
};

const mapStateToProps = (state) => ({
  signedMandateId: state.thirdPillar.signedMandateId,
  pensionAccountNumber: state.login.user && state.login.user.pensionAccountNumber,
  isUserConverted:
    state.thirdPillar.exchangeableSourceFunds &&
    !state.thirdPillar.exchangeableSourceFunds.length &&
    state.login.userConversion &&
    state.login.userConversion.thirdPillar.selectionComplete,
});

export default connect(mapStateToProps)(ThirdPillarPayment2);
<commit_msg>Fix eslint<commit_after>import React, { useState } from 'react';
import Types from 'prop-types';
import { connect } from 'react-redux';
import { Link, Redirect } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import { Radio } from '../../../common';
import ThirdPillarPaymentsThisYear from '../../../account/statusBox/thirdPillarStatusBox/ThirdPillarYearToDateContribution';

export const ThirdPillarPayment2 = ({
  previousPath,
  nextPath,
  signedMandateId,
  pensionAccountNumber,
  isUserConverted,
}) => {
  const [paymentType, setPaymentType] = useState('SINGLE');
  const [paymentAmount, setPaymentAmount] = useState('');
  const [paymentBank, setPaymentBank] = useState('');

  const onPayment = (amount, bank) => {
    // eslint-disable-next-line no-console
    console.log(amount, bank);
  };

  return (
    <>
      {false && !signedMandateId && !isUserConverted && <Redirect to={previousPath} />}

      Millist tüüpi makset soovid teha?

      <Radio
        name="payment-type"
        id="payment-type-single"
        className="mt-3 p-3"
        selected={paymentType === 'SINGLE'}
        onSelect={() => {
          setPaymentType('SINGLE');
        }}
      >

          <FormattedMessage id="thirdPillarPayment.singlePayment" />

      </Radio>

      <Radio
        name="payment-type"
        id="payment-type-recurring"
        className="mt-3"
        selected={paymentType === 'RECURRING'}
        onSelect={() => {
          setPaymentType('RECURRING');
        }}
      >

          <FormattedMessage id="thirdPillarPayment.recurringPayment" />

      </Radio>

      {paymentType === 'SINGLE' && (

            Kui suures summas soovid sissemakset teha?

          <ThirdPillarPaymentsThisYear />

                <input
                  id="monthly-contribution"
                  type="number"
                  placeholder="200"
                  className="form-control"
                  min="0"
                  value={paymentAmount}
                  onChange={(event) => setPaymentAmount(event.target.value)}
                  onWheel={(event) => event.currentTarget.blur()}
                />

                  €

            Vali pank, kust soovid makset teha:

            <label
              className={`btn btn-light ${paymentBank === 'SWEDBANK' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('SWEDBANK');
              }}
            >
              <input type="radio" name="banks" id="swedbank" checked={paymentBank === 'SWEDBANK'} />{' '}
              Swedbank

            <label
              className={`btn btn-light ${paymentBank === 'SEB' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('SEB');
              }}
            >
              <input type="radio" name="banks" id="seb" checked={paymentBank === 'SEB'} /> SEB

            <label
              className={`btn btn-light ${paymentBank === 'LHV' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('LHV');
              }}
            >
              <input type="radio" name="banks" id="lhv" checked={paymentBank === 'LHV'} /> LHV

            <label
              className={`btn btn-light ${paymentBank === 'LUMINOR' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('LUMINOR');
              }}
            >
              <input type="radio" name="banks" id="luminor" checked={paymentBank === 'LUMINOR'} />{' '}
              Luminor

            <label
              className={`btn btn-light ${paymentBank === 'OTHER' ? 'active' : ''}`}
              onClick={() => {
                setPaymentBank('OTHER');
              }}
            >
              <input type="radio" name="banks" id="other" checked={paymentBank === 'OTHER'} />{' '}
              Muu pank

          {paymentBank !== 'OTHER' && paymentType === 'SINGLE' && (

              <button
                type="button"
                className="btn btn-primary"
                disabled={
                  !paymentBank || paymentBank === 'OTHER' || !paymentAmount || paymentAmount <= 0
                }
                onClick={() => {
                  onPayment(paymentAmount, paymentBank);
                }}
              >
                <FormattedMessage id="thirdPillarPayment.makePayment" />
              </button>

          )}

      )}

      {(paymentBank === 'OTHER' || paymentType === 'RECURRING') && (

            <FormattedMessage
              id="thirdPillarPayment.description"
              values={{ b: (chunks) => {chunks} }}
            />

                <FormattedMessage id="thirdPillarPayment.accountName" />:{' '}

                AS Pensionikeskus

                <FormattedMessage id="thirdPillarPayment.accountNumber" />:{' '}

                EE362200221067235244 - Swedbank

                EE141010220263146225 - SEB

                EE547700771002908125 - LHV

                EE961700017004379157 - Luminor

                <FormattedMessage id="thirdPillarPayment.details" />:{' '}

                30101119828

                <FormattedMessage id="thirdPillarPayment.reference" />:{' '}

                {pensionAccountNumber}

            <FormattedMessage id="thirdPillarPayment.paymentQuestion" />

          <Link to={nextPath}>
            <button type="button" className="btn btn-primary">
              <FormattedMessage id="thirdPillarPayment.paymentButton" />
            </button>
          </Link>

      )}
    </>
  );
};

ThirdPillarPayment2.propTypes = {
  previousPath: Types.string,
  nextPath: Types.string,

  signedMandateId: Types.number,
  pensionAccountNumber: Types.string,
  isUserConverted: Types.bool,
};

ThirdPillarPayment2.defaultProps = {
  previousPath: '',
  nextPath: '',

  signedMandateId: null,
  pensionAccountNumber: null,
  isUserConverted: false,
};

const mapStateToProps = (state) => ({
  signedMandateId: state.thirdPillar.signedMandateId,
  pensionAccountNumber: state.login.user && state.login.user.pensionAccountNumber,
  isUserConverted:
    state.thirdPillar.exchangeableSourceFunds &&
    !state.thirdPillar.exchangeableSourceFunds.length &&
    state.login.userConversion &&
    state.login.userConversion.thirdPillar.selectionComplete,
});

export default connect(mapStateToProps)(ThirdPillarPayment2);
<|endoftext|>


<commit_before>'use strict';

var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'];

/**
 * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
 * used to construct connections.
 *
 * @example
 * var ReplSet = require('mongodb-core').ReplSet
 *   , ReadPreference = require('mongodb-core').ReadPreference
 *   , assert = require('assert');
 *
 * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'});
 * // Wait for the connection event
 * server.on('connect', function(server) {
 *   var cursor = server.cursor('db.test'
 *     , {find: 'db.test', query: {}}
 *     , {readPreference: new ReadPreference('secondary')});
 *   cursor.next(function(err, doc) {
 *     server.destroy();
 *   });
 * });
 *
 * // Start connecting
 * server.connect();
 */

/**
 * Creates a new Pool instance
 * @class
 * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
 * @param {array} tags The tags object
 * @param {object} [options] Additional read preference options
 * @param {number} [options.maxStalenessSeconds] Max Secondary Read Stalleness in Seconds, Minimum value is 90 seconds.
 * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
 * @property {array} tags The tags object
 * @property {object} options Additional read preference options
 * @property {number} maxStalenessSeconds MaxStalenessSeconds value for the read preference
 * @return {ReadPreference}
 */
var ReadPreference = function(preference, tags, options) {
  this.preference = preference;
  this.tags = tags;
  this.options = options;

  // Add the maxStalenessSeconds value to the read Preference
  if (this.options && this.options.maxStalenessSeconds != null) {
    this.options = options;
    this.maxStalenessSeconds =
      this.options.maxStalenessSeconds >= 0 ? this.options.maxStalenessSeconds : null;
  } else if (tags && typeof tags === 'object') {
    (this.options = tags), (tags = null);
  }
};

/**
 * This needs slaveOk bit set
 * @method
 * @return {boolean}
 */
ReadPreference.prototype.slaveOk = function() {
  return needSlaveOk.indexOf(this.preference) !== -1;
};

/**
 * Are the two read preference equal
 * @method
 * @return {boolean}
 */
ReadPreference.prototype.equals = function(readPreference) {
  return readPreference.preference === this.preference;
};

/**
 * Return JSON representation
 * @method
 * @return {Object}
 */
ReadPreference.prototype.toJSON = function() {
  var readPreference = { mode: this.preference };
  if (Array.isArray(this.tags)) readPreference.tags = this.tags;
  if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds;
  return readPreference;
};

/**
 * Primary read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.primary = new ReadPreference('primary');
/**
 * Primary Preferred read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred');
/**
 * Secondary read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.secondary = new ReadPreference('secondary');
/**
 * Secondary Preferred read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred');
/**
 * Nearest read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.nearest = new ReadPreference('nearest');

module.exports = ReadPreference;
<commit_msg>refactor(read-preference): merge missing api from native version<commit_after>'use strict';

/**
 * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
 * used to construct connections.
 *
 * @example
 * const ReplSet = require('mongodb-core').ReplSet,
 *   ReadPreference = require('mongodb-core').ReadPreference,
 *   assert = require('assert');
 *
 * const server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'});
 * // Wait for the connection event
 * server.on('connect', function(server) {
 *   const cursor = server.cursor(
 *     'db.test',
 *     { find: 'db.test', query: {} },
 *     { readPreference: new ReadPreference('secondary') }
 *   );
 *
 *   cursor.next(function(err, doc) {
 *     server.destroy();
 *   });
 * });
 *
 * // Start connecting
 * server.connect();
 */

/**
 * Creates a new Pool instance
 * @class
 * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
 * @param {array} tags The tags object
 * @param {object} [options] Additional read preference options
 * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds.
 * @property {string} mode The read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
 * @property {array} tags The tags object
 * @property {object} options Additional read preference options
 * @property {number} maxStalenessSeconds MaxStalenessSeconds value for the read preference
 * @return {ReadPreference}
 */
const ReadPreference = function(mode, tags, options) {
  this.mode = mode;
  this.tags = tags;
  this.options = options;

  // Add the maxStalenessSeconds value to the read Preference
  if (this.options && this.options.maxStalenessSeconds != null) {
    this.options = options;
    this.maxStalenessSeconds =
      this.options.maxStalenessSeconds >= 0 ? this.options.maxStalenessSeconds : null;
  } else if (tags && typeof tags === 'object') {
    (this.options = tags), (tags = null);
  }
};

// Support the deprecated `preference` property introduced in the porcelain layer
Object.defineProperty(ReadPreference.prototype, 'preference', {
  enumerable: true,
  get: function() {
    return this.mode;
  }
});

/**
 * Validate if a mode is legal
 *
 * @method
 * @param {string} mode The string representing the read preference mode.
 * @return {boolean}
 */
ReadPreference.isValid = function(mode) {
  return (
    mode === ReadPreference.PRIMARY ||
    mode === ReadPreference.PRIMARY_PREFERRED ||
    mode === ReadPreference.SECONDARY ||
    mode === ReadPreference.SECONDARY_PREFERRED ||
    mode === ReadPreference.NEAREST ||
    mode === true ||
    mode === false ||
    mode == null
  );
};

/**
 * Validate if a mode is legal
 *
 * @method
 * @param {string} mode The string representing the read preference mode.
 * @return {boolean}
 */
ReadPreference.prototype.isValid = function(mode) {
  return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode);
};

const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'];

/**
 * This needs slaveOk bit set
 * @method
 * @return {boolean}
 */
ReadPreference.prototype.slaveOk = function() {
  return needSlaveOk.indexOf(this.mode) !== -1;
};

/**
 * Are the two read preference equal
 * @method
 * @return {boolean}
 */
ReadPreference.prototype.equals = function(readPreference) {
  return readPreference.mode === this.mode;
};

/**
 * Return JSON representation
 * @method
 * @return {Object}
 */
ReadPreference.prototype.toJSON = function() {
  const readPreference = { mode: this.mode };
  if (Array.isArray(this.tags)) readPreference.tags = this.tags;
  if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds;
  return readPreference;
};

/**
 * Primary read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.primary = new ReadPreference('primary');
/**
 * Primary Preferred read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred');
/**
 * Secondary read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.secondary = new ReadPreference('secondary');
/**
 * Secondary Preferred read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred');
/**
 * Nearest read preference
 * @method
 * @return {ReadPreference}
 */
ReadPreference.nearest = new ReadPreference('nearest');

/**
 * Read preference mode constants
 */
ReadPreference.PRIMARY = 'primary';
ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';
ReadPreference.SECONDARY = 'secondary';
ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';
ReadPreference.NEAREST = 'nearest';

module.exports = ReadPreference;
<|endoftext|>


<commit_before>/*
 * Author: CM
 */

(function(global) {

  /**
   * @callback PromiseThrottled
   * @param {*} any number of optional params
   * @return {Promise}
   */

  /**
   * @param {PromiseThrottled} fn
   * @param {Object|null} [options]
   * @param {Boolean} options.cancelLeading Whether to cancel the previous promise if it is still running.
   * @param {Boolean} options.cancelTrailing Whether to cancel the next promises if the current is not yet finished.
   * @param {Boolean} options.queue Whether to queue the next promises.
   * @param {String} options.key A custom key to store the resulted PromiseThrottled.
   * @returns {PromiseThrottled}
   */
  function promiseThrottler(fn, options) {
    options = _.defaults(
      options || {}, {
        cancelLeading: false,
        cancelTrailing: false,
        queue: false
      }
    );
    if ((+options.cancelLeading) + (+options.cancelTrailing) + (+options.queue) > 1) {
      throw new Error('PromiseThrottler options "cancelLeading", "cancelTrailing", "queue" exclude each other.');
    }
    if (options.key) {
      return namespaceThrottler(options.key, fn, options);
    } else {
      return nonameThrottler(fn, options);
    }
  }

  /**
   * @see promiseThrottler
   */
  function nonameThrottler(fn, options) {
    var promise;

    return function() {
      if (options.cancelLeading && promise && promise.isPending() && promise.isCancellable()) {
        promise.cancel();
        promise = null;
      }
      if (options.cancelTrailing && promise && promise.isPending()) {
        return Promise.reject(new Promise.CancellationError);
      }
      if (options.queue && promise && promise.isPending()) {
        var args = arguments;
        promise = promise.then(function() {
          return fn.apply(null, args);
        }).catch(function() {
          return fn.apply(null, args);
        });
      }
      if (!promise || !promise.isPending()) {
        promise = fn.apply(null, arguments);
      }
      return promise;
    };
  }

  var storage = {};

  /**
   * @see promiseThrottler
   */
  function namespaceThrottler(namespace, fn, options) {
    if (!storage[namespace]) {
      storage[namespace] = nonameThrottler(fn, options);
    }
    return storage[namespace];
  }

  global.promiseThrottler = promiseThrottler;

})(window);
<commit_msg>Pass context of caller to promiseThrottler.<commit_after>/*
 * Author: CM
 */

(function(global) {

  /**
   * @callback PromiseThrottled
   * @param {*} any number of optional params
   * @return {Promise}
   */

  /**
   * @param {PromiseThrottled} fn
   * @param {Object|null} [options]
   * @param {Boolean} options.cancelLeading Whether to cancel the previous promise if it is still running.
   * @param {Boolean} options.cancelTrailing Whether to cancel the next promises if the current is not yet finished.
   * @param {Boolean} options.queue Whether to queue the next promises.
   * @param {String} options.key A custom key to store the resulted PromiseThrottled.
   * @returns {PromiseThrottled}
   */
  function promiseThrottler(fn, options) {
    options = _.defaults(
      options || {}, {
        cancelLeading: false,
        cancelTrailing: false,
        queue: false
      }
    );
    if ((+options.cancelLeading) + (+options.cancelTrailing) + (+options.queue) > 1) {
      throw new Error('PromiseThrottler options "cancelLeading", "cancelTrailing", "queue" exclude each other.');
    }
    if (options.key) {
      return namespaceThrottler(options.key, fn, options);
    } else {
      return nonameThrottler(fn, options);
    }
  }

  /**
   * @see promiseThrottler
   */
  function nonameThrottler(fn, options) {
    var promise;

    return function() {
      if (options.cancelLeading && promise && promise.isPending() && promise.isCancellable()) {
        promise.cancel();
        promise = null;
      }
      if (options.cancelTrailing && promise && promise.isPending()) {
        return Promise.reject(new Promise.CancellationError);
      }
      if (options.queue && promise && promise.isPending()) {
        var args = arguments;
        var self = this;
        promise = promise.then(function() {
          return fn.apply(self, args);
        }).catch(function() {
          return fn.apply(self, args);
        });
      }
      if (!promise || !promise.isPending()) {
        promise = fn.apply(this, arguments);
      }
      return promise;
    };
  }

  var storage = {};

  /**
   * @see promiseThrottler
   */
  function namespaceThrottler(namespace, fn, options) {
    if (!storage[namespace]) {
      storage[namespace] = nonameThrottler(fn, options);
    }
    return storage[namespace];
  }

  global.promiseThrottler = promiseThrottler;

})(window);
<|endoftext|>


<commit_before>//Run on: *//scratch.mit.edu/users/*/

url = window.location.href;
yourUsername = Scratch.INIT_DATA.LOGGED_IN_USER.model.username;
usernameFromURL = url.substring(url.lastIndexOf("users/")+6,url.lastIndexOf("/"));

if (typeof(localStorage['following_myself']) === "undefined") { localStorage['following_myself'] = false; }
divClass = localStorage['following_myself'] == "false" ? "follow-button button notfollowing blue" : "follow-button button following grey";
dataControl = localStorage['following_myself'] == "true" ? "unfollow" : "follow";

Scratch.changeStatusForMyself = function() {
  if (localStorage['following_myself'] == "true") {
    localStorage['following_myself'] = false;
    return;
  }
  localStorage['following_myself'] = true;
}

$(".header-text").after('

FollowUnfollow

');
<commit_msg>Update followMyself.js<commit_after>//Run on: *//scratch.mit.edu/users/*/
// ==UserScript==
// @name         Follow myself for Scratch
// @version      1.0
// @description  Do You want to follow myself?
// @author       SzAmmi
// @match        *//scratch.mit.edu/users/*/
// @grant        none
// ==/UserScript==

url = window.location.href;
yourUsername = Scratch.INIT_DATA.LOGGED_IN_USER.model.username;
usernameFromURL = url.substring(url.lastIndexOf("users/")+6,url.lastIndexOf("/"));

if (typeof(localStorage['following_myself']) === "undefined") { localStorage['following_myself'] = false; }
divClass = localStorage['following_myself'] == "false" ? "follow-button button notfollowing blue" : "follow-button button following grey";
dataControl = localStorage['following_myself'] == "true" ? "unfollow" : "follow";

Scratch.changeStatusForMyself = function() {
  if (localStorage['following_myself'] == "true") {
    localStorage['following_myself'] = false;
    return;
  }
  localStorage['following_myself'] = true;
}

$(".header-text").after('

FollowUnfollow

');
<|endoftext|>


<commit_before>var app = angular.module('wptview', ['angularSpinner']);

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.bind('change', onChangeHandler);
    }
  };
});

app.filter('arrFilter', function() {
  return function(collection, currentRun) {
    var output = [];
    collection.forEach((item) => {
        if (currentRun != item.name) {
            output.push(item);
        }
    });
    return output;
  }
});

function WorkerService(workerScript) {
  this.msg_id = 0;
  this.resolvers = {};

  this.worker = new Worker(workerScript);
  this.worker.onmessage = function(event) {
    var msg_id = event.data[0];
    var data = event.data[1];
    if (!this.resolvers.hasOwnProperty(msg_id)) {
      throw Error("Unexpected message " + msg_id);
    }
    resolve = this.resolvers[msg_id];
    delete this.resolvers[msg_id];
    console.log(data);
    resolve(data);
  }.bind(this);
}

WorkerService.prototype.run = function(command, data) {
  var data = data || [];
  var msg = [this.msg_id++, command, data];
  this.worker.postMessage(msg);
  return new Promise((resolve) => {
    console.log("Adding resolver " + msg[0]);
    this.resolvers[msg[0]] = resolve;
  });
}

app.factory('ResultsModel',function() {
  var ResultsModel = function() {
    this.service = new WorkerService("LovefieldService.js");
    this.logReader = new WorkerService("logcruncher.js");
  }

  ResultsModel.prototype.addResultsFromLogs = function (file, runName) {
    var lovefield = this.service;
    var resultData = null;
    var testData = null;
    var testRunData = null;
    var duplicates = null;
    return this.logReader.run("read", [file])
      .then((data) => {resultData = data})
      // Filling the test_runs table
      .then(() => {return lovefield.run("selectParticularRun", [runName])})
      .then((testRuns) => {return lovefield.run("insertTestRuns", [runName, testRuns])})
      // Selecting current tests table, adding extra entries only
      .then((testRuns) => {testRunData = testRuns;
                           return lovefield.run("selectAllParentTests")})
      .then((parentTests) => {return lovefield.run("insertTests", [resultData, parentTests])})
      .then((insertData) => {
        duplicates = insertData[1];
        return lovefield.run("selectAllParentTests")
      })
      // populating results table with parent test results
      .then((tests) => {testData = tests;
                        return lovefield.run("insertTestResults",
                                             [resultData, testData, testRunData])})
      // add subtests to tests table
      .then(() => {return lovefield.run("selectAllSubtests")})
      .then((subtests) => {return lovefield.run("insertSubtests",
                                                [resultData, testData, subtests])})
      .then((subtestData) => {duplicates = duplicates.concat(subtestData[1]);
                              return lovefield.run("selectAllSubtests")})
      // adding subtest results
      .then((subtests) => {return lovefield.run("insertSubtestResults",
                                                [resultData, subtests, testRunData])})
      .then(() => duplicates);
  }

  /*
    Load the results of a specified number of tests, ordered by test id, either taking all
    results above a lower limit test id, all results below an upper limit id, or all results
    starting from the first test.
    Results may be filtered by various filters.
    @param {Object[]} filter - Array of filter definitions for the allowed test results.
    @param {} pathFilter - Array if filter definitions for the allowed test names.
    @param {(number|null)} minTestId - Exclusive lower bound on the test ID to load, or null if
                                     there is no lower limit.
    @param {(number|null)} maxTestId - Exclusive upper bound on the test ID to load, or null if
                                     there is no upper limit.
    @param {(number)} limit - Number of tests to load.
   */
  ResultsModel.prototype.getResults = function(filter, minTestId, maxTestId, limit) {
    return this.service.run("selectFilteredResults",
                            [filter, minTestId, maxTestId, limit]);
  }

  ResultsModel.prototype.removeResults = function(run_id) {
    return this.service.run("deleteEntries", [run_id]);
  }

  ResultsModel.prototype.getRuns = function() {
    return this.service.run("getRuns");
  }

  return ResultsModel;
});

app.controller('wptviewController', function($scope, ResultsModel) {
  $scope.results = null;
  $scope.warnings = [];
  $scope.showImport = false;
  $scope.busy = true;
  $scope.runs = null;
  $scope.upload = {};
  $scope.resultsView = {
      limit: 50,
      firstPage: true,
      lastPage: false,
      minTestId: null,
      maxTestId: null,
      firstTestId: null
  }
  $scope.filter = {
    "statusFilter": [],
    "pathFilter": [],
    "testTypeFilter": {
      type:"both"
    }
  }
  var runIndex = {};
  var resultsModel = new ResultsModel();

  function updateRuns() {
    var runs;
    return resultsModel.getRuns()
      .then((runsData) => runs = runsData)
      .then(() => {
        $scope.runs = runs;
        $scope.runs.forEach((run, i) => {
          runIndex[run.run_id] = i;
        });
      });
  }

  updateRuns().then(() => {
    $scope.busy = false;
    $scope.$apply();
  });

  function updateWarnings(duplicates) {
    $scope.$apply(function() {
      $scope.warnings = duplicates;
    })
  }

  $scope.range = function(min, max, step) {
      step = step || 1;
      var input = [];
      for (var i = min; i < max; i += step) {
          input.push(i);
      }
      return input;
  };

  $scope.uploadFile = function () {
    $scope.busy = true;
    var evt = $scope.fileEvent;
    var file = evt.target.files[0];
    resultsModel.addResultsFromLogs(file, $scope.upload.runName)
    .then((duplicates) => updateWarnings(duplicates))
    .then(updateRuns)
    .then(() => {
      $scope.isFileEmpty = true;
      $scope.upload.runName = "";
      $scope.busy = false;
      $scope.$apply();
    });
  }

  $scope.clearTable = function(run_id) {
    $scope.busy = true;
    resultsModel.removeResults(run_id)
      .then(() => {
        console.log("Table successfully cleared!");
        $scope.results = null;
        $scope.warnings = []})
    .then(updateRuns)
    .then(() => {
      $scope.busy = false;
      $scope.$apply();
    });
  }

  $scope.fillTable = function(page) {
    var minTestId = null;
    var maxTestId = null;

    $scope.busy = true;

    if (page === "next") {
      var minTestId = $scope.resultsView.maxTestId;
    } else if (page === "prev") {
      var maxTestId = $scope.resultsView.minTestId;
    }

    resultsModel.getResults($scope.filter, minTestId, maxTestId, $scope.resultsView.limit)
      .then((results) => {
        if (results.length) {
          if (!page) {
            $scope.resultsView.firstTestId = results[0].test_id;
          }
          $scope.resultsView.lastPage = results.length < $scope.resultsView.limit;
          $scope.resultsView.firstPage = results[0].test_id === $scope.resultsView.firstTestId;
          $scope.resultsView.minTestId = results[0].test_id;
          $scope.resultsView.maxTestId = results[results.length - 1].test_id;
        } else {
          // We want to disable NEXT when we are on the last page
          $scope.resultsView.lastPage = true;
        }
        var finalResults = organizeResults(results);
        $scope.results = finalResults;
        $scope.busy = false;
        $scope.$apply();
      });
  }

  $scope.newFile = function(evt) {
    $scope.isFileEmpty = false;
    $scope.fileEvent = evt;
    $scope.$apply();
  }

  $scope.addConstraint = function() {
    $scope.filter.statusFilter.push({
      run : $scope.runs[0].name,
      equality : "is",
      status : ["PASS"]
    });
  }

  $scope.deleteConstraint = function() {
    $scope.filter.statusFilter.pop();
  }

  $scope.addOrConstraint = function(index) {
    $scope.filter.statusFilter[index].status.push("");
  }

  $scope.deleteOrConstraint = function(index) {
    $scope.filter.statusFilter[index].status.pop();
  }

  $scope.addPath = function() {
    $scope.filter.pathFilter.push({
      choice: "include:start",
      path: ""
    });
  }

  $scope.deletePath = function() {
    $scope.filter.pathFilter.pop();
  }

  $scope.warning_message = function() {
    return $scope.warnings.length + " warnings found.";
  }

  function organizeResults(results) {
    var testMap = {};
    results.forEach(function(result) {
      if (result.title === undefined) {
        result.title = "";
      }
      if (!testMap.hasOwnProperty(result.test)) {
        testMap[result.test] = {};
      }
      if (!testMap[result.test].hasOwnProperty(result.title)) {
        testMap[result.test][result.title] = [];
        for (var i = 0; i < $scope.runs.length; i++) {
          testMap[result.test][result.title].push({
            'run_id': $scope.runs[i].run_id,
            'run_name': $scope.runs[i].run_name,
            'status': "",
            'expected': "",
            'message': ""
          });
        }
      }
      testMap[result.test][result.title][runIndex[result.run_id]] = {
        'run_id': result.run_id,
        'run_name': result.run_name,
        'status': result.status,
        'expected': result.expected,
        'message': result.message
      };
    });
    var finalResults = [];
    for (var test in testMap) {
      for (var subtest in testMap[test]) {
        finalResults.push({
          'test': test,
          'subtest': subtest,
          'runs': testMap[test][subtest]
        });
      }
    }
    return finalResults;
  }
});
<commit_msg>Adding a default PASS value for the OR option as well<commit_after>var app = angular.module('wptview', ['angularSpinner']);

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.bind('change', onChangeHandler);
    }
  };
});

app.filter('arrFilter', function() {
  return function(collection, currentRun) {
    var output = [];
    collection.forEach((item) => {
        if (currentRun != item.name) {
            output.push(item);
        }
    });
    return output;
  }
});

function WorkerService(workerScript) {
  this.msg_id = 0;
  this.resolvers = {};

  this.worker = new Worker(workerScript);
  this.worker.onmessage = function(event) {
    var msg_id = event.data[0];
    var data = event.data[1];
    if (!this.resolvers.hasOwnProperty(msg_id)) {
      throw Error("Unexpected message " + msg_id);
    }
    resolve = this.resolvers[msg_id];
    delete this.resolvers[msg_id];
    console.log(data);
    resolve(data);
  }.bind(this);
}

WorkerService.prototype.run = function(command, data) {
  var data = data || [];
  var msg = [this.msg_id++, command, data];
  this.worker.postMessage(msg);
  return new Promise((resolve) => {
    console.log("Adding resolver " + msg[0]);
    this.resolvers[msg[0]] = resolve;
  });
}

app.factory('ResultsModel',function() {
  var ResultsModel = function() {
    this.service = new WorkerService("LovefieldService.js");
    this.logReader = new WorkerService("logcruncher.js");
  }

  ResultsModel.prototype.addResultsFromLogs = function (file, runName) {
    var lovefield = this.service;
    var resultData = null;
    var testData = null;
    var testRunData = null;
    var duplicates = null;
    return this.logReader.run("read", [file])
      .then((data) => {resultData = data})
      // Filling the test_runs table
      .then(() => {return lovefield.run("selectParticularRun", [runName])})
      .then((testRuns) => {return lovefield.run("insertTestRuns", [runName, testRuns])})
      // Selecting current tests table, adding extra entries only
      .then((testRuns) => {testRunData = testRuns;
                           return lovefield.run("selectAllParentTests")})
      .then((parentTests) => {return lovefield.run("insertTests", [resultData, parentTests])})
      .then((insertData) => {
        duplicates = insertData[1];
        return lovefield.run("selectAllParentTests")
      })
      // populating results table with parent test results
      .then((tests) => {testData = tests;
                        return lovefield.run("insertTestResults",
                                             [resultData, testData, testRunData])})
      // add subtests to tests table
      .then(() => {return lovefield.run("selectAllSubtests")})
      .then((subtests) => {return lovefield.run("insertSubtests",
                                                [resultData, testData, subtests])})
      .then((subtestData) => {duplicates = duplicates.concat(subtestData[1]);
                              return lovefield.run("selectAllSubtests")})
      // adding subtest results
      .then((subtests) => {return lovefield.run("insertSubtestResults",
                                                [resultData, subtests, testRunData])})
      .then(() => duplicates);
  }

  /*
    Load the results of a specified number of tests, ordered by test id, either taking all
    results above a lower limit test id, all results below an upper limit id, or all results
    starting from the first test.
    Results may be filtered by various filters.
    @param {Object[]} filter - Array of filter definitions for the allowed test results.
    @param {} pathFilter - Array if filter definitions for the allowed test names.
    @param {(number|null)} minTestId - Exclusive lower bound on the test ID to load, or null if
                                     there is no lower limit.
    @param {(number|null)} maxTestId - Exclusive upper bound on the test ID to load, or null if
                                     there is no upper limit.
    @param {(number)} limit - Number of tests to load.
   */
  ResultsModel.prototype.getResults = function(filter, minTestId, maxTestId, limit) {
    return this.service.run("selectFilteredResults",
                            [filter, minTestId, maxTestId, limit]);
  }

  ResultsModel.prototype.removeResults = function(run_id) {
    return this.service.run("deleteEntries", [run_id]);
  }

  ResultsModel.prototype.getRuns = function() {
    return this.service.run("getRuns");
  }

  return ResultsModel;
});

app.controller('wptviewController', function($scope, ResultsModel) {
  $scope.results = null;
  $scope.warnings = [];
  $scope.showImport = false;
  $scope.busy = true;
  $scope.runs = null;
  $scope.upload = {};
  $scope.resultsView = {
      limit: 50,
      firstPage: true,
      lastPage: false,
      minTestId: null,
      maxTestId: null,
      firstTestId: null
  }
  $scope.filter = {
    "statusFilter": [],
    "pathFilter": [],
    "testTypeFilter": {
      type:"both"
    }
  }
  var runIndex = {};
  var resultsModel = new ResultsModel();

  function updateRuns() {
    var runs;
    return resultsModel.getRuns()
      .then((runsData) => runs = runsData)
      .then(() => {
        $scope.runs = runs;
        $scope.runs.forEach((run, i) => {
          runIndex[run.run_id] = i;
        });
      });
  }

  updateRuns().then(() => {
    $scope.busy = false;
    $scope.$apply();
  });

  function updateWarnings(duplicates) {
    $scope.$apply(function() {
      $scope.warnings = duplicates;
    })
  }

  $scope.range = function(min, max, step) {
      step = step || 1;
      var input = [];
      for (var i = min; i < max; i += step) {
          input.push(i);
      }
      return input;
  };

  $scope.uploadFile = function () {
    $scope.busy = true;
    var evt = $scope.fileEvent;
    var file = evt.target.files[0];
    resultsModel.addResultsFromLogs(file, $scope.upload.runName)
    .then((duplicates) => updateWarnings(duplicates))
    .then(updateRuns)
    .then(() => {
      $scope.isFileEmpty = true;
      $scope.upload.runName = "";
      $scope.busy = false;
      $scope.$apply();
    });
  }

  $scope.clearTable = function(run_id) {
    $scope.busy = true;
    resultsModel.removeResults(run_id)
      .then(() => {
        console.log("Table successfully cleared!");
        $scope.results = null;
        $scope.warnings = []})
    .then(updateRuns)
    .then(() => {
      $scope.busy = false;
      $scope.$apply();
    });
  }

  $scope.fillTable = function(page) {
    var minTestId = null;
    var maxTestId = null;

    $scope.busy = true;

    if (page === "next") {
      var minTestId = $scope.resultsView.maxTestId;
    } else if (page === "prev") {
      var maxTestId = $scope.resultsView.minTestId;
    }

    resultsModel.getResults($scope.filter, minTestId, maxTestId, $scope.resultsView.limit)
      .then((results) => {
        if (results.length) {
          if (!page) {
            $scope.resultsView.firstTestId = results[0].test_id;
          }
          $scope.resultsView.lastPage = results.length < $scope.resultsView.limit;
          $scope.resultsView.firstPage = results[0].test_id === $scope.resultsView.firstTestId;
          $scope.resultsView.minTestId = results[0].test_id;
          $scope.resultsView.maxTestId = results[results.length - 1].test_id;
        } else {
          // We want to disable NEXT when we are on the last page
          $scope.resultsView.lastPage = true;
        }
        var finalResults = organizeResults(results);
        $scope.results = finalResults;
        $scope.busy = false;
        $scope.$apply();
      });
  }

  $scope.newFile = function(evt) {
    $scope.isFileEmpty = false;
    $scope.fileEvent = evt;
    $scope.$apply();
  }

  $scope.addConstraint = function() {
    $scope.filter.statusFilter.push({
      run : $scope.runs[0].name,
      equality : "is",
      status : ["PASS"]
    });
  }

  $scope.deleteConstraint = function() {
    $scope.filter.statusFilter.pop();
  }

  $scope.addOrConstraint = function(index) {
    $scope.filter.statusFilter[index].status.push("PASS");
  }

  $scope.deleteOrConstraint = function(index) {
    $scope.filter.statusFilter[index].status.pop();
  }

  $scope.addPath = function() {
    $scope.filter.pathFilter.push({
      choice: "include:start",
      path: ""
    });
  }

  $scope.deletePath = function() {
    $scope.filter.pathFilter.pop();
  }

  $scope.warning_message = function() {
    return $scope.warnings.length + " warnings found.";
  }

  function organizeResults(results) {
    var testMap = {};
    results.forEach(function(result) {
      if (result.title === undefined) {
        result.title = "";
      }
      if (!testMap.hasOwnProperty(result.test)) {
        testMap[result.test] = {};
      }
      if (!testMap[result.test].hasOwnProperty(result.title)) {
        testMap[result.test][result.title] = [];
        for (var i = 0; i < $scope.runs.length; i++) {
          testMap[result.test][result.title].push({
            'run_id': $scope.runs[i].run_id,
            'run_name': $scope.runs[i].run_name,
            'status': "",
            'expected': "",
            'message': ""
          });
        }
      }
      testMap[result.test][result.title][runIndex[result.run_id]] = {
        'run_id': result.run_id,
        'run_name': result.run_name,
        'status': result.status,
        'expected': result.expected,
        'message': result.message
      };
    });
    var finalResults = [];
    for (var test in testMap) {
      for (var subtest in testMap[test]) {
        finalResults.push({
          'test': test,
          'subtest': subtest,
          'runs': testMap[test][subtest]
        });
      }
    }
    return finalResults;
  }
});
<|endoftext|>


<commit_before>/*******************************************************************************
 * (C) Copyright 2016 Jerome Comte and Dorian Cransac
 *
 * This file is part of STEP
 *
 * STEP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * STEP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with STEP.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
angular.module('repositoryControllers', [ 'step','dataTable' ])

//This controller is used to force reload of the following Controllers after location change. This is a trick but it works
.controller('RepositoryLoadCtrl', function($scope, $location ,$timeout) {
	$scope.reload = true;
	$scope.$on('$locationChangeSuccess',function(event) {
		$scope.reload = false;
		$timeout(function(){$scope.reload=true});
	});
})

.controller('RepositoryCtrl', [
	'$rootScope',
	'$scope',
	'$http',
	'$location',
	'stateStorage',
	'AuthService',
	function($rootScope, $scope, $http, $location, $stateStorage, AuthService) {

		$scope.session = AuthService.getContext().session;

		$scope.setRemoteProject = function(projectId) {
			if(!$scope.session.attributes['step.controller.multitenancy.TenantContext']){
				$scope.session.attributes['step.controller.multitenancy.TenantContext'] = {};
			}
			if(!$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues){
				$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues = {};
			}
			$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues.project = projectId;
		};

		$scope.reload = true;
		$scope.prepareProjectSession = function(callback) {

			var repositoryProjectName = $location.search().repositoryId;

			if(repositoryProjectName ==! 'local'){
				$http.post('/rest/tenants/project/search', { 'name' : repositoryProjectName}, {headers : {'ignoreContext': 'true'}}).then(function(response){
					if(response.data.id){
						$scope.setRemoteProject(response.data.id);
						$http.post('rest/tenants/context', {contextValues:$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues}).then(function(){
							callback();
						});
					}else{
						callback();
					}
				});
			}else{
				callback();
			}
		};

		$scope.runController = function(){

			$stateStorage.push($scope, 'repository', {});

			if($location.search().user) {
				$rootScope.context.userID = $location.search().user;
			}

			$scope.isolateExecution = $location.search().isolate?$location.search().isolate:false;

			if($location.search().repositoryId) {
				$scope.repoRef = {'repositoryID':$location.search().repositoryId,'repositoryParameters':$location.search()};
				$scope.loading = true;
				$http.post("rest/controller/repository/artefact/info",$scope.repoRef).then(
						function(response) {
							$scope.loading = false
							$scope.artefactInfo = response.data;
						},
						function errorCallback(response) {
							$scope.loading = false
							$scope.error = response.data;
						});

				$scope.functions = {};
			}
		};

		$scope.prepareProjectSession($scope.runController);
	}
	])

	.controller('TestSetOverviewCtrl', [
		'$scope',
		'$http',
		'$location',
		'stateStorage',
		function($scope, $http, $location, $stateStorage) {
			$scope.testCaseTable = {};
			$scope.testCaseTable.columns = [ { "title" : "ID", "visible" : false },
				{"title" : "Name"},
				{ "title" : "Status", "width":"80px", "searchmode":"select","render": function ( data, type, row ) {
					return '
'  +data+ '
';
				}} ];
			$scope.testCaseTable.defaultSelection = "all";

			$scope.repoRef = {'repositoryID':$location.search().repositoryId,'repositoryParameters':$location.search()};
			$http.post("rest/controller/repository/report",$scope.repoRef).then(
					function(response) {
						var data = response.data;
						var dataSet = [];
						var runs = data.runs;
						for (i = 0; i < runs.length; i++) {
							dataSet[i] = [ runs[i].testplanName, runs[i].testplanName, runs[i].status];
						}
						$scope.testCaseTable.data = dataSet;
					});
			$scope.functions.getIncludedTestcases = function() {
				var selectionMode = $scope.testCaseTable.getSelectionMode();
				if(selectionMode=='all') {
					return null;
				} else if (selectionMode=='custom' || selectionMode=='none') {
					var includedTestCases = {"by":"name"};
					var result = [];
					if($scope.testCaseTable.getRows!=null) {
						_.each($scope.testCaseTable.getRows(true),function(value){result.push(value[0])});
					}
					includedTestCases.list = result;
					return includedTestCases;
				} else {
					throw "Unsupported selection mode: "+selectionMode;
				}
			}
		}
		])<commit_msg>Bugfixing operator mistake in repository.js<commit_after>/*******************************************************************************
 * (C) Copyright 2016 Jerome Comte and Dorian Cransac
 *
 * This file is part of STEP
 *
 * STEP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * STEP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with STEP.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
angular.module('repositoryControllers', [ 'step','dataTable' ])

//This controller is used to force reload of the following Controllers after location change. This is a trick but it works
.controller('RepositoryLoadCtrl', function($scope, $location ,$timeout) {
	$scope.reload = true;
	$scope.$on('$locationChangeSuccess',function(event) {
		$scope.reload = false;
		$timeout(function(){$scope.reload=true});
	});
})

.controller('RepositoryCtrl', [
	'$rootScope',
	'$scope',
	'$http',
	'$location',
	'stateStorage',
	'AuthService',
	function($rootScope, $scope, $http, $location, $stateStorage, AuthService) {

		$scope.session = AuthService.getContext().session;

		$scope.setRemoteProject = function(projectId) {
			if(!$scope.session.attributes['step.controller.multitenancy.TenantContext']){
				$scope.session.attributes['step.controller.multitenancy.TenantContext'] = {};
			}
			if(!$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues){
				$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues = {};
			}
			$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues.project = projectId;
		};

		$scope.reload = true;
		$scope.prepareProjectSession = function(callback) {

			var repositoryProjectName = $location.search().repositoryId;

			if(repositoryProjectName !== 'local'){
				$http.post('/rest/tenants/project/search', { 'name' : repositoryProjectName}, {headers : {'ignoreContext': 'true'}}).then(function(response){
					if(response.data.id){
						$scope.setRemoteProject(response.data.id);
						$http.post('rest/tenants/context', {contextValues:$scope.session.attributes['step.controller.multitenancy.TenantContext'].contextValues}).then(function(){
							callback();
						});
					}else{
						callback();
					}
				});
			}else{
				callback();
			}
		};

		$scope.runController = function(){

			$stateStorage.push($scope, 'repository', {});

			if($location.search().user) {
				$rootScope.context.userID = $location.search().user;
			}

			$scope.isolateExecution = $location.search().isolate?$location.search().isolate:false;

			if($location.search().repositoryId) {
				$scope.repoRef = {'repositoryID':$location.search().repositoryId,'repositoryParameters':$location.search()};
				$scope.loading = true;
				$http.post("rest/controller/repository/artefact/info",$scope.repoRef).then(
						function(response) {
							$scope.loading = false
							$scope.artefactInfo = response.data;
						},
						function errorCallback(response) {
							$scope.loading = false
							$scope.error = response.data;
						});

				$scope.functions = {};
			}
		};

		$scope.prepareProjectSession($scope.runController);
	}
	])

	.controller('TestSetOverviewCtrl', [
		'$scope',
		'$http',
		'$location',
		'stateStorage',
		function($scope, $http, $location, $stateStorage) {
			$scope.testCaseTable = {};
			$scope.testCaseTable.columns = [ { "title" : "ID", "visible" : false },
				{"title" : "Name"},
				{ "title" : "Status", "width":"80px", "searchmode":"select","render": function ( data, type, row ) {
					return '
'  +data+ '
';
				}} ];
			$scope.testCaseTable.defaultSelection = "all";

			$scope.repoRef = {'repositoryID':$location.search().repositoryId,'repositoryParameters':$location.search()};
			$http.post("rest/controller/repository/report",$scope.repoRef).then(
					function(response) {
						var data = response.data;
						var dataSet = [];
						var runs = data.runs;
						for (i = 0; i < runs.length; i++) {
							dataSet[i] = [ runs[i].testplanName, runs[i].testplanName, runs[i].status];
						}
						$scope.testCaseTable.data = dataSet;
					});
			$scope.functions.getIncludedTestcases = function() {
				var selectionMode = $scope.testCaseTable.getSelectionMode();
				if(selectionMode=='all') {
					return null;
				} else if (selectionMode=='custom' || selectionMode=='none') {
					var includedTestCases = {"by":"name"};
					var result = [];
					if($scope.testCaseTable.getRows!=null) {
						_.each($scope.testCaseTable.getRows(true),function(value){result.push(value[0])});
					}
					includedTestCases.list = result;
					return includedTestCases;
				} else {
					throw "Unsupported selection mode: "+selectionMode;
				}
			}
		}
		])<|endoftext|>