<commit_before>//
// HLF Hover Intent Visual Tests
// =============================
// [Page](../../../tests/hover-intent.visual.html) | [Source](../../src/js/hover-intent.html)
//
(function() {
  'use strict';
  if (window.guard && !guard.isNavigatorSupported) { return; }

  require.config({
    baseUrl: '../',
    paths: {
      hlf: 'src/js',
      test: 'tests/js',
    }
  });

  define(['hlf/core', 'test/base', 'hlf/hover-intent'], function(hlf, base, hoverIntent) {

    // ---

    let tests = [];
    const { createVisualTest, runVisualTests } = base;
    const { eventName } = hlf.hoverIntent;
    tests.push(createVisualTest({
      label: 'by default',
      template(vars) {
        return (
`

enter count:

0

leave count:

0

raw-enter count:

0

raw-leave count:

0

`
        );
      },
      footerHtml: (
`
  <input type="checkbox" id="default-enabled" checked />
  enabled
`
      ),
      beforeTest(testElement) {
        const inputElement = document.getElementById('default-enabled');
        inputElement.addEventListener('change', (_) => {
          let element = testElement.querySelector('.box');
          if (inputElement.checked) {
            hoverIntent(element);
          } else {
            hoverIntent(element, 'remove');
          }
        });
      },
      test(testElement) {
        function setUpCounters(element, {
          enterCounter, leaveCounter, enterEvent, leaveEvent,
        }) {
          enterCounter = element.querySelector(enterCounter);
          leaveCounter = element.querySelector(leaveCounter);
          element.addEventListener(enterEvent, (event) => {
            enterCounter.textContent = parseInt(enterCounter.textContent) + 1;
            leaveCounter.textContent = 0;
          });
          element.addEventListener(leaveEvent, (event) => {
            enterCounter.textContent = 0;
            leaveCounter.textContent = parseInt(leaveCounter.textContent) + 1;
          });
        }
        let element = testElement.querySelector('.box');
        hoverIntent(element);
        setUpCounters(element, {
          enterCounter: '.enter-counter',
          leaveCounter: '.leave-counter',
          enterEvent: eventName('enter'),
          leaveEvent: eventName('leave'),
        });
        setUpCounters(element, {
          enterCounter: '.raw-enter-counter',
          leaveCounter: '.raw-leave-counter',
          enterEvent: 'mouseover',
          leaveEvent: 'mouseleave',
        });
      },
      anchorName: 'default',
      className: 'default-call',
      vars: {},
    }));
    runVisualTests(tests);
  });

}());
<commit_msg>Test hover-intent support for event delegation.<commit_after>//
// HLF Hover Intent Visual Tests
// =============================
// [Page](../../../tests/hover-intent.visual.html) | [Source](../../src/js/hover-intent.html)
//
(function() {
  'use strict';
  if (window.guard && !guard.isNavigatorSupported) { return; }

  require.config({
    baseUrl: '../',
    paths: {
      hlf: 'src/js',
      test: 'tests/js',
    }
  });

  define(['hlf/core', 'test/base', 'hlf/hover-intent'], function(hlf, base, hoverIntent) {

    // ---

    let tests = [];
    const { createVisualTest, runVisualTests } = base;
    const { eventName } = hlf.hoverIntent;
    tests.push(createVisualTest({
      label: 'by default',
      template(vars) {
        return (
`

enter count:

0

leave count:

0

raw-enter count:

0

raw-leave count:

0

`
        );
      },
      footerHtml: (
`
  <input type="checkbox" id="default-enabled" checked />
  enabled
`
      ),
      beforeTest(testElement) {
        const inputElement = document.getElementById('default-enabled');
        inputElement.addEventListener('change', (_) => {
          let element = testElement.querySelector('.box');
          if (inputElement.checked) {
            hoverIntent(element);
          } else {
            hoverIntent(element, 'remove');
          }
        });
      },
      test(testElement) {
        function setUpCounters(element, {
          enterCounter, leaveCounter, enterEvent, leaveEvent,
        }) {
          enterCounter = element.querySelector(enterCounter);
          leaveCounter = element.querySelector(leaveCounter);
          element.addEventListener(enterEvent, (event) => {
            enterCounter.textContent = parseInt(enterCounter.textContent) + 1;
            leaveCounter.textContent = 0;
          });
          element.addEventListener(leaveEvent, (event) => {
            enterCounter.textContent = 0;
            leaveCounter.textContent = parseInt(leaveCounter.textContent) + 1;
          });
        }
        let contextElement = testElement.querySelector('.box');
        let element = contextElement.querySelector('dl');
        hoverIntent(element, contextElement);
        setUpCounters(contextElement, {
          enterCounter: '.enter-counter',
          leaveCounter: '.leave-counter',
          enterEvent: eventName('enter'),
          leaveEvent: eventName('leave'),
        });
        setUpCounters(element, {
          enterCounter: '.raw-enter-counter',
          leaveCounter: '.raw-leave-counter',
          enterEvent: 'mouseover',
          leaveEvent: 'mouseleave',
        });
      },
      anchorName: 'default',
      className: 'default-call',
      vars: {},
    }));
    runVisualTests(tests);
  });

}());
<|endoftext|>


<commit_before>'use strict';

describe('The CLI called with', function () {
    var run = require('../src/run.js');
    var args;

    require('chai').should();

    var stdMocks = require('std-mocks');

    function stdout() {
        return stdMocks.flush().stdout.join('');
    }

    beforeEach(function () {
        args = {K: null, T: 'xdot', V: false, o: null, files: [], prog: 'dot'};

        stdMocks.use();
    });

    afterEach(function () {
        stdMocks.restore();
        stdMocks.flush();
    });

    describe('-V', function () {
        beforeEach(function () {
            args.V = true;
        });

        it('should print version information', function () {
            run(args);
            stdout().should.equal('dot - graphviz version 2.38.0 (20140413.2041)\n');
        });
        it('should print the called executable name', function () {
            args.prog = 'circo';
            run(args);
            stdout().should.equal('circo - graphviz version 2.38.0 (20140413.2041)\n');
        });
    });
});
<commit_msg>add structuring comments to integration test<commit_after>'use strict';

