<commit_before>var el_residence_list;
window.onload = function() {
    var frm_select_residence     = document.getElementById('frm_select_residence');
    var frm_accept_disclaimer    = document.getElementById('frm_accept_disclaimer');
    var frm_accept_second_notice = document.getElementById('frm_accept_second_notice');
    el_residence_list            = document.getElementById('residence_list');

    // Get and then Populate residence list
    getResidenceList();

    function isRestrictedCountry(val) {
        // restricted countries code
        var regex = new RegExp(['^(',
            'as|af|at|au|be|bg|ca|ch|cy|cz|de|dk|ee|es|fi|fr|gb|gg|gr|gu|hk|hr|hu|ie|il|im|it|',
            'iq|ir|je|jp|kp|lt|lu|lv|mp|mt|my|nl|nz|pl|pt|pr|ro|se|sg|si|sk|sy|sz|us|vi|vg|vu',
            ')$'].join(''));
        if (regex.test(val)) {
            return true;
        }
        return false;
    }

    var country_names = [
        { code: 'ca', name: 'Canada' },
        { code: 'gb', name: 'the United Kingdom' },
        { code: 'eu', name: 'the European Economic Area' },
        { code: 'hk', name: 'Hong Kong' },
        { code: 'jp', name: 'Japan' },
        { code: 'sg', name: 'Singapore' },
        { code: 'ch', name: 'Switzerland' },
    ]

    function showSecondNotice(val) {
        var country_name;
        country_names.map(function(item, idx) {
            if (item.code === val) {
                country_name = item.name;
            }
        });
        document.getElementById('country_name').appendChild(document.createTextNode(country_name));
        document.getElementById('notice_msg').classList.remove('invisible');
        document.getElementById(val).classList.remove('invisible');
    }

    function showDisclaimer(val) {
        if (isRestrictedCountry(val)) {
            // eu countries code
            if (/^(al|ad|at|by|be|ba|bg|hr|cy|cz|dk|ee|fo|fi|fr|de|gi|gr|hu|is|ie|im|it|ru|lv|li|lt|lu|mk|mt|md|mc|me|nl|no|pl|pt|ro|sm|sk|si|es|se|ch|ua|va)$/.test(val)) {
                val = 'eu';
            }

            if (/^(ca|jp|sg|hk|uk|ch|eu)$/.test(val)) {
                showSecondNotice(val);
            } else {
                document.getElementById('access_denied_msg').classList.remove('invisible');
            }
        } else {
            document.getElementById('disclaimer_msg').classList.remove('invisible');
        }
    }

    function hideForm() {
        frm_select_residence.parentNode.classList.add('invisible');
    }

    frm_accept_disclaimer.addEventListener('submit', function (e) {
        e.preventDefault();
        var val = document.getElementById('checkbox').checked; // true or false
        var url = 'https://ico_documents.binary.com/im.pdf';
        if (val) {
            window.open(url, '_self');
        } else {
            document.getElementById('frm_accept_disclaimer_error').classList.remove('invisible');
        }
    });

    frm_select_residence.addEventListener('submit', function (e) {
        e.preventDefault();
        var val = document.getElementById('residence_list').value;
        hideForm();
        showDisclaimer(val);
    });

    frm_accept_second_notice.addEventListener('submit', function(e) {
        e.preventDefault();
        var val = document.getElementById('checkbox-2').checked; // true or false
        var url = 'https://ico_documents.binary.com/im.pdf';
        if (val) {
            document.getElementById('notice_msg').classList.add('invisible');
            showDisclaimer(val);
        } else {
            document.getElementById('frm_accept_notice_error').classList.remove('invisible');
        }
    })
};

function getResidenceList() {
    var residence_list = JSON.parse(sessionStorage.getItem('residence_list') || null);
    if (residence_list) {
        populateResidenceList(residence_list);
    } else {
        var ws = wsConnect();
        function sendResidenceList() {
            wsSend(ws, { residence_list: 1 });
        }

        if (ws.readyState === 1) {
            sendResidenceList();
        } else {
            ws.onopen = sendResidenceList;
        }

        ws.onmessage = function(msg) {
            var response = JSON.parse(msg.data);
            if (response.residence_list) {
                populateResidenceList(response.residence_list);
                setSession('residence_list', JSON.stringify(response.residence_list));
            }
        }
    }
}

function populateResidenceList(residence_list) {
    residence_list.forEach(function(res) {
        var el_option = document.createElement('option');
        el_option.text  = res.text;
        el_option.value = res.value;
        el_residence_list.appendChild(el_option);
    });
    document.getElementById('loading').classList.add('invisible');
    document.getElementById('disclaimer_form').classList.remove('invisible');
}
<commit_msg>Remove gb from restricted countries<commit_after>var el_residence_list;
window.onload = function() {
    var frm_select_residence     = document.getElementById('frm_select_residence');
    var frm_accept_disclaimer    = document.getElementById('frm_accept_disclaimer');
    var frm_accept_second_notice = document.getElementById('frm_accept_second_notice');
    el_residence_list            = document.getElementById('residence_list');

    // Get and then Populate residence list
    getResidenceList();

    function isRestrictedCountry(val) {
        // restricted countries code
        var regex = new RegExp(['^(',
            'as|af|at|au|be|bg|ca|ch|cy|cz|de|dk|ee|es|fi|fr|gg|gr|gu|hk|hr|hu|ie|il|im|it|',
            'iq|ir|je|jp|kp|lt|lu|lv|mp|mt|my|nl|nz|pl|pt|pr|ro|se|sg|si|sk|sy|sz|us|vi|vg|vu',
            ')$'].join(''));
        if (regex.test(val)) {
            return true;
        }
        return false;
    }

    var country_names = [
        { code: 'ca', name: 'Canada' },
        { code: 'gb', name: 'the United Kingdom' },
        { code: 'eu', name: 'the European Economic Area' },
        { code: 'hk', name: 'Hong Kong' },
        { code: 'jp', name: 'Japan' },
        { code: 'sg', name: 'Singapore' },
        { code: 'ch', name: 'Switzerland' },
    ]

    function showSecondNotice(val) {
        var country_name;
        country_names.map(function(item, idx) {
            if (item.code === val) {
                country_name = item.name;
            }
        });
        document.getElementById('country_name').appendChild(document.createTextNode(country_name));
        document.getElementById('notice_msg').classList.remove('invisible');
        document.getElementById(val).classList.remove('invisible');
    }

    function showDisclaimer(val) {
        if (isRestrictedCountry(val)) {
            // eu countries code
            if (/^(al|ad|at|by|be|ba|bg|hr|cy|cz|dk|ee|fo|fi|fr|de|gi|gr|hu|is|ie|im|it|ru|lv|li|lt|lu|mk|mt|md|mc|me|nl|no|pl|pt|ro|sm|sk|si|es|se|ch|ua|va)$/.test(val)) {
                val = 'eu';
            }

            if (/^(ca|jp|sg|hk|uk|ch|eu)$/.test(val)) {
                showSecondNotice(val);
            } else {
                document.getElementById('access_denied_msg').classList.remove('invisible');
            }
        } else {
            document.getElementById('disclaimer_msg').classList.remove('invisible');
        }
    }

    function hideForm() {
        frm_select_residence.parentNode.classList.add('invisible');
    }

    frm_accept_disclaimer.addEventListener('submit', function (e) {
        e.preventDefault();
        var val = document.getElementById('checkbox').checked; // true or false
        var url = 'https://ico_documents.binary.com/im.pdf';
        if (val) {
            window.open(url, '_self');
        } else {
            document.getElementById('frm_accept_disclaimer_error').classList.remove('invisible');
        }
    });

    frm_select_residence.addEventListener('submit', function (e) {
        e.preventDefault();
        var val = document.getElementById('residence_list').value;
        hideForm();
        showDisclaimer(val);
    });

    frm_accept_second_notice.addEventListener('submit', function(e) {
        e.preventDefault();
        var val = document.getElementById('checkbox-2').checked; // true or false
        var url = 'https://ico_documents.binary.com/im.pdf';
        if (val) {
            document.getElementById('notice_msg').classList.add('invisible');
            showDisclaimer(val);
        } else {
            document.getElementById('frm_accept_notice_error').classList.remove('invisible');
        }
    })
};

function getResidenceList() {
    var residence_list = JSON.parse(sessionStorage.getItem('residence_list') || null);
    if (residence_list) {
        populateResidenceList(residence_list);
    } else {
        var ws = wsConnect();
        function sendResidenceList() {
            wsSend(ws, { residence_list: 1 });
        }

        if (ws.readyState === 1) {
            sendResidenceList();
        } else {
            ws.onopen = sendResidenceList;
        }

        ws.onmessage = function(msg) {
            var response = JSON.parse(msg.data);
            if (response.residence_list) {
                populateResidenceList(response.residence_list);
                setSession('residence_list', JSON.stringify(response.residence_list));
            }
        }
    }
}

function populateResidenceList(residence_list) {
    residence_list.forEach(function(res) {
        var el_option = document.createElement('option');
        el_option.text  = res.text;
        el_option.value = res.value;
        el_residence_list.appendChild(el_option);
    });
    document.getElementById('loading').classList.add('invisible');
    document.getElementById('disclaimer_form').classList.remove('invisible');
}
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Typeahead from 'react-bootstrap-typeahead';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { Input, Button, Panel, Popover, OverlayTrigger, ButtonGroup, Grid, Row, Col } from 'react-bootstrap';
import { searchWorkflows, getWorkflowDefs } from '../../../actions/WorkflowActions';

function linkMaker(cell) {
  return <Link to={`/workflow/id/${cell}`}>{cell}</Link>;
}

function zeroPad(num) {
  return `0${num}`.slice(-2);
}

function formatDate(cell) {
  if (cell == null || !cell.split) {
    return '';
  }
  const c = cell.split('T');
  const time = c[1].split(':');
  const hh = zeroPad(time[0]);
  const mm = zeroPad(time[1]);
  const ss = zeroPad(time[2].replace('Z', ''));

  const dt = `${c[0]}T${hh}:${mm}:${ss}Z`;

  if (dt == null || dt === '') {
    return '';
  }

  return new Date(dt).toLocaleString('en-US');
}

function miniDetails(cell, row) {
  return (
    <ButtonGroup>
      <OverlayTrigger
        trigger="click"
        rootClose
        placement="left"
        overlay={
          <Popover title="Workflow Details" width={400}>

              {row.reasonForIncompletion == null ? (
                ''
              ) : (

                  {row.reasonForIncompletion}

              )}

            Input

              {row.input}

            Output

            {row.output}

          </Popover>
        }
      >
        <Button bsSize="xsmall">details</Button>
      </OverlayTrigger>
    </ButtonGroup>
  );
}

class Workflow extends React.Component {
  constructor(props) {
    super(props);
    let workflowTypes = props.location.query.workflowTypes;
    if (workflowTypes != null && workflowTypes !== '') {
      workflowTypes = workflowTypes.split(',');
    } else {
      workflowTypes = [];
    }
    let status = props.location.query.status;
    if (status != null && status !== '') {
      status = status.split(',');
    } else {
      status = [];
    }
    let search = props.location.query.q;
    if (search == null || search === 'undefined' || search === '') {
      search = '';
    }
    const st = props.location.query.start;
    let start = 0;
    if (!isNaN(st, 10)) {
      start = parseInt(st, 10);
    }

    this.state = {
      search,
      workflowTypes,
      status,
      h: this.props.location.query.h,
      workflows: [],
      update: true,
      fullstr: true,
      start
    };
  }

