<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classSet from 'classnames';
import PageButton from './PageButton.js';
import SizePerPageDropDown from './SizePerPageDropDown';
import Const from '../Const';
import Util from '../util';

class PaginationList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      "open": this.props.open
    };
  }

  componentWillReceiveProps() {
    const { keepSizePerPageState } = this.props;
    if (!keepSizePerPageState) {
      this.setState(() => { return { "open": false }; });
    }
  }

  changePage = page => {
    const {
      pageStartIndex,
      prePage,
      currPage,
      nextPage,
      lastPage,
      firstPage,
      sizePerPage,
      keepSizePerPageState
    } = this.props;

    if (page === prePage) {
      page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1;
    } else if (page === nextPage) {
      page = currPage + 1 > this.lastPage ? this.lastPage : currPage + 1;
    } else if (page === lastPage) {
      page = this.lastPage;
    } else if (page === firstPage) {
      page = pageStartIndex;
    } else {
      page = parseInt(page, 10);
    }

    if (keepSizePerPageState) { this.setState(() => { return { "open": false }; }); }

    if (page !== currPage) {
      this.props.changePage(page, sizePerPage);
    }
  }

  changeSizePerPage = pageNum => {
    const selectSize = typeof pageNum === 'string' ? parseInt(pageNum, 10) : pageNum;
    let { currPage } = this.props;
    if (selectSize !== this.props.sizePerPage) {
      this.totalPages = Math.ceil(this.props.dataSize / selectSize);
      this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
      if (currPage > this.lastPage) {currPage = this.lastPage;}
      this.props.changePage(currPage, selectSize);
      if (this.props.onSizePerPageList) {
        this.props.onSizePerPageList(selectSize);
      }
    }

    this.setState(() => { return { "open": false }; });
  }

  toggleDropDown = () => {
    this.setState(() => {
      return {
        "open": !this.state.open
      };
    });
  }

  render() {
    const {
      currPage,
      dataSize,
      sizePerPage,
      sizePerPageList,
      paginationShowsTotal,
      pageStartIndex,
      paginationPanel,
      hidePageListOnlyOnePage
    } = this.props;
    this.totalPages = Math.ceil(dataSize / sizePerPage);
    this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
    const pageBtns = this.makePage(Util.isFunction(paginationPanel));
    const dropdown = this.makeDropDown();

    const offset = Math.abs(Const.PAGE_START_INDEX - pageStartIndex);
    let start = (currPage - pageStartIndex) * sizePerPage;
    start = dataSize === 0 ? 0 : start + 1;
    let to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize);
    if (to >= dataSize) {to--;}
    let total = paginationShowsTotal ?
      Showing rows { start } to { to + 1 } of { dataSize }
     : null;

    if (Util.isFunction(paginationShowsTotal)) {
      total = paginationShowsTotal(start, to + 1, dataSize);
    }

    const content = paginationPanel && paginationPanel({
      currPage,
      sizePerPage,
      sizePerPageList,
      pageStartIndex,
      "changePage": this.changePage,
      "toggleDropDown": this.toggleDropDown,
      "changeSizePerPage": this.changeSizePerPage,
      "components": {
        "totalText": total,
        "sizePerPageDropdown": dropdown,
        "pageList": pageBtns
      }
    });

    const hidePageList = hidePageListOnlyOnePage && this.totalPages === 1 ? 'none' : 'block';
    return (

        {
          content ||

              { total }{ sizePerPageList.length > 1 ? dropdown : null }

              { pageBtns }

        }

    );
  }

  makeDropDown() {
    let dropdown;
    let dropdownProps;
    let sizePerPageText = '';
    const {
      sizePerPageDropDown,
      hideSizePerPage,
      sizePerPage,
      sizePerPageList
    } = this.props;
    if (sizePerPageDropDown) {
      dropdown = sizePerPageDropDown({
        "open": this.state.open,
        hideSizePerPage,
        "currSizePerPage": String(sizePerPage),
        sizePerPageList,
        "toggleDropDown": this.toggleDropDown,
        "changeSizePerPage": this.changeSizePerPage
      });
      if (dropdown.type.name === SizePerPageDropDown.name) {
        dropdownProps = dropdown.props;
      } else {
        return dropdown;
      }
    }

    if (dropdownProps || !dropdown) {
      const sizePerPageOptions = sizePerPageList.map((_sizePerPage) => {
        const pageText = _sizePerPage.text || _sizePerPage;
        const pageNum = _sizePerPage.value || _sizePerPage;
        if (sizePerPage === pageNum) {sizePerPageText = pageText;}
        return (

             {
                e.preventDefault();
                this.changeSizePerPage(pageNum);
              }}>{ pageText }

        );
      });
      dropdown =
        <SizePerPageDropDown
          open={this.state.open}
          hidden={hideSizePerPage}
          currSizePerPage={String(sizePerPageText)}
          options={sizePerPageOptions}
          onClick={this.toggleDropDown}
          {...dropdownProps}/>
      ;
    }
    return dropdown;
  }

  makePage(isCustomPagingPanel = false) {
    const pages = this.getPages();
    const isStart = (page, { currPage, pageStartIndex, firstPage, prePage }) =>
      currPage === pageStartIndex && (page === firstPage || page === prePage);
    const isEnd = (page, { currPage, nextPage, lastPage }) =>
      currPage === this.lastPage && (page === nextPage || page === lastPage );
    const pageBtns = pages
      .filter(function(page) {
        if (this.props.alwaysShowAllBtns) {
          return true;
        }
        return isStart(page, this.props) || isEnd(page, this.props) ?
          false :
          true;
      }, this)
      .map(function(page) {
        const isActive = page === this.props.currPage;
        const isDisabled = isStart(page, this.props) || isEnd(page, this.props) ?
          true :
          false;
        let title = page + '';

        if (page === this.props.nextPage) {
          title = this.props.nextPageTitle;
        } else if (page === this.props.prePage) {
          title = this.props.prePageTitle;
        } else if (page === this.props.firstPage) {
          // title = this.props.firstPageTitle;
          console.log("FirstPage: ", page);
        } else if (page === this.props.lastPage) {
          title = this.props.lastPageTitle;
        }

        console.log("Page: ", page);

        return (
          <PageButton key={page}
            title={title}
            changePage={this.changePage}
            active={isActive}
            disable={isDisabled}>
            { page }
          </PageButton>
        );
      }, this);
    const classname = classSet(
      isCustomPagingPanel ? null : 'react-bootstrap-table-page-btns-ul',
      'pagination'
    );
    return (

          { pageBtns }

      );
  }

  getLastPage() {
    return this.lastPage;
  }

  getPages() {
    let pages;
    let endPage = this.totalPages;
    if (endPage <= 0) {return [];}
    let startPage = Math.max(
      this.props.currPage - Math.floor(this.props.paginationSize / 2),
      this.props.pageStartIndex
    );
    endPage = startPage + this.props.paginationSize - 1;

    if (endPage > this.lastPage) {
      endPage = this.lastPage;
      startPage = endPage - this.props.paginationSize + 1;
    }

    if (startPage !== this.props.pageStartIndex
      && this.totalPages > this.props.paginationSize
      && this.props.withFirstAndLast) {
      pages = [ this.props.firstPage, this.props.prePage ];
    } else if (this.totalPages > 1 || this.props.alwaysShowAllBtns) {
      pages = [ this.props.prePage ];
    } else {
      pages = [];
    }

    for (let i = startPage; i <= endPage; i++) {
      if (i >= this.props.pageStartIndex) {pages.push(i);}
    }

    if (endPage <= this.lastPage && pages.length > 1) {
      pages.push(this.props.nextPage);
    }
    if (endPage !== this.lastPage && this.props.withFirstAndLast) {
      pages.push(this.props.lastPage);
    }

    console.log("Pages: ", pages);

    return pages;
  }
}
PaginationList.propTypes = {
  "currPage": PropTypes.number,
  "sizePerPage": PropTypes.number,
  "dataSize": PropTypes.number,
  "changePage": PropTypes.func,
  "sizePerPageList": PropTypes.array,
  "paginationShowsTotal": PropTypes.oneOfType([ PropTypes.bool, PropTypes.func ]),
  "paginationSize": PropTypes.number,
  "onSizePerPageList": PropTypes.func,
  "prePage": PropTypes.string,
  "pageStartIndex": PropTypes.number,
  "hideSizePerPage": PropTypes.bool,
  "alwaysShowAllBtns": PropTypes.bool,
  "withFirstAndLast": PropTypes.bool,
  "sizePerPageDropDown": PropTypes.func,
  "paginationPanel": PropTypes.func,
  "prePageTitle": PropTypes.string,
  "nextPageTitle": PropTypes.string,
  "firstPageTitle": PropTypes.string,
  "lastPageTitle": PropTypes.string,
  "hidePageListOnlyOnePage": PropTypes.bool,
  "keepSizePerPageState": PropTypes.bool
};

PaginationList.defaultProps = {
  "sizePerPage": Const.SIZE_PER_PAGE,
  "pageStartIndex": Const.PAGE_START_INDEX
};

export default PaginationList;<commit_msg>Remove console logs and uncomment code.<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classSet from 'classnames';
import PageButton from './PageButton.js';
import SizePerPageDropDown from './SizePerPageDropDown';
import Const from '../Const';
import Util from '../util';