describe('The CLI called with', function () {
    var run = require('../src/run.js');
    var args;

    // chai
    require('chai').should();

    // std-mocks
    var stdMocks = require('std-mocks');

    function stdout() {
        return stdMocks.flush().stdout.join('');
    }

    beforeEach(function () {
        args = {K: null, T: 'xdot', V: false, o: null, files: [], prog: 'dot'};

        stdMocks.use();
    });

    afterEach(function () {
        stdMocks.restore();
        stdMocks.flush();
    });

    describe('-V', function () {
        beforeEach(function () {
            args.V = true;
        });

        it('should print version information', function () {
            run(args);
            stdout().should.equal('dot - graphviz version 2.38.0 (20140413.2041)\n');
        });
        it('should print the called executable name', function () {
            args.prog = 'circo';
            run(args);
            stdout().should.equal('circo - graphviz version 2.38.0 (20140413.2041)\n');
        });
    });
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { NavBar } from 'antd-mobile'
import styles from './Header.less'

const Header = ({ dispatch, children, ...headerProps }) => {
  const handleBack = () => {
    // router.goBack()
  }

  const navBarProps = {
    leftContent: '返回',
    // iconName: require('../../svg/back.svg'),
    mode: 'dark',
    onLeftClick: handleBack,
    ...headerProps,
  }

  return (

      <NavBar {...navBarProps}>
        {children.length > 8 ? `${children.substr(0, 8)}...` : children}
      </NavBar>

  )
}

Header.propTypes = {
  dispatch: PropTypes.func.isRequired,
  children: PropTypes.string.isRequired,
  headerProps: PropTypes.object,
}

export default connect()(Header)
<commit_msg>fix Introduce<commit_after>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { NavBar } from 'antd-mobile'
import styles from './Header.less'

const Header = ({ dispatch, children, ...headerProps }) => {
  const handleBack = () => {
    // router.goBack()
  }

  const navBarProps = {
    leftContent: '返回',
    iconName: `#${require('../../svg/back.svg').default.id}`,
    mode: 'dark',
    onLeftClick: handleBack,
    ...headerProps,
  }

  return (

      <NavBar {...navBarProps}>
        {children.length > 8 ? `${children.substr(0, 8)}...` : children}
      </NavBar>

  )
}

Header.propTypes = {
  dispatch: PropTypes.func.isRequired,
  children: PropTypes.string.isRequired,
  headerProps: PropTypes.object,
}

export default connect()(Header)
<|endoftext|>


<commit_before>var util = require('util');
var moment = require('moment');
var async = require('async');
var executor = require('./executor');
var items = require('../db/items');
var networks = require('../db/networks');
var logger = require('../utils/logger');
var config = require('../../config');
var connectors = require('./connectors');

function allowedToExecute (state) {
	if (state.skip || state.disabled) {
		return false;
	}

	if (!state.scheduledTo) {
		return true;
	}

	return moment().diff(state.scheduledTo) > 0;
}

function task(state) {
	return function (callback) { return executor (state, connectors, callback); };
}

function createTasks(mode, states) {
	var tasks = states.map(function (state) {
		return allowedToExecute(state) ? task(state) : null;
	}).filter(function (task) {
		return task !== null;
	});

	return tasks;
}

function runAllTasks(tasks, callback) {
	logger.info('currently allowed to run: ' + tasks.length);
	async.series(tasks, callback);
}

function createQuery(mode) {
	var queries = {
		initial: {
			$or: [ {mode: {$exists: false }}, { mode: 'initial'}, {mode: 'rateLimit'}]
		},

		normal: {
			mode: 'normal'
		}
	};

	return queries[mode];

}

module.exports = function (mode) {
	function schedulerLoop() {
		var query = createQuery(mode);
		networks.findAll(query, function (err, states) {
			if (err && !states) {
				return schedulerCallback({message: 'failed to read network states', err: err});
			}

			var tasks = createTasks(mode, states);
			var started = moment();

			runAllTasks(tasks, function (err) {
				var finished = moment();
				var duration = moment.duration(finished.diff(started));

				schedulerCallback(err, duration);
			});
		});
	}

	function schedulerCallback(err, duration) {
		if (err) {
			logger.error(err);
		}

		logger.info(util.format('collection cycle: %d sec. (%d mins.)', duration.asSeconds().toFixed(2), duration.asMinutes().toFixed(2)));
		restartScheduler();
	}

	function restartScheduler () {
		// http://stackoverflow.com/questions/16072699/nodejs-settimeout-memory-leak
		var timeout = setTimeout(schedulerLoop, config.collector.schedulerRestart);
	}

	return {
		run: function () {
			schedulerLoop();
		}
	};
};<commit_msg>prevent runtime error if mongo query failed<commit_after>var util = require('util');
var moment = require('moment');
var async = require('async');
var executor = require('./executor');
var items = require('../db/items');
var networks = require('../db/networks');
var logger = require('../utils/logger');
var config = require('../../config');
var connectors = require('./connectors');

function allowedToExecute (state) {
	if (state.skip || state.disabled) {
		return false;
	}

	if (!state.scheduledTo) {
		return true;
	}

	return moment().diff(state.scheduledTo) > 0;
}

function task(state) {
	return function (callback) { return executor (state, connectors, callback); };
}

function createTasks(mode, states) {
	var tasks = states.map(function (state) {
		return allowedToExecute(state) ? task(state) : null;
	}).filter(function (task) {
		return task !== null;
	});

	return tasks;
}

function runAllTasks(tasks, callback) {
	logger.info('currently allowed to run: ' + tasks.length);
	async.series(tasks, callback);
}

function createQuery(mode) {
	var queries = {
		initial: {
			$or: [ {mode: {$exists: false }}, { mode: 'initial'}, {mode: 'rateLimit'}]
		},

		normal: {
			mode: 'normal'
		}
	};

	return queries[mode];

}

module.exports = function (mode) {
	function schedulerLoop() {
		var query = createQuery(mode);
		networks.findAll(query, function (err, states) {
			if (err) {
				return schedulerCallback({message: 'error during networks query', err: err});
			}

			if (!states) {
				return schedulerCallback({message: 'failed to read networks states', states: states});
			}

			var tasks = createTasks(mode, states);
			var started = moment();

			runAllTasks(tasks, function (err) {
				var finished = moment();
				var duration = moment.duration(finished.diff(started));

				schedulerCallback(err, duration);
			});
		});
	}

	function schedulerCallback(err, duration) {
		if (err) {
			logger.error(err);
		}

		if (duration) {
			logger.info(util.format('collection cycle: %d sec. (%d mins.)', duration.asSeconds().toFixed(2), duration.asMinutes().toFixed(2)));
		}

		restartScheduler();
	}

	function restartScheduler () {
		// http://stackoverflow.com/questions/16072699/nodejs-settimeout-memory-leak
		var timeout = setTimeout(schedulerLoop, config.collector.schedulerRestart);
	}

	return {
		run: function () {
			schedulerLoop();
		}
	};
};<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Items from './Items';

const getVisibleItems = (
  items,
  filter
) => {
  switch (filter) {
    case 'SHOW_ALL':
      return items;
    case 'SHOW_ENABLED':
      return items.filter(
        i => i.enabled
      );
    case 'SHOW_DISABLED':
      return items.filter(
        i => !i.enabled
      );
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
}

class VisibleItems extends Component {
  componentDidMount() {
    const { store } = this.context;
    this.unsubscribe = store.subscribe(() =>
      this.forceUpdate()
    );
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { store } = this.context;
    const state = store.getState();

    return (
      <Items
        items={
          getVisibleItems(
            state.items,
            state.visibilityFilter
          )
        }
        onItemClick={id =>
          store.dispatch({
            type: 'TOGGLE_ITEM',
            id
          })
        }
      />
    );
  }
}

VisibleItems.contextTypes = {
  store: PropTypes.object
}

export default VisibleItems;<commit_msg>refactor: Generating Containers with connect() from React Redux (VisibleItems)<commit_after>import { connect } from 'react-redux';
import Items from './Items';

const getVisibleItems = (
  items,
  filter
) => {
  switch (filter) {
    case 'SHOW_ALL':
      return items;
    case 'SHOW_ENABLED':
      return items.filter(
        i => i.enabled
      );
    case 'SHOW_DISABLED':
      return items.filter(
        i => !i.enabled
      );
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
}

const mapStateToProps = (state) => {
  return {
    items: getVisibleItems(
      state.items,
      state.visibilityFilter
    )
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    onItemClick: id =>
      dispatch({
        type: 'TOGGLE_ITEM',
        id
      })
  }
}

const VisibleItems = connect(
  mapStateToProps,
  mapDispatchToProps
)(Items)

export default VisibleItems;<|endoftext|>


<commit_before>export const CURRENT_YEAR = (new Date()).getFullYear() - 1;

export const TYPES = {
  javascript: 'JavaScript',
  css: 'CSS',
  php: 'PHP',
  ux: 'Design / UX',
  ruby: 'Ruby',
  ios: 'iOS / Swift',
  android: 'Android',
  general: 'General',
};

const DEFAULT_URL = 'https://raw.githubusercontent.com/tech-conferences/confs.tech/master/conferences';

const REPO_URLS = {
  javascript: 'https://github.com/tech-conferences/javascript-conferences',
  css: 'https://github.com/tech-conferences/confs.tech',
  php: 'https://github.com/tech-conferences/confs.tech',
  ux: 'https://github.com/tech-conferences/confs.tech',
  ruby: 'https://github.com/tech-conferences/confs.tech',
  ios: 'https://github.com/tech-conferences/confs.tech',
  android: 'https://github.com/tech-conferences/confs.tech',
  general: 'https://github.com/tech-conferences/confs.tech',
};

const RAW_CONTENT_URLS = {
  javascript: 'https://raw.githubusercontent.com/tech-conferences/javascript-conferences/master/conferences',
  css: DEFAULT_URL,
  php: DEFAULT_URL,
  ux: DEFAULT_URL,
  ruby: DEFAULT_URL,
  ios: DEFAULT_URL,
  android: DEFAULT_URL,
  general: DEFAULT_URL,
};

export function getConferenceUrl(state) {
  const {type, year} = state;
  const _type = type.toLocaleLowerCase();

  return `${RAW_CONTENT_URLS[_type]}/${year}/${_type}.json`;
}

export function getAddConferenceUrl(type) {
  return `${REPO_URLS[type.toLocaleLowerCase()]}/issues/new`;
}
<commit_msg>Moved PHP section before General<commit_after>export const CURRENT_YEAR = (new Date()).getFullYear() - 1;

export const TYPES = {
  javascript: 'JavaScript',
  css: 'CSS',
  ux: 'Design / UX',
  ruby: 'Ruby',
  ios: 'iOS / Swift',
  android: 'Android',
  php: 'PHP',
  general: 'General',
};

const DEFAULT_URL = 'https://raw.githubusercontent.com/tech-conferences/confs.tech/master/conferences';

const REPO_URLS = {
  javascript: 'https://github.com/tech-conferences/javascript-conferences',
  css: 'https://github.com/tech-conferences/confs.tech',
  php: 'https://github.com/tech-conferences/confs.tech',
  ux: 'https://github.com/tech-conferences/confs.tech',
  ruby: 'https://github.com/tech-conferences/confs.tech',
  ios: 'https://github.com/tech-conferences/confs.tech',
  android: 'https://github.com/tech-conferences/confs.tech',
  general: 'https://github.com/tech-conferences/confs.tech',
};

const RAW_CONTENT_URLS = {
  javascript: 'https://raw.githubusercontent.com/tech-conferences/javascript-conferences/master/conferences',
  css: DEFAULT_URL,
  php: DEFAULT_URL,
  ux: DEFAULT_URL,
  ruby: DEFAULT_URL,
  ios: DEFAULT_URL,
  android: DEFAULT_URL,
  general: DEFAULT_URL,
};

export function getConferenceUrl(state) {
  const {type, year} = state;
  const _type = type.toLocaleLowerCase();

  return `${RAW_CONTENT_URLS[_type]}/${year}/${_type}.json`;
}

export function getAddConferenceUrl(type) {
  return `${REPO_URLS[type.toLocaleLowerCase()]}/issues/new`;
}
<|endoftext|>


<commit_before>'use strict';

var nock = require('nock');
var jsdom = require('jsdom');
var path = require('path');

var document = null;
var window = null;

// intercept request for schema
nock.disableNetConnect();

describe('long-press-mouse', function () {

    // create a new browser instance before each test
    beforeEach(function (done) {

        nock('http://localhost:8080')
            .get('/src/long-press-event.js')
            .replyWithFile(200, path.resolve('./src/long-press-event.js'));

        var virtualConsole = new jsdom.VirtualConsole();

        var options = {
            url: 'http://localhost:8080',
            contentType: 'text/html',
            runScripts: 'dangerously',
            resources: 'usable',
            virtualConsole: virtualConsole.sendTo(console) // redirect browser output to terminal
        };

        // load test page from disk (includes links to dependent scripts)
        jsdom.JSDOM.fromFile(path.resolve(__dirname, 'test-page.html'), options).then(function(dom) {

            // expose the window/document object to tests
            window = dom.window;
            document = window.document;

            // slight wait to allow scripts to load
            setTimeout(function() {
                expect(document).toBeDefined();
                expect(document.title).toBe('long-press Test Page');
                done();
            }, 250);
        });
    });

    it('should fire long-press event after default 1.5s', function(done) {

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'mousedown');

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, 1500);
    });

    it('should fire long-press event using data-long-press-delay', function(done) {

        var longPressDelay = 100;

        var el = document.createElement('div');

        el.setAttribute('data-long-press-delay', longPressDelay);

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'mousedown');

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, longPressDelay + 10);
    });

    it('should fire with correct clientX and clientY', function(done) {

        var clientX = 10,
            clientY = 10;

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.detail.clientX).toEqual(clientX);
            expect(e.detail.clientY).toEqual(clientY);
            done();
        });

        window.fireEvent(el, 'mousedown', { clientX: clientX, clientY: clientY });

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, 1500);
    });

});