  componentWillMount() {
    this.props.dispatch(getWorkflowDefs());
    this.doDispatch();
  }

  componentWillReceiveProps(nextProps) {
    const { workflows = [] } = nextProps;

    const workflowDefs = workflows.map(workflowDef => workflowDef.name);

    let search = nextProps.location.query.q;
    if (search == null || search == 'undefined' || search == '') {
      search = '';
    }
    let h = nextProps.location.query.h;
    if (isNaN(h)) {
      h = '';
    }
    let start = nextProps.location.query.start;
    if (isNaN(start)) {
      start = 0;
    }
    let status = nextProps.location.query.status;
    if (status != null && status != '') {
      status = status.split(',');
    } else {
      status = [];
    }

    let update = true;
    update = this.state.search !== search;
    update = update || this.state.h !== h;
    update = update || this.state.start !== start;
    update = update || this.state.status.join(',') !== status.join(',');

    this.setState({
      search,
      h,
      update,
      status,
      workflows: workflowDefs,
      start
    });

    this.refreshResults();
  }

  searchBtnClick = () => {
    this.state.update = true;
    this.refreshResults();
  };

  refreshResults = () => {
    if (this.state.update) {
      this.state.update = false;
      this.urlUpdate();
      this.doDispatch();
    }
  };

  urlUpdate = () => {
    const { workflowTypes, status, start, h, search: q } = this.state;

    this.props.history.pushState(
      null,
      `/workflow?q=${q}&h=${h}&workflowTypes=${workflowTypes}&status=${status}&start=${start}`
    );
  };

  doDispatch = () => {
    const { search = '' } = this.state;
    const query = [];

    if (this.state.workflowTypes.length > 0) {
      query.push(`workflowType IN (${this.state.workflowTypes.join(',')}) `);
    }
    if (this.state.status.length > 0) {
      query.push(`status IN (${this.state.status.join(',')}) `);
    }
    this.props.dispatch(
      searchWorkflows(query.join(' AND '), search, this.state.h, this.state.fullstr, this.state.start)
    );
  };

  workflowTypeChange = workflowTypes => {
    this.state.update = true;
    this.state.workflowTypes = workflowTypes;
    this.refreshResults();
  };

  statusChange = status => {
    this.state.update = true;
    this.state.status = status;
    this.refreshResults();
  };

  nextPage = () => {
    this.state.start = 100 + parseInt(this.state.start, 10);
    this.state.update = true;
    this.refreshResults();
  };

  prevPage = () => {
    this.state.start = parseInt(this.state.start, 10) - 100;
    if (this.state.start < 0) {
      this.state.start = 0;
    }
    this.state.update = true;
    this.refreshResults();
  };

  searchChange = e => {
    const val = e.target.value;
    this.setState({ search: val });
  };

  hourChange = e => {
    this.state.update = true;
    this.state.h = e.target.value;
    this.refreshResults();
  };

  keyPress = e => {
    if (e.key == 'Enter') {
      this.state.update = true;
      var q = e.target.value;
      this.setState({ search: q });
      this.refreshResults();
    }
  };

  prefChange = e => {
    this.setState({
      fullstr: e.target.checked
    });
    this.state.update = true;
    this.refreshResults();
  };

  render() {
    let wfs = [];
    let filteredWfs = [];

    let totalHits = 0;
    let found = 0;
    if (this.props.data.hits) {
      wfs = this.props.data.hits;
      totalHits = this.props.data.totalHits;
      found = wfs.length;
    }
    const start = parseInt(this.state.start);
    let max = start + 100;
    if (found < 100) {
      max = start + found;
    }
    const workflowNames = this.state.workflows ? this.state.workflows : [];
    const statusList = ['RUNNING', 'COMPLETED', 'FAILED', 'TIMED_OUT', 'TERMINATED', 'PAUSED'];

    // secondary filter to match sure we only show workflows that match the the status
    var currentStatusArray = this.state.status;
    if (currentStatusArray.length > 0 && wfs.length > 0) {
      filteredWfs = wfs.filter(wf => currentStatusArray.includes(wf.status));
    } else {
      filteredWfs = wfs;
    }

    return (

          <Panel header="Filter Workflows (Press Enter to search)">
            <Grid fluid>
              <Row className="show-grid">
                <Col md={4}>
                  <Input
                    type="input"
                    placeholder="Search"
                    groupClassName=""
                    ref="search"
                    value={this.state.search}
                    labelClassName=""
                    onKeyPress={this.keyPress}
                    onChange={this.searchChange}
                  />

                    Free Text Query

                    <input
                    type="checkbox"
                    checked={this.state.fullstr}
                    onChange={this.prefChange}
                    ref="fullstr"
                  />
                   Search for entire string
                </Col>
                <Col md={4}>
                  <Typeahead
                    ref="workflowTypes"
                    onChange={this.workflowTypeChange}
                    options={workflowNames}
                    placeholder="Filter by workflow type"
                    multiple
                    selected={this.state.workflowTypes}
                  />

                    Filter by Workflow Type

                </Col>
                <Col md={2}>
                  <Typeahead
                    ref="status"
                    onChange={this.statusChange}
                    options={statusList}
                    placeholder="Filter by status"
                    selected={this.state.status}
                    multiple
                  />

                    Filter by Workflow Status

                </Col>
                <Col md={2}>
                  <Input
                    className="number-input"
                    type="text"
                    ref="h"
                    groupClassName="inline"
                    labelClassName=""
                    label=""
                    value={this.state.h}
                    onChange={this.hourChange}
                  />
                     <Button
                    bsStyle="success"
                    onClick={this.searchBtnClick}
                    className="search-label btn"
                  >
                      Search
                  </Button>

                    Created (in past hours)

                </Col>
              </Row>
            </Grid>
            <form />
          </Panel>

          Total Workflows Found: {totalHits}, Displaying {this.state.start} to {max}

          {parseInt(this.state.start, 10) >= 100 ? (

               Previous Page

          ) : (
            ''
          )}
          {parseInt(this.state.start, 10) + 100 <= totalHits ? (

                Next Page

          ) : (
            ''
          )}

        <BootstrapTable
          data={filteredWfs}
          striped
          hover
          search={false}
          exportCSV={false}
          pagination={false}
          options={{ sizePerPage: 100 }}
        >
          <TableHeaderColumn dataField="workflowType" isKey dataAlign="left" dataSort>
            Workflow
          </TableHeaderColumn>
          <TableHeaderColumn dataField="workflowId" dataSort dataFormat={linkMaker}>
            Workflow ID
          </TableHeaderColumn>
          <TableHeaderColumn dataField="status" dataSort>
            Status
          </TableHeaderColumn>
          <TableHeaderColumn dataField="startTime" dataSort dataFormat={formatDate}>
            Start Time
          </TableHeaderColumn>
          <TableHeaderColumn dataField="updateTime" dataSort dataFormat={formatDate}>
            Last Updated
          </TableHeaderColumn>
          <TableHeaderColumn dataField="endTime" hidden={false} dataFormat={formatDate}>
            End Time
          </TableHeaderColumn>
          <TableHeaderColumn dataField="reasonForIncompletion" hidden={false}>
            Failure Reason
          </TableHeaderColumn>
          <TableHeaderColumn dataField="failedReferenceTaskNames" hidden={false}>
            Failed Tasks
          </TableHeaderColumn>
          <TableHeaderColumn dataField="input" width="300">
            Input
          </TableHeaderColumn>
          <TableHeaderColumn dataField="workflowId" width="300" dataFormat={miniDetails}>

          </TableHeaderColumn>
        </BootstrapTable>

    );
  }
}

export default connect(state => state.workflow)(Workflow);
<commit_msg>createClass() is not supported in newer versions of react, refactoring in preparation for upgrade - WorkflowList.js<commit_after>/* eslint-disable no-restricted-globals */

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Typeahead from 'react-bootstrap-typeahead';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { Input, Button, Panel, Popover, OverlayTrigger, ButtonGroup, Grid, Row, Col } from 'react-bootstrap';
import { searchWorkflows, getWorkflowDefs } from '../../../actions/WorkflowActions';

function linkMaker(cell) {
  return <Link to={`/workflow/id/${cell}`}>{cell}</Link>;
}

function zeroPad(num) {
  return `0${num}`.slice(-2);
}

function formatDate(cell) {
  if (cell == null || !cell.split) {
    return '';
  }
  const c = cell.split('T');
  const time = c[1].split(':');
  const hh = zeroPad(time[0]);
  const mm = zeroPad(time[1]);
  const ss = zeroPad(time[2].replace('Z', ''));

  const dt = `${c[0]}T${hh}:${mm}:${ss}Z`;

  if (dt == null || dt === '') {
    return '';
  }

  return new Date(dt).toLocaleString('en-US');
}

function miniDetails(cell, row) {
  return (
    <ButtonGroup>
      <OverlayTrigger
        trigger="click"
        rootClose
        placement="left"
        overlay={
          <Popover title="Workflow Details" width={400}>

              {row.reasonForIncompletion == null ? (
                ''
              ) : (

                  {row.reasonForIncompletion}

              )}

            Input

              {row.input}

            Output

            {row.output}

          </Popover>
        }
      >
        <Button bsSize="xsmall">details</Button>
      </OverlayTrigger>
    </ButtonGroup>
  );
}

class Workflow extends React.Component {
  constructor(props) {
    super(props);
    const {
      location: {
        query: { workflowTypes = '', q = '', status = '', start = 0 }
      }
    } = props;

    this.state = {
      search: q === 'undefined' || q === '' ? '' : q,
      workflowTypes: workflowTypes === '' ? [] : workflowTypes.split(','),
      status: status !== '' ? status.split(',') : [],
      h: this.props.location.query.h,
      workflows: [],
      update: true,
      fullstr: true,
      start: !isNaN(start, 10) ? parseInt(start, 10) : start
    };
  }

  componentWillMount() {
    this.props.dispatch(getWorkflowDefs());
    this.doDispatch();
  }

  componentWillReceiveProps({
    workflows = [],
    location: {
      query: { h, start, status = '', q }
    }
  }) {
    const workflowDefs = workflows.map(workflowDef => workflowDef.name);

    let search = q;
    if (search == null || search === 'undefined' || search === '') {
      search = '';
    }

    let update = true;
    update = this.state.search !== search;
    update = update || this.state.h !== h;
    update = update || this.state.start !== start;

    this.setState({
      search,
      h: isNaN(h, 10) ? '' : h,
      update,
      status: status !== '' ? status.split(',') : [],
      workflows: workflowDefs,
      start: isNaN(start, 10) ? 0 : start
    });

    this.refreshResults();
  }

  searchBtnClick = () => {
    this.state.update = true;
    this.refreshResults();
  };

  refreshResults = () => {
    if (this.state.update) {
      this.state.update = false;
      this.urlUpdate();
      this.doDispatch();
    }
  };

  urlUpdate = () => {
    const { workflowTypes, status, start, h, search: q } = this.state;

    this.props.history.pushState(
      null,
      `/workflow?q=${q}&h=${h}&workflowTypes=${workflowTypes}&status=${status}&start=${start}`
    );
  };