class PaginationList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      "open": this.props.open
    };
  }

  componentWillReceiveProps() {
    const { keepSizePerPageState } = this.props;
    if (!keepSizePerPageState) {
      this.setState(() => { return { "open": false }; });
    }
  }

  changePage = page => {
    const {
      pageStartIndex,
      prePage,
      currPage,
      nextPage,
      lastPage,
      firstPage,
      sizePerPage,
      keepSizePerPageState
    } = this.props;

    if (page === prePage) {
      page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1;
    } else if (page === nextPage) {
      page = currPage + 1 > this.lastPage ? this.lastPage : currPage + 1;
    } else if (page === lastPage) {
      page = this.lastPage;
    } else if (page === firstPage) {
      page = pageStartIndex;
    } else {
      page = parseInt(page, 10);
    }

    if (keepSizePerPageState) { this.setState(() => { return { "open": false }; }); }

    if (page !== currPage) {
      this.props.changePage(page, sizePerPage);
    }
  }

  changeSizePerPage = pageNum => {
    const selectSize = typeof pageNum === 'string' ? parseInt(pageNum, 10) : pageNum;
    let { currPage } = this.props;
    if (selectSize !== this.props.sizePerPage) {
      this.totalPages = Math.ceil(this.props.dataSize / selectSize);
      this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
      if (currPage > this.lastPage) {currPage = this.lastPage;}
      this.props.changePage(currPage, selectSize);
      if (this.props.onSizePerPageList) {
        this.props.onSizePerPageList(selectSize);
      }
    }

    this.setState(() => { return { "open": false }; });
  }

  toggleDropDown = () => {
    this.setState(() => {
      return {
        "open": !this.state.open
      };
    });
  }

  render() {
    const {
      currPage,
      dataSize,
      sizePerPage,
      sizePerPageList,
      paginationShowsTotal,
      pageStartIndex,
      paginationPanel,
      hidePageListOnlyOnePage
    } = this.props;
    this.totalPages = Math.ceil(dataSize / sizePerPage);
    this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
    const pageBtns = this.makePage(Util.isFunction(paginationPanel));
    const dropdown = this.makeDropDown();

    const offset = Math.abs(Const.PAGE_START_INDEX - pageStartIndex);
    let start = (currPage - pageStartIndex) * sizePerPage;
    start = dataSize === 0 ? 0 : start + 1;
    let to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize);
    if (to >= dataSize) {to--;}
    let total = paginationShowsTotal ?
      Showing rows { start } to { to + 1 } of { dataSize }
     : null;

    if (Util.isFunction(paginationShowsTotal)) {
      total = paginationShowsTotal(start, to + 1, dataSize);
    }

    const content = paginationPanel && paginationPanel({
      currPage,
      sizePerPage,
      sizePerPageList,
      pageStartIndex,
      "changePage": this.changePage,
      "toggleDropDown": this.toggleDropDown,
      "changeSizePerPage": this.changeSizePerPage,
      "components": {
        "totalText": total,
        "sizePerPageDropdown": dropdown,
        "pageList": pageBtns
      }
    });

    const hidePageList = hidePageListOnlyOnePage && this.totalPages === 1 ? 'none' : 'block';
    return (

        {
          content ||

              { total }{ sizePerPageList.length > 1 ? dropdown : null }

              { pageBtns }

        }

    );
  }

  makeDropDown() {
    let dropdown;
    let dropdownProps;
    let sizePerPageText = '';
    const {
      sizePerPageDropDown,
      hideSizePerPage,
      sizePerPage,
      sizePerPageList
    } = this.props;
    if (sizePerPageDropDown) {
      dropdown = sizePerPageDropDown({
        "open": this.state.open,
        hideSizePerPage,
        "currSizePerPage": String(sizePerPage),
        sizePerPageList,
        "toggleDropDown": this.toggleDropDown,
        "changeSizePerPage": this.changeSizePerPage
      });
      if (dropdown.type.name === SizePerPageDropDown.name) {
        dropdownProps = dropdown.props;
      } else {
        return dropdown;
      }
    }

    if (dropdownProps || !dropdown) {
      const sizePerPageOptions = sizePerPageList.map((_sizePerPage) => {
        const pageText = _sizePerPage.text || _sizePerPage;
        const pageNum = _sizePerPage.value || _sizePerPage;
        if (sizePerPage === pageNum) {sizePerPageText = pageText;}
        return (

             {
                e.preventDefault();
                this.changeSizePerPage(pageNum);
              }}>{ pageText }

        );
      });
      dropdown =
        <SizePerPageDropDown
          open={this.state.open}
          hidden={hideSizePerPage}
          currSizePerPage={String(sizePerPageText)}
          options={sizePerPageOptions}
          onClick={this.toggleDropDown}
          {...dropdownProps}/>
      ;
    }
    return dropdown;
  }

  makePage(isCustomPagingPanel = false) {
    const pages = this.getPages();
    const isStart = (page, { currPage, pageStartIndex, firstPage, prePage }) =>
      currPage === pageStartIndex && (page === firstPage || page === prePage);
    const isEnd = (page, { currPage, nextPage, lastPage }) =>
      currPage === this.lastPage && (page === nextPage || page === lastPage );
    const pageBtns = pages
      .filter(function(page) {
        if (this.props.alwaysShowAllBtns) {
          return true;
        }
        return isStart(page, this.props) || isEnd(page, this.props) ?
          false :
          true;
      }, this)
      .map(function(page) {
        const isActive = page === this.props.currPage;
        const isDisabled = isStart(page, this.props) || isEnd(page, this.props) ?
          true :
          false;
        let title = page + '';

        if (page === this.props.nextPage) {
          title = this.props.nextPageTitle;
        } else if (page === this.props.prePage) {
          title = this.props.prePageTitle;
        } else if (page === this.props.firstPage) {
          title = this.props.firstPageTitle;
        } else if (page === this.props.lastPage) {
          title = this.props.lastPageTitle;
        }

        return (
          <PageButton key={page}
            title={title}
            changePage={this.changePage}
            active={isActive}
            disable={isDisabled}>
            { page }
          </PageButton>
        );
      }, this);
    const classname = classSet(
      isCustomPagingPanel ? null : 'react-bootstrap-table-page-btns-ul',
      'pagination'
    );
    return (

          { pageBtns }

      );
  }

  getLastPage() {
    return this.lastPage;
  }

  getPages() {
    let pages;
    let endPage = this.totalPages;
    if (endPage <= 0) {return [];}
    let startPage = Math.max(
      this.props.currPage - Math.floor(this.props.paginationSize / 2),
      this.props.pageStartIndex
    );
    endPage = startPage + this.props.paginationSize - 1;

    if (endPage > this.lastPage) {
      endPage = this.lastPage;
      startPage = endPage - this.props.paginationSize + 1;
    }

    if (startPage !== this.props.pageStartIndex
      && this.totalPages > this.props.paginationSize
      && this.props.withFirstAndLast) {
      pages = [ this.props.firstPage, this.props.prePage ];
    } else if (this.totalPages > 1 || this.props.alwaysShowAllBtns) {
      pages = [ this.props.prePage ];
    } else {
      pages = [];
    }

    for (let i = startPage; i <= endPage; i++) {
      if (i >= this.props.pageStartIndex) {pages.push(i);}
    }

    if (endPage <= this.lastPage && pages.length > 1) {
      pages.push(this.props.nextPage);
    }
    if (endPage !== this.lastPage && this.props.withFirstAndLast) {
      pages.push(this.props.lastPage);
    }

    return pages;
  }
}
PaginationList.propTypes = {
  "currPage": PropTypes.number,
  "sizePerPage": PropTypes.number,
  "dataSize": PropTypes.number,
  "changePage": PropTypes.func,
  "sizePerPageList": PropTypes.array,
  "paginationShowsTotal": PropTypes.oneOfType([ PropTypes.bool, PropTypes.func ]),
  "paginationSize": PropTypes.number,
  "onSizePerPageList": PropTypes.func,
  "prePage": PropTypes.string,
  "pageStartIndex": PropTypes.number,
  "hideSizePerPage": PropTypes.bool,
  "alwaysShowAllBtns": PropTypes.bool,
  "withFirstAndLast": PropTypes.bool,
  "sizePerPageDropDown": PropTypes.func,
  "paginationPanel": PropTypes.func,
  "prePageTitle": PropTypes.string,
  "nextPageTitle": PropTypes.string,
  "firstPageTitle": PropTypes.string,
  "lastPageTitle": PropTypes.string,
  "hidePageListOnlyOnePage": PropTypes.bool,
  "keepSizePerPageState": PropTypes.bool
};

PaginationList.defaultProps = {
  "sizePerPage": Const.SIZE_PER_PAGE,
  "pageStartIndex": Const.PAGE_START_INDEX
};

export default PaginationList;
<|endoftext|>


<commit_before>/* @flow strict-local */
import { connect } from 'react-redux';
import React, { PureComponent } from 'react';
import type { ComponentType, ElementConfig } from 'react';
import { Text } from 'react-native';
import { IntlProvider } from 'react-intl';
import type { IntlShape } from 'react-intl';

import type { ChildrenArray, GetText, GlobalState } from '../types';
import { getSettings } from '../selectors';
import '../../vendor/intl/intl';
import messages from '../i18n/messages';

import '../i18n/locale';

/* eslint-disable react/no-multi-comp */

// $FlowFixMe could put a well-typed mock value here, to help write tests
export const TranslationContext = React.createContext(undefined);

/**
 * Provide `_` to the wrapped component, passing other props through.
 *
 * This is useful when the component is already using its `context` property
 * for the legacy context API.  When that isn't the case, simply saying
 * `context: TranslationContext` may be more convenient.
 */
export function withGetText<P: { _: GetText }, C: ComponentType<P>>(
  WrappedComponent: C,
): ComponentType<{ _: GetText, ...ElementConfig<C> }> {
  return class extends React.Component<ElementConfig<C>> {
    render() {
      return (
        <TranslationContext.Consumer>
          {_ => <WrappedComponent _={_} {...this.props} />}
        </TranslationContext.Consumer>
      );
    }
  };
}

const makeGetText = (intl: IntlShape): GetText => {
  const _ = value => intl.formatMessage({ id: value });
  _.intl = intl;
  return _;
};

/**
 * Consume the old-API context from IntlProvider, and provide a new-API context.
 *
 * This consumes the context provided by react-intl through React's
 * "legacy context API" from before 16.3, and provides a context through the
 * new API.
 *
 * See https://reactjs.org/docs/context.html
 * vs. https://reactjs.org/docs/legacy-context.html .
 */
class TranslationContextTranslator extends PureComponent<{
  children: ChildrenArray<*>,
}> {
  context: { intl: IntlShape };

  static contextTypes = {
    intl: () => null,
  };

  _ = makeGetText(this.context.intl);

  render() {
    return (
      <TranslationContext.Provider value={this._}>
        {this.props.children}
      </TranslationContext.Provider>
    );
  }
}

type Props = {|
  locale: string,
  children: ChildrenArray<*>,
|};

class TranslationProvider extends PureComponent<Props> {
  render() {
    const { locale, children } = this.props;

    return (
      /* `IntlProvider` uses React's "legacy context API", deprecated since
       * React 16.3, of which the docs say:
       *
       *   ## Updating Context
       *
       *   Don't do it.
       *
       *   React has an API to update context, but it is fundamentally
       *   broken and you should not use it.
       *
       * To work around that, we set `key={locale}` to force the whole tree
       * to rerender if the locale changes.  Not cheap, but the locale
       * changing is rare.
       */
      <IntlProvider key={locale} locale={locale} textComponent={Text} messages={messages[locale]}>
        <TranslationContextTranslator>{children}</TranslationContextTranslator>
      </IntlProvider>
    );
  }
}

export default connect((state: GlobalState) => ({
  locale: getSettings(state).locale,
}))(TranslationProvider);
<commit_msg>i18n: Fix type signature of withGetText.<commit_after>/* @flow strict-local */
import { connect } from 'react-redux';
import React, { PureComponent } from 'react';
import type { ComponentType, ElementConfig } from 'react';
import { Text } from 'react-native';
import { IntlProvider } from 'react-intl';
import type { IntlShape } from 'react-intl';

import type { ChildrenArray, GetText, GlobalState } from '../types';
import { getSettings } from '../selectors';
import '../../vendor/intl/intl';
import messages from '../i18n/messages';

import '../i18n/locale';

/* eslint-disable react/no-multi-comp */

// $FlowFixMe could put a well-typed mock value here, to help write tests
export const TranslationContext = React.createContext(undefined);

/**
 * Provide `_` to the wrapped component, passing other props through.
 *
 * This is useful when the component is already using its `context` property
 * for the legacy context API.  When that isn't the case, simply saying
 * `context: TranslationContext` may be more convenient.
 */
export function withGetText<P: { _: GetText }, C: ComponentType<P>>(
  WrappedComponent: C,
): ComponentType<$Diff<ElementConfig<C>, { _: GetText }>> {
  return class extends React.Component<ElementConfig<C>> {
    render() {
      return (
        <TranslationContext.Consumer>
          {_ => <WrappedComponent _={_} {...this.props} />}
        </TranslationContext.Consumer>
      );
    }
  };
}

const makeGetText = (intl: IntlShape): GetText => {
  const _ = value => intl.formatMessage({ id: value });
  _.intl = intl;
  return _;
};

/**
 * Consume the old-API context from IntlProvider, and provide a new-API context.
 *
 * This consumes the context provided by react-intl through React's
 * "legacy context API" from before 16.3, and provides a context through the
 * new API.
 *
 * See https://reactjs.org/docs/context.html
 * vs. https://reactjs.org/docs/legacy-context.html .
 */
class TranslationContextTranslator extends PureComponent<{
  children: ChildrenArray<*>,
}> {
  context: { intl: IntlShape };

  static contextTypes = {
    intl: () => null,
  };

  _ = makeGetText(this.context.intl);

  render() {
    return (
      <TranslationContext.Provider value={this._}>
        {this.props.children}
      </TranslationContext.Provider>
    );
  }
}

type Props = {|
  locale: string,
  children: ChildrenArray<*>,
|};