describe('long-press-touch', function () {

    // create a new browser instance before each test
    beforeEach(function (done) {

        nock('http://localhost:8080')
            .get('/src/long-press-event.js')
            .replyWithFile(200, path.resolve('./src/long-press-event.js'));

        var virtualConsole = new jsdom.VirtualConsole();

        var options = {
            url: 'http://localhost:8080',
            contentType: 'text/html',
            runScripts: 'dangerously',
            resources: 'usable',
            virtualConsole: virtualConsole.sendTo(console) // redirect browser output to terminal
        };

        // load test page from disk (includes links to dependent scripts)
        jsdom.JSDOM.fromFile(path.resolve(__dirname, 'test-page.html'), options).then(function(dom) {

            // expose the window/document object to tests
            window = dom.window;
            window.ontouchstart = function() {};
            document = window.document;

            // slight wait to allow scripts to load
            setTimeout(function() {
                expect(document).toBeDefined();
                expect(document.title).toBe('long-press Test Page');
                done();
            }, 250);
        });
    });

    it('should fire long-press event after default 1.5s', function(done) {

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'touchstart');

        setTimeout(function() {
            window.fireEvent(el, 'touchend');
        }, 1500);
    });

    it('should fire long-press event using data-long-press-delay', function(done) {

        var longPressDealy = 100;

        var el = document.createElement('div');

        el.setAttribute('data-long-press-delay', longPressDealy);

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'touchstart');

        setTimeout(function() {
            window.fireEvent(el, 'touchend');
        }, longPressDealy + 10);
    });

});

<commit_msg>Fixed typo<commit_after>'use strict';

var nock = require('nock');
var jsdom = require('jsdom');
var path = require('path');

var document = null;
var window = null;

// intercept request for schema
nock.disableNetConnect();

describe('long-press-mouse', function () {

    // create a new browser instance before each test
    beforeEach(function (done) {

        nock('http://localhost:8080')
            .get('/src/long-press-event.js')
            .replyWithFile(200, path.resolve('./src/long-press-event.js'));

        var virtualConsole = new jsdom.VirtualConsole();

        var options = {
            url: 'http://localhost:8080',
            contentType: 'text/html',
            runScripts: 'dangerously',
            resources: 'usable',
            virtualConsole: virtualConsole.sendTo(console) // redirect browser output to terminal
        };

        // load test page from disk (includes links to dependent scripts)
        jsdom.JSDOM.fromFile(path.resolve(__dirname, 'test-page.html'), options).then(function(dom) {

            // expose the window/document object to tests
            window = dom.window;
            document = window.document;

            // slight wait to allow scripts to load
            setTimeout(function() {
                expect(document).toBeDefined();
                expect(document.title).toBe('long-press Test Page');
                done();
            }, 250);
        });
    });

    it('should fire long-press event after default 1.5s', function(done) {

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'mousedown');

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, 1500);
    });

    it('should fire long-press event using data-long-press-delay', function(done) {

        var longPressDelay = 100;

        var el = document.createElement('div');

        el.setAttribute('data-long-press-delay', longPressDelay);

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'mousedown');

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, longPressDelay + 10);
    });

    it('should fire with correct clientX and clientY', function(done) {

        var clientX = 10,
            clientY = 10;

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.detail.clientX).toEqual(clientX);
            expect(e.detail.clientY).toEqual(clientY);
            done();
        });

        window.fireEvent(el, 'mousedown', { clientX: clientX, clientY: clientY });

        setTimeout(function() {
            window.fireEvent(el, 'mouseup');
        }, 1500);
    });

});

describe('long-press-touch', function () {

    // create a new browser instance before each test
    beforeEach(function (done) {

        nock('http://localhost:8080')
            .get('/src/long-press-event.js')
            .replyWithFile(200, path.resolve('./src/long-press-event.js'));

        var virtualConsole = new jsdom.VirtualConsole();

        var options = {
            url: 'http://localhost:8080',
            contentType: 'text/html',
            runScripts: 'dangerously',
            resources: 'usable',
            virtualConsole: virtualConsole.sendTo(console) // redirect browser output to terminal
        };

        // load test page from disk (includes links to dependent scripts)
        jsdom.JSDOM.fromFile(path.resolve(__dirname, 'test-page.html'), options).then(function(dom) {

            // expose the window/document object to tests
            window = dom.window;
            window.ontouchstart = function() {};
            document = window.document;

            // slight wait to allow scripts to load
            setTimeout(function() {
                expect(document).toBeDefined();
                expect(document.title).toBe('long-press Test Page');
                done();
            }, 250);
        });
    });

    it('should fire long-press event after default 1.5s', function(done) {

        var el = document.createElement('div');

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'touchstart');

        setTimeout(function() {
            window.fireEvent(el, 'touchend');
        }, 1500);
    });

    it('should fire long-press event using data-long-press-delay', function(done) {

        var longPressDelay = 100;

        var el = document.createElement('div');

        el.setAttribute('data-long-press-delay', longPressDelay);

        document.body.appendChild(el);

        el.addEventListener('long-press', function(e) {
            expect(e).toBeDefined();
            expect(e.target).toEqual(el);
            done();
        });

        window.fireEvent(el, 'touchstart');

        setTimeout(function() {
            window.fireEvent(el, 'touchend');
        }, longPressDelay + 10);
    });

});

<|endoftext|>


<commit_before>window.addEventListener('load', function() {
    (function() {
        var headerEle = document.getElementById('page-header');

        function toggleNavStyle() {
            var scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

            headerEle.classList[ scrollTop > 30 ? 'add' : 'remove' ]('page__header--small');
        }

        headerEle && document.addEventListener('scroll', toggleNavStyle);
    })();

    (function() {
        var
            btn = document.querySelector('button.page__menu-btn'),
            menu = document.querySelector('nav.page__nav');

        if (btn && menu) {
            var packMenu = new Pack(menu);

            packMenu.base('js-open').transfrom('page__nav--open');

            btn.addEventListener('click', function() {
                packMenu.toggle();
            });
        }
    })();

    (function() {
        var
            header = document.getElementById('page-header')
            title = header.querySelector('.info__title'),
            desc = header.querySelector('.info__desc');

        title && new Pack(title)
            .animation('js-animation')
            .end(function() {
                var arr = ['js-animation'];

                arr.forEach(function(item) {
                    title.classList.remove(item);
                });
            })
            .toggle();

        desc && new Pack(desc)
            .base('js-ease-out-leave-active')
            .base('js-ease-out-leave')
            .transfrom('js-ease-out-enter-active')
            .end(function() {
                var arr = ['js-ease-out-enter', 'js-ease-out-enter-active', 'js-ease-out-leave', 'js-ease-out-leave-active'];

                arr.forEach(function(item) {
                    desc.classList.remove(item);
                });
            })
            .toggle();
    })();
});<commit_msg>fix: fix header js bug<commit_after>window.addEventListener('load', function() {
    (function() {
        var headerEle = document.getElementById('page-header');

        function toggleNavStyle() {
            var scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

            headerEle.classList[ scrollTop > 30 ? 'add' : 'remove' ]('page__header--small');
        }

        headerEle && document.addEventListener('scroll', toggleNavStyle);
    })();

    (function() {
        var
            btn = document.querySelector('button.page__menu-btn'),
            menu = document.querySelector('nav.page__nav');

        if (btn && menu) {
            var packMenu = new Pack(menu);

            packMenu.base('js-open').transfrom('page__nav--open');

            btn.addEventListener('click', function() {
                packMenu.toggle();
            });
        }
    })();

    (function() {
        var header = document.getElementById('page-header');

        if (!header) return;

        var
            title = header.querySelector('.info__title'),
            desc = header.querySelector('.info__desc');

        title && new Pack(title)
            .animation('js-animation')
            .end(function() {
                var arr = ['js-animation'];

                arr.forEach(function(item) {
                    title.classList.remove(item);
                });
            })
            .toggle();

        desc && new Pack(desc)
            .base('js-ease-out-leave-active')
            .base('js-ease-out-leave')
            .transfrom('js-ease-out-enter-active')
            .end(function() {
                var arr = ['js-ease-out-enter', 'js-ease-out-enter-active', 'js-ease-out-leave', 'js-ease-out-leave-active'];

                arr.forEach(function(item) {
                    desc.classList.remove(item);
                });
            })
            .toggle();
    })();
});<|endoftext|>


<commit_before>/**
 * SyntaxHighlighter
 * http://alexgorbatchev.com/SyntaxHighlighter
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
 *
 * @version
 * 3.0.83 (July 02 2010)
 *
 * @copyright
 * Copyright (C) 2004-2010 Alex Gorbatchev.
 *
 * @license
 * Dual licensed under the MIT and GPL licenses.
 */
;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		var keywords =	'abs addr and ansichar ansistring array as asm begin boolean byte cardinal ' +
						'case char class comp const constructor currency destructor div do double ' +
						'downto else end except exports extended false file finalization finally ' +
						'for function goto if implementation in inherited int64 initialization ' +
						'integer interface is label library longint longword mod nil not object ' +
						'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended ' +
						'pint64 pointer private procedure program property pshortstring pstring ' +
						'pvariant pwidechar pwidestring protected public published raise real real48 ' +
						'record repeat set shl shortint shortstring shr single smallint string then ' +
						'threadvar to true try type unit until uses val var varirnt while widechar ' +
						'widestring with word write writeln xor';

		this.regexList = [
			{ regex: /\(\*[\s\S]*?\*\)/gm,								css: 'comments' },  	// multiline comments (* *)
			{ regex: /{(?!\$)[\s\S]*?}/gm,								css: 'comments' },  	// multiline comments { }
			{ regex: SyntaxHighlighter.regexLib.singleLineCComments,	css: 'comments' },  	// one line
			{ regex: SyntaxHighlighter.regexLib.singleQuotedString,		css: 'string' },		// strings
			{ regex: /\{\$[a-zA-Z]+ .+\}/g,								css: 'color1' },		// compiler Directives and Region tags
			{ regex: /\b[\d\.]+\b/g,									css: 'value' },			// numbers 12345
			{ regex: /\$[a-zA-Z0-9]+\b/g,								css: 'value' },			// numbers $F5D3
			{ regex: new RegExp(this.getKeywords(keywords), 'gmi'),		css: 'keyword' }		// keyword
			];
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['delphi', 'pascal', 'pas'];

	SyntaxHighlighter.brushes.Delphi = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