  doDispatch = () => {
    const { search = '' } = this.state;
    const query = [];

    if (this.state.workflowTypes.length > 0) {
      query.push(`workflowType IN (${this.state.workflowTypes.join(',')}) `);
    }
    if (this.state.status.length > 0) {
      query.push(`status IN (${this.state.status.join(',')}) `);
    }
    this.props.dispatch(
      searchWorkflows(query.join(' AND '), search, this.state.h, this.state.fullstr, this.state.start)
    );
  };

  workflowTypeChange = workflowTypes => {
    this.state.update = true;
    this.state.workflowTypes = workflowTypes;
    this.refreshResults();
  };

  statusChange = status => {
    this.state.update = true;
    this.state.status = status;
    this.refreshResults();
  };

  nextPage = () => {
    this.state.start = 100 + parseInt(this.state.start, 10);
    this.state.update = true;
    this.refreshResults();
  };

  prevPage = () => {
    this.state.start = parseInt(this.state.start, 10) - 100;
    if (this.state.start < 0) {
      this.state.start = 0;
    }
    this.state.update = true;
    this.refreshResults();
  };

  searchChange = e => {
    const val = e.target.value;
    this.setState({ search: val });
  };

  hourChange = e => {
    this.state.update = true;
    this.state.h = e.target.value;
    this.refreshResults();
  };

  keyPress = e => {
    if (e.key == 'Enter') {
      this.state.update = true;
      var q = e.target.value;
      this.setState({ search: q });
      this.refreshResults();
    }
  };

  prefChange = e => {
    this.setState({
      fullstr: e.target.checked
    });
    this.state.update = true;
    this.refreshResults();
  };

  render() {
    let wfs = [];
    let filteredWfs = [];

    let totalHits = 0;
    let found = 0;
    if (this.props.data.hits) {
      wfs = this.props.data.hits;
      totalHits = this.props.data.totalHits;
      found = wfs.length;
    }
    const start = parseInt(this.state.start);
    let max = start + 100;
    if (found < 100) {
      max = start + found;
    }
    const workflowNames = this.state.workflows ? this.state.workflows : [];
    const statusList = ['RUNNING', 'COMPLETED', 'FAILED', 'TIMED_OUT', 'TERMINATED', 'PAUSED'];

    // secondary filter to match sure we only show workflows that match the the status
    var currentStatusArray = this.state.status;
    if (currentStatusArray.length > 0 && wfs.length > 0) {
      filteredWfs = wfs.filter(wf => currentStatusArray.includes(wf.status));
    } else {
      filteredWfs = wfs;
    }

    return (

          <Panel header="Filter Workflows (Press Enter to search)">
            <Grid fluid>
              <Row className="show-grid">
                <Col md={4}>
                  <Input
                    type="input"
                    placeholder="Search"
                    groupClassName=""
                    ref="search"
                    value={this.state.search}
                    labelClassName=""
                    onKeyPress={this.keyPress}
                    onChange={this.searchChange}
                  />

                    Free Text Query

                    <input
                    type="checkbox"
                    checked={this.state.fullstr}
                    onChange={this.prefChange}
                    ref="fullstr"
                  />
                   Search for entire string
                </Col>
                <Col md={4}>
                  <Typeahead
                    ref="workflowTypes"
                    onChange={this.workflowTypeChange}
                    options={workflowNames}
                    placeholder="Filter by workflow type"
                    multiple
                    selected={this.state.workflowTypes}
                  />

                    Filter by Workflow Type

                </Col>
                <Col md={2}>
                  <Typeahead
                    ref="status"
                    onChange={this.statusChange}
                    options={statusList}
                    placeholder="Filter by status"
                    selected={this.state.status}
                    multiple
                  />

                    Filter by Workflow Status

                </Col>
                <Col md={2}>
                  <Input
                    className="number-input"
                    type="text"
                    ref="h"
                    groupClassName="inline"
                    labelClassName=""
                    label=""
                    value={this.state.h}
                    onChange={this.hourChange}
                  />
                     <Button
                    bsStyle="success"
                    onClick={this.searchBtnClick}
                    className="search-label btn"
                  >
                      Search
                  </Button>

                    Created (in past hours)

                </Col>
              </Row>
            </Grid>
            <form />
          </Panel>

          Total Workflows Found: {totalHits}, Displaying {this.state.start} to {max}

          {parseInt(this.state.start, 10) >= 100 ? (

               Previous Page

          ) : (
            ''
          )}
          {parseInt(this.state.start, 10) + 100 <= totalHits ? (

                Next Page

          ) : (
            ''
          )}

        <BootstrapTable
          data={filteredWfs}
          striped
          hover
          search={false}
          exportCSV={false}
          pagination={false}
          options={{ sizePerPage: 100 }}
        >
          <TableHeaderColumn dataField="workflowType" isKey dataAlign="left" dataSort>
            Workflow
          </TableHeaderColumn>
          <TableHeaderColumn dataField="workflowId" dataSort dataFormat={linkMaker}>
            Workflow ID
          </TableHeaderColumn>
          <TableHeaderColumn dataField="status" dataSort>
            Status
          </TableHeaderColumn>
          <TableHeaderColumn dataField="startTime" dataSort dataFormat={formatDate}>
            Start Time
          </TableHeaderColumn>
          <TableHeaderColumn dataField="updateTime" dataSort dataFormat={formatDate}>
            Last Updated
          </TableHeaderColumn>
          <TableHeaderColumn dataField="endTime" hidden={false} dataFormat={formatDate}>
            End Time
          </TableHeaderColumn>
          <TableHeaderColumn dataField="reasonForIncompletion" hidden={false}>
            Failure Reason
          </TableHeaderColumn>
          <TableHeaderColumn dataField="failedReferenceTaskNames" hidden={false}>
            Failed Tasks
          </TableHeaderColumn>
          <TableHeaderColumn dataField="input" width="300">
            Input
          </TableHeaderColumn>
          <TableHeaderColumn dataField="workflowId" width="300" dataFormat={miniDetails}>

          </TableHeaderColumn>
        </BootstrapTable>

    );
  }
}

export default connect(state => state.workflow)(Workflow);
<|endoftext|>


<commit_before>import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLayoutEffect } from '../../utils/use-isomorphic-layout-effect';
import {
  findScrollParent,
  findScrollParents,
  isNodeAfterScroll,
  isNodeBeforeScroll,
} from '../../utils';
import { Box } from '../Box';
import { InfiniteScrollPropTypes } from './propTypes';

const calculateLastPageBound = (show, step) =>
  show ? Math.floor((show + step) / step) - 1 : 0;