class TranslationProvider extends PureComponent<Props> {
  render() {
    const { locale, children } = this.props;

    return (
      /* `IntlProvider` uses React's "legacy context API", deprecated since
       * React 16.3, of which the docs say:
       *
       *   ## Updating Context
       *
       *   Don't do it.
       *
       *   React has an API to update context, but it is fundamentally
       *   broken and you should not use it.
       *
       * To work around that, we set `key={locale}` to force the whole tree
       * to rerender if the locale changes.  Not cheap, but the locale
       * changing is rare.
       */
      <IntlProvider key={locale} locale={locale} textComponent={Text} messages={messages[locale]}>
        <TranslationContextTranslator>{children}</TranslationContextTranslator>
      </IntlProvider>
    );
  }
}

export default connect((state: GlobalState) => ({
  locale: getSettings(state).locale,
}))(TranslationProvider);
<|endoftext|>


<commit_before>var notifier = require('node-notifier');
var argv = require('yargs').argv;

module.exports = (function () {
    var projectName = "novicell-gulp";

    var projectPath = "./";
    var bowerPath = projectPath + "vendor/bower";
    var distPath = projectPath + "dist";

    var cleanPaths = [distPath];

    var debug = true;

    return {
        debug: (argv.debug !== undefined ? argv.debug == "true" : debug),

        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    "title": taskName,
                    "message": "An error occured in the " + e.plugin + " plugin."
                });
                console.log(e.message);
                this.emit("end");
            };
        },

        bowerPath: bowerPath,
        cleanPaths: cleanPaths,

        loadTasks: [
            "bower", "styles", "scripts",
            "images", "icons", "copy",
            "watch", "build", "html2js"
        ],
        buildTasks: [
            "bower", "styles", "scripts",
            "images", "icons", "copy",
            "html2js"
        ],

        // ------------- Scripts -------------
        scriptsDist: distPath + "/scripts",

        // ------------- Icons -------------
        iconsDist: distPath + "/images/icons",

        // ------------- Fonts -------------
        fontsDist: distPath + "/fonts",

        // ------------- Styles -------------
        stylesDist: distPath + "/css",
        stylesVendorPrefixes: [
            "last 2 version",
            "safari 5",
            "ie 8",
            "ie 9",
            "opera 12.1",
            "ios 6",
            "android 4"
        ],

        // ------------- Images -------------
        imagesDist: distPath + "/images",
        imagesOptimizationLevel: 5,
        imagesProgressive: true,
        imagesInterlaced: true,

        // ------------- Livereload -------------
        livereloadPort: 35729,
        livereloadPaths: [
            "./dist/scripts/*.js",
            "./dist/css/*.css",
            "./macroScripts/*.{cshtml,master,xslt,php,phtml,html}",
            "./MasterPages/*.{cshtml,master,xslt,php,phtml,html}"
        ],

        // ------------- Watch -------------
        watchImages: ["./images/*"],
        watchIcons: ["./images/icons/*"],
        watchFonts: ["./fonts/*"],
        watchScripts: [
            "./scripts/**/*.js",
            "./vendor/**/*.js"
        ],
        watchStyles: [
            "./less/**/*.less",
            "./vendor/**/*.less"
        ],

        // ------------- Copy on build -------------
        buildCopy: [{
            from: "./fonts/**/*",
            to: distPath  + "/fonts"
        }],

        // ------------- Bundles -------------
        bundles: [{
            name: "vendor",
            ignorePlugins: ["jscs", "jshint"],
            scripts: ["./vendor/bower/jquery/dist/jquery.js" ]
        },
        {
            name: "master",
            scripts: ["./scripts/master.js"],
            styles: ["./less/master.less"],
            images: ["./images/*.{jpg,png}"],
            icons: ["./images/icons/*.svg"],
            tpl: [ "./tpl/*.tpl.html" ]
        }]
    }
})();<commit_msg>case 60766: debug arg to lowercase.<commit_after>var notifier = require('node-notifier');
var argv = require('yargs').argv;

module.exports = (function () {
    var projectName = "novicell-gulp";

    var projectPath = "./";
    var bowerPath = projectPath + "vendor/bower";
    var distPath = projectPath + "dist";

    var cleanPaths = [distPath];

    var debug = true;

    return {
        debug: (argv.debug !== undefined ? argv.debug.toLowerCase() == "true" : debug),

        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    "title": taskName,
                    "message": "An error occured in the " + e.plugin + " plugin."
                });
                console.log(e.message);
                this.emit("end");
            };
        },

        bowerPath: bowerPath,
        cleanPaths: cleanPaths,

        loadTasks: [
            "bower", "styles", "scripts",
            "images", "icons", "copy",
            "watch", "build", "html2js"
        ],
        buildTasks: [
            "bower", "styles", "scripts",
            "images", "icons", "copy",
            "html2js"
        ],

        // ------------- Scripts -------------
        scriptsDist: distPath + "/scripts",

        // ------------- Icons -------------
        iconsDist: distPath + "/images/icons",

        // ------------- Fonts -------------
        fontsDist: distPath + "/fonts",

        // ------------- Styles -------------
        stylesDist: distPath + "/css",
        stylesVendorPrefixes: [
            "last 2 version",
            "safari 5",
            "ie 8",
            "ie 9",
            "opera 12.1",
            "ios 6",
            "android 4"
        ],

        // ------------- Images -------------
        imagesDist: distPath + "/images",
        imagesOptimizationLevel: 5,
        imagesProgressive: true,
        imagesInterlaced: true,

        // ------------- Livereload -------------
        livereloadPort: 35729,
        livereloadPaths: [
            "./dist/scripts/*.js",
            "./dist/css/*.css",
            "./macroScripts/*.{cshtml,master,xslt,php,phtml,html}",
            "./MasterPages/*.{cshtml,master,xslt,php,phtml,html}"
        ],

        // ------------- Watch -------------
        watchImages: ["./images/*"],
        watchIcons: ["./images/icons/*"],
        watchFonts: ["./fonts/*"],
        watchScripts: [
            "./scripts/**/*.js",
            "./vendor/**/*.js"
        ],
        watchStyles: [
            "./less/**/*.less",
            "./vendor/**/*.less"
        ],

        // ------------- Copy on build -------------
        buildCopy: [{
            from: "./fonts/**/*",
            to: distPath  + "/fonts"
        }],

        // ------------- Bundles -------------
        bundles: [{
            name: "vendor",
            ignorePlugins: ["jscs", "jshint"],
            scripts: ["./vendor/bower/jquery/dist/jquery.js" ]
        },
        {
            name: "master",
            scripts: ["./scripts/master.js"],
            styles: ["./less/master.less"],
            images: ["./images/*.{jpg,png}"],
            icons: ["./images/icons/*.svg"],
            tpl: [ "./tpl/*.tpl.html" ]
        }]
    }
})();<|endoftext|>


<commit_before>import React from 'react';
import ItemLink from 'common/ItemLink';
import ITEM_QUALITIES from 'common/ITEM_QUALITIES';

import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

// Make sure to push this once we get to 1000!
const MAX_LEGENDARY_ILVL = 970;
const debug = false;

class LegendaryUpgradeChecker extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  suggestions(when) {
    const slots = this.combatants.selected._gearItemsBySlotId;
    Object.values(slots)
      .filter(item => item.quality === ITEM_QUALITIES.LEGENDARY)
      .forEach(item => {
        debug && console.log(`Legendary ${item.id} is ${item.itemLevel}`);

        when(item.itemLevel).isLessThan(MAX_LEGENDARY_ILVL)
          .addSuggestion((suggest, actual, recommended) => {
            return suggest(<ItemLink id={item.id} /> is not the maximum item level it can be. You should upgrade <ItemLink id={item.id} /> to the maximum item level for legendaries.)
              .icon(item.icon)
              .actual(`It's currently ${actual}`)
              .recommended(`the current maximum is ${recommended}`)
              .staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
          });
      });
  }
}

export default LegendaryUpgradeChecker;
<commit_msg>updated leggo ilvl to 1000<commit_after>import React from 'react';
import ItemLink from 'common/ItemLink';
import ITEM_QUALITIES from 'common/ITEM_QUALITIES';

import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

// Make sure to push this once we get to 1000!
const MAX_LEGENDARY_ILVL = 1000;
const debug = false;

class LegendaryUpgradeChecker extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  suggestions(when) {
    const slots = this.combatants.selected._gearItemsBySlotId;
    Object.values(slots)
      .filter(item => item.quality === ITEM_QUALITIES.LEGENDARY)
      .forEach(item => {
        debug && console.log(`Legendary ${item.id} is ${item.itemLevel}`);

        when(item.itemLevel).isLessThan(MAX_LEGENDARY_ILVL)
          .addSuggestion((suggest, actual, recommended) => {
            return suggest(<ItemLink id={item.id} /> is not the maximum item level it can be. You should upgrade <ItemLink id={item.id} /> to the maximum item level for legendaries.)
              .icon(item.icon)
              .actual(`It's currently ${actual}`)
              .recommended(`the current maximum is ${recommended}`)
              .staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
          });
      });
  }
}

export default LegendaryUpgradeChecker;
<|endoftext|>


<commit_before>'use strict';

var	  byline     = require("byline"),
      fs         = require("fs"),
      utils      = require(__dirname+'/utils.js'),
      staff      = require(__dirname+'/staff.js');

var Parser = function Parser() {};

Parser.prototype.getSections = function(params, callback){

  var stream          = byline(fs.createReadStream(params.dxfPath, { encoding: 'utf8' })),
      sectionNameTab  = ['HEADER', 'CLASSES', 'TABLES', 'BLOCKS', 'ENTITIES', 'OBJECTS', 'THUMBNAILIMAGE'],
      sectionCur      = '',
      dxfTab          = [],
      section         = false,
      endsec          = false;

  stream.on('data', function(line) {

    if (sectionNameTab.indexOf(line) != -1){
      sectionCur = line.toLowerCase();
      section = true;
      dxfTab[sectionCur] = [];
      endsec = false;
    }
    else if (section == true){
        if (line == 'ENDSEC') {
          endsec=true;
          section=false;
          sectionCur = '';
        }
        else if (endsec == false) {
          dxfTab[sectionCur].push(line);
        }
      }
  });
  stream.on('end', function(){
    if(params.sectionName != null){
      callback(dxfTab[params.sectionName]);
    }
    else{
      callback(dxfTab);
    }
  });
}

Parser.prototype.getPolygons = function (sectionTab){
  var polygons    = [],
      countPoly   = 0,
      lwpolyline  = false;

  sectionTab.forEach(function (line, li){
    if(line == 'LWPOLYLINE'){
      lwpolyline = true;
      polygons[countPoly] = {pInd : countPoly, layer : null, nPoint : null, points: []};
    }
    else if(lwpolyline == true && line == '  8') polygons[countPoly].layer=sectionTab[li+1];
    else if(lwpolyline == true && line == ' 90') polygons[countPoly].nPoint=parseInt(sectionTab[li+1]);
    else if(lwpolyline == true && line == ' 10') polygons[countPoly].points.push(new utils.point(parseFloat(sectionTab[li+1]), parseFloat(sectionTab[li+3])));
    else if(lwpolyline == true && polygons[countPoly].points.length === polygons[countPoly].nPoint){
      lwpolyline=false;
      countPoly++;
    }
  });

  return polygons;
}