<commit_msg>Delete shBrushDelphi.js<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = {

  controller: function (args) {
    this.servico = args.servico;

    this.adicionar = function () {
      this.servico().legislacoes().push('');
    };

    this.remover = function (i) {
      this.servico().legislacoes().splice(i, 1);
    };
  },

  view: function (ctrl) {
    return m('fieldset#legislacoes', [
      m('h3', [
        'Legislações relacionadas ao serviço',
        m.component(require('tooltips').legislacoes)
      ]),

      ctrl.servico().legislacoes().map(function (legislacao, i) {
        return [
          m('input.inline[type=text]', {
            value: legislacao,
            onchange: function (e) {
              ctrl.servico().legislacoes()[i] = e.target.value;
            }
          }),
          m('button.remove', {
            onclick: ctrl.remover.bind(ctrl, i)
          }, [
            m('span.fa.fa-trash-o')
          ])
        ];
      }),
      m('button.adicionar.adicionar-legislacao', {
        onclick: ctrl.adicionar.bind(ctrl)
      }, [
        m('i.fa.fa-plus'),
        ' Adicionar legislação '
      ])
    ]);
  }
};
<commit_msg>Resolve #205<commit_after>'use strict';

module.exports = {

  controller: function (args) {
    this.servico = args.servico;

    this.adicionar = function () {
      this.servico().legislacoes().push('');
    };

    this.remover = function (i) {
      this.servico().legislacoes().splice(i, 1);
    };
  },

  view: function (ctrl) {
    return m('fieldset#legislacoes', [
      m('h3', [
        'Legislações relacionadas ao serviço',
        m.component(require('tooltips').legislacoes)
      ]),

      ctrl.servico().legislacoes().map(function (legislacao, i) {
        return [
          m('input.inline[type=text]', {
            value: legislacao,
            onchange: function (e) {
              ctrl.servico().legislacoes()[i] = e.target.value;
            }
          }),
          m('button.remove', {
            onclick: ctrl.remover.bind(ctrl, i)
          }, [
            m('span.fa.fa-trash-o')
          ])
        ];
      }),
      m('button.adicionar.adicionar-legislacao', {
        onclick: ctrl.adicionar.bind(ctrl)
      }, [
        m('i.fa.fa-plus'),
        ' Adicionar lei, decreto ou portaria '
      ])
    ]);
  }
};
<|endoftext|>


<commit_before>(function (require, describe, it) {
  'use strict';

  var superagent = require('superagent');
  var expect = require('expect.js');
  var testData = require('./testData.js');
  var utils = require('../include/utils.js');
  var serverModule = require('../server.js');

  describe('Project API tests', function () {
    var id;
    var users = testData.getTestUsers();
    var projects = testData.getTestProjects();
    var devices = testData.getTestDevices();
    var agent = superagent.agent();
    var project = null;
    var profileId = null;
    var device = null;

    it('Start server', function (done) {
      serverModule.start(function (e, server) {
        expect(e)
          .to.eql(null);

        done();
      });
    });

    it('Login user [2]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[2])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Get project created by device API tests', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body.length)
            .to.be(1);

          project = res.body[0];

          done();
        });
    });

    it('Get device created by device API tests', function (done) {
      agent.get('http://localhost:3000/projects/' +
        project._id + '/devices/' + devices[0].macAddress + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          device = res.body;

          done();
        });
    });

    it('Save current session as profile [0]', function (done) {
      var data = {
        profileName: 'test profile 1'
      };

      agent.put('http://localhost:3000/projects/' +
        device.projectId + '/profiles/')
        .query({
          deviceId: device._id
        })
        .send(data)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body._id)
            .to.be.ok();

          profileId = res.body._id;

          done();
        });
    });

    it('Retrieve profile [0]', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          var profile = res.body;

          expect(utils.objMatch(
            device.currentState,
            profile.profileData))
            .to.be.ok();

          done();
        });
    });

    it('Logout user [2]', function (done) {
      agent.get('http://localhost:3000/logout/')
        .send()
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('Login user [1]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[1])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Delete profile [0] as non owner', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);

          expect(res.status)
            .to.be(401);

          done();
        });
    });

    it('Retrieve profile [0]', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          var profile = res.body;

          expect(utils.objMatch(
            device.currentState,
            profile.profileData))
            .to.be.ok();

          done();
        });
    });

    it('Logout user [1]', function (done) {
      agent.get('http://localhost:3000/logout/')
        .send()
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('Login user [2]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[2])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Delete profile [0]', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          done();
        });
    });

    it('Retrieve profile [0] after deletion', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(404);

          done();
        });
    });

    it('Delete non existant profile', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + 'fdsdfdfsfd' + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(404);

          done();
        });
    });

  });

})(require, describe, it);
<commit_msg>Added some more profile tests to improve code coverage.<commit_after>(function (require, describe, it) {
  'use strict';

  var superagent = require('superagent');
  var expect = require('expect.js');
  var testData = require('./testData.js');
  var utils = require('../include/utils.js');
  var serverModule = require('../server.js');

  describe('Project API tests', function () {
    var id;
    var users = testData.getTestUsers();
    var projects = testData.getTestProjects();
    var devices = testData.getTestDevices();
    var agent = superagent.agent();
    var project = null;
    var profileId = null;
    var device = null;

    it('Start server', function (done) {
      serverModule.start(function (e, server) {
        expect(e)
          .to.eql(null);

        done();
      });
    });

    it('Login user [2]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[2])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Get project created by device API tests', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body.length)
            .to.be(1);

          project = res.body[0];

          done();
        });
    });

    it('Get device created by device API tests', function (done) {
      agent.get('http://localhost:3000/projects/' +
        project._id + '/devices/' + devices[0].macAddress + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          device = res.body;

          done();
        });
    });

    it('Save current session as profile [0]', function (done) {
      var data = {
        profileName: 'test profile 1'
      };

      agent.put('http://localhost:3000/projects/' +
        device.projectId + '/profiles/')
        .query({
          deviceId: device._id
        })
        .send(data)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body._id)
            .to.be.ok();

          profileId = res.body._id;

          done();
        });
    });

    it('Retrieve profile [0]', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          var profile = res.body;

          expect(utils.objMatch(
            device.currentState,
            profile.profileData))
            .to.be.ok();

          done();
        });
    });

    it('List profiles [0] of project [0]', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          var profile = res.body[0];

          expect(utils.objMatch(
            device.currentState,
            profile.profileData))
            .to.be.ok();

          done();
        });
    });

    it('List profiles [0] of non existant project', function (done) {

      agent.get('http://localhost:3000/projects/' +
        '!@#$%^&**())' + '/profiles/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(404);

          done();
        });
    });

    it('Logout user [2]', function (done) {
      agent.get('http://localhost:3000/logout/')
        .send()
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('Retrieve profile [0] while not logged in', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be.ok(401);

          done();
        });
    });

    it('List profiles [0] of project [0] while not logged in', function (
      done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(401);

          done();
        });
    });

    it('Login user [1]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[1])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Delete profile [0] as non owner', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);

          expect(res.status)
            .to.be(401);

          done();
        });
    });

    it('Retrieve profile [0]', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          var profile = res.body;

          expect(utils.objMatch(
            device.currentState,
            profile.profileData))
            .to.be.ok();

          done();
        });
    });

    it('Logout user [1]', function (done) {
      agent.get('http://localhost:3000/logout/')
        .send()
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('Login user [2]', function (done) {
      agent.post('http://localhost:3000/login/')
        .send(users[2])
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(200);
          done();
        });
    });

    it('Delete profile [0]', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          done();
        });
    });

    it('Retrieve profile [0] after deletion', function (done) {

      agent.get('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + profileId + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(404);

          done();
        });
    });

    it('Delete non existant profile', function (done) {

      agent.del('http://localhost:3000/projects/' +
        device.projectId + '/profiles/' + 'fdsdfdfsfd' + '/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(404);

          done();
        });
    });

  });

})(require, describe, it);
<|endoftext|>


<commit_before>/**
 * Author: Dmitry Kmita <dmitry@kmita.ru>
 *
 * Under MIT Licence
 *
 * Custom Modal Library for easy modal usage
 */