const InfiniteScroll = ({
  children,
  items = [],
  onMore,
  renderMarker,
  replace,
  show,
  step = 50,
}) => {
  // item index to be made visible initially
  const [scrollShow, setScrollShow] = useState();

  // the last page we have items for
  const lastPage = useMemo(
    () => Math.floor(items.length / step),
    [items.length, step],
  );

  // the pages we are rendering
  const [renderPageBounds, setRenderPageBounds] = useState([
    0,
    calculateLastPageBound(show, step),
  ]);

  // the heights of the pages, approximated after we render the first page
  // and then updated for pages that have rendered
  const [pageHeights, setPageHeights] = useState([]);

  // what we're waiting for onMore to give us
  const [pendingLength, setPendingLength] = useState(0);

  const aboveMarkerRef = useRef(); // only when replacing
  const belowMarkerRef = useRef();

  // scroll and resize handling
  useEffect(() => {
    let scrollParents;

    const evaluate = () => {
      if (!scrollParents) return;
      const scrollParent = scrollParents[0];

      // Determine the scroll position of the scroll container
      let top;
      let height;
      if (scrollParent === document) {
        top = document.documentElement.scrollTop || document.body.scrollTop;
        height = window.innerHeight;
      } else {
        top = scrollParent.scrollTop;
        const rect = scrollParent.getBoundingClientRect();
        ({ height } = rect);
      }
      const offset = height / 4; // so we pre-load when the user scrolls slowly

      // Use the pageHeights to determine what pages we should render based
      // on the current scroll window.
      let nextBeginPage = 0;
      let index = 0;
      let pagesHeight = pageHeights[index] || 0;
      while (pageHeights[index + 1] && pagesHeight < top - offset) {
        index += 1;
        nextBeginPage += 1;
        pagesHeight += pageHeights[index];
      }
      let nextEndPage = nextBeginPage;
      while (
        pageHeights[index] !== undefined &&
        pagesHeight < top + height + offset
      ) {
        index += 1;
        nextEndPage += 1;
        // when we haven't rendered the nextEndPage and we aren't replacing,
        // we might not have a height for it yet
        pagesHeight += pageHeights[index] || 0;
      }

      if (!replace) {
        // when not replacing, never shrink bounds
        nextBeginPage = 0;
        nextEndPage = Math.max(renderPageBounds[1], nextEndPage);
      }

      if (show) {
        // ensure we try to render any show page
        const showPage = calculateLastPageBound(show, step);
        nextBeginPage = Math.min(showPage, nextBeginPage);
        nextEndPage = Math.max(showPage, nextEndPage);
      }

      if (
        nextBeginPage !== renderPageBounds[0] ||
        nextEndPage !== renderPageBounds[1]
      ) {
        setRenderPageBounds([nextBeginPage, nextEndPage]);
      }
    };

    let timer;
    const debounce = () => {
      clearTimeout(timer);
      timer = setTimeout(evaluate, 10);
    };

    // might not be there yet or might have already rendered everything
    if (belowMarkerRef.current) {
      scrollParents = findScrollParents(belowMarkerRef.current);
      scrollParents.forEach((sp) => sp.addEventListener('scroll', debounce));
    }
    window.addEventListener('resize', debounce);
    evaluate();
    return () => {
      if (scrollParents) {
        scrollParents.forEach((sp) =>
          sp.removeEventListener('scroll', debounce),
        );
      }
      window.removeEventListener('resize', debounce);
      clearTimeout(timer);
    };
  }, [pageHeights, renderPageBounds, replace, show, step]);

  // check if we need to ask for more
  useEffect(() => {
    if (
      onMore &&
      renderPageBounds[1] === lastPage &&
      items.length >= pendingLength
    ) {
      // remember we've asked for more, so we don't keep asking if it takes
      // a while
      setPendingLength(items.length + 1);
      onMore();
    }
  }, [items.length, lastPage, onMore, pendingLength, renderPageBounds, step]);

  useEffect(() => {
    if (items.length === 0 && lastPage === 0 && pendingLength !== 0) {
      setPageHeights([]);
      setPendingLength(0);
      setRenderPageBounds([0, calculateLastPageBound(show, step)]);
    }
  }, [lastPage, pendingLength, show, step, items.length]);

  // scroll to any 'show'
  useLayoutEffect(() => {
    // ride out any animation delays, 100ms empirically measured
    const timer = setTimeout(() => {
      if (show && belowMarkerRef.current && show !== scrollShow) {
        // calculate show index based on beginPage
        const showIndex =
          show - renderPageBounds[0] * step + (renderPageBounds[0] ? 1 : 0);
        const showNode =
          belowMarkerRef.current.parentNode.children.item(showIndex);
        if (showNode) {
          const scrollParent = findScrollParent(showNode);
          if (isNodeBeforeScroll(showNode, scrollParent)) {
            showNode.scrollIntoView(true);
          } else if (isNodeAfterScroll(showNode, scrollParent)) {
            showNode.scrollIntoView(false);
          }
          // clean up after having shown
          setScrollShow(show);
        }
      }
    }, 100);
    return () => clearTimeout(timer);
    // Omitting scrollShow as a dependency due to concern that setScrollShow
    // is being called within the timer. If left included, re-renders and other
    // dependency values could change in an unpredictable manner during timer
    // and potentially result in an infinite loop.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [renderPageBounds, show, step]);

  // calculate and keep track of page heights
  useLayoutEffect(() => {
    // if don't have a belowMarker, we must have rendered everything already
    if (!belowMarkerRef.current) return;

    // calculate page heights for rendered pages
    const {
      current: {
        parentNode: { children: rendered },
      },
    } = belowMarkerRef;
    // ensure we've rendered the state we have
    // above? + items in rendered pages + below === rendered DOM elements length
    if (
      (aboveMarkerRef.current ? 1 : 0) +
        (renderPageBounds[1] - renderPageBounds[0] + 1) * step +
        1 ===
      rendered.length
    ) {
      let nextPageHeights;

      // step through each page
      let i = renderPageBounds[0];
      let lastBottom;
      while (i <= renderPageBounds[1]) {
        const topIndex =
          (aboveMarkerRef.current ? 1 : 0) + (i - renderPageBounds[0]) * step;
        const bottomIndex = Math.min(topIndex + step - 1, rendered.length - 1);
        // we use lastBottom for top to ensure grid layouts work
        const top =
          lastBottom !== undefined
            ? lastBottom
            : rendered.item(topIndex).getBoundingClientRect().top;
        const { bottom } = rendered.item(bottomIndex).getBoundingClientRect();
        const height = bottom - top;
        if (bottom && (!pageHeights || pageHeights[i] !== height)) {
          if (!nextPageHeights) nextPageHeights = [...(pageHeights || [])];
          nextPageHeights[i] = height;
        }
        lastBottom = bottom;
        i += 1;
      }

      // estimate page heights for pages we haven't rendered yet
      while (replace && i <= lastPage) {
        if (!pageHeights[i] && pageHeights[i] !== pageHeights[0]) {
          if (!nextPageHeights) nextPageHeights = [...(pageHeights || [])];
          [nextPageHeights[i]] = nextPageHeights; // set to first page height
        }
        i += 1;
      }

      if (nextPageHeights) setPageHeights(nextPageHeights);
    }
  }, [lastPage, pageHeights, renderPageBounds, replace, step]);

  // calculate the height above the first rendered page using the pageHeights
  const aboveHeight = useMemo(() => {
    if (!replace) return 0;
    let height = 0;
    let i = 0;
    while (i < renderPageBounds[0]) {
      height += pageHeights[i] || 0;
      i += 1;
    }
    return height;
  }, [pageHeights, renderPageBounds, replace]);

  // calculate the height below the last rendered page using the pageHeights
  const belowHeight = useMemo(() => {
    if (!replace) return 0;
    let height = 0;
    let i = renderPageBounds[1] + 1;
    while (i <= lastPage) {
      height += pageHeights[i] || 0;
      i += 1;
    }
    return height;
  }, [lastPage, pageHeights, renderPageBounds, replace]);

  const firstIndex = renderPageBounds[0] * step;
  const lastIndex =
    Math.min((renderPageBounds[1] + 1) * step, items.length) - 1;

  const result = [];

  if (aboveHeight) {
    let marker = (
      <Box
        key="above"
        ref={aboveMarkerRef}
        flex={false}
        height={`${aboveHeight}px`}
      />
    );
    if (renderMarker) {
      // need to give it a key
      marker = React.cloneElement(renderMarker(marker), { key: 'above' });
    }
    result.push(marker);
  }

  items.slice(firstIndex, lastIndex + 1).forEach((item, index) => {
    const itemsIndex = firstIndex + index;
    const child = children(item, itemsIndex);
    result.push(child);
  });

  if (replace || renderPageBounds[1] < lastPage || onMore) {
    let marker = (
      <Box
        key="below"
        ref={(!renderMarker && belowMarkerRef) || undefined}
        flex={false}
        height={`${belowHeight || 0}px`}
      />
    );
    if (renderMarker) {
      // need to give it a key
      const renderedMarker = renderMarker(marker);
      marker = React.cloneElement(renderedMarker, {
        key: 'below',
        // We need to make sure our belowMarkerRef is tied to a component
        // that has the same parent as the items being rendered. This is so
        // we can use belowMarkerRef.current.parentNode.children to
        // get a reference to the items in the DOM for calculating pageHeights.
        //
        // Since the caller might have included a ref in what their
        // renderMarker returns, we have to take care of both refs.
        // https://github.com/facebook/react/issues/8873#issuecomment-489579878
        ref: (node) => {
          // Keep your own reference
          belowMarkerRef.current = node;
          // Call the original ref, if any
          const { ref } = renderedMarker;
          if (typeof ref === 'function') {
            ref(node);
          } else if (ref !== null) {
            ref.current = node;
          }
        },
      });
    }
    result.push(marker);
  }

  return result;
};

InfiniteScroll.propTypes = InfiniteScrollPropTypes;

export { InfiniteScroll };
<commit_msg>Fix an InfiniteScroll onMore infinite recursion (#5636)<commit_after>import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLayoutEffect } from '../../utils/use-isomorphic-layout-effect';
import {
  findScrollParent,
  findScrollParents,
  isNodeAfterScroll,
  isNodeBeforeScroll,
} from '../../utils';
import { Box } from '../Box';
import { InfiniteScrollPropTypes } from './propTypes';

const calculateLastPageBound = (show, step) =>
  show ? Math.floor((show + step) / step) - 1 : 0;

const InfiniteScroll = ({
  children,
  items = [],
  onMore,
  renderMarker,
  replace,
  show,
  step = 50,
}) => {
  // item index to be made visible initially
  const [scrollShow, setScrollShow] = useState();

  // the last page we have items for
  const lastPage = useMemo(
    () => Math.floor(items.length / step),
    [items.length, step],
  );

  // the pages we are rendering
  const [renderPageBounds, setRenderPageBounds] = useState([
    0,
    calculateLastPageBound(show, step),
  ]);

  // the heights of the pages, approximated after we render the first page
  // and then updated for pages that have rendered
  const [pageHeights, setPageHeights] = useState([]);

  // what we're waiting for onMore to give us
  const [pendingLength, setPendingLength] = useState(0);

  const aboveMarkerRef = useRef(); // only when replacing
  const belowMarkerRef = useRef();

  // scroll and resize handling
  useEffect(() => {
    let scrollParents;

    const evaluate = () => {
      if (!scrollParents) return;
      const scrollParent = scrollParents[0];

      // Determine the scroll position of the scroll container
      let top;
      let height;
      if (scrollParent === document) {
        top = document.documentElement.scrollTop || document.body.scrollTop;
        height = window.innerHeight;
      } else {
        top = scrollParent.scrollTop;
        const rect = scrollParent.getBoundingClientRect();
        ({ height } = rect);
      }
      const offset = height / 4; // so we pre-load when the user scrolls slowly

      // Use the pageHeights to determine what pages we should render based
      // on the current scroll window.
      let nextBeginPage = 0;
      let index = 0;
      let pagesHeight = pageHeights[index] || 0;
      while (pageHeights[index + 1] && pagesHeight < top - offset) {
        index += 1;
        nextBeginPage += 1;
        pagesHeight += pageHeights[index];
      }
      let nextEndPage = nextBeginPage;
      while (
        pageHeights[index] !== undefined &&
        pagesHeight < top + height + offset
      ) {
        index += 1;
        nextEndPage += 1;
        // when we haven't rendered the nextEndPage and we aren't replacing,
        // we might not have a height for it yet
        pagesHeight += pageHeights[index] || 0;
      }

      if (!replace) {
        // when not replacing, never shrink bounds
        nextBeginPage = 0;
        nextEndPage = Math.max(renderPageBounds[1], nextEndPage);
      }

      if (show) {
        // ensure we try to render any show page
        const showPage = calculateLastPageBound(show, step);
        nextBeginPage = Math.min(showPage, nextBeginPage);
        nextEndPage = Math.max(showPage, nextEndPage);
      }

      if (
        nextBeginPage !== renderPageBounds[0] ||
        nextEndPage !== renderPageBounds[1]
      ) {
        setRenderPageBounds([nextBeginPage, nextEndPage]);
      }
    };

    let timer;
    const debounce = () => {
      clearTimeout(timer);
      timer = setTimeout(evaluate, 10);
    };

    // might not be there yet or might have already rendered everything
    if (belowMarkerRef.current) {
      scrollParents = findScrollParents(belowMarkerRef.current);
      scrollParents.forEach((sp) => sp.addEventListener('scroll', debounce));
    }
    window.addEventListener('resize', debounce);
    evaluate();
    return () => {
      if (scrollParents) {
        scrollParents.forEach((sp) =>
          sp.removeEventListener('scroll', debounce),
        );
      }
      window.removeEventListener('resize', debounce);
      clearTimeout(timer);
    };
  }, [pageHeights, renderPageBounds, replace, show, step]);

  // check if we need to ask for more
  useEffect(() => {
    if (
      onMore &&
      renderPageBounds[1] === lastPage &&
      items.length >= pendingLength &&
      items.length > 0
    ) {
      // remember we've asked for more, so we don't keep asking if it takes
      // a while
      setPendingLength(items.length + 1);
      onMore();
    }
  }, [items.length, lastPage, onMore, pendingLength, renderPageBounds, step]);

  useEffect(() => {
    if (items.length === 0 && lastPage === 0 && pendingLength !== 0) {
      setPageHeights([]);
      setPendingLength(0);
      setRenderPageBounds([0, calculateLastPageBound(show, step)]);
    }
  }, [lastPage, pendingLength, show, step, items.length]);

  // scroll to any 'show'
  useLayoutEffect(() => {
    // ride out any animation delays, 100ms empirically measured
    const timer = setTimeout(() => {
      if (show && belowMarkerRef.current && show !== scrollShow) {
        // calculate show index based on beginPage
        const showIndex =
          show - renderPageBounds[0] * step + (renderPageBounds[0] ? 1 : 0);
        const showNode =
          belowMarkerRef.current.parentNode.children.item(showIndex);
        if (showNode) {
          const scrollParent = findScrollParent(showNode);
          if (isNodeBeforeScroll(showNode, scrollParent)) {
            showNode.scrollIntoView(true);
          } else if (isNodeAfterScroll(showNode, scrollParent)) {
            showNode.scrollIntoView(false);
          }
          // clean up after having shown
          setScrollShow(show);
        }
      }
    }, 100);
    return () => clearTimeout(timer);
    // Omitting scrollShow as a dependency due to concern that setScrollShow
    // is being called within the timer. If left included, re-renders and other
    // dependency values could change in an unpredictable manner during timer
    // and potentially result in an infinite loop.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [renderPageBounds, show, step]);

  // calculate and keep track of page heights
  useLayoutEffect(() => {
    // if don't have a belowMarker, we must have rendered everything already
    if (!belowMarkerRef.current) return;

    // calculate page heights for rendered pages
    const {
      current: {
        parentNode: { children: rendered },
      },
    } = belowMarkerRef;
    // ensure we've rendered the state we have
    // above? + items in rendered pages + below === rendered DOM elements length
    if (
      (aboveMarkerRef.current ? 1 : 0) +
        (renderPageBounds[1] - renderPageBounds[0] + 1) * step +
        1 ===
      rendered.length
    ) {
      let nextPageHeights;

      // step through each page
      let i = renderPageBounds[0];
      let lastBottom;
      while (i <= renderPageBounds[1]) {
        const topIndex =
          (aboveMarkerRef.current ? 1 : 0) + (i - renderPageBounds[0]) * step;
        const bottomIndex = Math.min(topIndex + step - 1, rendered.length - 1);
        // we use lastBottom for top to ensure grid layouts work
        const top =
          lastBottom !== undefined
            ? lastBottom
            : rendered.item(topIndex).getBoundingClientRect().top;
        const { bottom } = rendered.item(bottomIndex).getBoundingClientRect();
        const height = bottom - top;
        if (bottom && (!pageHeights || pageHeights[i] !== height)) {
          if (!nextPageHeights) nextPageHeights = [...(pageHeights || [])];
          nextPageHeights[i] = height;
        }
        lastBottom = bottom;
        i += 1;
      }

      // estimate page heights for pages we haven't rendered yet
      while (replace && i <= lastPage) {
        if (!pageHeights[i] && pageHeights[i] !== pageHeights[0]) {
          if (!nextPageHeights) nextPageHeights = [...(pageHeights || [])];
          [nextPageHeights[i]] = nextPageHeights; // set to first page height
        }
        i += 1;
      }

      if (nextPageHeights) setPageHeights(nextPageHeights);
    }
  }, [lastPage, pageHeights, renderPageBounds, replace, step]);

  // calculate the height above the first rendered page using the pageHeights
  const aboveHeight = useMemo(() => {
    if (!replace) return 0;
    let height = 0;
    let i = 0;
    while (i < renderPageBounds[0]) {
      height += pageHeights[i] || 0;
      i += 1;
    }
    return height;
  }, [pageHeights, renderPageBounds, replace]);

  // calculate the height below the last rendered page using the pageHeights
  const belowHeight = useMemo(() => {
    if (!replace) return 0;
    let height = 0;
    let i = renderPageBounds[1] + 1;
    while (i <= lastPage) {
      height += pageHeights[i] || 0;
      i += 1;
    }
    return height;
  }, [lastPage, pageHeights, renderPageBounds, replace]);

  const firstIndex = renderPageBounds[0] * step;
  const lastIndex =
    Math.min((renderPageBounds[1] + 1) * step, items.length) - 1;

  const result = [];

  if (aboveHeight) {
    let marker = (
      <Box
        key="above"
        ref={aboveMarkerRef}
        flex={false}
        height={`${aboveHeight}px`}
      />
    );
    if (renderMarker) {
      // need to give it a key
      marker = React.cloneElement(renderMarker(marker), { key: 'above' });
    }
    result.push(marker);
  }

  items.slice(firstIndex, lastIndex + 1).forEach((item, index) => {
    const itemsIndex = firstIndex + index;
    const child = children(item, itemsIndex);
    result.push(child);
  });

  if (replace || renderPageBounds[1] < lastPage || onMore) {
    let marker = (
      <Box
        key="below"
        ref={(!renderMarker && belowMarkerRef) || undefined}
        flex={false}
        height={`${belowHeight || 0}px`}
      />
    );
    if (renderMarker) {
      // need to give it a key
      const renderedMarker = renderMarker(marker);
      marker = React.cloneElement(renderedMarker, {
        key: 'below',
        // We need to make sure our belowMarkerRef is tied to a component
        // that has the same parent as the items being rendered. This is so
        // we can use belowMarkerRef.current.parentNode.children to
        // get a reference to the items in the DOM for calculating pageHeights.
        //
        // Since the caller might have included a ref in what their
        // renderMarker returns, we have to take care of both refs.
        // https://github.com/facebook/react/issues/8873#issuecomment-489579878
        ref: (node) => {
          // Keep your own reference
          belowMarkerRef.current = node;
          // Call the original ref, if any
          const { ref } = renderedMarker;
          if (typeof ref === 'function') {
            ref(node);
          } else if (ref !== null) {
            ref.current = node;
          }
        },
      });
    }
    result.push(marker);
  }

  return result;
};

InfiniteScroll.propTypes = InfiniteScrollPropTypes;

export { InfiniteScroll };
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  internal hook registry  */
_cs.hooks = {};

/*  internal hook processing  */
_cs.hook_proc = {
    "none":   { init: undefined,                     step: function (    ) {                          } },
    "pass":   { init: function (a) { return a[0]; }, step: function (a, b) { return b;                } },
    "or":     { init: false,                         step: function (a, b) { return a || b;           } },
    "and":    { init: true,                          step: function (a, b) { return a && b;           } },
    "mult":   { init: 1,                             step: function (a, b) { return a * b;            } },
    "add":    { init: 0,                             step: function (a, b) { return a + b;            } },
    "append": { init: "",                            step: function (a, b) { return a + b;            } },
    "push":   { init: [],                            step: function (a, b) { a.push(b); return a;     } },
    "concat": { init: [],                            step: function (a, b) { return _cs.concat(a, b); } },
    "insert": { init: {},                            step: function (a, b) { a[b] = true; return a;   } },
    "extend": { init: {},                            step: function (a, b) { return _cs.extend(a, b); } }
};

/*  latch into internal ComponentJS hook  */
_cs.latch = function (name, cb) {
    /*  sanity check arguments  */
    if (arguments.length < 2)
        throw _cs.exception("latch(internal)", "missing arguments");

    /*  on-the-fly create hook callback registry  */
    if (typeof _cs.hooks[name] === "undefined")
        _cs.hooks[name] = [];

    /*  store callback in hook callback registry  */
    var args = _cs.slice(arguments, 2);
    var id = _cs.cid();
    _cs.hooks[name].push({ id: id, cb: cb, args: args });
    return id;
};

/*  unlatch from internal ComponentJS hook  */
_cs.unlatch = function (name, id) {
    /*  sanity check arguments  */
    if (arguments.length !== 2)
        throw _cs.exception("unlatch(internal)", "invalid number of arguments");
    if (typeof _cs.hooks[name] === "undefined")
        throw _cs.exception("unlatch(internal)", "no such hook");

    /*  search for callback in hook callback registry  */
    var k = -1;
    for (var i = 0; i < _cs.hooks[name].length; i++) {
        if (_cs.hooks[name][i].id === id) {
            k = i;
            break;
        }
    }
    if (k === -1)
        throw _cs.exception("unlatch(internal)", "no such latched callback");

    /*  remove callback from hook callback registry  */
    _cs.hooks[name] = _cs.hooks[name].splice(k, 1);
    return;
};

/*  provide internal ComponentJS hook  */
_cs.hook = function (name, proc) {
    /*  sanity check arguments  */
    if (arguments.length < 2)
        throw _cs.exception("hook(internal)", "missing argument");
    if (typeof _cs.hook_proc[proc] === "undefined")
        throw _cs.exception("hook(internal)", "no such result processing defined");

    /*  start result with the initial value  */
    var result = _cs.hook_proc[proc].init;
    var args = null;
    if (typeof result === "function") {
        args = _cs.slice(arguments, 2);
        result = result.call(null, args);
    }

    /*  give all registered callbacks a chance to
        execute and modify the current result  */
    if (typeof _cs.hooks[name] !== "undefined") {
        if (args === null)
            args = _cs.slice(arguments, 2);
        _cs.foreach(_cs.hooks[name], function (s) {
            var r = s.cb.apply({ args: s.args, _cs: _cs, $cs: $cs }, args);
            result = _cs.hook_proc[proc].step.call(null, result, r);
        });
    }

    /*  return the final result  */
    return result;
};

<commit_msg>improve internal hook functionality<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  internal hook registry  */
_cs.hooks = {};

/*  internal hook processing  */
_cs.hook_proc = {
    "none":   { init: undefined,                     step: function (    ) {                          } },
    "pass":   { init: function (a) { return a[0]; }, step: function (a, b) { return b;                } },
    "or":     { init: false,                         step: function (a, b) { return a || b;           } },
    "and":    { init: true,                          step: function (a, b) { return a && b;           } },
    "mult":   { init: 1,                             step: function (a, b) { return a * b;            } },
    "add":    { init: 0,                             step: function (a, b) { return a + b;            } },
    "append": { init: "",                            step: function (a, b) { return a + b;            } },
    "push":   { init: [],                            step: function (a, b) { a.push(b); return a;     } },
    "concat": { init: [],                            step: function (a, b) { return _cs.concat(a, b); } },
    "insert": { init: {},                            step: function (a, b) { a[b] = true; return a;   } },
    "extend": { init: {},                            step: function (a, b) { return _cs.extend(a, b); } }
};

/*  latch into internal ComponentJS hook  */
_cs.latch = function (name, cb) {
    /*  sanity check arguments  */
    if (arguments.length < 2)
        throw _cs.exception("latch(internal)", "missing arguments");

    /*  on-the-fly create hook callback registry  */
    if (typeof _cs.hooks[name] === "undefined")
        _cs.hooks[name] = [];

    /*  store callback in hook callback registry  */
    var args = _cs.slice(arguments, 2);
    var id = _cs.cid();
    _cs.hooks[name].push({ id: id, cb: cb, args: args });
    return id;
};

/*  unlatch from internal ComponentJS hook  */
_cs.unlatch = function (name, id) {
    /*  sanity check arguments  */
    if (arguments.length !== 2)
        throw _cs.exception("unlatch(internal)", "invalid number of arguments");
    if (typeof _cs.hooks[name] === "undefined")
        throw _cs.exception("unlatch(internal)", "no such hook");

    /*  search for callback in hook callback registry  */
    var k = -1;
    for (var i = 0; i < _cs.hooks[name].length; i++) {
        if (_cs.hooks[name][i].id === id) {
            k = i;
            break;
        }
    }
    if (k === -1)
        throw _cs.exception("unlatch(internal)", "no such latched callback");

    /*  remove callback from hook callback registry  */
    _cs.hooks[name] = _cs.hooks[name].splice(k, 1);
    return;
};

/*  provide internal ComponentJS hook  */
_cs.hook = function (name, proc) {
    /*  sanity check arguments  */
    if (arguments.length < 2)
        throw _cs.exception("hook(internal)", "missing argument");
    if (typeof _cs.hook_proc[proc] === "undefined")
        throw _cs.exception("hook(internal)", "no such result processing defined");

    /*  start result with the initial value  */
    var result = _cs.hook_proc[proc].init;
    var args = null;
    if (typeof result === "function") {
        args = _cs.slice(arguments, 2);
        result = result.call(null, args);
    }

    /*  give all registered callbacks a chance to
        execute and modify the current result  */
    if (typeof _cs.hooks[name] !== "undefined") {
        if (args === null)
            args = _cs.slice(arguments, 2);
        _cs.foreach(_cs.hooks[name], function (l) {
            /*  call latched callback  */
            var r = l.cb.apply({
                args:   l.args,                 /*  latch arguments  */
                result: result,                 /*  current result   */
                hooks:  _cs.hooks[name].length, /*  total number of hooks latched  */
                _cs:    _cs,                    /*  internal ComponentJS API  */
                $cs:    $cs                     /*  external ComponentJS API  */
            },  args);                          /*  hook arguments  */

            /*  process/merge results  */
            result = _cs.hook_proc[proc].step.call(null, result, r);
        });
    }

    /*  return the final result  */
    return result;
};

<|endoftext|>


<commit_before>var test = require('prova')
  , {{PascalName}} = require('./index.js')

test('{{PascalName}} Component: lifecycle functions', function(t){

  var {{camelName}} = new {{PascalName}}()
  t.equal(
    typeof {{camelName}}
    , 'object'
    , 'creates an object'
  )

  t.end()
})

test('{{PascalName}} Component: custom method', function(t){
  var {{camelName}} = new {{PascalName}}()

  t.end()
})
<commit_msg>Dry-er test template<commit_after>var test = require('prova')
  , {{PascalName}} = require('./index.js')
  , newView = function newView(options){
    return new {{PascalName}}(options)
  }

test('{{PascalName}} Component: beforeInit functions', function(t){

  var view = newView()
  t.equal(
    typeof view
    , 'object'
    , 'creates an object'
  )

  t.end()
})

test('{{PascalName}} Component: custom method', function(t){
  var view = newView()

  t.end()
})
<|endoftext|>


<commit_before>'use strict';

import React, {
  View,
  Text,
  TouchableNativeFeedback,
  StyleSheet,
  Alert
} from 'react-native';
const Icon = require('react-native-vector-icons/MaterialIcons');
const CardService = require('../data/cardFirebaseService');

var CardItem = React.createClass({

  render() {
    return (
      <View style={styles.cardItem}>
        <TouchableNativeFeedback onPress={this.openCardDetails}>
          <View style={styles.cardDescContainer}>
            <Text style={styles.cardName}>{this.props.card.name}</Text>
            <Text style={styles.cardNum}>(...{this.props.card.last4})</Text>
          </View>
        </TouchableNativeFeedback>
        <TouchableNativeFeedback onPress={this.confirmDelete}>
          <View style={styles.actionItem}>
            <Icon style={styles.actionIcon} name="delete" />
          </View>
        </TouchableNativeFeedback>
      </View>
    );
  },

  confirmDelete() {
    Alert.alert(
      `Delete '${this.props.card.name}'?`,
      'Are you sure you want to delete this card? This action cannot be undone.',
      [
        {text: 'Cancel'},
        {text: 'Delete', onPress: this.deleteCard}
      ]
    );
  },

  deleteCard() {
    const service = new CardService(this.props.uid);
    service.deleteCard(this.props.card.id);
  }
});

const styles = StyleSheet.create({
  cardItem: {
    height: 75,
    margin: 20,
    marginBottom: 0,
    backgroundColor: '#FFFFFF',
    elevation: 5,
    alignItems: 'center',
    flexDirection: 'row'
  },
  cardDescContainer: {
    flex:1,
    height: 75,
    padding: 10,
    justifyContent: 'center'
  },
  cardName: {
    fontSize: 18,
    color: '#757575'
  },
  cardNum: {
    fontSize: 12,
    color: '#9E9E9E'
  },
  actionItem: {
    padding: 10,
    height: 75,
    width: 75,
    justifyContent: 'center',
    alignItems: 'center'
  },
  actionIcon: {
    fontSize: 32,
    color: '#757575'
  }

});

module.exports = CardItem;
<commit_msg>Style tweaks<commit_after>'use strict';

import React, {
  View,
  Text,
  TouchableNativeFeedback,
  StyleSheet,
  Alert
} from 'react-native';
const Icon = require('react-native-vector-icons/MaterialIcons');
const CardService = require('../data/cardFirebaseService');

var CardItem = React.createClass({

  render() {
    return (
      <View style={styles.cardItem}>
        <TouchableNativeFeedback onPress={this.openCardDetails}>
          <View style={styles.cardDescContainer}>
            <Text style={styles.cardName}>{this.props.card.name}</Text>
            <Text style={styles.cardNum}>...{this.props.card.last4}</Text>
          </View>
        </TouchableNativeFeedback>
        <TouchableNativeFeedback onPress={this.confirmDelete}>
          <View style={styles.actionItem}>
            <Icon style={styles.actionIcon} name="delete" />
          </View>
        </TouchableNativeFeedback>
      </View>
    );
  },

  confirmDelete() {
    Alert.alert(
      `Delete '${this.props.card.name}'?`,
      'Are you sure you want to delete this card? This action cannot be undone.',
      [
        {text: 'Cancel'},
        {text: 'Delete', onPress: this.deleteCard}
      ]
    );
  },

  deleteCard() {
    const service = new CardService(this.props.uid);
    service.deleteCard(this.props.card.id);
  }
});

const styles = StyleSheet.create({
  cardItem: {
    height: 75,
    margin: 20,
    marginBottom: 0,
    backgroundColor: '#FFFFFF',
    elevation: 5,
    alignItems: 'center',
    flexDirection: 'row'
  },
  cardDescContainer: {
    flex:1,
    height: 75,
    padding: 10,
    justifyContent: 'center'
  },
  cardName: {
    fontSize: 18,
    color: '#757575'
  },
  cardNum: {
    fontSize: 14,
    color: '#9E9E9E'
  },
  actionItem: {
    padding: 10,
    height: 75,
    width: 75,
    justifyContent: 'center',
    alignItems: 'center'
  },
  actionIcon: {
    fontSize: 32,
    color: '#757575'
  }

});

module.exports = CardItem;
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import styled from 'styled-components';
import webp from '../../utils/webp';
import { unsplashParams } from '../../config';

const Picture = styled.picture`
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
  }
`;

const Image = styled.img`
  height: 100%;
  width: 100%;
  object-fit: cover;
`;

type Props = {
  image: {
    imageUrl: string,
    name: string,
    url?: string,
  },
};

const HeaderImage = ({ image }: Props) => {
  const imgUrl = `/static/images/posts/${image.imageUrl}`;
  const { url: webpImage, type } = webp(image.imageUrl);

  const webpbg = `/static/images/posts/${webpImage}`;

  return (
    <Picture>
      <source srcSet={webpbg} type="image/webp" />
      <source srcSet={image} type={type} />
      <Image
        src={`/static/images/posts/${image.imageUrl}`}
        alt={image.name ? `Taken by ${image.name}` : ''}
        data-source-url={unsplashParams(imgUrl)}
      />
    </Picture>
  );
};

export default HeaderImage;
<commit_msg>fix image paths with Header Image<commit_after>// @flow
import React from 'react';
import styled from 'styled-components';
import webp from '../../utils/webp';
import { unsplashParams } from '../../config';

const Picture = styled.picture`
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
  }
`;

const Image = styled.img`
  height: 100%;
  width: 100%;
  object-fit: cover;
`;

type Props = {
  image: {
    imageUrl: string,
    name: string,
    url?: string,
  },
};

const HeaderImage = ({ image }: Props) => {
  const imagePath = '/static/images/posts';
  const imgUrl = `${imagePath}/${image.imageUrl}`;
  const { url: webpImage, type } = webp(image.imageUrl);

  const webpbg = `${imagePath}/${webpImage}`;

  return (
    <Picture>
      <source srcSet={webpbg} type="image/webp" />
      <source srcSet={imgUrl} type={type} />
      <Image
        src={imgUrl}
        alt={image.name ? `Taken by ${image.name}` : ''}
        data-source-url={unsplashParams(image.url)}
      />
    </Picture>
  );
};

export default HeaderImage;
<|endoftext|>


<commit_before>import Event from './event';

const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ];
const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ];

const Day = ({ events, clickHandler }) => {
  const DAY = events[ 0 ].start_time;

  const DAY_NAME = DAY_NAMES[ DAY.getDay() ];
  const DATE = DAY.getDate();
  const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ];

  return (

{DAY_NAME} {`${DATE}. ${MONTH_NAME}`}

      { events.map((e, id) => {
        return <Event clickHandler={clickHandler} title={e.title} start_time={e.start_time} content={e.content} key={id}/>
      })}

  );
};

export default Day;
<commit_msg>Pass eventClickHandler and active element to Event form Day<commit_after>import Event from './event';

const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ];
const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ];