Parser.prototype.getTexts = function (sectionTab){
  var texts       = [],
      countTexts  = 0,
      text        = false;

  sectionTab.forEach(function (line, li){
    if(line == 'TEXT' || line == 'MTEXT'){
        text = true;
        texts[countTexts] = {tInd : countTexts, layer : null, txt : null, point : null};
      }
    else if(text == true && line == '  8') texts[countTexts].layer = sectionTab[li+1];
	  else if(text == true && line == ' 10') texts[countTexts].point = new utils.point(parseFloat(sectionTab[li+1]), parseFloat(sectionTab[li+3]));
	  else if(text == true && line == '  1') texts[countTexts].txt = sectionTab[li+1];
	  else if(text == true && texts[countTexts].point != null && texts[countTexts].txt != null){
	    text=false;
	    countTexts++;
	  }
  });

  return texts;
}

Parser.prototype.getLayers = function (sectionTab){
  var layers  = [],
      tab     = ['LWPOLYLINE', 'TEXT', 'MTEXT'],
      get     = false;

  sectionTab.forEach(function (line, li){
    if(tab.indexOf(line) != -1){
      get = true;
    }
    else if(get == true && line == '  8'){
      if(layers.indexOf(sectionTab[li+1]) == -1) layers.push(sectionTab[li+1]);
    }
  });

  return layers;
}

Parser.prototype.getMappings = function (texts, polygons){
  var mapping=[], textsAlone= texts;

  texts.forEach(function (text, t){
    polygons.forEach(function (polygon, p){
      if(utils.pnpoly(polygon.points, text.point)){
        if(!mapping[p]) {
          mapping[p] = {polygon : polygon, nText : 1 ,texts : [text]};
          textsAlone = utils.unset(textsAlone, text);
        }
        else{
          mapping[p].texts.push(text);
          mapping[p].nText=mapping[p].nText+1;
          textsAlone = utils.unset(textsAlone, text);
        }
      }
    });
  });
  return {map : mapping, textsAlone : textsAlone};
}

Parser.prototype.getDimension = function (polygons){
  var minPoint = new utils.point(0,0),
      maxPoint = new utils.point(0,0),
      dim = {};

  polygons.forEach(function (polygon, p) {
    polygon.points.forEach(function (tpoint, i) {
      minPoint.x = tpoint.x < minPoint.x ? tpoint.x : (i === 0 && p === 0 ? tpoint.x : minPoint.x);
      minPoint.y = tpoint.y < minPoint.y ? tpoint.y : (i === 0 && p === 0 ? tpoint.y : minPoint.y);
      maxPoint.x = tpoint.x > maxPoint.x ? tpoint.x : (i === 0 && p === 0 ? tpoint.x : maxPoint.x);
      maxPoint.y = tpoint.y > maxPoint.y ? tpoint.y : (i === 0 && p === 0 ? tpoint.y : maxPoint.y);
    });
  });
  return dim = {'min': minPoint,
                'max': maxPoint,}
}

Parser.prototype.splitPoly = function (mappings, polygons){

  mappings.forEach(function (mapping, mti){

    var newPoint    = new utils.point(0,0), newPoint1 = new utils.point(0,0),
        newPoint2   = new utils.point(0,0), newPoint3 = new utils.point(0,0),
        fourthPoint = new utils.point(0,0), fourthPoint1 = new utils.point(0,0),
        center      = new utils.point(0,0),
        newPolygons = [], tabNearestPoints = [], tabPolyPointsTmp = [];

    if(mapping.polygon.nPoint===4 && mapping.nText===2){

      tabPolyPointsTmp=mapping.polygon.points;

      (mapping.texts).forEach(function (text, ti){
        tabNearestPoints[ti] = staff.findNearestPoint(mapping.polygon.points, text.point);
        tabPolyPointsTmp=utils.unset(tabPolyPointsTmp, tabNearestPoints[ti]);
      });
      if (tabNearestPoints[0]!==tabNearestPoints[1]){
        newPoint.x=(tabNearestPoints[0].x+tabNearestPoints[1].x)/2;
        newPoint.y=(tabNearestPoints[0].y+tabNearestPoints[1].y)/2;
        newPoint1.x=(tabPolyPointsTmp[0].x+tabPolyPointsTmp[1].x)/2;
        newPoint1.y=(tabPolyPointsTmp[0].y+tabPolyPointsTmp[1].y)/2;
        fourthPoint=staff.findNearestPoint(tabPolyPointsTmp, tabNearestPoints[0]);
        fourthPoint1=staff.findNearestPoint(tabPolyPointsTmp, tabNearestPoints[1]);

        newPolygons[0]=[newPoint, tabNearestPoints[0], fourthPoint, newPoint1];
        newPolygons[1]=[newPoint, tabNearestPoints[1], fourthPoint1, newPoint1];

        polygons=utils.unset(polygons, {pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: mapping.polygon.points});
        polygons.push({pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[0]});
        polygons.push({pInd : mapping.polygon.pInd + polygons.length, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[1]});
      }
    }
    else if (mapping.polygon.nPoint===4 && mapping.nText===4){

      center=staff.getCenter(mapping.polygon.points);

      newPoint.x=(mapping.polygon.points[0].x+mapping.polygon.points[1].x)/2;
      newPoint.y=(mapping.polygon.points[0].y+mapping.polygon.points[1].y)/2;

      newPoint1.x=(mapping.polygon.points[1].x+mapping.polygon.points[2].x)/2;
      newPoint1.y=(mapping.polygon.points[1].y+mapping.polygon.points[2].y)/2;

      newPoint2.x=(mapping.polygon.points[2].x+mapping.polygon.points[3].x)/2;
      newPoint2.y=(mapping.polygon.points[2].y+mapping.polygon.points[3].y)/2;

      newPoint3.x=(mapping.polygon.points[3].x+mapping.polygon.points[0].x)/2;
      newPoint3.y=(mapping.polygon.points[3].y+mapping.polygon.points[0].y)/2;

      newPolygons[0]=[newPoint, mapping.polygon.points[0], newPoint3, center];
      newPolygons[1]=[newPoint, mapping.polygon.points[1], newPoint1, center];
      newPolygons[2]=[newPoint2, mapping.polygon.points[2], newPoint1, center];
      newPolygons[3]=[newPoint2, mapping.polygon.points[3], newPoint3, center];

      polygons=utils.unset(polygons, {pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: mapping.polygon.points});
      polygons.push({pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[0]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[1]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length+1, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[2]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length+2, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[3]});
    }
  });
  return polygons;
};

module.exports = Parser;
<commit_msg>update<commit_after>'use strict';

var	  byline     = require("byline"),
      fs         = require("fs"),
      utils      = require(__dirname+'/utils.js'),
      staff      = require(__dirname+'/staff.js');

var Parser = {};

Parser.getSections = function(params, callback){

  var stream          = byline(fs.createReadStream(params.dxfPath, { encoding: 'utf8' })),
      sectionNameTab  = ['HEADER', 'CLASSES', 'TABLES', 'BLOCKS', 'ENTITIES', 'OBJECTS', 'THUMBNAILIMAGE'],
      sectionCur      = '',
      dxfTab          = [],
      section         = false,
      endsec          = false;

  stream.on('data', function(line) {

    if (sectionNameTab.indexOf(line) != -1){
      sectionCur = line.toLowerCase();
      section = true;
      dxfTab[sectionCur] = [];
      endsec = false;
    }
    else if (section == true){
        if (line == 'ENDSEC') {
          endsec=true;
          section=false;
          sectionCur = '';
        }
        else if (endsec == false) {
          dxfTab[sectionCur].push(line);
        }
      }
  });
  stream.on('end', function(){
    if(params.sectionName != null){
      callback(dxfTab[params.sectionName]);
    }
    else{
      callback(dxfTab);
    }
  });
}

Parser.getPolygons = function (sectionTab){
  var polygons    = [],
      countPoly   = 0,
      lwpolyline  = false;

  sectionTab.forEach(function (line, li){
    if(line == 'LWPOLYLINE'){
      lwpolyline = true;
      polygons[countPoly] = {pInd : countPoly, layer : null, nPoint : null, points: []};
    }
    else if(lwpolyline == true && line == '  8') polygons[countPoly].layer=sectionTab[li+1];
    else if(lwpolyline == true && line == ' 90') polygons[countPoly].nPoint=parseInt(sectionTab[li+1]);
    else if(lwpolyline == true && line == ' 10') polygons[countPoly].points.push(new utils.point(parseFloat(sectionTab[li+1]), parseFloat(sectionTab[li+3])));
    else if(lwpolyline == true && polygons[countPoly].points.length === polygons[countPoly].nPoint){
      lwpolyline=false;
      countPoly++;
    }
  });

  return polygons;
}

Parser.getTexts = function (sectionTab){
  var texts       = [],
      countTexts  = 0,
      text        = false;

  sectionTab.forEach(function (line, li){
    if(line == 'TEXT' || line == 'MTEXT'){
        text = true;
        texts[countTexts] = {tInd : countTexts, layer : null, txt : null, point : null};
      }
    else if(text == true && line == '  8') texts[countTexts].layer = sectionTab[li+1];
	  else if(text == true && line == ' 10') texts[countTexts].point = new utils.point(parseFloat(sectionTab[li+1]), parseFloat(sectionTab[li+3]));
	  else if(text == true && line == '  1') texts[countTexts].txt = sectionTab[li+1];
	  else if(text == true && texts[countTexts].point != null && texts[countTexts].txt != null){
	    text=false;
	    countTexts++;
	  }
  });

  return texts;
}

Parser.getLayers = function (sectionTab){
  var layers  = [],
      tab     = ['LWPOLYLINE', 'TEXT', 'MTEXT'],
      get     = false;

  sectionTab.forEach(function (line, li){
    if(tab.indexOf(line) != -1){
      get = true;
    }
    else if(get == true && line == '  8'){
      if(layers.indexOf(sectionTab[li+1]) == -1) layers.push(sectionTab[li+1]);
    }
  });

  return layers;
}

Parser.getMappings = function (texts, polygons){
  var mapping=[], textsAlone= texts;

  texts.forEach(function (text, t){
    polygons.forEach(function (polygon, p){
      if(utils.pnpoly(polygon.points, text.point)){
        if(!mapping[p]) {
          mapping[p] = {polygon : polygon, nText : 1 ,texts : [text]};
          textsAlone = utils.unset(textsAlone, text);
        }
        else{
          mapping[p].texts.push(text);
          mapping[p].nText=mapping[p].nText+1;
          textsAlone = utils.unset(textsAlone, text);
        }
      }
    });
  });
  return {map : mapping, textsAlone : textsAlone};
}

Parser.getDimension = function (polygons){
  var minPoint = new utils.point(0,0),
      maxPoint = new utils.point(0,0),
      dim = {};

  polygons.forEach(function (polygon, p) {
    polygon.points.forEach(function (tpoint, i) {
      minPoint.x = tpoint.x < minPoint.x ? tpoint.x : (i === 0 && p === 0 ? tpoint.x : minPoint.x);
      minPoint.y = tpoint.y < minPoint.y ? tpoint.y : (i === 0 && p === 0 ? tpoint.y : minPoint.y);
      maxPoint.x = tpoint.x > maxPoint.x ? tpoint.x : (i === 0 && p === 0 ? tpoint.x : maxPoint.x);
      maxPoint.y = tpoint.y > maxPoint.y ? tpoint.y : (i === 0 && p === 0 ? tpoint.y : maxPoint.y);
    });
  });
  return dim = {'min': minPoint,
                'max': maxPoint,}
}