var modal = {
    currentContent: '',
    openAjaxModal: function(url, data, trigger) {
        var me = this;
        me._sendRequest(url, data, function(response){
            if (response.success) {
                me.currentContent = response.content;
                me.initModal();
                trigger();
            }
        });
    },
    openModal: function(text) {
        var me = this;
        if (text !== undefined) {
            me.currentContent = text;
        }
        me._initModal();
        me._bindButtons();
    },
    _sendRequest: function (url, data, success) {
        var request = $.ajax({
            url: url,
            type: "POST",
            async: true,
            data: data,
            dataType: "json"
        });
        request.done(success);
    },
    _bindButtons: function () {
        var me = this;
        $("#modal-window .close").click(function () {
            me.closeModal();
        });
    },
    closeModal: function () {
        var me = this;
        me._removeWindow();
        me._removeOverlay();
    },
    _initModal: function() {
        var me = this;
        me._initOverlay();
        me._initWindow();
    },
    _initOverlay: function() {
        if ($("#modal-overlay").length == 0) {
            $("body").prepend('

');
        }
    },
    _removeOverlay: function() {
        $("#modal-overlay").remove();
    },
    _initWindow: function() {
        var me = this;
        if ($("#modal-overlay").length == 0) {
            me._initOverlay();
        }
        $("body").prepend('

'+me.currentContent+'
');
    },
    _removeWindow: function() {
        $("#modal-window").remove();
    }
};<commit_msg>Fixed the private function name<commit_after>/**
 * Author: Dmitry Kmita <dmitry@kmita.ru>
 *
 * Under MIT Licence
 *
 * Custom Modal Library for easy modal usage
 */
var modal = {
    currentContent: '',
    openAjaxModal: function(url, data, trigger) {
        var me = this;
        me._sendRequest(url, data, function(response){
            if (response.success) {
                me.currentContent = response.content;
                me._initModal();
                trigger();
            }
        });
    },
    openModal: function(text) {
        var me = this;
        if (text !== undefined) {
            me.currentContent = text;
        }
        me._initModal();
        me._bindButtons();
    },
    _sendRequest: function (url, data, success) {
        var request = $.ajax({
            url: url,
            type: "POST",
            async: true,
            data: data,
            dataType: "json"
        });
        request.done(success);
    },
    _bindButtons: function () {
        var me = this;
        $("#modal-window .close").click(function () {
            me.closeModal();
        });
    },
    closeModal: function () {
        var me = this;
        me._removeWindow();
        me._removeOverlay();
    },
    _initModal: function() {
        var me = this;
        me._initOverlay();
        me._initWindow();
    },
    _initOverlay: function() {
        if ($("#modal-overlay").length == 0) {
            $("body").prepend('

');
        }
    },
    _removeOverlay: function() {
        $("#modal-overlay").remove();
    },
    _initWindow: function() {
        var me = this;
        if ($("#modal-overlay").length == 0) {
            me._initOverlay();
        }
        $("body").prepend('

'+me.currentContent+'
');
    },
    _removeWindow: function() {
        $("#modal-window").remove();
    }
};<|endoftext|>


<commit_before>import React from 'react'
import ReactCountdownClock from 'react-countdown-clock'
import { checkNetWorkByID, checkTxMined, sendTXToContract } from '../../utils/blockchainHelpers'
import {
  findCurrentContractRecursively,
  getAccumulativeCrowdsaleData,
  getContractStoreProperty,
  getCrowdsaleData,
  getCrowdsaleTargetDates,
  getCurrentRate,
  getJoinedTiers,
  initializeAccumulativeData
} from '../crowdsale/utils'
import { countDecimalPlaces, getQueryVariable, toast } from '../../utils/utils'
import { getWhiteListWithCapCrowdsaleAssets } from '../../stores/utils'
import {
  invalidCrowdsaleAddrAlert,
  investmentDisabledAlertInTime, noGasPriceAvailable,
  noMetaMaskAlert,
  successfulInvestmentAlert
} from '../../utils/alerts'
import { Loader } from '../Common/Loader'
import { CrowdsaleConfig } from '../Common/config'
import { CONTRACT_TYPES, INVESTMENT_OPTIONS, TOAST } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import QRPaymentProcess from './QRPaymentProcess'
import classNames from 'classnames'

@inject('contractStore', 'crowdsalePageStore', 'web3Store', 'tierStore', 'tokenStore', 'generalStore', 'investStore', 'gasPriceStore', 'generalStore')
@observer
export class Invest extends React.Component {
  constructor(props) {
    super(props)
    window.scrollTo(0, 0)

    this.state = {
      seconds: 0,
      loading: true,
      pristineTokenInput: true,
      web3Available: false,
      investThrough: INVESTMENT_OPTIONS.QR,
      crowdsaleAddress: CrowdsaleConfig.crowdsaleContractURL || getQueryVariable('addr')
    }
  }

  componentDidMount () {
    const { web3Store, contractStore, gasPriceStore, generalStore } = this.props
    const { web3 } = web3Store

    if (!web3) {
      this.setState({ loading: false })
      return
    }

    const networkID = CrowdsaleConfig.networkID ? CrowdsaleConfig.networkID : getQueryVariable('networkID')
    const contractType = CONTRACT_TYPES.whitelistwithcap
    checkNetWorkByID(networkID)
    contractStore.setContractType(contractType)

    const timeInterval = setInterval(() => this.setState({ seconds: this.state.seconds - 1 }), 1000)
    this.setState({
      timeInterval,
      web3Available: true,
      investThrough: INVESTMENT_OPTIONS.METAMASK
    })

    getWhiteListWithCapCrowdsaleAssets()
      .then(_newState => {
        this.setState(_newState)
        this.extractContractsData()
        gasPriceStore.updateValues()
          .then(() => generalStore.setGasPrice(gasPriceStore.slow.price))
          .catch(() => noGasPriceAvailable())
      })
  }

  extractContractsData() {
    const { contractStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    const crowdsaleAddr = CrowdsaleConfig.crowdsaleContractURL ? CrowdsaleConfig.crowdsaleContractURL : getQueryVariable('addr')

    if (!web3.utils.isAddress(crowdsaleAddr)) {
      this.setState({ loading: false })
      return invalidCrowdsaleAddrAlert()
    }

    getJoinedTiers(contractStore.crowdsale.abi, crowdsaleAddr, [], joinedCrowdsales => {
      console.log('joinedCrowdsales:', joinedCrowdsales)

      const crowdsaleAddrs = typeof joinedCrowdsales === 'string' ? [joinedCrowdsales] : joinedCrowdsales
      contractStore.setContractProperty('crowdsale', 'addr', crowdsaleAddrs)

      web3.eth.getAccounts().then((accounts) => {
        if (accounts.length === 0) {
          this.setState({ loading: false })
          return
        }

        this.setState({
          curAddr: accounts[0],
          web3
        })

        if (!contractStore.crowdsale.addr) {
          this.setState({ loading: false })
          return
        }

        findCurrentContractRecursively(0, null, crowdsaleContract => {
          if (!crowdsaleContract) {
            this.setState({ loading: false })
            return
          }

          initializeAccumulativeData()
            .then(() => getCrowdsaleData(crowdsaleContract))
            .then(() => getAccumulativeCrowdsaleData())
            .then(() => this.setState({ loading: false }))
            .catch(err => {
              this.setState({ loading: false })
              console.log(err)
            })

          getCrowdsaleTargetDates(this, () => {
            if (crowdsalePageStore.endDate) {
              this.setState({
                seconds: (crowdsalePageStore.endDate - new Date().getTime()) / 1000
              })
            }
          })
        })
      })
    })
  }

  investToTokens = event => {
    const { investStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    event.preventDefault()

    if (!this.isValidToken(investStore.tokensToInvest)) {
      this.setState({ pristineTokenInput: false })
      return
    }

    this.setState({ loading: true })

    const startBlock = parseInt(crowdsalePageStore.startBlock, 10)
    const { startDate } = crowdsalePageStore

    if ((isNaN(startBlock) || startBlock === 0) && !startDate) {
      this.setState({ loading: false })
      return
    }

    if (web3.eth.accounts.length === 0) {
      this.setState({ loading: false })
      return noMetaMaskAlert()
    }

    this.investToTokensForWhitelistedCrowdsale()
  }

  investToTokensForWhitelistedCrowdsale() {
    const { crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    if (crowdsalePageStore.startDate > (new Date()).getTime()) {
      this.setState({ loading: false })
      return investmentDisabledAlertInTime(crowdsalePageStore.startDate)
    }

    findCurrentContractRecursively(0, null, (crowdsaleContract, tierNum) => {
      if (!crowdsaleContract) {
        this.setState({ loading: false })
        return
      }

      getCurrentRate(crowdsaleContract)
        .then(() => web3.eth.getAccounts())
        .then((accounts) => this.investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, accounts))
        .catch(console.log)
    })
  }

  investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, accounts) {
    const { contractStore, tokenStore, crowdsalePageStore, investStore, generalStore } = this.props

    let nextTiers = []
    for (let i = tierNum + 1; i < contractStore.crowdsale.addr.length; i++) {
      nextTiers.push(contractStore.crowdsale.addr[i])
    }
    console.log('nextTiers:', nextTiers)
    console.log(nextTiers.length)

    const decimals = parseInt(tokenStore.decimals, 10)
    console.log('decimals:', decimals)

    const rate = parseInt(crowdsalePageStore.rate, 10) //it is from contract. It is already in wei. How much 1 token costs in wei.
    console.log('rate:', rate)

    const tokensToInvest = parseFloat(investStore.tokensToInvest)
    console.log('tokensToInvest:', tokensToInvest)

    const weiToSend = parseInt(tokensToInvest * rate, 10)
    console.log('weiToSend:', weiToSend)

    const opts = {
      from: accounts[0],
      value: weiToSend,
      gasPrice: generalStore.gasPrice
    }
    console.log(opts)

    crowdsaleContract.methods.buy().estimateGas(opts)
      .then(estimatedGas => {
        const estimatedGasMax = 4016260
        opts.gasLimit = !estimatedGas || estimatedGas > estimatedGasMax ? estimatedGasMax : estimatedGas + 100000

        return sendTXToContract(crowdsaleContract.methods.buy().send(opts))
      })
      .then(() => successfulInvestmentAlert(investStore.tokensToInvest))
      .catch(err => toast.showToaster({ type: TOAST.TYPE.ERROR, message: TOAST.MESSAGE.TRANSACTION_FAILED }))
      .then(() => this.setState({ loading: false }))
  }

  txMinedCallback(txHash, receipt) {
    const { investStore } = this.props

    if (receipt) {
      if (receipt.blockNumber) {
        this.setState({ loading: false })
        successfulInvestmentAlert(investStore.tokensToInvest)
      }
    } else {
      setTimeout(() => {
        checkTxMined(txHash, receipt => this.txMinedCallback(txHash, receipt))
      }, 500)
    }
  }

  tokensToInvestOnChange = event => {
    this.setState({ pristineTokenInput: false })
    this.props.investStore.setProperty('tokensToInvest', event.target.value)
  }

  isValidToken(token) {
    return +token > 0 && countDecimalPlaces(token) <= this.props.tokenStore.decimals
  }

  renderPieTracker () {
    return (

        <ReactCountdownClock
          seconds={this.state.seconds}
          color="#733EAB"
          alpha={0.9}
          size={270}
        />

    )
  }

  shouldStopCountDown () {
    if(this.state.seconds < 0) {
      this.setState({ seconds: 0 })
      clearInterval(this.state.timeInterval)
    }
  }

  getTimeStamps (seconds) {
    this.shouldStopCountDown()
    const days        = Math.floor(seconds / 24 / 60 / 60)
    const hoursLeft   = Math.floor(seconds - days * 86400)
    const hours       = Math.floor(hoursLeft / 3600)
    const minutesLeft = Math.floor(hoursLeft - hours * 3600)
    const minutes     = Math.floor(minutesLeft / 60)
    return { days, hours, minutes }
  }

  render () {
    const { crowdsalePageStore, tokenStore, contractStore, investStore } = this.props
    const { rate, tokenAmountOf, ethRaised, supply } = crowdsalePageStore
    const { crowdsale, contractType } = contractStore
    const { tokensToInvest } = investStore

    const { seconds, curAddr, pristineTokenInput, investThrough, crowdsaleAddress, web3Available } = this.state
    const { days, hours, minutes } = this.getTimeStamps(seconds)

    const { decimals, ticker, name } = tokenStore
    const isWhitelistWithCap = contractType === CONTRACT_TYPES.whitelistwithcap

    const tokenDecimals = !isNaN(decimals) ? decimals : 0
    const tokenTicker = ticker ? ticker.toString() : ''
    const tokenName = name ? name.toString() : ''
    const maxCapBeforeDecimals = crowdsalePageStore.maximumSellableTokens / 10 ** tokenDecimals
    const tokenAddress = getContractStoreProperty('token', 'addr')

    //balance: tiers, standard
    const investorBalanceTiers = tokenAmountOf ? (tokenAmountOf / 10 ** tokenDecimals).toString() : '0'
    const investorBalanceStandard = ethRaised ? (ethRaised / rate).toString() : '0'
    const investorBalance = isWhitelistWithCap ? investorBalanceTiers : investorBalanceStandard

    //total supply: tiers, standard
    const tierCap = !isNaN(maxCapBeforeDecimals) ? maxCapBeforeDecimals.toString() : '0'
    const standardCrowdsaleSupply = !isNaN(supply) ? supply.toString() : '0'
    const totalSupply = isWhitelistWithCap ? tierCap : standardCrowdsaleSupply

    let invalidTokenDescription = null
    if (!pristineTokenInput && !this.isValidToken(tokensToInvest)) {
      invalidTokenDescription = (

          Number of tokens to buy should be positive and should not exceed {decimals} decimals.

      )
    }

    const QRPaymentProcessElement = investThrough === INVESTMENT_OPTIONS.QR ?
      <QRPaymentProcess crowdsaleAddress={crowdsaleAddress} /> :
      null

    const ContributeButton = investThrough === INVESTMENT_OPTIONS.METAMASK ?
      Contribute :
      null

    const rightColumnClasses = classNames('invest-table-cell', 'invest-table-cell_right', {
      'qr-selected': investThrough === INVESTMENT_OPTIONS.QR
    })

    return

{days}

Days

{hours}

Hours

{minutes}

Mins

            {this.renderPieTracker()}

{curAddr}

Current Account

{tokenAddress}

Token Address

{crowdsale && crowdsale.addr && crowdsale.addr[0]}

Crowdsale Contract Address

{tokenName}

Name

{tokenTicker}

Ticker

{totalSupply} {tokenTicker}

Total Supply

Invest page

            {'Here you can invest in the crowdsale campaign. At the moment, you need Metamask client to invest into the crowdsale. If you don\'t have Metamask, you can send ethers to the crowdsale address with a MethodID: 0xa6f2ae3a. Sample '}
            transaction on Kovan network.

{investorBalance} {tokenTicker}

Balance

              Your balance in tokens.

          <form className="invest-form" onSubmit={this.investToTokens}>
            Choose amount to invest

              <input type="text" className="invest-form-input" value={tokensToInvest} onChange={this.tokensToInvestOnChange} placeholder="0"/>

TOKENS

              {invalidTokenDescription}

              <select value={investThrough} className="invest-through" onChange={(e) => this.setState({ investThrough: e.target.value })}>
                <option disabled={!web3Available} value={INVESTMENT_OPTIONS.METAMASK}>Metamask {!web3Available ? ' (not available)' : null}</option>
                <option value={INVESTMENT_OPTIONS.QR}>QR</option>
              </select>
              { ContributeButton }

              Think twice before contributing to Crowdsales. Tokens will be deposited on a wallet you used to buy tokens.

          </form>
          { QRPaymentProcessElement }

      <Loader show={this.state.loading}></Loader>

  }
}
<commit_msg>Fix supply calculus for invest page<commit_after>import React from 'react'
import ReactCountdownClock from 'react-countdown-clock'
import { checkNetWorkByID, checkTxMined, sendTXToContract } from '../../utils/blockchainHelpers'
import {
  findCurrentContractRecursively,
  getAccumulativeCrowdsaleData,
  getContractStoreProperty,
  getCrowdsaleData,
  getCrowdsaleTargetDates,
  getCurrentRate,
  getJoinedTiers,
  initializeAccumulativeData,
  toBigNumber
} from '../crowdsale/utils'
import { countDecimalPlaces, getQueryVariable, toast } from '../../utils/utils'
import { getWhiteListWithCapCrowdsaleAssets } from '../../stores/utils'
import {
  invalidCrowdsaleAddrAlert,
  investmentDisabledAlertInTime, noGasPriceAvailable,
  noMetaMaskAlert,
  successfulInvestmentAlert
} from '../../utils/alerts'
import { Loader } from '../Common/Loader'
import { CrowdsaleConfig } from '../Common/config'
import { CONTRACT_TYPES, INVESTMENT_OPTIONS, TOAST } from '../../utils/constants'
import { inject, observer } from 'mobx-react'
import QRPaymentProcess from './QRPaymentProcess'
import classNames from 'classnames'

@inject('contractStore', 'crowdsalePageStore', 'web3Store', 'tierStore', 'tokenStore', 'generalStore', 'investStore', 'gasPriceStore', 'generalStore')
@observer
export class Invest extends React.Component {
  constructor(props) {
    super(props)
    window.scrollTo(0, 0)

    this.state = {
      seconds: 0,
      loading: true,
      pristineTokenInput: true,
      web3Available: false,
      investThrough: INVESTMENT_OPTIONS.QR,
      crowdsaleAddress: CrowdsaleConfig.crowdsaleContractURL || getQueryVariable('addr')
    }
  }

  componentDidMount () {
    const { web3Store, contractStore, gasPriceStore, generalStore } = this.props
    const { web3 } = web3Store

    if (!web3) {
      this.setState({ loading: false })
      return
    }

    const networkID = CrowdsaleConfig.networkID ? CrowdsaleConfig.networkID : getQueryVariable('networkID')
    const contractType = CONTRACT_TYPES.whitelistwithcap
    checkNetWorkByID(networkID)
    contractStore.setContractType(contractType)

    const timeInterval = setInterval(() => this.setState({ seconds: this.state.seconds - 1 }), 1000)
    this.setState({
      timeInterval,
      web3Available: true,
      investThrough: INVESTMENT_OPTIONS.METAMASK
    })

    getWhiteListWithCapCrowdsaleAssets()
      .then(_newState => {
        this.setState(_newState)
        this.extractContractsData()
        gasPriceStore.updateValues()
          .then(() => generalStore.setGasPrice(gasPriceStore.slow.price))
          .catch(() => noGasPriceAvailable())
      })
  }

  extractContractsData() {
    const { contractStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    const crowdsaleAddr = CrowdsaleConfig.crowdsaleContractURL ? CrowdsaleConfig.crowdsaleContractURL : getQueryVariable('addr')

    if (!web3.utils.isAddress(crowdsaleAddr)) {
      this.setState({ loading: false })
      return invalidCrowdsaleAddrAlert()
    }

    getJoinedTiers(contractStore.crowdsale.abi, crowdsaleAddr, [], joinedCrowdsales => {
      console.log('joinedCrowdsales:', joinedCrowdsales)

      const crowdsaleAddrs = typeof joinedCrowdsales === 'string' ? [joinedCrowdsales] : joinedCrowdsales
      contractStore.setContractProperty('crowdsale', 'addr', crowdsaleAddrs)

      web3.eth.getAccounts().then((accounts) => {
        if (accounts.length === 0) {
          this.setState({ loading: false })
          return
        }

        this.setState({
          curAddr: accounts[0],
          web3
        })

        if (!contractStore.crowdsale.addr) {
          this.setState({ loading: false })
          return
        }

        findCurrentContractRecursively(0, null, crowdsaleContract => {
          if (!crowdsaleContract) {
            this.setState({ loading: false })
            return
          }

          initializeAccumulativeData()
            .then(() => getCrowdsaleData(crowdsaleContract))
            .then(() => getAccumulativeCrowdsaleData())
            .then(() => this.setState({ loading: false }))
            .catch(err => {
              this.setState({ loading: false })
              console.log(err)
            })

          getCrowdsaleTargetDates(this, () => {
            if (crowdsalePageStore.endDate) {
              this.setState({
                seconds: (crowdsalePageStore.endDate - new Date().getTime()) / 1000
              })
            }
          })
        })
      })
    })
  }

  investToTokens = event => {
    const { investStore, crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    event.preventDefault()

    if (!this.isValidToken(investStore.tokensToInvest)) {
      this.setState({ pristineTokenInput: false })
      return
    }

    this.setState({ loading: true })

    const startBlock = parseInt(crowdsalePageStore.startBlock, 10)
    const { startDate } = crowdsalePageStore

    if ((isNaN(startBlock) || startBlock === 0) && !startDate) {
      this.setState({ loading: false })
      return
    }

    if (web3.eth.accounts.length === 0) {
      this.setState({ loading: false })
      return noMetaMaskAlert()
    }

    this.investToTokensForWhitelistedCrowdsale()
  }

  investToTokensForWhitelistedCrowdsale() {
    const { crowdsalePageStore, web3Store } = this.props
    const { web3 } = web3Store

    if (crowdsalePageStore.startDate > (new Date()).getTime()) {
      this.setState({ loading: false })
      return investmentDisabledAlertInTime(crowdsalePageStore.startDate)
    }

    findCurrentContractRecursively(0, null, (crowdsaleContract, tierNum) => {
      if (!crowdsaleContract) {
        this.setState({ loading: false })
        return
      }

      getCurrentRate(crowdsaleContract)
        .then(() => web3.eth.getAccounts())
        .then((accounts) => this.investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, accounts))
        .catch(console.log)
    })
  }

  investToTokensForWhitelistedCrowdsaleInternal(crowdsaleContract, tierNum, accounts) {
    const { contractStore, tokenStore, crowdsalePageStore, investStore, generalStore } = this.props

    let nextTiers = []
    for (let i = tierNum + 1; i < contractStore.crowdsale.addr.length; i++) {
      nextTiers.push(contractStore.crowdsale.addr[i])
    }
    console.log('nextTiers:', nextTiers)
    console.log(nextTiers.length)

    const decimals = parseInt(tokenStore.decimals, 10)
    console.log('decimals:', decimals)

    const rate = parseInt(crowdsalePageStore.rate, 10) //it is from contract. It is already in wei. How much 1 token costs in wei.
    console.log('rate:', rate)

    const tokensToInvest = parseFloat(investStore.tokensToInvest)
    console.log('tokensToInvest:', tokensToInvest)

    const weiToSend = parseInt(tokensToInvest * rate, 10)
    console.log('weiToSend:', weiToSend)

    const opts = {
      from: accounts[0],
      value: weiToSend,
      gasPrice: generalStore.gasPrice
    }
    console.log(opts)

    crowdsaleContract.methods.buy().estimateGas(opts)
      .then(estimatedGas => {
        const estimatedGasMax = 4016260
        opts.gasLimit = !estimatedGas || estimatedGas > estimatedGasMax ? estimatedGasMax : estimatedGas + 100000

        return sendTXToContract(crowdsaleContract.methods.buy().send(opts))
      })
      .then(() => successfulInvestmentAlert(investStore.tokensToInvest))
      .catch(err => toast.showToaster({ type: TOAST.TYPE.ERROR, message: TOAST.MESSAGE.TRANSACTION_FAILED }))
      .then(() => this.setState({ loading: false }))
  }

  txMinedCallback(txHash, receipt) {
    const { investStore } = this.props

    if (receipt) {
      if (receipt.blockNumber) {
        this.setState({ loading: false })
        successfulInvestmentAlert(investStore.tokensToInvest)
      }
    } else {
      setTimeout(() => {
        checkTxMined(txHash, receipt => this.txMinedCallback(txHash, receipt))
      }, 500)
    }
  }

  tokensToInvestOnChange = event => {
    this.setState({ pristineTokenInput: false })
    this.props.investStore.setProperty('tokensToInvest', event.target.value)
  }

  isValidToken(token) {
    return +token > 0 && countDecimalPlaces(token) <= this.props.tokenStore.decimals
  }

  renderPieTracker () {
    return (

        <ReactCountdownClock
          seconds={this.state.seconds}
          color="#733EAB"
          alpha={0.9}
          size={270}
        />

    )
  }

  shouldStopCountDown () {
    if(this.state.seconds < 0) {
      this.setState({ seconds: 0 })
      clearInterval(this.state.timeInterval)
    }
  }

  getTimeStamps (seconds) {
    this.shouldStopCountDown()
    const days        = Math.floor(seconds / 24 / 60 / 60)
    const hoursLeft   = Math.floor(seconds - days * 86400)
    const hours       = Math.floor(hoursLeft / 3600)
    const minutesLeft = Math.floor(hoursLeft - hours * 3600)
    const minutes     = Math.floor(minutesLeft / 60)
    return { days, hours, minutes }
  }

  render () {
    const { crowdsalePageStore, tokenStore, contractStore, investStore } = this.props
    const { rate, tokenAmountOf, ethRaised } = crowdsalePageStore
    const { crowdsale, contractType } = contractStore
    const { tokensToInvest } = investStore

    const { seconds, curAddr, pristineTokenInput, investThrough, crowdsaleAddress, web3Available } = this.state
    const { days, hours, minutes } = this.getTimeStamps(seconds)

    const { decimals, ticker, name } = tokenStore
    const isWhitelistWithCap = contractType === CONTRACT_TYPES.whitelistwithcap

    const tokenDecimals = !isNaN(decimals) ? decimals : 0
    const tokenTicker = ticker ? ticker.toString() : ''
    const tokenName = name ? name.toString() : ''
    const supply = toBigNumber(crowdsalePageStore.supply)
    const maximumSellableTokens = toBigNumber(crowdsalePageStore.maximumSellableTokens)
    const maxCapBeforeDecimals = toBigNumber(maximumSellableTokens).div(`1e${tokenDecimals}`)
    const tokenAddress = getContractStoreProperty('token', 'addr')

    //balance: tiers, standard
    const investorBalanceTiers = tokenAmountOf ? (tokenAmountOf / 10 ** tokenDecimals).toString() : '0'
    const investorBalanceStandard = ethRaised ? (ethRaised / rate).toString() : '0'
    const investorBalance = isWhitelistWithCap ? investorBalanceTiers : investorBalanceStandard

    //total supply: tiers, standard
    const tierCap = maxCapBeforeDecimals.toFixed()
    const standardCrowdsaleSupply = supply.toFixed()
    const totalSupply = isWhitelistWithCap ? tierCap : standardCrowdsaleSupply

    let invalidTokenDescription = null
    if (!pristineTokenInput && !this.isValidToken(tokensToInvest)) {
      invalidTokenDescription = (

          Number of tokens to buy should be positive and should not exceed {decimals} decimals.

      )
    }

    const QRPaymentProcessElement = investThrough === INVESTMENT_OPTIONS.QR ?
      <QRPaymentProcess crowdsaleAddress={crowdsaleAddress} /> :
      null

    const ContributeButton = investThrough === INVESTMENT_OPTIONS.METAMASK ?
      Contribute :
      null

    const rightColumnClasses = classNames('invest-table-cell', 'invest-table-cell_right', {
      'qr-selected': investThrough === INVESTMENT_OPTIONS.QR
    })

    return

{days}

Days

{hours}

Hours

{minutes}

Mins

            {this.renderPieTracker()}

{curAddr}

Current Account

{tokenAddress}

Token Address

{crowdsale && crowdsale.addr && crowdsale.addr[0]}

Crowdsale Contract Address

{tokenName}

Name

{tokenTicker}

Ticker

{totalSupply} {tokenTicker}

Total Supply

Invest page

            {'Here you can invest in the crowdsale campaign. At the moment, you need Metamask client to invest into the crowdsale. If you don\'t have Metamask, you can send ethers to the crowdsale address with a MethodID: 0xa6f2ae3a. Sample '}
            transaction on Kovan network.

{investorBalance} {tokenTicker}

Balance

              Your balance in tokens.

          <form className="invest-form" onSubmit={this.investToTokens}>
            Choose amount to invest

              <input type="text" className="invest-form-input" value={tokensToInvest} onChange={this.tokensToInvestOnChange} placeholder="0"/>

TOKENS

              {invalidTokenDescription}

              <select value={investThrough} className="invest-through" onChange={(e) => this.setState({ investThrough: e.target.value })}>
                <option disabled={!web3Available} value={INVESTMENT_OPTIONS.METAMASK}>Metamask {!web3Available ? ' (not available)' : null}</option>
                <option value={INVESTMENT_OPTIONS.QR}>QR</option>
              </select>
              { ContributeButton }

              Think twice before contributing to Crowdsales. Tokens will be deposited on a wallet you used to buy tokens.

          </form>
          { QRPaymentProcessElement }

      <Loader show={this.state.loading}></Loader>

  }
}
<|endoftext|>


<commit_before><commit_msg>test(expenses): wait for the expense to be saved before continuing<commit_after><|endoftext|>


<commit_before>define(
  'ephox.phoenix.api.dom.DomGather',

  [
    'ephox.boss.api.DomUniverse',
    'ephox.phoenix.api.general.Gather'
  ],

  /**
   * Documentation is in the actual implementations.
   */
  function (DomUniverse, Gather) {
    var universe = DomUniverse();

    var gather = function (element, prune, transform) {
      return Gather.gather(universe, element, prune, transform);
    };

    var before = function (element, isRoot) {
      return Gather.before(universe, element, isRoot);
    };

    var after = function (element, isRoot) {
      return Gather.after(universe, element, isRoot);
    };

    var seekLeft = function (element, isRoot) {
      return Gather.seekLeft(universe, element, isRoot);
    };

    var seekRight = function (element, isRoot) {
      return Gather.seekRight(universe, element, isRoot);
    };

    var walkers = function () {
      return Gather.walkers();
    };

    var walk = function (item, mode, direction, _rules) {
      return Gather.walk(universe, item, mode, direction, _rules);
    };

    return {
      gather: gather,
      before: before,
      after: after,
      seekLeft: seekLeft,
      seekRight: seekRight,
      walkers: walkers,
      walk: walk
      // Due to exact references being required, these can't go through the DOM layer.
      // Outside modules need to be able to creates sets of rules which use the exports directly,
      // because when we are applying the rules we use a simple equality check to work out which
      // rule is which. If we delegate here, the memory address of the API rule and the internal
      // rule will be different.
      // backtrack: backtrack,
      // sidestep: sidestep,
      // advance: advance
    };
  }
);
<commit_msg>refactor DomGather seekLeft, seekRight<commit_after>define(
  'ephox.phoenix.api.dom.DomGather',

  [
    'ephox.boss.api.DomUniverse',
    'ephox.phoenix.api.general.Gather'
  ],

  /**
   * Documentation is in the actual implementations.
   */
  function (DomUniverse, Gather) {
    var universe = DomUniverse();

    var gather = function (element, prune, transform) {
      return Gather.gather(universe, element, prune, transform);
    };

    var before = function (element, isRoot) {
      return Gather.before(universe, element, isRoot);
    };

    var after = function (element, isRoot) {
      return Gather.after(universe, element, isRoot);
    };

    var seekLeft = function (element, predicate, isRoot) {
      return Gather.seekLeft(universe, element, predicate, isRoot);
    };

    var seekRight = function (element, predicate, isRoot) {
      return Gather.seekRight(universe, element, predicate, isRoot);
    };

    var walkers = function () {
      return Gather.walkers();
    };

    var walk = function (item, mode, direction, _rules) {
      return Gather.walk(universe, item, mode, direction, _rules);
    };

    return {
      gather: gather,
      before: before,
      after: after,
      seekLeft: seekLeft,
      seekRight: seekRight,
      walkers: walkers,
      walk: walk
      // Due to exact references being required, these can't go through the DOM layer.
      // Outside modules need to be able to creates sets of rules which use the exports directly,
      // because when we are applying the rules we use a simple equality check to work out which
      // rule is which. If we delegate here, the memory address of the API rule and the internal
      // rule will be different.
      // backtrack: backtrack,
      // sidestep: sidestep,
      // advance: advance
    };
  }
);
<|endoftext|>


<commit_before>'use strict';

// Add testing server to provide pages for tests
const nodeTestingServer = require('node-testing-server').nodeTestingServer;

module.exports.config = {
    useAllAngular2AppRoots: true,
    directConnect: true,
    // Set to "custom" instead of cucumber
    framework: 'custom',

    // Path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),

    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: [
                // Disable "Chrome is being controlled by automated test software" infobar
                '--disable-infobars'
            ],
            prefs: {
                // Disable Chrome's annoying password manager
                'profile.password_manager_enabled': false,
                'credentials_enable_service': false,
                'password_manager_enabled': false
            }
        }
    },

    // Spec patterns are relative to this directory
    specs: [
        'specs/**/*.feature' // accepts a glob
    ],
    cucumberOpts: {
        // Require step definitions
        require: [
            'step_definitions/**/*.js', // accepts a glob
            '../index.js',
            '../node_modules/.bin/protractor-cucumber-steps/index.js'
        ]
    },
    // Time of retries looking for angular exceeded - timeout in milliseconds
    getPageTimeout: 10000,
    // Before performing any action, Protractor waits until there are no pending
    // asynchronous tasks in your Angular application
    allScriptsTimeout: 120000,

    // Custom parameters can be specified here
    params: {
        // Path to file with all page objects
        pageObjects: require('./page_objects/index.js'),
        // Custom timeout to wait for elements on the page
        customTimeout: 5000,
        // Params for setting browser window width and height - can be also
        // changed via the command line as: --params.browserConfig.width 1024
        browserConfig: {
            width: 1280,
            height: 1024
        }
    },

    plugins: [{
        inline: {
            /*
            * Sets up plugins before tests are run. This is called after the WebDriver
            * session has been started, but before the test framework has been set up.
            *
            * @this {Object} bound to module.exports
            *
            * @throws {*} If this function throws an error, a failed assertion is added to
            *     the test results.
            *
            * @return {q.Promise=} Can return a promise, in which case protractor will wait
            *     for the promise to resolve before continuing.  If the promise is
            *     rejected, a failed assertion is added to the test results.
            */
            setup: function () {
            },
            teardown: function () {
            }
        }
    }],
    /*
    * A callback function called once configs are read but before any
    * environment setup. This will only run once, and before onPrepare.
    *
    * You can specify a file containing code to run by setting beforeLaunch to
    * the filename string.
    *
    * At this point, global variable 'protractor' object will NOT be set up,
    * and globals from the test framework will NOT be available. The main
    * purpose of this function should be to bring up test dependencies.
    */
    beforeLaunch: function () {
        // Settings for node testing server
        nodeTestingServer.config = {
            hostname: 'localhost',
            port: 8001,
            logsEnabled: 0,
            pages: {
                '/test1.html': `<title>Test1 Page</title>Test2 page

Test1 page

`,
                '/test2.html': `<title>Test2 Page</title>

Test2 page

Selected color is:

                    <select id="dropdown-colors" name="colors">
                        <option value="default color">Default color</option>
                        <option value="black">Black</option>
                        <option value="grey">Grey</option>
                        <option value="white">White</option>
                        <option value="red">Red</option>
                        <option value="crimson">Crimson</option>
                        <option value="magenta">Magenta</option>
                        <option value="blue">Blue</option>
                        <option value="aqua">Aqua</option>
                        <option value="cyan">Cyan</option>
                        <option value="indigo">Indigo</option>
                        <option value="green">Green</option>
                        <option value="yellow">Yellow</option>
                        <option value="Gold">Gold</option>
                        <option value="orange">Orange</option>
                    </select>`,
                '/test-iframe.html': `<title>Test Page with iframe</title>

Test page with iframe

Your browser does not support iframes

                    `
            }
        }
        // Start node testing server
        return nodeTestingServer.start();
    },
    /*
    * A callback function called once all tests have finished running and
    * the WebDriver instance has been shut down. It is passed the exit code
    * (0 if the tests passed). afterLaunch must return a promise if you want
    * asynchronous code to be executed before the program exits.
    * This is called only once before the program exits (after onCleanUp).
    */
    afterLaunch: function () {
        // Stop node testing server
        return Promise.resolve(nodeTestingServer.stop());
    },
    /*
    * This is called before the test have been run but after the test framework has
    * been set up.  Analogous to a config file's `onPreare`.
    *
    * Very similar to using `setup`, but allows you to access framework-specific
    * variables/funtions (e.g. `jasmine.getEnv().addReporter()`)
    *
    * @throws {*} If this function throws an error, a failed assertion is added to
    *     the test results.
    *
    * @return {Q.Promise=} Can return a promise, in which case protractor will wait
    *     for the promise to resolve before continuing.  If the promise is
    *     rejected, a failed assertion is added to the test results.
    */
    onPrepare: function () {
        // If you need to navigate to a page which does not use Angular,
        // you can turn off waiting for Angular
        browser.ignoreSynchronization = true;

        // Set custom window size for browser
        browser.driver.manage().window().setSize(
            browser.params.browserConfig.width,
            browser.params.browserConfig.height
        );
    }
};
<commit_msg>Added page for alerts testing<commit_after>'use strict';

// Add testing server to provide pages for tests
const nodeTestingServer = require('node-testing-server').nodeTestingServer;

module.exports.config = {
    useAllAngular2AppRoots: true,
    directConnect: true,
    // Set to "custom" instead of cucumber
    framework: 'custom',

    // Path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),

    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: [
                // Disable "Chrome is being controlled by automated test software" infobar
                '--disable-infobars'
            ],
            prefs: {
                // Disable Chrome's annoying password manager
                'profile.password_manager_enabled': false,
                'credentials_enable_service': false,
                'password_manager_enabled': false
            }
        }
    },

    // Spec patterns are relative to this directory
    specs: [
        'specs/**/*.feature' // accepts a glob
    ],
    cucumberOpts: {
        // Require step definitions
        require: [
            'step_definitions/**/*.js', // accepts a glob
            '../index.js',
            '../node_modules/.bin/protractor-cucumber-steps/index.js'
        ]
    },
    // Time of retries looking for angular exceeded - timeout in milliseconds
    getPageTimeout: 10000,
    // Before performing any action, Protractor waits until there are no pending
    // asynchronous tasks in your Angular application
    allScriptsTimeout: 120000,

    // Custom parameters can be specified here
    params: {
        // Path to file with all page objects
        pageObjects: require('./page_objects/index.js'),
        // Custom timeout to wait for elements on the page
        customTimeout: 5000,
        // Params for setting browser window width and height - can be also
        // changed via the command line as: --params.browserConfig.width 1024
        browserConfig: {
            width: 1280,
            height: 1024
        }
    },

    plugins: [{
        inline: {
            /*
            * Sets up plugins before tests are run. This is called after the WebDriver
            * session has been started, but before the test framework has been set up.
            *
            * @this {Object} bound to module.exports
            *
            * @throws {*} If this function throws an error, a failed assertion is added to
            *     the test results.
            *
            * @return {q.Promise=} Can return a promise, in which case protractor will wait
            *     for the promise to resolve before continuing.  If the promise is
            *     rejected, a failed assertion is added to the test results.
            */
            setup: function () {
            },
            teardown: function () {
            }
        }
    }],
    /*
    * A callback function called once configs are read but before any
    * environment setup. This will only run once, and before onPrepare.
    *
    * You can specify a file containing code to run by setting beforeLaunch to
    * the filename string.
    *
    * At this point, global variable 'protractor' object will NOT be set up,
    * and globals from the test framework will NOT be available. The main
    * purpose of this function should be to bring up test dependencies.
    */
    beforeLaunch: function () {
        // Settings for node testing server
        nodeTestingServer.config = {
            hostname: 'localhost',
            port: 8001,
            logsEnabled: 0,
            pages: {
                '/test1.html': `<title>Test1 Page</title>Test2 page

Test1 page

`,
                '/test2.html': `<title>Test2 Page</title>

Test2 page

Selected color is:

                    <select id="dropdown-colors" name="colors">
                        <option value="default color">Default color</option>
                        <option value="black">Black</option>
                        <option value="grey">Grey</option>
                        <option value="white">White</option>
                        <option value="red">Red</option>
                        <option value="crimson">Crimson</option>
                        <option value="magenta">Magenta</option>
                        <option value="blue">Blue</option>
                        <option value="aqua">Aqua</option>
                        <option value="cyan">Cyan</option>
                        <option value="indigo">Indigo</option>
                        <option value="green">Green</option>
                        <option value="yellow">Yellow</option>
                        <option value="Gold">Gold</option>
                        <option value="orange">Orange</option>
                    </select>`,
                '/test-iframe.html': `<title>Test Page with iframe</title>

Test page with iframe

Your browser does not support iframes

                    `,
                '/test-alert.html': `<title>Test Page with alert</title>

Test page with alert

                    <button id="button-launch-alert">Launch alert</button>

`
            }
        }
        // Start node testing server
        return nodeTestingServer.start();
    },
    /*
    * A callback function called once all tests have finished running and
    * the WebDriver instance has been shut down. It is passed the exit code
    * (0 if the tests passed). afterLaunch must return a promise if you want
    * asynchronous code to be executed before the program exits.
    * This is called only once before the program exits (after onCleanUp).
    */
    afterLaunch: function () {
        // Stop node testing server
        return Promise.resolve(nodeTestingServer.stop());
    },
    /*
    * This is called before the test have been run but after the test framework has
    * been set up.  Analogous to a config file's `onPreare`.
    *
    * Very similar to using `setup`, but allows you to access framework-specific
    * variables/funtions (e.g. `jasmine.getEnv().addReporter()`)
    *
    * @throws {*} If this function throws an error, a failed assertion is added to
    *     the test results.
    *
    * @return {Q.Promise=} Can return a promise, in which case protractor will wait
    *     for the promise to resolve before continuing.  If the promise is
    *     rejected, a failed assertion is added to the test results.
    */
    onPrepare: function () {
        // If you need to navigate to a page which does not use Angular,
        // you can turn off waiting for Angular
        browser.ignoreSynchronization = true;

        // Set custom window size for browser
        browser.driver.manage().window().setSize(
            browser.params.browserConfig.width,
            browser.params.browserConfig.height
        );
    }
};
<|endoftext|>