const Day = ({ events, eventClickHandler, active }) => {
  const DAY = events[ 0 ].start_time;

  const DAY_NAME = DAY_NAMES[ DAY.getDay() ];
  const DATE = DAY.getDate();
  const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ];

  return (

{DAY_NAME} {`${DATE}. ${MONTH_NAME}`}

      { events.map((e, id) => {
        return <Event eventClickHandler={eventClickHandler} active={active} title={e.title} start_time={e.start_time} content={e.content} key={id} index={e.index} />
      })}

  );
};

export default Day;
<|endoftext|>


<commit_before>Prism.languages.keyman = {
	'comment': /\bc\s.*/i,
	'function': /\[\s*((CTRL|SHIFT|ALT|LCTRL|RCTRL|LALT|RALT|CAPS|NCAPS)\s+)*([TKU]_[a-z0-9_?]+|".+?"|'.+?')\s*\]/i,  // virtual key
	'string': /("|')((?!\1).)*\1/,
	'keyword': /\b(any|beep|call|context|deadkey|dk|if|index|notany|nul|outs|return|reset|save|set|store|use)\b/i,  // rule keywords
	'atrule': /\b(ansi|begin|unicode|group|using keys|match|nomatch)\b/i,   // structural keywords
	'bold': [   // header statements
		/&(baselayout|bitmap|capsononly|capsalwaysoff|shiftfreescaps|copyright|ethnologuecode|hotkey|includecodes|keyboardversion|kmw_embedcss|kmw_embdjs|kmw_helpfile|kmw_helptext|kmw_rtl|language|layer|layoutfile|message|mnemoniclayout|name|oldcharposmatching|platform|targets|version|visualkeyboard|windowslanguages)\b/i,
		/\b(bitmap|bitmaps|caps on only|caps always off|shift frees caps|copyright|hotkey|language|layout|message|name|version)\b/i
	],
	'number': /\b(U\+[\dA-F]+|d\d+|x[\da-f]+|\d+)\b/i, // U+####, x###, d### characters and numbers
	'operator': /[+>\\,()]/,
	'tag': /\$(keyman|kmfl|weaver|keymanweb|keymanonly):/i   // prefixes
};<commit_msg>fix typo in kmw_embedjs<commit_after>Prism.languages.keyman = {
	'comment': /\bc\s.*/i,
	'function': /\[\s*((CTRL|SHIFT|ALT|LCTRL|RCTRL|LALT|RALT|CAPS|NCAPS)\s+)*([TKU]_[a-z0-9_?]+|".+?"|'.+?')\s*\]/i,  // virtual key
	'string': /("|')((?!\1).)*\1/,
	'keyword': /\b(any|beep|call|context|deadkey|dk|if|index|notany|nul|outs|return|reset|save|set|store|use)\b/i,  // rule keywords
	'atrule': /\b(ansi|begin|unicode|group|using keys|match|nomatch)\b/i,   // structural keywords
	'bold': [   // header statements
		/&(baselayout|bitmap|capsononly|capsalwaysoff|shiftfreescaps|copyright|ethnologuecode|hotkey|includecodes|keyboardversion|kmw_embedcss|kmw_embedjs|kmw_helpfile|kmw_helptext|kmw_rtl|language|layer|layoutfile|message|mnemoniclayout|name|oldcharposmatching|platform|targets|version|visualkeyboard|windowslanguages)\b/i,
		/\b(bitmap|bitmaps|caps on only|caps always off|shift frees caps|copyright|hotkey|language|layout|message|name|version)\b/i
	],
	'number': /\b(U\+[\dA-F]+|d\d+|x[\da-f]+|\d+)\b/i, // U+####, x###, d### characters and numbers
	'operator': /[+>\\,()]/,
	'tag': /\$(keyman|kmfl|weaver|keymanweb|keymanonly):/i   // prefixes
};<|endoftext|>


<commit_before>NCI.setupCommunities = function(data){
	NCI.Communities = data.Communities;

	// for (var k = 0; k < 50; k++){
	// 	var fakeEndpoints = [];
	// 	var fakeInteractions = [];
	//     for (var i=1; i< 5; i++){
	// 	    fakeEndpoints.push(k*5 + i + "");
	//     }
	//     for (var j=2; j< 5; j++){
	// 	    fakeInteractions.push([k*5 + 1 + "", k*5 + j + ""]);
	//     }
	//     NCI.Communities.push({"Endpoints" : fakeEndpoints, "Interactions" : fakeInteractions});
	// };
	//
	NCI.Communities.sort(function(a, b){
		return a.Endpoints.length - b.Endpoints.length;
	});
	NCI.timestampNCI = data.NCI;
	NCI.timestamp = data.Time;
	$("#histogramGeneral").html("NETWORK COMPLEXITY INDEX at    " + NCI.parceDateForLastUpdate(NCI.timestamp) + "" +
	    "   NCI " + NCI.timestampNCI + "" );
};

NCI.nciHistogram = (function(){
	var me = $('#nciHistogram');

	var barWidth = 4;
	var chart = d3.select("#nciHistogram");
	var margin = {top: 40, right: 40, bottom: 40, left:40},
	    width = 600,
	    height = 350;

	me.show = function(){
		chart.text("");
		var endpointsMax = d3.max(NCI.Communities, function(d) { return d.Endpoints.length; });
		var endpointsMin;
		var endpointsScale;
		if (endpointsMax > 100) {
			endpointsMin = 1;
			endpointsScale = d3.scale.log();
		} else {
			endpointsMin = 0;
			endpointsScale = d3.scale.linear();
		}
		endpointsScale.domain([endpointsMax, endpointsMin])
				.range([0, height - margin.top - margin.bottom]);

		var activitiesScale;
		var activitiesMin;
		if (NCI.Communities.length > 60) {
			activitiesMin = 0.9;
			activitiesScale = d3.scale.log();
		} else {
			activitiesMin = 0;
			activitiesScale = d3.scale.linear();
		}
		activitiesScale.domain([NCI.Communities.length + 1, activitiesMin])
					    .range([width - margin.right - margin.left, margin.left]);

		var activitiesAxis = d3.svg.axis()
		    .scale(activitiesScale)
		    .orient('bottom')
		    .tickSize(0)
			.ticks(Math.min(NCI.Communities.length + 2, 10),  d3.format("d"))
		    .tickPadding(8);

		var endpointsAxis = d3.svg.axis()
		    .scale(endpointsScale)
		    .orient('left')
			.tickSize(0)
			.ticks(10,  d3.format("d"))
		    .tickPadding(10);

		var barChartSvg = chart.append('svg')
		    .attr('width', width)
		    .attr('height', height)
		    .append('g')
		    .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

        //draw and animate bars
        var index = 0;
		barChartSvg.selectAll('g')
		    .data(NCI.Communities)
		    .enter().append('rect')
		    .attr('x', function(d) { return activitiesScale(NCI.Communities.length - index++) - barWidth/2})
		    .attr('y', function(d) { return   endpointsScale(d.Endpoints.length)}) //- selfwidth
		    .attr('width', function(d) { return barWidth})
		    .attr('height',function(d) { return height - margin.top - margin.bottom - endpointsScale(d.Endpoints.length) })
			.on("click", me.showDetails);

		barChartSvg.append("circle").attr("cy", endpointsScale(NCI.timestampNCI))
		    .attr("cx", activitiesScale(NCI.timestampNCI) ).style("fill", "red").attr("r", 6);
	    barChartSvg.append("circle").attr("cy", endpointsScale(endpointsMin))
		    .attr("cx", activitiesScale(NCI.timestampNCI) ).style("fill", "red").attr("r", 4);
		barChartSvg.append("circle").attr("cy", endpointsScale(NCI.timestampNCI))
		    .attr("cx", activitiesScale(activitiesMin) ).style("fill", "red").attr("r", 4);
		//draw axis
		barChartSvg.append('g')
		    .attr('class', 'x axis')
			.attr('transform', 'translate(0,' + (height - margin.top - margin.bottom) + ')')
			.call(activitiesAxis);
		barChartSvg.append('g')
			.attr('class', 'y axis')
			.attr('transform', 'translate(' + margin.left + ')')
			.call(endpointsAxis);
		//draw axis labels
		barChartSvg.append('text').
		attr('style', 'font-weight:bold').
		html('Activities Sorted by Size     j').attr('x', width/2 - 100).attr('y', height - 45);
		barChartSvg.append('text').
		attr('style', 'font-weight:bold').
		html('Number of Endpoints per Activity      x[j]').attr('x', -height/2 - 40).attr('y', 0)
		.attr('transform', 'rotate(-90)');
		//axis names, formula

	};

	me.showDetails = function(d){
		chart.select("#bar_endpoints").remove();
		var detailsDim = 300;
		var activityDetails = chart.append('svg')
			.attr("id","bar_endpoints")
			.attr('width', detailsDim)
		    .attr('height', detailsDim);

	    var graph = NCI.prepareDataForForceGraph([d]);

		var force = d3.layout.force()
			.charge(-60)
			.linkDistance(30)
			.size([detailsDim, detailsDim])
			.linkStrength(1).nodes(graph.nodes).links(graph.links).start();

		var link = activityDetails.selectAll(".link")
		    .data(graph.links)
			.enter().append("line")
			.attr("class", "activities_link")
			.style("stroke-width", function(d) { return Math.sqrt(d.value); });

		var node = activityDetails.selectAll(".node")
		    .data(graph.nodes)
		    .enter().append("circle")
		    .attr("r", 5);

		node.append("title").html(function(d) {  return d.name + "
" + d.neighbours + " connections" ;});

		force.on("tick", function() {
			link.attr("x1", function(d) { return d.source.x; })
			    .attr("y1", function(d) { return d.source.y; })
				.attr("x2", function(d) { return d.target.x; })
				.attr("y2", function(d) { return d.target.y; });

			node.attr("cx", function(d) { return d.x; })
			    .attr("cy", function(d) { return d.y; });
		});
	};

	return me;
}());

NCI.socialGraph  = (function(){
	var me = $("#socialGraph");

	var force;
	var color = d3.scale.category10();
	me.clustered = false;
	var networkColor = "#000000";

	me.show = function(devided, clustered, filtered){
		if (me.clustered && !clustered){
			NCI.socialGraph.text("");
			me.draw(devided, clustered);
			me.clustered  = clustered;
			return;
		}
		me.clustered = clustered;
		if (me.text().length<20){
			me.draw(devided, clustered, filtered);
		} else {
			me.setupNodes(filtered, devided, clustered);
	  	    force.start();
		}
	};

	me.setupNodes = function(filtered, devided, clustered){
		me.node.style("fill", function(d) {
		    if ( filtered && (d.name.indexOf("10.") == 0 ||  d.name.indexOf("192.168") == 0)){
			    return networkColor;
		    }
		    return devided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) { return (filtered &&  (d.name.indexOf("10.") == 0 ||  d.name.indexOf("192.168") == 0)) ? 6 : 4})
		force.linkStrength(clustered ? 1 : 0);
	}

	me.draw = function(devided, clustered, filtered){
		d3.select("#activities_graph").remove();
	    me.graph = NCI.prepareDataForForceGraph(NCI.Communities);

		force = d3.layout.force()
		    .charge(-20)
			.linkDistance(30)
			.size([$('#nciDetails').width(),  $('#nciDetails').height() - 200 ])
			//.resume()
			//.gravity(0.1)
			.linkStrength(clustered ? 1 : 0)
			.nodes(me.graph.nodes).links(me.graph.links).start();

	    me.activitiesGraphSvg = d3.select("#socialGraph").append("svg")
		    .attr("id","activities_graph")
			.attr("width", $('#nciDetails').width())
			.attr("height", $('#nciDetails').height() - 200);

		var link = me.activitiesGraphSvg.selectAll(".link")
		    .data(me.graph.links)
			.enter().append("line")
			.attr("class", "activities_link")
			.style("stroke-width", function(d) { return Math.sqrt(d.value); });

		me.node = me.activitiesGraphSvg.selectAll(".node")
		    .data(me.graph.nodes)
			.enter().append("circle");
			//.classed("fixed",  function(d) {d.fixed = true})
		me.setupNodes(filtered, devided, clustered);
		// node.on("mouseover", function(d, e) { console.log( d); console.log(e) })
		me.node.append("title").html(function(d) { return d.name });//+ "
" + d.neighbours + " connections" ; });

	    force.on("tick", function() {
	        link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
	}

	return me;
}());

NCI.prepareDataForForceGraph = function(communities){
    var graph = { "nodes":[], "links": []};

	var nodeIndex = function(ip){
		var val = -1;
		$.each(graph.nodes, function(index, node){
			if (node.name == ip)
			   val = index;
		});
		return val;
	};

	$.each(communities, function(index, community){
		$.each(community.Endpoints, function(index2, endpoint){
			if (index2 < 50)
			graph.nodes.push({
				"name": endpoint,
				"group": index
			});
		});
		$.each(community.Interactions, function(index2, interacton){
			if (nodeIndex(interacton[1]) > 0 && nodeIndex(interacton[0]) > 0)
			graph.links.push({
				"source": nodeIndex(interacton[1]),
				"target": nodeIndex(interacton[0]),
				"value": 1});
		});
	});

	// //TODO optimaze calculations
	// $.each(graph.nodes, function(index, node){
	// 	var numOfConnections = 0;
	// 	$.each(graph.links, function(index, link){
	// 		if (link.source != -1 &&  link.target != -1)
	// 		if (graph.nodes[link.source].name == node.name || graph.nodes[link.target].name == node.name){
	// 			numOfConnections++;
	// 		}
	// 		if (link.source != -1 &&  link.target != -1)
	// 		if (graph.nodes[link.source].group != graph.nodes[link.target].group)
	// 		    node.hasExternalConnections = true;
	// 	});
	// 	node.neighbours = numOfConnections/2;
	// });
	//
	// graph.nodes.sort(function(node1, node2){
	// 	return node2.neighbours - node1.neighbours;
	// });

	// var nodes = [];
	// $.each(graph.nodes, function(index, node){
	// 	if (index < 50){
	// 		nodes.push(node);
	// 	}
	// });
	// graph.nodes = nodes;
	//
	// graph.links = [];
	//
	// $.each(communities, function(index, community){
	//     $.each(community.Interactions, function(index, interacton){
	// 	    var sIndex = nodeIndex(interacton[1]);
	// 	    var tIndex = nodeIndex(interacton[0]);
	// 	    if (sIndex >= 0 && tIndex >= 0){
	// 		    graph.links.push({
	// 			    "source": sIndex,
	// 			    "target": tIndex,
	// 			    "value": 1});
	// 	    }
	//     });
	//     });

	return graph;
};

// NCI.filterGraphInfo = function(graph){
// 	$.each(graph.nodes, function(index, node){
// 		//todo optimaze
// 		var numOfConnections = 0;
// 		$.each(graph.links, function(index, link){
// 			if (graph.nodes[link.source].name == node.name || graph.nodes[link.target].name == node.name){
// 				numOfConnections++;
// 			}
// 			if (graph.nodes[link.source].group != graph.nodes[link.target].group)
// 			    node.hasExternalConnections = true;
// 		});
// 		node.neighbours = numOfConnections;
// 	});
// };<commit_msg>Remove points limitations<commit_after>NCI.setupCommunities = function(data){
	NCI.Communities = data.Communities;

	// for (var k = 0; k < 50; k++){
	// 	var fakeEndpoints = [];
	// 	var fakeInteractions = [];
	//     for (var i=1; i< 5; i++){
	// 	    fakeEndpoints.push(k*5 + i + "");
	//     }
	//     for (var j=2; j< 5; j++){
	// 	    fakeInteractions.push([k*5 + 1 + "", k*5 + j + ""]);
	//     }
	//     NCI.Communities.push({"Endpoints" : fakeEndpoints, "Interactions" : fakeInteractions});
	// };
	//
	NCI.Communities.sort(function(a, b){
		return a.Endpoints.length - b.Endpoints.length;
	});
	NCI.timestampNCI = data.NCI;
	NCI.timestamp = data.Time;
	$("#histogramGeneral").html("NETWORK COMPLEXITY INDEX at    " + NCI.parceDateForLastUpdate(NCI.timestamp) + "" +
	    "   NCI " + NCI.timestampNCI + "" );
};

NCI.nciHistogram = (function(){
	var me = $('#nciHistogram');

	var barWidth = 4;
	var chart = d3.select("#nciHistogram");
	var margin = {top: 40, right: 40, bottom: 40, left:40},
	    width = 600,
	    height = 350;

	me.show = function(){
		chart.text("");
		var endpointsMax = d3.max(NCI.Communities, function(d) { return d.Endpoints.length; });
		var endpointsMin;
		var endpointsScale;
		if (endpointsMax > 100) {
			endpointsMin = 1;
			endpointsScale = d3.scale.log();
		} else {
			endpointsMin = 0;
			endpointsScale = d3.scale.linear();
		}
		endpointsScale.domain([endpointsMax, endpointsMin])
				.range([0, height - margin.top - margin.bottom]);

		var activitiesScale;
		var activitiesMin;
		if (NCI.Communities.length > 60) {
			activitiesMin = 0.9;
			activitiesScale = d3.scale.log();
		} else {
			activitiesMin = 0;
			activitiesScale = d3.scale.linear();
		}
		activitiesScale.domain([NCI.Communities.length + 1, activitiesMin])
					    .range([width - margin.right - margin.left, margin.left]);

		var activitiesAxis = d3.svg.axis()
		    .scale(activitiesScale)
		    .orient('bottom')
		    .tickSize(0)
			.ticks(Math.min(NCI.Communities.length + 2, 10),  d3.format("d"))
		    .tickPadding(8);

		var endpointsAxis = d3.svg.axis()
		    .scale(endpointsScale)
		    .orient('left')
			.tickSize(0)
			.ticks(10,  d3.format("d"))
		    .tickPadding(10);

		var barChartSvg = chart.append('svg')
		    .attr('width', width)
		    .attr('height', height)
		    .append('g')
		    .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

        //draw and animate bars
        var index = 0;
		barChartSvg.selectAll('g')
		    .data(NCI.Communities)
		    .enter().append('rect')
		    .attr('x', function(d) { return activitiesScale(NCI.Communities.length - index++) - barWidth/2})
		    .attr('y', function(d) { return   endpointsScale(d.Endpoints.length)}) //- selfwidth
		    .attr('width', function(d) { return barWidth})
		    .attr('height',function(d) { return height - margin.top - margin.bottom - endpointsScale(d.Endpoints.length) })
			.on("click", me.showDetails);

		barChartSvg.append("circle").attr("cy", endpointsScale(NCI.timestampNCI))
		    .attr("cx", activitiesScale(NCI.timestampNCI) ).style("fill", "red").attr("r", 6);
	    barChartSvg.append("circle").attr("cy", endpointsScale(endpointsMin))
		    .attr("cx", activitiesScale(NCI.timestampNCI) ).style("fill", "red").attr("r", 4);
		barChartSvg.append("circle").attr("cy", endpointsScale(NCI.timestampNCI))
		    .attr("cx", activitiesScale(activitiesMin) ).style("fill", "red").attr("r", 4);
		//draw axis
		barChartSvg.append('g')
		    .attr('class', 'x axis')
			.attr('transform', 'translate(0,' + (height - margin.top - margin.bottom) + ')')
			.call(activitiesAxis);
		barChartSvg.append('g')
			.attr('class', 'y axis')
			.attr('transform', 'translate(' + margin.left + ')')
			.call(endpointsAxis);
		//draw axis labels
		barChartSvg.append('text').
		attr('style', 'font-weight:bold').
		html('Activities Sorted by Size     j').attr('x', width/2 - 100).attr('y', height - 45);
		barChartSvg.append('text').
		attr('style', 'font-weight:bold').
		html('Number of Endpoints per Activity      x[j]').attr('x', -height/2 - 40).attr('y', 0)
		.attr('transform', 'rotate(-90)');
		//axis names, formula

	};

	me.showDetails = function(d){
		chart.select("#bar_endpoints").remove();
		var detailsDim = 300;
		var activityDetails = chart.append('svg')
			.attr("id","bar_endpoints")
			.attr('width', detailsDim)
		    .attr('height', detailsDim);

	    var graph = NCI.prepareDataForForceGraph([d]);

		var force = d3.layout.force()
			.charge(-60)
			.linkDistance(30)
			.size([detailsDim, detailsDim])
			.linkStrength(1).nodes(graph.nodes).links(graph.links).start();

		var link = activityDetails.selectAll(".link")
		    .data(graph.links)
			.enter().append("line")
			.attr("class", "activities_link")
			.style("stroke-width", function(d) { return Math.sqrt(d.value); });

		var node = activityDetails.selectAll(".node")
		    .data(graph.nodes)
		    .enter().append("circle")
		    .attr("r", 5);

		node.append("title").html(function(d) {  return d.name + "
" + d.neighbours + " connections" ;});

		force.on("tick", function() {
			link.attr("x1", function(d) { return d.source.x; })
			    .attr("y1", function(d) { return d.source.y; })
				.attr("x2", function(d) { return d.target.x; })
				.attr("y2", function(d) { return d.target.y; });

			node.attr("cx", function(d) { return d.x; })
			    .attr("cy", function(d) { return d.y; });
		});
	};

	return me;
}());

NCI.socialGraph  = (function(){
	var me = $("#socialGraph");

	var force;
	var color = d3.scale.category10();
	me.clustered = false;
	var networkColor = "#000000";

	me.show = function(devided, clustered, filtered){
		if (me.clustered && !clustered){
			NCI.socialGraph.text("");
			me.draw(devided, clustered);
			me.clustered  = clustered;
			return;
		}
		me.clustered = clustered;
		if (me.text().length<20){
			me.draw(devided, clustered, filtered);
		} else {
			me.setupNodes(filtered, devided, clustered);
	  	    force.start();
		}
	};

	me.setupNodes = function(filtered, devided, clustered){
		me.node.style("fill", function(d) {
		    if ( filtered && (d.name.indexOf("10.") == 0 ||  d.name.indexOf("192.168") == 0)){
			    return networkColor;
		    }
		    return devided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) { return (filtered &&  (d.name.indexOf("10.") == 0 ||  d.name.indexOf("192.168") == 0)) ? 6 : 4})
		force.linkStrength(clustered ? 1 : 0);
	}

	me.draw = function(devided, clustered, filtered){
		d3.select("#activities_graph").remove();
	    me.graph = NCI.prepareDataForForceGraph(NCI.Communities);

		force = d3.layout.force()
		    .charge(-20)
			.linkDistance(30)
			.size([$('#nciDetails').width(),  $('#nciDetails').height() - 200 ])
			//.resume()
			//.gravity(0.1)
			.linkStrength(clustered ? 1 : 0)
			.nodes(me.graph.nodes).links(me.graph.links).start();

	    me.activitiesGraphSvg = d3.select("#socialGraph").append("svg")
		    .attr("id","activities_graph")
			.attr("width", $('#nciDetails').width())
			.attr("height", $('#nciDetails').height() - 200);

		var link = me.activitiesGraphSvg.selectAll(".link")
		    .data(me.graph.links)
			.enter().append("line")
			.attr("class", "activities_link")
			.style("stroke-width", function(d) { return Math.sqrt(d.value); });

		me.node = me.activitiesGraphSvg.selectAll(".node")
		    .data(me.graph.nodes)
			.enter().append("circle");
			//.classed("fixed",  function(d) {d.fixed = true})
		me.setupNodes(filtered, devided, clustered);
		// node.on("mouseover", function(d, e) { console.log( d); console.log(e) })
		me.node.append("title").html(function(d) { return d.name });//+ "
" + d.neighbours + " connections" ; });

	    force.on("tick", function() {
	        link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
	}

	return me;
}());

NCI.prepareDataForForceGraph = function(communities){
    var graph = { "nodes":[], "links": []};

	var nodeIndex = function(ip){
		var val = -1;
		$.each(graph.nodes, function(index, node){
			if (node.name == ip)
			   val = index;
		});
		return val;
	};

	$.each(communities, function(index, community){
		$.each(community.Endpoints, function(index2, endpoint){
			graph.nodes.push({
				"name": endpoint,
				"group": index
			});
		});
	});
	$.each(communities, function(index, community){
		$.each(community.Interactions, function(index2, interacton){
			if (nodeIndex(interacton[1]) > 0 && nodeIndex(interacton[0]) > 0)
			graph.links.push({
				"source": nodeIndex(interacton[1]),
				"target": nodeIndex(interacton[0]),
				"value": 1});
		});
	});

	// //TODO optimaze calculations
	// $.each(graph.nodes, function(index, node){
	// 	var numOfConnections = 0;
	// 	$.each(graph.links, function(index, link){
	// 		if (link.source != -1 &&  link.target != -1)
	// 		if (graph.nodes[link.source].name == node.name || graph.nodes[link.target].name == node.name){
	// 			numOfConnections++;
	// 		}
	// 		if (link.source != -1 &&  link.target != -1)
	// 		if (graph.nodes[link.source].group != graph.nodes[link.target].group)
	// 		    node.hasExternalConnections = true;
	// 	});
	// 	node.neighbours = numOfConnections/2;
	// });
	//
	// graph.nodes.sort(function(node1, node2){
	// 	return node2.neighbours - node1.neighbours;
	// });

	// var nodes = [];
	// $.each(graph.nodes, function(index, node){
	// 	if (index < 50){
	// 		nodes.push(node);
	// 	}
	// });
	// graph.nodes = nodes;
	//
	// graph.links = [];
	//
	// $.each(communities, function(index, community){
	//     $.each(community.Interactions, function(index, interacton){
	// 	    var sIndex = nodeIndex(interacton[1]);
	// 	    var tIndex = nodeIndex(interacton[0]);
	// 	    if (sIndex >= 0 && tIndex >= 0){
	// 		    graph.links.push({
	// 			    "source": sIndex,
	// 			    "target": tIndex,
	// 			    "value": 1});
	// 	    }
	//     });
	//     });

	return graph;
};

// NCI.filterGraphInfo = function(graph){
// 	$.each(graph.nodes, function(index, node){
// 		//todo optimaze
// 		var numOfConnections = 0;
// 		$.each(graph.links, function(index, link){
// 			if (graph.nodes[link.source].name == node.name || graph.nodes[link.target].name == node.name){
// 				numOfConnections++;
// 			}
// 			if (graph.nodes[link.source].group != graph.nodes[link.target].group)
// 			    node.hasExternalConnections = true;
// 		});
// 		node.neighbours = numOfConnections;
// 	});
// };<|endoftext|>