Parser.splitPoly = function (mappings, polygons){

  mappings.forEach(function (mapping, mti){

    var newPoint    = new utils.point(0,0), newPoint1 = new utils.point(0,0),
        newPoint2   = new utils.point(0,0), newPoint3 = new utils.point(0,0),
        fourthPoint = new utils.point(0,0), fourthPoint1 = new utils.point(0,0),
        center      = new utils.point(0,0),
        newPolygons = [], tabNearestPoints = [], tabPolyPointsTmp = [];

    if(mapping.polygon.nPoint===4 && mapping.nText===2){

      tabPolyPointsTmp=mapping.polygon.points;

      (mapping.texts).forEach(function (text, ti){
        tabNearestPoints[ti] = staff.findNearestPoint(mapping.polygon.points, text.point);
        tabPolyPointsTmp=utils.unset(tabPolyPointsTmp, tabNearestPoints[ti]);
      });
      if (tabNearestPoints[0]!==tabNearestPoints[1]){
        newPoint.x=(tabNearestPoints[0].x+tabNearestPoints[1].x)/2;
        newPoint.y=(tabNearestPoints[0].y+tabNearestPoints[1].y)/2;
        newPoint1.x=(tabPolyPointsTmp[0].x+tabPolyPointsTmp[1].x)/2;
        newPoint1.y=(tabPolyPointsTmp[0].y+tabPolyPointsTmp[1].y)/2;
        fourthPoint=staff.findNearestPoint(tabPolyPointsTmp, tabNearestPoints[0]);
        fourthPoint1=staff.findNearestPoint(tabPolyPointsTmp, tabNearestPoints[1]);

        newPolygons[0]=[newPoint, tabNearestPoints[0], fourthPoint, newPoint1];
        newPolygons[1]=[newPoint, tabNearestPoints[1], fourthPoint1, newPoint1];

        polygons=utils.unset(polygons, {pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: mapping.polygon.points});
        polygons.push({pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[0]});
        polygons.push({pInd : mapping.polygon.pInd + polygons.length, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[1]});
      }
    }
    else if (mapping.polygon.nPoint===4 && mapping.nText===4){

      center=staff.getCenter(mapping.polygon.points);

      newPoint.x=(mapping.polygon.points[0].x+mapping.polygon.points[1].x)/2;
      newPoint.y=(mapping.polygon.points[0].y+mapping.polygon.points[1].y)/2;

      newPoint1.x=(mapping.polygon.points[1].x+mapping.polygon.points[2].x)/2;
      newPoint1.y=(mapping.polygon.points[1].y+mapping.polygon.points[2].y)/2;

      newPoint2.x=(mapping.polygon.points[2].x+mapping.polygon.points[3].x)/2;
      newPoint2.y=(mapping.polygon.points[2].y+mapping.polygon.points[3].y)/2;

      newPoint3.x=(mapping.polygon.points[3].x+mapping.polygon.points[0].x)/2;
      newPoint3.y=(mapping.polygon.points[3].y+mapping.polygon.points[0].y)/2;

      newPolygons[0]=[newPoint, mapping.polygon.points[0], newPoint3, center];
      newPolygons[1]=[newPoint, mapping.polygon.points[1], newPoint1, center];
      newPolygons[2]=[newPoint2, mapping.polygon.points[2], newPoint1, center];
      newPolygons[3]=[newPoint2, mapping.polygon.points[3], newPoint3, center];

      polygons=utils.unset(polygons, {pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: mapping.polygon.points});
      polygons.push({pInd : mapping.polygon.pInd, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[0]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[1]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length+1, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[2]});
      polygons.push({pInd : mapping.polygon.pInd+polygons.length+2, layer : mapping.polygon.layer, nPoint : mapping.polygon.nPoint, points: newPolygons[3]});
    }
  });
  return polygons;
};

module.exports = Parser;
<|endoftext|>


<commit_before>function DiFlowChart(canvasId, gGraph){
    this.stage = new createjs.Stage(canvasId);
    this.stage.enableMouseOver(5);
    this.graph = gGraph;
    this.flowItems = {};

    this.width = this.stage.canvas.width;
    this.height = this.stage.canvas.height;

    this.itemRadius = 15;
    this.yJumpSize = this.itemRadius * 4;
    this.xJumpSize = this.itemRadius * 9;

    this.lineWidth = 6;
    this.color = "purple";
    this.background = "white";

    this.startX = (this.width/2) - ((this.graph.getLongestLength()-1)*(this.xJumpSize)/2);
    this.startY = this.height / 2;

    this.stage.canvas.style.background = this.background;

    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", this.stage);
}

DiFlowChart.prototype.draw = function(){

    var usedSpots = {};

    console.log("started drawing. graph:", this.graph, this);

    var drawNode = function(node){
        var usedCount = usedSpots[node.rank] || 0;
        usedSpots[node.rank] = usedCount + 1;

        var flowItem = this._createItem(node, node.rank, gGraph.getRankSize(node.rank), usedCount);
        console.log("drawing Node", flowItem.flowItem, "rank", node.rank, "usedCount", usedCount, "id", node.id);
        this.flowItems[node.id] = flowItem;
    };

    var drawConnections = function(node){
        var currentFlowItem = this.flowItems[node.id];

        node.next.each(function(nextNodeId){
            var nextFlowItem = this.flowItems[nextNodeId].flowItem;
            var connector = this._createConnector(currentFlowItem.flowItem, nextFlowItem);
            currentFlowItem.connectors = currentFlowItem.connectors || [];
            currentFlowItem.connectors.push(connector);

        }, this);

        this.flowItems[node.id] = currentFlowItem;
    };

    this.graph.forEach(drawNode, this);
    this.graph.forEach(drawConnections, this);
    this.submitItems();
};

DiFlowChart.prototype._createItem = function(node, rowNum, rowItemCount, rowUsedSpots){
    var offset = ((rowItemCount-1) * (this.yJumpSize/2));
    var y = this.startY - this.itemRadius - offset + (rowUsedSpots * this.yJumpSize);
    var x = this.startX + (rowNum*this.xJumpSize);

    var flowItem = new flowjsItem(x, y, node.id, this.itemRadius, this.onItemUpdate);
    flowItem.color = this.color;
    flowItem.background = this.background;
    flowItem.refresh();

    return {node: node, flowItem: flowItem};
};

DiFlowChart.prototype._createConnector = function(itemA, itemB){
    var start = itemA.getLocation();
    var end = itemB.getLocation();

    var connector = new flowConnector(start.x, start.y, end.x, end.y);

    connector.color = this.color;
    connector.strokeWidth = this.lineWidth;
    connector.refresh();
    return connector;
};

DiFlowChart.prototype.submitItems = function(){
    var connetorShapes = [];
    var pointShapes = [];

    for (var key in this.flowItems){
        var flowShapes = this.flowItems[key].flowItem.getDrawableItems();
        flowShapes.forEach(function(shape){
            pointShapes.push(shape);
        });

        var connectors = this.flowItems[key].connectors;
        if(connectors !== undefined){
            connectors.forEach(function(conn){
                conn.getDrawableItems().forEach(function(shape){
                    connetorShapes.push(shape);
                })
            })
        }
    }

    var stage = this.stage;
    connetorShapes.forEach(function(shape){
        stage.addChild(shape);
    });

    pointShapes.forEach(function(shape){
        stage.addChild(shape);
    });

    this.stage.update();
};

/*  Update a flow item properties.
    The given function will be called and will be passed the flow item object */
DiFlowChart.prototype.updateItem = function(itemId, func){
    var item = this.flowItems[itemId];
    if(item === undefined){
        return;
    }

    func(item);

    item.flowItem.refresh();
    if (item.connectors !== undefined){
        item.connectors.forEach(function(connector){
            connector.refresh();
        });
    }

    this.stage.update();
};
<commit_msg>changed flow to work with graph walker<commit_after>function DiFlowChart(canvasId, gGraph){
    console.log("NEW FLOW CHART");

    this.stage = new createjs.Stage(canvasId);
    this.stage.enableMouseOver(5);
    this.graph = gGraph;
    this.flowItems = {};

    this.width = this.stage.canvas.width;
    this.height = this.stage.canvas.height;

    this.itemRadius = 15;
    this.yJumpSize = this.itemRadius * 4;
    this.xJumpSize = this.itemRadius * 9;

    this.lineWidth = 6;
    this.color = "purple";
    this.background = "white";

    this.startX = (this.width/2) - ((this.graph.getLongestLength()-1)*(this.xJumpSize)/2);
    this.startY = this.height / 2;

    this.stage.canvas.style.background = this.background;

    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", this.stage);
}

DiFlowChart.prototype.draw = function(){

    var usedSpots = {};

    var drawNode = function(node){
        var usedCount = usedSpots[node.rank] || 0;
        usedSpots[node.rank] = usedCount + 1;

        var flowItem = this._createItem(node, node.rank, this.graph.getRankSize(node.rank), usedCount);
        this.flowItems[node.id] = flowItem;
    };

    var drawConnections = function(node){
        var currentFlowItem = this.flowItems[node.id];

        node.next.each(function(nextNodeId){
            var nextFlowItem = this.flowItems[nextNodeId].flowItem;
            var connector = this._createConnector(currentFlowItem.flowItem, nextFlowItem);
            currentFlowItem.connectors = currentFlowItem.connectors || [];
            currentFlowItem.connectors.push(connector);

        }, this);

        this.flowItems[node.id] = currentFlowItem;
    };

    var walker = new GraphWalker(this.graph);
    walker.forEach(drawNode, this);
    walker.forEach(drawConnections, this);

    this.submitItems();
};

DiFlowChart.prototype._createItem = function(node, rowNum, rowItemCount, rowUsedSpots){
    var offset = ((rowItemCount-1) * (this.yJumpSize/2));
    var y = this.startY - this.itemRadius - offset + (rowUsedSpots * this.yJumpSize);
    var x = this.startX + (rowNum*this.xJumpSize);

    var flowItem = new flowjsItem(x, y, node.id, this.itemRadius, this.onItemUpdate);
    flowItem.color = this.color;
    flowItem.background = this.background;
    flowItem.refresh();

    return {node: node, flowItem: flowItem};
};

DiFlowChart.prototype._createConnector = function(itemA, itemB){
    var start = itemA.getLocation();
    var end = itemB.getLocation();

    var connector = new flowConnector(start.x, start.y, end.x, end.y);

    connector.color = this.color;
    connector.strokeWidth = this.lineWidth;
    connector.refresh();
    return connector;
};

DiFlowChart.prototype.submitItems = function(){
    var connetorShapes = [];
    var pointShapes = [];

    for (var key in this.flowItems){
        var flowShapes = this.flowItems[key].flowItem.getDrawableItems();
        flowShapes.forEach(function(shape){
            pointShapes.push(shape);
        });

        var connectors = this.flowItems[key].connectors;
        if(connectors !== undefined){
            connectors.forEach(function(conn){
                conn.getDrawableItems().forEach(function(shape){
                    connetorShapes.push(shape);
                })
            })
        }
    }

    var stage = this.stage;
    connetorShapes.forEach(function(shape){
        stage.addChild(shape);
    });

    pointShapes.forEach(function(shape){
        stage.addChild(shape);
    });

    this.stage.update();
};

/*  Update a flow item properties.
    The given function will be called and will be passed the flow item object */
DiFlowChart.prototype.updateItem = function(itemId, func){
    var item = this.flowItems[itemId];
    if(item === undefined){
        return;
    }

    func(item);

    item.flowItem.refresh();
    if (item.connectors !== undefined){
        item.connectors.forEach(function(connector){
            connector.refresh();
        });
    }

    this.stage.update();
};
<|endoftext|>


<commit_before>'use strict';

const utils = require('./utils');

const assert = require('assert');
const child_process = require('child_process');
const fs = require('fs');

const all_tests = () => {
  [ 'http', 'https' ].forEach((transport) => {
    describe(transport, () => {
      let port, proc;
      before('Start standalone fusion server', (done) => {
        let args = [ '--connect', `localhost:${utils.rdb_port()}`, '--port', '0' ];
        if (transport === 'http') {
          args.push('--unsecure');
        }
        proc = child_process.fork('./src/main.js', args, { silent: true });

        // Error if we didn't get the port before the server exited
        proc.stdout.once('end', () => assert.notStrictEqual(port, undefined));

        let buffer = '';
        proc.stdout.on('data', (data) => {
          buffer += data.toString();

          const endline_pos = buffer.indexOf('\n');
          if (endline_pos === -1) { return; }

          const line = buffer.slice(0, endline_pos);
          buffer = buffer.slice(endline_pos + 1);

          const matches = line.match(/Listening on .*:(\d+)\.$/);
          if (matches === null || matches.length !== 2) { return; }
          port = parseInt(matches[1]);
          proc.stdout.removeAllListeners('data');
          done();
        });
      });

      after('Shutdown standalone fusion server', () => {
        if (proc) {
          proc.kill('SIGKILL');
          proc = undefined;
        }
      });

      it('localhost/fusion.js', (done) => {
        require(transport).get({ hostname: 'localhost',
                                 port,
                                 path: '/fusion.js',
                                 rejectUnauthorized: false }, (res) => {
          const code = fs.readFileSync('../client/dist/build.js');
          let buffer = '';
          assert.strictEqual(res.statusCode, 200);
          res.on('data', (delta) => buffer += delta);
          res.on('end', () => (assert.equal(buffer, code), done()));
        });
      });
    });
  });
};

const suite = (table) => describe('Webserver', () => all_tests(table));

module.exports = { suite };
<commit_msg>fixing client source path in server tests<commit_after>'use strict';

const utils = require('./utils');

const assert = require('assert');
const child_process = require('child_process');
const fs = require('fs');

const all_tests = () => {
  [ 'http', 'https' ].forEach((transport) => {
    describe(transport, () => {
      let port, proc;
      before('Start standalone fusion server', (done) => {
        let args = [ '--connect', `localhost:${utils.rdb_port()}`, '--port', '0' ];
        if (transport === 'http') {
          args.push('--unsecure');
        }
        proc = child_process.fork('./src/main.js', args, { silent: true });

        // Error if we didn't get the port before the server exited
        proc.stdout.once('end', () => assert.notStrictEqual(port, undefined));

        let buffer = '';
        proc.stdout.on('data', (data) => {
          buffer += data.toString();

          const endline_pos = buffer.indexOf('\n');
          if (endline_pos === -1) { return; }

          const line = buffer.slice(0, endline_pos);
          buffer = buffer.slice(endline_pos + 1);

          const matches = line.match(/Listening on .*:(\d+)\.$/);
          if (matches === null || matches.length !== 2) { return; }
          port = parseInt(matches[1]);
          proc.stdout.removeAllListeners('data');
          done();
        });
      });

      after('Shutdown standalone fusion server', () => {
        if (proc) {
          proc.kill('SIGKILL');
          proc = undefined;
        }
      });

      it('localhost/fusion.js', (done) => {
        require(transport).get({ hostname: 'localhost',
                                 port,
                                 path: '/fusion.js',
                                 rejectUnauthorized: false }, (res) => {
          const code = fs.readFileSync('../client/dist/fusion.js');
          let buffer = '';
          assert.strictEqual(res.statusCode, 200);
          res.on('data', (delta) => buffer += delta);
          res.on('end', () => (assert.equal(buffer, code), done()));
        });
      });
    });
  });
};

const suite = (table) => describe('Webserver', () => all_tests(table));

module.exports = { suite };
<|endoftext|>


<commit_before>
var tries = require('../lib/tries');

exports['get trie as object'] = function (test) {
    var trie = tries.trie();

    test.ok(trie);
    test.equal(typeof trie, 'object');
};

exports['get no data from empty trie'] = function (test) {
    var trie = tries.trie();

    var result = trie.get('0123');

    test.equal(result, null);
};

exports['put data and create another trie'] = function (test) {
    var trie = tries.trie();

    var result = trie.put('0123', 42);

    test.ok(result);
    test.ok(result !== trie);
};

exports['put data and get data'] = function (test) {
    var trie = tries.trie();

    var result = trie.put('0123', 42).get('0123');

    test.ok(result);
    test.equal(result, 42);
};

<commit_msg>Trie additional test<commit_after>
var tries = require('../lib/tries');

exports['get trie as object'] = function (test) {
    var trie = tries.trie();

    test.ok(trie);
    test.equal(typeof trie, 'object');
};

exports['get no data from empty trie'] = function (test) {
    var trie = tries.trie();

    var result = trie.get('0123');

    test.equal(result, null);
};

exports['put data and create another trie'] = function (test) {
    var trie = tries.trie();

    var result = trie.put('0123', 42);

    test.ok(result);
    test.ok(result !== trie);
};

exports['put data and get data'] = function (test) {
    var trie = tries.trie();

    var result = trie.put('0123', 42).get('0123');

    test.ok(result);
    test.equal(result, 42);
};

exports['put two new data and retrieve them'] = function (test) {
    var trie = tries.trie();

    var result = trie.put('0123', 42)
        .put('3210', 1);

    test.ok(result);
    test.equal(result.get('0123'), 42);
    test.equal(result.get('3210'), 1);
    test.equal(trie.get('0123'), null);
    test.equal(trie.get('3210'), null);
};

<|endoftext|>


<commit_before>/**
 *******************************************************
 *                                                     *
 *   Copyright (C) Microsoft. All rights reserved.     *
 *                                                     *
 *******************************************************
 */

var path = require('path');
var configParser = require('./configParser');
var glob = require('glob');
var multiPlatforms = require('./platforms');
var fs = require('fs');
var nopt = require('nopt');

// Checks whether a command is compatible with livereload
// Currently, Only the following commands are compatible with LiveReload : `* (run|emulate) android -- --livereload`, `* (run|emulate) android --livereload`
//   Examples:
//     - `cordova run android -- --livereload`
//     - `phonegap run android -- --livereload`
//     - `cordova run android --livereload`
//     - `cordova emulate android -- --livereload`
//     - `cordova emulate android --livereload`
//     - `taco emulate android --livereload`
//     - `phonegap emulate android --livereload`
module.exports.IsCmdLiveReloadCompatible = function(context) {

    // There is a bug in cordova-lib upto at least version 5.3.x that prevents the `cordova emulate` command
    // ... from passing context object of plugins from passing the -- --livereload flag correctly.
    // ... using `isLiveReloadActive` allows us to circumvent that issue.
    var livereloadOptions = parseOptions();
    return livereloadOptions.livereload && ((livereloadOptions.run || livereloadOptions.emulate) && !isLiveReloadActivated()); // Make sure we're not already in livereload mode
};

// config.xml can be found in the projectRoot directory or within the projectRoot/www folder
module.exports.GetConfigXMLFile = GetConfigXMLFile = function(projectRoot) {
    var rootPath = path.join(projectRoot, 'config.xml');
    var wwwPath = path.join(projectRoot, 'www', 'config.xml');
    if (fs.existsSync(rootPath)) {
        return rootPath;
    } else if (fs.existsSync(wwwPath)) {
        return wwwPath;
    }
    return rootPath;
};

// Retrieve the start page for a cordova project, given the project's root directory
module.exports.GetStartPage = function(projectRoot) {
    var configXML = GetConfigXMLFile(projectRoot);
    var startPage = configParser.GetStartPage(configXML);
    return startPage;
};

module.exports.ChangeStartPage = function(projectRoot, plat, platformIndexUrl) {
    var configXmlFolder = path.join(projectRoot, 'platforms', plat, multiPlatforms.getConfigFolder(plat));
    glob.sync('**/config.xml', {
        cwd: configXmlFolder,
        ignore: '*build/**'
    }).forEach(function(filename) {
        var configXML = path.join(configXmlFolder, filename);
        configParser.ChangeStartPage(platformIndexUrl, configXML);
    });
};

// Parses LiveReload options off of process.argv
module.exports.parseOptions = parseOptions = function() {

    // --livereload and --devicesync can be used interchangeably.
    // e.g: `cordova run android -- --livereload` is the same as `cordova run android -- --devicesync`
    // Making them be the same is necessary because of two reasons:
    //    1- From TACO, we have to be able to run either `taco run ios android --devicesync` or `taco run android --livereload`
    //    2- Due to a bug in cordova-lib, we have to parse process.args and not the context. What this means is that when parsing process.args,
    //         ... we'll see --devicesync and not --livereload. otherwise, we could have just passed the '--livereload' flag through the plugin's context from TACO.
    var knownOpts = {
        'livereload': Boolean,
        'devicesync': Boolean,
        'ignore': String,
        'tunnel': Boolean,
        'ghostMode': Boolean
    };

    var parsedOptions = nopt(knownOpts, {}, process.args, 2);
    var parsedLivereloadOptions = nopt(knownOpts, {}, parsedOptions.argv.remain, 2);

    return {
        run: parsedOptions.argv.original.indexOf('run') > -1,
        emulate: parsedOptions.argv.original.indexOf('emulate') > -1,
        livereload: parsedOptions.livereload || parsedLivereloadOptions.livereload || parsedOptions.devicesync || parsedLivereloadOptions.devicesync,
        ignore: parsedOptions.ignore || parsedLivereloadOptions.ignore,
        tunnel: parsedOptions.tunnel || parsedLivereloadOptions.tunnel,
        ghostMode: parsedOptions.ghostMode || parsedLivereloadOptions.ghostMode
    };
};

module.exports.setLiveReloadToActive = function() {
    GLOBAL.isLiveReloadActive = true;
};

module.exports.isLiveReloadActivated = isLiveReloadActivated = function() {
    return !!GLOBAL.isLiveReloadActive;
};

module.exports.replaceStringOccurrencesInPage = function(stringToBeReplaced, stringToBeReplacedWith, htmlPagePath) {

};
<commit_msg>Reverting change to helpers.js<commit_after>/**
 *******************************************************
 *                                                     *
 *   Copyright (C) Microsoft. All rights reserved.     *
 *                                                     *
 *******************************************************
 */

var path = require('path');
var configParser = require('./configParser');
var glob = require('glob');
var multiPlatforms = require('./platforms');
var fs = require('fs');
var nopt = require('nopt');

// Checks whether a command is compatible with livereload
// Currently, Only the following commands are compatible with LiveReload : `* (run|emulate) android -- --livereload`, `* (run|emulate) android --livereload`
//   Examples:
//     - `cordova run android -- --livereload`
//     - `phonegap run android -- --livereload`
//     - `cordova run android --livereload`
//     - `cordova emulate android -- --livereload`
//     - `cordova emulate android --livereload`
//     - `taco emulate android --livereload`
//     - `phonegap emulate android --livereload`
module.exports.IsCmdLiveReloadCompatible = function(context) {

    // There is a bug in cordova-lib upto at least version 5.3.x that prevents the `cordova emulate` command
    // ... from passing context object of plugins from passing the -- --livereload flag correctly.
    // ... using `isLiveReloadActive` allows us to circumvent that issue.
    var livereloadOptions = parseOptions();
    return livereloadOptions.livereload && ((livereloadOptions.run || livereloadOptions.emulate) && !isLiveReloadActivated()); // Make sure we're not already in livereload mode
};

// config.xml can be found in the projectRoot directory or within the projectRoot/www folder
module.exports.GetConfigXMLFile = GetConfigXMLFile = function(projectRoot) {
    var rootPath = path.join(projectRoot, 'config.xml');
    var wwwPath = path.join(projectRoot, 'www', 'config.xml');
    if (fs.existsSync(rootPath)) {
        return rootPath;
    } else if (fs.existsSync(wwwPath)) {
        return wwwPath;
    }
    return rootPath;
};

// Retrieve the start page for a cordova project, given the project's root directory
module.exports.GetStartPage = function(projectRoot) {
    var configXML = GetConfigXMLFile(projectRoot);
    var startPage = configParser.GetStartPage(configXML);
    return startPage;
};

module.exports.ChangeStartPage = function(projectRoot, plat, platformIndexUrl) {
    var configXmlFolder = path.join(projectRoot, 'platforms', plat, multiPlatforms.getConfigFolder(plat));
    glob.sync('**/config.xml', {
        cwd: configXmlFolder,
        ignore: '*build/**'
    }).forEach(function(filename) {
        var configXML = path.join(configXmlFolder, filename);
        configParser.ChangeStartPage(platformIndexUrl, configXML);
    });
};

// Parses LiveReload options off of process.argv
module.exports.parseOptions = parseOptions = function() {

    // --livereload and --devicesync can be used interchangeably.
    // e.g: `cordova run android -- --livereload` is the same as `cordova run android -- --devicesync`
    // Making them be the same is necessary because of two reasons:
    //    1- From TACO, we have to be able to run either `taco run ios android --devicesync` or `taco run android --livereload`
    //    2- Due to a bug in cordova-lib, we have to parse process.args and not the context. What this means is that when parsing process.args,
    //         ... we'll see --devicesync and not --livereload. otherwise, we could have just passed the '--livereload' flag through the plugin's context from TACO.
    var knownOpts = {
        'livereload': Boolean,
        'devicesync': Boolean,
        'ignore': String,
        'tunnel': Boolean,
        'ghostMode': Boolean
    };

    var parsedOptions = nopt(knownOpts, {}, process.args, 2);
    var parsedLivereloadOptions = nopt(knownOpts, {}, parsedOptions.argv.remain, 2);

    return {
        run: parsedOptions.argv.original.indexOf('run') > -1,
        emulate: parsedOptions.argv.original.indexOf('emulate') > -1,
        livereload: parsedOptions.livereload || parsedLivereloadOptions.livereload || parsedOptions.devicesync || parsedLivereloadOptions.devicesync,
        ignore: parsedOptions.ignore || parsedLivereloadOptions.ignore,
        tunnel: parsedOptions.tunnel || parsedLivereloadOptions.tunnel,
        ghostMode: parsedOptions.ghostMode || parsedLivereloadOptions.ghostMode
    };
};

module.exports.setLiveReloadToActive = function() {
    GLOBAL.isLiveReloadActive = true;
};

module.exports.isLiveReloadActivated = isLiveReloadActivated = function() {
    return !!GLOBAL.isLiveReloadActive;
};
<|endoftext|>


<commit_before>/**
 * Dependencies.
 */
const _ = require('lodash');
const Joi = require('joi');
const config = require('config');
const errors = require('../lib/errors');

const roles = require('../constants/roles');
const constants = require('../constants/transactions');

const tier = Joi.object().keys({
  name: Joi.string().required(), // lowercase, act as a slug. E.g. "donors", "sponsors", "backers", "members", ...
  title: Joi.string().required(), // e.g. "Sponsors"
  description: Joi.string().required(), // what do people get as a member of this tier?
  button: Joi.string().required(), // Call To Action, e.g. "Become a sponsor"
  range: Joi.array().items(Joi.number().integer()).length(2).required(), // e.g. [100, 10000000]: Need to donate at least $100/interval to be a sponsor
  presets: Joi.array().items(Joi.number().integer()), // e.g. [1, 5, 20] for presets of $1, $5 and $20
  interval: Joi.string().valid(['monthly', 'yearly', 'one-time']).required()
});

const tiers = Joi.array().items(tier);

/**
 * Model.
 */
module.exports = function(Sequelize, DataTypes) {

  const models = Sequelize.models;

  var Group = Sequelize.define('Group', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },

    mission: DataTypes.STRING(100),

    description: DataTypes.STRING, // max 95 characters

    longDescription: DataTypes.TEXT,
    whyJoin: DataTypes.TEXT,

    // We should update those two fields periodically (but no need to be real time)
    budget: DataTypes.INTEGER, // yearly budget in cents
    burnrate: DataTypes.INTEGER, // monthly burnrate (last 3 months average, in cents)

    currency: {
      type: DataTypes.STRING,
      defaultValue: 'USD'
    },

    logo: DataTypes.STRING,

    video: DataTypes.STRING,

    image: DataTypes.STRING,
    backgroundImage: DataTypes.STRING,

    expensePolicy: DataTypes.TEXT,

    tiers: {
      type: DataTypes.JSON,
      allowNull: true,
      validate: {
        schema: (value) => {
          Joi.validate(value, tiers, (err) => {
            if (err) throw new Error(err.details[0].message);
          })
        }
      }
    },

    settings: {
      type: DataTypes.JSON,
      allowNull: true
    },

    data: {
      type: DataTypes.JSON,
      allowNull: true
    },

    hostFeePercent: {
      type: DataTypes.FLOAT,
      defaultValue: constants.HOST_FEE_PERCENT
    },

    createdAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },

    isPublic: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },

    slug: {
      type: DataTypes.STRING,
      unique: true,
      set(slug) {
        if (slug && slug.toLowerCase) {
          this.setDataValue('slug', slug.toLowerCase());
        }
      }
    },

    twitterHandle: {
      type: DataTypes.STRING, // without the @ symbol. Ex: 'asood123'
      set(username) {
        if (username.substr(0,1) === '@') {
          this.setDataValue('twitterHandle', username.substr(1));
        }
      }
    },

    website: DataTypes.STRING,

    publicUrl: {
      type: new DataTypes.VIRTUAL(DataTypes.STRING, ['slug']),
      get() {
        return `${config.host.website}/${this.get('slug')}`;
      }
    },

    tags: {
      type: DataTypes.ARRAY(DataTypes.STRING)
    },

    isSupercollective: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    }

  }, {
    paranoid: true,

    getterMethods: {
      // Info.
      info: function() {
        return {
          id: this.id,
          name: this.name,
          mission: this.mission,
          description: this.description,
          longDescription: this.longDescription,
          whyJoin: this.whyJoin,
          budget: this.budget,
          burnrate: this.burnrate,
          currency: this.currency,
          logo: this.logo,
          video: this.video,
          image: this.image,
          data: this.data,
          backgroundImage: this.backgroundImage,
          expensePolicy: this.expensePolicy,
          createdAt: this.createdAt,
          updatedAt: this.updatedAt,
          isPublic: this.isPublic,
          slug: this.slug,
          tiers: this.tiers,
          settings: this.settings,
          website: this.website,
          twitterHandle: this.twitterHandle,
          publicUrl: this.publicUrl,
          hostFeePercent: this.hostFeePercent,
          tags: this.tags,
          isSupercollective: this.isSupercollective
        };
      },
      minimal: function() {
        return {
          id: this.id,
          name: this.name,
          logo: this.logo,
          publicUrl: this.publicUrl,
          mission: this.mission,
          isSupercollective: this.isSupercollective
        }
      }
    },

    instanceMethods: {
      hasUserWithRole(userId, roles, cb) {
        this
          .getUsers({
            where: {
              id: userId
            }
          })
          .tap((users) => {
            if (users.length === 0) {
              return cb(null, false);
            } else if (!_.contains(roles, users[0].UserGroup.role)) {
              return cb(null, false);
            }

            cb(null, true);
          })
          .catch(cb);
      },

      addUserWithRole(user, role) {
        return Sequelize.models.UserGroup.create({
          role,
          UserId: user.id,
          GroupId: this.id
        });
      },

      getStripeAccount() {
        return Sequelize.models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then((userGroup) => {
          if (!userGroup) {
            return { stripeAccount: null };
          }

          return Sequelize.models.User.find({
            where: {
              id: userGroup.UserId
            },
            include: [{
              model: Sequelize.models.StripeAccount
            }]
          });
        })
        .then((user) => user.StripeAccount);
      },

      getConnectedAccount() {

        return models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then((userGroup) => {
          if (!userGroup) {
            throw new errors.NotFound(`No group with ID ${this.id} and host user found`);
          }

          return models.ConnectedAccount.find({
            where: {
              UserId: userGroup.UserId
            }
          });
        });
      },

      getBalance() {
        return models.Transaction.find({
          attributes: [
            [Sequelize.fn('SUM', Sequelize.col('netAmountInGroupCurrency')), 'total']
          ],
          where: {
            GroupId: this.id
            }
          })
        .then(result => Promise.resolve(result.toJSON().total));
      },

      getYearlyIncome() {
        return Sequelize.query(`
          SELECT
            (SELECT
             COALESCE(SUM( t."netAmountInGroupCurrency"*12),0)
              FROM "Subscriptions" s
              LEFT JOIN "Transactions" t
              ON (s.id = t."SubscriptionId"
                AND t.id = (SELECT MAX(id) from "Transactions" t where t."SubscriptionId" = s.id))
              WHERE "GroupId" = :GroupId
                AND t.amount > 0
                AND t."deletedAt" IS NULL
                AND s.interval = 'month'
                AND s."isActive" IS TRUE
                AND s."deletedAt" IS NULL)
            +
            (SELECT
              COALESCE(SUM(t."netAmountInGroupCurrency"),0) FROM "Transactions" t
              LEFT JOIN "Subscriptions" s ON t."SubscriptionId" = s.id
              WHERE "GroupId" = :GroupId
                AND t.amount > 0
                AND t."deletedAt" IS NULL
                AND ((s.interval = 'year' AND s."isActive" IS TRUE AND s."deletedAt" IS NULL) OR s.interval IS NULL)) "yearlyIncome"
        `, {
          replacements: { GroupId: this.id },
          type: Sequelize.QueryTypes.SELECT
        }).then(result => Promise.resolve(parseInt(result[0].yearlyIncome,10)));
      },

      getTotalDonations() {
        return models.Transaction
          .find({
            attributes: [
              [Sequelize.fn('SUM', Sequelize.col('amount')), 'donationTotal']
            ],
            where: {
              GroupId: this.id,
              amount: {
                $gt: 0
              }
            }
          })
          .then((result) => {
            const json = result.toJSON();
            return Promise.resolve(Number(json.donationTotal));
          })
      },

      getBackersCount() {
        return models.Transaction
          .find({
            attributes: [
              [Sequelize.fn('COUNT', Sequelize.col('UserId')), 'backersCount']
            ],
            where: {
              GroupId: this.id,
              amount: {
                $gt: 0
              }
            }
          })
          .then((result) => {
            const json = result.toJSON();

            return Promise.resolve(Number(json.backersCount));
          })
      },

      hasHost() {
        return Sequelize.models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then(userGroup => Promise.resolve(!!userGroup));
      }

    }
  });

  return Group;
};
<commit_msg>add another case to the yearlyIncome query<commit_after>/**
 * Dependencies.
 */
const _ = require('lodash');
const Joi = require('joi');
const config = require('config');
const errors = require('../lib/errors');

const roles = require('../constants/roles');
const constants = require('../constants/transactions');

const tier = Joi.object().keys({
  name: Joi.string().required(), // lowercase, act as a slug. E.g. "donors", "sponsors", "backers", "members", ...
  title: Joi.string().required(), // e.g. "Sponsors"
  description: Joi.string().required(), // what do people get as a member of this tier?
  button: Joi.string().required(), // Call To Action, e.g. "Become a sponsor"
  range: Joi.array().items(Joi.number().integer()).length(2).required(), // e.g. [100, 10000000]: Need to donate at least $100/interval to be a sponsor
  presets: Joi.array().items(Joi.number().integer()), // e.g. [1, 5, 20] for presets of $1, $5 and $20
  interval: Joi.string().valid(['monthly', 'yearly', 'one-time']).required()
});

const tiers = Joi.array().items(tier);

/**
 * Model.
 */
module.exports = function(Sequelize, DataTypes) {

  const models = Sequelize.models;

  var Group = Sequelize.define('Group', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },

    mission: DataTypes.STRING(100),

    description: DataTypes.STRING, // max 95 characters

    longDescription: DataTypes.TEXT,
    whyJoin: DataTypes.TEXT,

    // We should update those two fields periodically (but no need to be real time)
    budget: DataTypes.INTEGER, // yearly budget in cents
    burnrate: DataTypes.INTEGER, // monthly burnrate (last 3 months average, in cents)

    currency: {
      type: DataTypes.STRING,
      defaultValue: 'USD'
    },

    logo: DataTypes.STRING,

    video: DataTypes.STRING,

    image: DataTypes.STRING,
    backgroundImage: DataTypes.STRING,

    expensePolicy: DataTypes.TEXT,

    tiers: {
      type: DataTypes.JSON,
      allowNull: true,
      validate: {
        schema: (value) => {
          Joi.validate(value, tiers, (err) => {
            if (err) throw new Error(err.details[0].message);
          })
        }
      }
    },

    settings: {
      type: DataTypes.JSON,
      allowNull: true
    },

    data: {
      type: DataTypes.JSON,
      allowNull: true
    },

    hostFeePercent: {
      type: DataTypes.FLOAT,
      defaultValue: constants.HOST_FEE_PERCENT
    },

    createdAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },

    isPublic: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },

    slug: {
      type: DataTypes.STRING,
      unique: true,
      set(slug) {
        if (slug && slug.toLowerCase) {
          this.setDataValue('slug', slug.toLowerCase());
        }
      }
    },

    twitterHandle: {
      type: DataTypes.STRING, // without the @ symbol. Ex: 'asood123'
      set(username) {
        if (username.substr(0,1) === '@') {
          this.setDataValue('twitterHandle', username.substr(1));
        }
      }
    },

    website: DataTypes.STRING,

    publicUrl: {
      type: new DataTypes.VIRTUAL(DataTypes.STRING, ['slug']),
      get() {
        return `${config.host.website}/${this.get('slug')}`;
      }
    },

    tags: {
      type: DataTypes.ARRAY(DataTypes.STRING)
    },

    isSupercollective: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    }

  }, {
    paranoid: true,

    getterMethods: {
      // Info.
      info: function() {
        return {
          id: this.id,
          name: this.name,
          mission: this.mission,
          description: this.description,
          longDescription: this.longDescription,
          whyJoin: this.whyJoin,
          budget: this.budget,
          burnrate: this.burnrate,
          currency: this.currency,
          logo: this.logo,
          video: this.video,
          image: this.image,
          data: this.data,
          backgroundImage: this.backgroundImage,
          expensePolicy: this.expensePolicy,
          createdAt: this.createdAt,
          updatedAt: this.updatedAt,
          isPublic: this.isPublic,
          slug: this.slug,
          tiers: this.tiers,
          settings: this.settings,
          website: this.website,
          twitterHandle: this.twitterHandle,
          publicUrl: this.publicUrl,
          hostFeePercent: this.hostFeePercent,
          tags: this.tags,
          isSupercollective: this.isSupercollective
        };
      },
      minimal: function() {
        return {
          id: this.id,
          name: this.name,
          logo: this.logo,
          publicUrl: this.publicUrl,
          mission: this.mission,
          isSupercollective: this.isSupercollective
        }
      }
    },

    instanceMethods: {
      hasUserWithRole(userId, roles, cb) {
        this
          .getUsers({
            where: {
              id: userId
            }
          })
          .tap((users) => {
            if (users.length === 0) {
              return cb(null, false);
            } else if (!_.contains(roles, users[0].UserGroup.role)) {
              return cb(null, false);
            }

            cb(null, true);
          })
          .catch(cb);
      },

      addUserWithRole(user, role) {
        return Sequelize.models.UserGroup.create({
          role,
          UserId: user.id,
          GroupId: this.id
        });
      },

      getStripeAccount() {
        return Sequelize.models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then((userGroup) => {
          if (!userGroup) {
            return { stripeAccount: null };
          }

          return Sequelize.models.User.find({
            where: {
              id: userGroup.UserId
            },
            include: [{
              model: Sequelize.models.StripeAccount
            }]
          });
        })
        .then((user) => user.StripeAccount);
      },

      getConnectedAccount() {

        return models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then((userGroup) => {
          if (!userGroup) {
            throw new errors.NotFound(`No group with ID ${this.id} and host user found`);
          }

          return models.ConnectedAccount.find({
            where: {
              UserId: userGroup.UserId
            }
          });
        });
      },

      getBalance() {
        return models.Transaction.find({
          attributes: [
            [Sequelize.fn('SUM', Sequelize.col('netAmountInGroupCurrency')), 'total']
          ],
          where: {
            GroupId: this.id
            }
          })
        .then(result => Promise.resolve(result.toJSON().total));
      },

      getYearlyIncome() {
        /*
          Three cases:
          1) All active monthly subscriptions. Multiply by 12
          2) All one-time and yearly subscriptions
          3) All inactive monthly subscriptions that have contributed in the past
        */
        return Sequelize.query(`
          SELECT
            (SELECT
             COALESCE(SUM( t."netAmountInGroupCurrency"*12),0)
              FROM "Subscriptions" s
              LEFT JOIN "Transactions" t
              ON (s.id = t."SubscriptionId"
                AND t.id = (SELECT MAX(id) from "Transactions" t where t."SubscriptionId" = s.id))
              WHERE "GroupId" = :GroupId
                AND t.amount > 0
                AND t."deletedAt" IS NULL
                AND s.interval = 'month'
                AND s."isActive" IS TRUE
                AND s."deletedAt" IS NULL)
            +
            (SELECT
              COALESCE(SUM(t."netAmountInGroupCurrency"),0) FROM "Transactions" t
              LEFT JOIN "Subscriptions" s ON t."SubscriptionId" = s.id
              WHERE "GroupId" = :GroupId
                AND t.amount > 0
                AND t."deletedAt" IS NULL
                AND ((s.interval = 'year' AND s."isActive" IS TRUE AND s."deletedAt" IS NULL) OR s.interval IS NULL))
            +
            (SELECT
              COALESCE(SUM(t."netAmountInGroupCurrency"),0) FROM "Transactions" t
              LEFT JOIN "Subscriptions" s ON t."SubscriptionId" = s.id
              WHERE "GroupId" = :GroupId
                AND t.amount > 0
                AND t."deletedAt" IS NULL
                AND s.interval = 'month' AND s."isActive" IS FALSE AND s."deletedAt" IS NULL)
            "yearlyIncome"
        `, {
          replacements: { GroupId: this.id },
          type: Sequelize.QueryTypes.SELECT
        }).then(result => Promise.resolve(parseInt(result[0].yearlyIncome,10)));
      },

      getTotalDonations() {
        return models.Transaction
          .find({
            attributes: [
              [Sequelize.fn('SUM', Sequelize.col('amount')), 'donationTotal']
            ],
            where: {
              GroupId: this.id,
              amount: {
                $gt: 0
              }
            }
          })
          .then((result) => {
            const json = result.toJSON();
            return Promise.resolve(Number(json.donationTotal));
          })
      },

      getBackersCount() {
        return models.Transaction
          .find({
            attributes: [
              [Sequelize.fn('COUNT', Sequelize.col('UserId')), 'backersCount']
            ],
            where: {
              GroupId: this.id,
              amount: {
                $gt: 0
              }
            }
          })
          .then((result) => {
            const json = result.toJSON();

            return Promise.resolve(Number(json.backersCount));
          })
      },

      hasHost() {
        return Sequelize.models.UserGroup.find({
          where: {
            GroupId: this.id,
            role: roles.HOST
          }
        })
        .then(userGroup => Promise.resolve(!!userGroup));
      }

    }
  });

  return Group;
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Helmet from 'react-helmet';
import { Grid, Row, Col, Well, Label, Button, Modal } from 'react-bootstrap/lib';
import { connect } from 'react-redux';
import superagent from 'superagent';
import cookie from 'react-cookie';
import { Link } from 'react-router';

/* Import here only for Dispatchers */
import { getUser } from '../../redux/actions/getUserActions';
import { activateNewUser } from '../../redux/actions/activateNewUserActions';

@connect((store) => {
  return {
    getUserState: store.getUser.user,
    activateNewUserState: store.activateNewUser.userStatus,
  };
})

export default class MyProfile extends Component {
  state = {
    formStatus: 0,
    formMsg: '',
    showModal: false
  }

  editProfile = () => {
    alert("Edit dude!");
  }

  modalOpen = () => {
    this.setState({ showModal: true });
  }
  modalClose = () => {
    this.setState({ showModal: false });
  }

  render() {
    const { getUserState } = this.props;
    const { formStatus, formMsg } = this.state;
    const styles = require('./MyProfile.scss');

    return (

Mein Profil

          <Helmet title="Mein Profil"/>
          <Grid>
            <Row className="show-grid">
              <Col xs={12} md={6}>
                <Row className="show-grid">
                  <Col xs={2}>
                    <Link onClick={this.modalOpen}>

                    </Link>
                  </Col>
                  <Col xs={9}>
Nichname XY
</Col>
                  <Col xs={1}><Link onClick={this.editProfile}></Link></Col>
                </Row>
              </Col>
              <Col xs={12} md={6}>{'Avatar3'}</Col>
            </Row>
          </Grid>

          <Modal show={this.state.showModal} onHide={this.modalClose}>
            <Modal.Header closeButton>
              <Modal.Title>Avatar auswählen</Modal.Title>
            </Modal.Header>
            <Modal.Body>

Text in a modal

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Popover in a modal

there is a here

            </Modal.Body>
            <Modal.Footer>
              <Button onClick={this.modalClose}>Schliessen</Button>
            </Modal.Footer>
          </Modal>

    );
  }

}
<commit_msg>mexiko v9.0<commit_after>import React, {Component} from 'react';
import Helmet from 'react-helmet';
import { Grid, Row, Col, Well, Label, Button, Modal } from 'react-bootstrap/lib';
import { connect } from 'react-redux';
import superagent from 'superagent';
import cookie from 'react-cookie';
import { Link } from 'react-router';

/* Import here only for Dispatchers */
import { getUser } from '../../redux/actions/getUserActions';
import { activateNewUser } from '../../redux/actions/activateNewUserActions';

@connect((store) => {
  return {
    getUserState: store.getUser.user,
    activateNewUserState: store.activateNewUser.userStatus,
  };
})

export default class MyProfile extends Component {
  state = {
    formStatus: 0,
    formMsg: '',
    showModal: false
  }

  editProfile = () => {
    alert("Edit dude!");
  }

  modalOpen = () => {
    this.setState({ showModal: true });
  }
  modalClose = () => {
    this.setState({ showModal: false });
  }

  render() {
    const { getUserState } = this.props;
    const { formStatus, formMsg } = this.state;
    const styles = require('./MyProfile.scss');

    return (

Mein Profil

          <Helmet title="Mein Profil"/>
          <Grid>
            <Row className="show-grid">
              <Col xs={12} md={6}>
                <Row className="show-grid">
                  <Col xs={2}>
                    <Link onClick={this.modalOpen}>

                    </Link>
                  </Col>
                  <Col xs={9}>
{'Nichname XY'}
</Col>
                  <Col xs={1}></Col>
                </Row>
              </Col>
              <Col xs={12} md={6}>{'Avatar3'}</Col>
            </Row>
          </Grid>
          <Modal show={this.state.showModal} onHide={this.modalClose}>
            <Modal.Header closeButton>
              <Modal.Title>Avatar auswählen</Modal.Title>
            </Modal.Header>
            <Modal.Body>

Text in a modal

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Popover in a modal

there is a here

            </Modal.Body>
            <Modal.Footer>
              <Button onClick={this.modalClose}>Schliessen</Button>
            </Modal.Footer>
          </Modal>

    );
  }

}
<|endoftext|>