<commit_before>/**
 * test-bones.js - basic functionality tests for bones.js's functions.
 *
 * author R. S. Doiel, <rsdoiel@gmail.com>
 *
 * copyright (c) 2011 all rights reserved
 *
 * Notes: runs under NodeJS
 */

var assert = require('assert'),
    web = require('./bones');

console.log("[test-bones.js] start ...");

attr = web.assemble_attributes();
assert.equal(attr, '', 'Should have an empty attribute string.');

attr = assemble_attributes('class="myclass"');
assert.equal(attr, ' class="myclass"', 'Should have class="myclass" [' + attr + '] from string');

attr = assemble_attributes({'class' : 'myclass'});
assert.equal(attr, ' class="myclass"', 'Should have class="myclass" [' + attr + '] from assoc. array');

attr = assemble_attributes({'checked' : null, 'id' : 'mything'});
assert.equal(attr, ' checked id="mything"', 'Should have checked id="mything" [' + attr + '] from assoc. array');

src = web.Html('');
assert.equal(web.trim(src), web.trim('<!DOCTYPE html>' + "\n" + '' + "\n" + '' + "\n"), "Should have an html wrapper:" + src);

src = web.Head('');
assert.equal(web.trim(src), web.trim('' + "\n" + '' + "\n"), "Should have a head elments:" + src);

src = web.Title('hello world');
assert.equal(web.trim(src), web.trim('<title>hello world</title>'), "Should have hello world title:" + src);

src = web.Link('');
assert.equal(web.trim(src), web.trim('<link />'), "Should have <link />:" + src);

src = web.Body('');
assert.equal(web.trim(src), web.trim('' + "\n" + '' + "\n"), "Should have body block.:" + src);

src = web.H1('hello world');
assert.equal(src, '
hello world
', "Should have h1:" + src);

src = web.H2('hello world');
assert.equal(src, '
hello world
', "Should have h2:" + src);

src = web.H3('hello world');
assert.equal(src, '
hello world
', "Should have h3:" + src);

src = web.H4('hello world');
assert.equal(src, '
hello world
', "Should have h4:" + src);

src = web.H5('hello world');
assert.equal(src, '
hello world
', "Should have h5:" + src);

src = web.H6('hello world');
assert.equal(src, '
hello world
', "Should have h6:" + src);

src = web.P();
assert.equal(src, '
', "Should have a simple p tag.:" + src);

src = web.P("hello world");
assert.equal(src, '
hello world
', "Should have a wrapping p tag.:" + src);

src = web.A("", null);
assert.equal(src, '', "Should have an empty wrapping anchor tag:" + src);

src = web.A("here", {"href" : "http://example.com"});
assert.equal(src, 'here', "Should have a basic link to example.com:" + src);

src = web.Ul('');
assert.equal(src, '

', "Should have a ul wrapper:" + src);

src = web.Ol('');
assert.equal(src, '

', "Should have a ol wrapper:" + src);

src = web.Li('');
assert.equal(src, '

', "Should have a li wrapper:" + src);

src = web.Dl('');
assert.equal(src, '

', "Should have a dl wrapper:" + src);

src = web.Dt('');
assert.equal(src, '

', "Should have a dt wrapper:" + src);

src = web.Dd('');
assert.equal(src, '

', "Should have a dd wrapper:" + src);

src = web.Table('');
assert.equal(src, '

', "Should have a table wrapper:" + src);

src = web.Tr('');
assert.equal(src, '

', "Should have a tr wrapper:" + src);

src = web.Td('');
assert.equal(src, '	', "Should have a td wrapper:" + src);

src = web.Form();
assert.equal(src, '<form></form>', "Should have a form wrapper:" + src);

src = web.Input();
assert.equal(src, '<input name="" value="" />', "Should have a simple input tag:" + src);

src = web.Select();
assert.equal(src, '<select name=""></select>', "Should have a simple select wrapper:" + src);

src = web.Option();
assert.equal(src, '<option value=""></option>', "Should have a simple select wrapper:" + src);

src = web.Label();
assert.equal(src, '', "Should have a simple label wrapper:" + src);

console.log("Success!");

<commit_msg>snapshot<commit_after>/**
 * test-bones.js - basic functionality tests for bones.js's functions.
 *
 * author R. S. Doiel, <rsdoiel@gmail.com>
 *
 * copyright (c) 2011 all rights reserved
 *
 * Notes: runs under NodeJS
 */

var assert = require('assert'),
    web = require('./bones');

console.log("[bones_test.js] start ...");

attr = web.assemble_attributes();
assert.equal(attr, '', 'Should have an empty attribute string.');

attr = assemble_attributes('class="myclass"');
assert.equal(attr, ' class="myclass"', 'Should have class="myclass" [' + attr + '] from string');

attr = assemble_attributes({'class' : 'myclass'});
assert.equal(attr, ' class="myclass"', 'Should have class="myclass" [' + attr + '] from assoc. array');

attr = assemble_attributes({'checked' : null, 'id' : 'mything'});
assert.equal(attr, ' checked id="mything"', 'Should have checked id="mything" [' + attr + '] from assoc. array');

src = web.Html('');
assert.equal(web.trim(src), web.trim('<!DOCTYPE html>' + "\n" + '' + "\n" + '' + "\n"), "Should have an html wrapper:" + src);

src = web.Head('');
assert.equal(web.trim(src), web.trim('' + "\n" + '' + "\n"), "Should have a head elments:" + src);

src = web.Title('hello world');
assert.equal(web.trim(src), web.trim('<title>hello world</title>'), "Should have hello world title:" + src);

src = web.Link('');
assert.equal(web.trim(src), web.trim('<link />'), "Should have <link />:" + src);

src = web.Body('');
assert.equal(web.trim(src), web.trim('' + "\n" + '' + "\n"), "Should have body block.:" + src);

src = web.H1('hello world');
assert.equal(src, '
hello world
', "Should have h1:" + src);

src = web.H2('hello world');
assert.equal(src, '
hello world
', "Should have h2:" + src);

src = web.H3('hello world');
assert.equal(src, '
hello world
', "Should have h3:" + src);

src = web.H4('hello world');
assert.equal(src, '
hello world
', "Should have h4:" + src);

src = web.H5('hello world');
assert.equal(src, '
hello world
', "Should have h5:" + src);

src = web.H6('hello world');
assert.equal(src, '
hello world
', "Should have h6:" + src);

src = web.P();
assert.equal(src, '
', "Should have a simple p tag.:" + src);

src = web.P("hello world");
assert.equal(src, '
hello world
', "Should have a wrapping p tag.:" + src);

src = web.A("", null);
assert.equal(src, '', "Should have an empty wrapping anchor tag:" + src);

src = web.A("here", {"href" : "http://example.com"});
assert.equal(src, 'here', "Should have a basic link to example.com:" + src);

src = web.Ul('');
assert.equal(src, '

', "Should have a ul wrapper:" + src);

src = web.Ol('');
assert.equal(src, '

', "Should have a ol wrapper:" + src);

src = web.Li('');
assert.equal(src, '

', "Should have a li wrapper:" + src);

src = web.Dl('');
assert.equal(src, '

', "Should have a dl wrapper:" + src);

src = web.Dt('');
assert.equal(src, '

', "Should have a dt wrapper:" + src);

src = web.Dd('');
assert.equal(src, '

', "Should have a dd wrapper:" + src);

src = web.Table('');
assert.equal(src, '

', "Should have a table wrapper:" + src);

src = web.Tr('');
assert.equal(src, '

', "Should have a tr wrapper:" + src);

src = web.Td('');
assert.equal(src, '	', "Should have a td wrapper:" + src);

src = web.Form();
assert.equal(src, '<form></form>', "Should have a form wrapper:" + src);

src = web.Input();
assert.equal(src, '<input name="" value="" />', "Should have a simple input tag:" + src);

src = web.Select();
assert.equal(src, '<select name=""></select>', "Should have a simple select wrapper:" + src);

src = web.Option();
assert.equal(src, '<option value=""></option>', "Should have a simple select wrapper:" + src);

src = web.Label();
assert.equal(src, '', "Should have a simple label wrapper:" + src);

console.log("Success!");

<|endoftext|>


<commit_before>import Router from 'koa-router'

const router = new Router()

router.get('/all', async (ctx, next) => {
    ctx.body = {
        'code': 200,
        'data': [{
            'id': 1,
            'name': 'pro1'
        }, {
            'id': 2,
            'name': 'pro2'
        }],
        'msg': 'ok'
    }
})

export default router
<commit_msg>rest projects ad<commit_after>import Router from 'koa-router'

const router = new Router()

router.get('/', async (ctx, next) => {
    ctx.body = {
        'code': 200,
        'data': [{
            'id': 1,
            'name': 'pro1'
        }, {
            'id': 2,
            'name': 'pro2'
        }],
        'msg': 'ok'
    }
})

router.get('/11', async (ctx, next) => {
    ctx.body = {
        'code': 200,
        'data': [{
            'id': 11,
            'name': 'a1'
        }, {
            'id': 22,
            'name': 'a2'
        }],
        'msg': 'ok'
    }
})

export default router
<|endoftext|>


<commit_before>import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
import PropTypes from 'prop-types';
import moment from 'moment';
import DayPicker from 'react-day-picker';
import MomentLocaleUtils from 'react-day-picker/moment';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import InputGroup from 'react-bootstrap/lib/InputGroup';
import Overlay from 'react-bootstrap/lib/Overlay';

import iconCalendar from './images/calendar.svg';

class DateFilter extends React.Component {
  static propTypes = {
    date: PropTypes.instanceOf(Date),
    intl: intlShape.isRequired,
    onChange: PropTypes.func.isRequired,
    label: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
    };
  }

  onChange = (newDate) => {
    const { onChange } = this.props;

    this.setState({
      isOpen: false,
    });

    onChange(newDate);
  };

  render() {
    const {
      intl,
      label,
      date,
    } = this.props;
    const { isOpen } = this.state;

    return (

        <ControlLabel>{label}</ControlLabel>
        <FormGroup onClick={() => this.setState({ isOpen: !isOpen })}>
          <InputGroup>
            <InputGroup.Addon className="app-DateFilter__title">

              {moment(date).format('L')}
            </InputGroup.Addon>
            <InputGroup.Addon className="app-DateFilter__triangle">
              <Glyphicon glyph="triangle-bottom" />
            </InputGroup.Addon>
          </InputGroup>
        </FormGroup>
        <Overlay
          animation={false}
          container={this}
          onHide={() => this.setState({ isOpen: false })}
          placement="bottom"
          rootClose
          show={isOpen}
        >

            <DayPicker
              disabledDays={day => moment(day).isBefore(moment(), 'date')}
              locale={intl.locale}
              localeUtils={MomentLocaleUtils}
              onDayClick={newDate => this.onChange(newDate)}
              selectedDays={date}
              showOutsideDays
              showWeekNumbers
            />

        </Overlay>

    );
  }
}

export default injectIntl(DateFilter);
<commit_msg>Fix issue with react-bootstrap Overlay in DateFilter component<commit_after>import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
import PropTypes from 'prop-types';
import moment from 'moment';
import DayPicker from 'react-day-picker';
import MomentLocaleUtils from 'react-day-picker/moment';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import InputGroup from 'react-bootstrap/lib/InputGroup';
import Overlay from 'react-bootstrap/lib/Overlay';

import iconCalendar from './images/calendar.svg';

const DatePickerWrapper = ({ children }) => (

    {children}

);

DatePickerWrapper.propTypes = {
  children: PropTypes.any,
};

class DateFilter extends React.Component {
  static propTypes = {
    date: PropTypes.instanceOf(Date),
    intl: intlShape.isRequired,
    onChange: PropTypes.func.isRequired,
    label: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
    };
  }

  onChange = (newDate) => {
    const { onChange } = this.props;

    this.setState({
      isOpen: false,
    });

    onChange(newDate);
  };

  render() {
    const {
      intl,
      label,
      date,
    } = this.props;
    const { isOpen } = this.state;

    return (

        <ControlLabel>{label}</ControlLabel>
        <FormGroup onClick={() => this.setState({ isOpen: !isOpen })}>
          <InputGroup>
            <InputGroup.Addon className="app-DateFilter__title">

              {moment(date).format('L')}
            </InputGroup.Addon>
            <InputGroup.Addon className="app-DateFilter__triangle">
              <Glyphicon glyph="triangle-bottom" />
            </InputGroup.Addon>
          </InputGroup>
        </FormGroup>
        <Overlay
          animation={false}
          container={this}
          onHide={() => this.setState({ isOpen: false })}
          placement="bottom"
          rootClose
          show={isOpen}
        >
          <DatePickerWrapper>
            <DayPicker
              disabledDays={day => moment(day).isBefore(moment(), 'date')}
              locale={intl.locale}
              localeUtils={MomentLocaleUtils}
              onDayClick={newDate => this.onChange(newDate)}
              selectedDays={date}
              showOutsideDays
              showWeekNumbers
            />
          </DatePickerWrapper>
        </Overlay>

    );
  }
}

export default injectIntl(DateFilter);
<|endoftext|>


<commit_before>import React, {Component} from 'react';

class TranscriptViewer extends Component {

  constructor(props) {
    super(props);
    this.state = {imageStatus: 'loading'};
  }

  handleImageErrored() {
    this.setState({imageStatus: 'Error loading transcript preview.'});
  }

  handleImageLoaded() {
    this.setState({imageStatus: ''});
  }

  render() {
    // let externalPrefix = 'http://bw.scottcain.net/jbrowse/?data=data%2F';
    // let externalPrefix = 'http://ec2-34-208-22-23.us-west-2.compute.amazonaws.com/jbrowse/overview.html?data=data%2F';
    // let externalPrefix = 'http://localhost/jbrowse/overview.html?data=data%2F';
    let externalPrefix = 'http://jbrowse.alliancegenome.org/jbrowse/overview.html?data=data%2F';
    // let externalPrefix = 'http://ec2-52-43-125-139.us-west-2.compute.amazonaws.com/jbrowse/overview.html?data=data%2F';

    // let visualizationPrefix = 'http://ec2-34-208-22-23.us-west-2.compute.amazonaws.com:8080/?url=';
    // let visualizationPrefix = 'http://dev.alliancegenome.org:8891/?url=';
    // let visualizationPrefix = 'http://localhost:8891/?url=';
    let visualizationPrefix = 'http://jbrowse.alliancegenome.org:8891/?url=';
    // let visualizationPrefix = 'http://ec2-52-43-125-139.us-west-2.compute.amazonaws.com:8891/?url=';

    let delay = 10000;
    let visualizationSuffix = '&format=PNG&delay=' + delay + '&width=800&height=1000&zoom=1&quality=0.7&cors=true';
    // location based data
    let locationString = this.props.chromosome + ':' + this.props.fmin + '..' + this.props.fmax;
    let uniqueLocation = encodeURI(this.props.species) + '&loc=' + encodeURI(locationString);

    let geneSymbolUrl = '&lookupSymbol=' + this.props.geneSymbol;
    let externalJbrowseUrl = externalPrefix + uniqueLocation + '&tracks=All%20Genes&highlight=' + geneSymbolUrl;

    // TODO: move EVERYTHING to the externalJBrowseUrl
    let visualizationUrl = visualizationPrefix + encodeURIComponent(externalJbrowseUrl) + visualizationSuffix;

    let styles = {
      makeSpace: {
        display: 'block',
        marginTop: '20px',
        marginBottom: '20px',
        marginLeft: '15px'
      },
      buttonSpace: {
        marginLeft: '15px'
      }
    };

    return (

          Genome Location: Chr{this.props.chromosome}:{this.props.fmin}...{this.props.fmax} {this.props.assembly} {this.props.strand}

        {this.state.imageStatus === 'loading'
          ?
Loading ...

          : ''
        }

    );
  }

}

TranscriptViewer.propTypes = {
  assembly: React.PropTypes.string,
  chromosome: React.PropTypes.string,
  fmax: React.PropTypes.number,
  fmin: React.PropTypes.number,
  geneSymbol: React.PropTypes.string.isRequired,
  species: React.PropTypes.string.isRequired,
  strand: React.PropTypes.string,
};

export default TranscriptViewer;

<commit_msg>Updated formatting to match<commit_after>import React, {Component} from 'react';

class TranscriptViewer extends Component {

  constructor(props) {
    super(props);
    this.state = {imageStatus: 'loading'};
  }

  handleImageErrored() {
    this.setState({imageStatus: 'Error loading transcript preview.'});
  }

  handleImageLoaded() {
    this.setState({imageStatus: ''});
  }

  render() {
    // let externalPrefix = 'http://bw.scottcain.net/jbrowse/?data=data%2F';
    // let externalPrefix = 'http://ec2-34-208-22-23.us-west-2.compute.amazonaws.com/jbrowse/overview.html?data=data%2F';
    // let externalPrefix = 'http://localhost/jbrowse/overview.html?data=data%2F';
    let externalPrefix = 'http://jbrowse.alliancegenome.org/jbrowse/overview.html?data=data%2F';
    // let externalPrefix = 'http://ec2-52-43-125-139.us-west-2.compute.amazonaws.com/jbrowse/overview.html?data=data%2F';

    // let visualizationPrefix = 'http://ec2-34-208-22-23.us-west-2.compute.amazonaws.com:8080/?url=';
    // let visualizationPrefix = 'http://dev.alliancegenome.org:8891/?url=';
    // let visualizationPrefix = 'http://localhost:8891/?url=';
    let visualizationPrefix = 'http://jbrowse.alliancegenome.org:8891/?url=';
    // let visualizationPrefix = 'http://ec2-52-43-125-139.us-west-2.compute.amazonaws.com:8891/?url=';

    let delay = 10000;
    let visualizationSuffix = '&format=PNG&delay=' + delay + '&width=800&height=1000&zoom=1&quality=0.7&cors=true';
    // location based data
    let locationString = this.props.chromosome + ':' + this.props.fmin + '..' + this.props.fmax;
    let uniqueLocation = encodeURI(this.props.species) + '&loc=' + encodeURI(locationString);

    let geneSymbolUrl = '&lookupSymbol=' + this.props.geneSymbol;
    let externalJbrowseUrl = externalPrefix + uniqueLocation + '&tracks=All%20Genes&highlight=' + geneSymbolUrl;

    // TODO: move EVERYTHING to the externalJBrowseUrl
    let visualizationUrl = visualizationPrefix + encodeURIComponent(externalJbrowseUrl) + visualizationSuffix;

    let styles = {
      makeSpace: {
        display: 'block',
        marginTop: '20px',
        marginBottom: '20px',
        marginLeft: '15px'
      },
      buttonSpace: {
        marginLeft: '15px'
      }
    };

    return (

Genome Location

 Chr{this.props.chromosome}:{this.props.fmin}...{this.props.fmax} {this.props.assembly} {this.props.strand}

        {this.state.imageStatus === 'loading'
          ?
Loading ...

          : ''
        }

    );
  }

}

TranscriptViewer.propTypes = {
  assembly: React.PropTypes.string,
  chromosome: React.PropTypes.string,
  fmax: React.PropTypes.number,
  fmin: React.PropTypes.number,
  geneSymbol: React.PropTypes.string.isRequired,
  species: React.PropTypes.string.isRequired,
  strand: React.PropTypes.string,
};

export default TranscriptViewer;

<|endoftext|>


<commit_before>import turfBBox from '@turf/bbox';
import $ from 'jquery';
import _ from 'underscore';
import { transformExtent } from 'ol/proj';
import ModalView from '../../core/views/ModalView';

import template from './DownloadOptionsModalView.hbs';
import './DownloadOptionsModalView.css';

import FiltersModel from '../../core/models/FiltersModel';

import { downloadRecord, downloadMultipleRecords } from '../../download';
import { getProjectionOl } from '../../contrib/OpenLayers/utils';

export default ModalView.extend({
  template,
  templateHelpers() {
    return {
      records: this.records,
      downloadOptions: this.showDownloadOptions,
      bbox: this.bbox.map(v => v.toFixed(4)),
      projection_4326: this.mapProjection.getCode() === 'EPSG:4326',
    };
  },

  onRender() {
    const preferences = this.getPreferences();
    const preferredFormat = preferences.preferredFormat;
    const preferredPackage = preferences.preferredPackage;
    const preferredInterpolation = preferences.preferredInterpolation;
    const preferredProjection = preferences.preferredProjection;
    const preferredScalingMethod = preferences.preferredScalingMethod;
    const preferredSize = preferences.preferredSize;
    const preferredResolution = preferences.preferredResolution;
    const preferredScale = preferences.preferredScale;
    const subsetByBounds = preferences.subsetByBounds;
    const useMultipleDownload = preferences.UseMultipleDownload

    if (subsetByBounds) {
      this.$('.subset-by-bounds').prop('checked', true);
      this.model.set('subsetByBounds', subsetByBounds);
    }
    if (useMultipleDownload) {
      this.$('.use-multiple-download').prop('checked', true);
      this.model.set('useMultipleDownload', useMultipleDownload);
    }
    if (preferredPackage) {
      this.$('.select-package').val(preferredPackage);
      this.model.set('selectedDownloadPackage', preferredPackage);
    }
    if (preferredFormat) {
      this.$('.select-format').val(preferredFormat);
      this.model.set('selectedDownloadFormat', preferredFormat);
    }
    if (preferredInterpolation) {
      this.$('.select-interpolation').val(preferredInterpolation);
      this.model.set('selectedInterpolation', preferredInterpolation);
    }
    if (preferredProjection) {
      this.$('.select-projection').val(preferredProjection);
      this.model.set('selectedProjection', preferredProjection);
    }
    if (preferredScalingMethod) {
      this.$(`input[name="scale-method"][value=${preferredScalingMethod}]`).prop('checked', true);
      if (preferredScalingMethod === 'resolution' && !isNaN(preferredResolution[0]) && !isNaN(preferredResolution[1])) {
        this.$('[name="resolution-x"]').val(preferredResolution[0]);
        this.$('[name="resolution-y"]').val(preferredResolution[1]);
      } else if (preferredScalingMethod === 'size' && !isNaN(preferredSize[0]) && !isNaN(preferredSize[1])) {
        this.$('[name="size-x"]').val(preferredSize[0]);
        this.$('[name="size-y"]').val(preferredSize[1]);
      } else if (preferredScalingMethod === 'scale') {
        this.$('[name="scalefactor"]').val(preferredScale * 100);
      }
      this.onScaleMethodChange();
      this.onSizeOrResolutionChange();
    }
  },

  events: {
    'change .select-projection': 'onProjectionChange',
    'change .select-format': 'onFormatChange',
    'change .select-package': 'onPackageChange',
    'change .select-interpolation': 'onInterpolationChange',
    'change .subset-by-bounds': 'onSubsetByBoundsChange',
    'change .use-multiple-download': 'onUseMultipleDownload',
    'click .start-download': 'onStartDownloadClicked',
    'click .btn-draw-bbox': 'onDrawBBoxClicked',
    'change .show-bbox': 'onBBoxInputChange',
    'change [name="scale-method"]': 'onScaleMethodChange',
    [`change [name^='size-']`]: 'onSizeOrResolutionChange',
    [`change [name^='resolution-']`]: 'onSizeOrResolutionChange',
    'change [name="scalefactor"]': 'onSizeOrResolutionChange',
  },

  initialize(options) {
    this.mapModel = options.mapModel;
    this.mapProjection = getProjectionOl(this.mapModel.get('projection'));
    this.filtersModel = options.filtersModel;
    const filtersArea = options.mapModel.get('area');
    if (filtersArea) {
      if (Array.isArray(filtersArea)) {
        this.bbox = filtersArea;
      } else {
        this.bbox = turfBBox(filtersArea);
      }
    } else {
      this.bbox = options.mapModel.get('bbox');
    }
    this.bbox = transformExtent(this.bbox, 'EPSG:4326', this.mapProjection);

    this.listenTo(this.mapModel, 'change:area', () => {
      const bbox = this.mapModel.get('area');
      if (Array.isArray(bbox)) {
        this.bbox = transformExtent(bbox, 'EPSG:4326', this.mapProjection);
        this.render();
      }
      else if ( bbox && typeof bbox =='object'){
        this.bbox = turfBBox(bbox);
        this.mapModel.set('area', null);
        this.render();

      }
    });

    if (options.records) {
      this.records = options.records;
    } else {
      const searchCollection = options.searchCollection;
      this.records = searchCollection.reduce((acc, searchModel) => (
        acc.concat(searchModel.get('downloadSelection')
          .map(recordModel => [recordModel, searchModel]))
      ), []);
    }
    this.showDownloadOptions = this.records.reduce((acc, record) => (
      acc || record[1].get('layerModel').get('download.protocol') === 'EO-WCS'
    ), false);
    this.defaultLabelsSet();
  },

  onProjectionChange() {
    const val = this.$('.select-projection').val();
    this.model.set('selectedProjection', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredProjection', (val !== '' && val !== '---') ? val : null);
  },

  onFormatChange() {
    const val = this.$('.select-format').val();
    this.model.set('selectedDownloadFormat', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredFormat', (val !== '' && val !== '---') ? val : null);
  },
  onPackageChange() {
    const val = this.$('.select-package').val();
    this.model.set('selectedDownloadPackage', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredPackage', (val !== '' && val !== '---') ? val : null);
  },

  onInterpolationChange() {
    const val = this.$('.select-interpolation').val();
    this.model.set('selectedInterpolation', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredInterpolation', (val !== '' && val !== '---') ? val : null);
  },

  onScaleMethodChange() {
    switch (this.$('input[name="scale-method"]:checked').val()) {
      case 'full':
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', true);
        this.model.set({
          scaleMethod: 'none',
        });
        break;
      case 'resolution': {
        this.$(`input[name^='resolution']`).prop('disabled', false);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', true);

        this.model.set({
          scaleMethod: 'resolution',
          resolutionX: parseFloat(this.$('input[name="resolution-x"]').val()),
          resolutionY: parseFloat(this.$('input[name="resolution-y"]').val()),
        });
        break;
      }
      case 'size': {
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', false);
        this.$('input[name="scalefactor"]').prop('disabled', true);

        this.model.set({
          scaleMethod: 'size',
          sizeX: parseInt(this.$('input[name="size-x"]').val(), 10),
          sizeY: parseInt(this.$('input[name="size-y"]').val(), 10),
        });
        break;
      }
      case 'scale': {
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', false);

        this.model.set({
          scaleMethod: 'scale',
          scale: parseFloat(this.$('input[name="scalefactor"]').val()) / 100,
        });
        break;
      }
      default:
        break;
    }
    this.updatePreferences(
      'preferredScalingMethod',
      this.$('input[name="scale-method"]:checked').val()
    );
  },

  onSizeOrResolutionChange() {
    const resolution = [
      parseFloat(this.$('input[name="resolution-x"]').val()),
      parseFloat(this.$('input[name="resolution-y"]').val()),
    ];
    const size = [
      parseInt(this.$('input[name="size-x"]').val(), 10),
      parseInt(this.$('input[name="size-y"]').val(), 10),
    ];
    const scale = parseFloat(this.$('input[name="scalefactor"]').val()) / 100;

    this.model.set({
      resolutionX: resolution[0],
      resolutionY: resolution[1],
      sizeX: size[0],
      sizeY: size[1],
      scale,
    });
    this.updatePreferences('preferredResolution', resolution);
    this.updatePreferences('preferredSize', size);
    this.updatePreferences('preferredScale', scale);
  },

  onDrawBBoxClicked() {
    this.mapModel.set('tool', 'bbox');
    this.close();

    this.listenToOnce(this.mapModel, 'change:tool', () => {
      this.open();
    });
  },

  onSubsetByBoundsChange() {
    const checked = this.$('.subset-by-bounds').is(':checked');
    this.model.set('subsetByBounds', checked);
    this.updatePreferences('subsetByBounds', checked);
  },

  onUseMultipleDownload() {
    const checked = this.$('.use-multiple-download').is(':checked');
    this.model.set('useMultipleDownload', checked);
    this.updatePreferences('useMultipleDownload', checked);
    this.$('.select-package').prop('disabled', !checked);

    if (checked){
      this.$('.select-format').val('---');

      this.$('.select-interpolation').val('---');
    }

  },
  getPreferences() {
    try {
      return JSON.parse(localStorage.getItem(
        'download-options-view-preferences'
      ) || '{}');
    } catch (error) {
      return {};
    }
  },

  updatePreferences(key, value) {
    const preferences = this.getPreferences();
    preferences[key] = value;
    localStorage.setItem(
      'download-options-view-preferences',
      JSON.stringify(preferences),
    );
  },

  defaultLabelsSet() {
    _.each(this.model.get('availableDownloadFormats'), (format) => {
      if (typeof format.name === 'undefined' && format.mimeType !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        format.name = format.mimeType;
      }
    });
    _.each(this.model.get('availableProjections'), (proj) => {
      if (typeof proj.name === 'undefined' && proj.identifier !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        proj.name = proj.identifier;
      }
    });
    _.each(this.model.get('availableInterpolations'), (interpolation) => {
      if (typeof interpolation.name === 'undefined' && interpolation.identifier !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        interpolation.name = interpolation.identifier;
      }
    });
  },

  onBBoxInputChange() {
    const bbox = this.$('.show-bbox')
      .map((index, elem) => $(elem).val())
      .get()
      .map(parseFloat);

    if (bbox.reduce((prev, current) => prev && !isNaN(current), true)) {
      this.mapModel.set('drawnArea', null);
      this.mapModel.set('area', transformExtent(bbox, this.mapProjection, 'EPSG:4326'));
    }
  },

  onStartDownloadClicked() {
    this.onSizeOrResolutionChange();
    let subsetProj = this.mapProjection.getCode();
    // get numeric code and parse it into opengis def url
    if (subsetProj) {
      subsetProj = subsetProj.slice(subsetProj.lastIndexOf(':') + 1);
      subsetProj = `http://www.opengis.net/def/crs/EPSG/0/${subsetProj}`;
    }
    const options = {
      format: this.model.get('selectedDownloadFormat'),
      package: this.model.get('selectedDownloadPackage'),
      outputCRS: this.model.get('selectedProjection'),
      subsetCRS: subsetProj,
      interpolation: this.model.get('selectedInterpolation'),
    };

    const filtersModel = new FiltersModel();
    if (this.model.get('subsetByBounds')) {
      const bboxSubset = this.bbox;
      // min-max coordinates can not be the same for subsetting
      // do not modify the input forms & mapModel filter, only values for subset
      if (bboxSubset[0] === bboxSubset[2]) {
        bboxSubset[0] -= 0.001;
        bboxSubset[2] += 0.001;
      }
      if (bboxSubset[1] === bboxSubset[3]) {
        bboxSubset[1] -= 0.001;
        bboxSubset[3] += 0.001;
      }
      filtersModel.set('area', bboxSubset);
    }

    switch (this.model.get('scaleMethod')) {
      case 'resolution': {
        // size will be computed later per-record
        options.resolutionX = this.model.get('resolutionX');
        options.resolutionY = this.model.get('resolutionY');
        break;
      }
      case 'size':
        options.sizeX = this.model.get('sizeX');
        options.sizeY = this.model.get('sizeY');
        options.sizeX = options.sizeX < 1 ? 1 : options.sizeX;
        options.sizeY = options.sizeY < 1 ? 1 : options.sizeY;
        break;
      case 'scale':
        options.scale = this.model.get('scale');
        options.scale = options.scale < 0 ? 1 : options.scale;
        break;
      default:
        break;
    }

    let GetEOCoverageSet = this.model.get('useMultipleDownload')
    if (GetEOCoverageSet){
      let eoids= []
      var url
      this.records.forEach(([recordModel, searchModel], i) => {
        if (i === 0){
          url = searchModel.get('layerModel').get('download.url')
        }
        eoids.push(recordModel.id)
      }
      );
      downloadMultipleRecords(eoids, url, filtersModel, options)
    }else{
    // if EO-WCS, use a timeout
    const timeout = this.showDownloadOptions ? 500 : 0;
    this.records.forEach(([recordModel, searchModel], i) => {
      setTimeout(() =>
        downloadRecord(
          searchModel.get('layerModel'), filtersModel, recordModel, options), i * timeout
      );
    });
    }
  }
});
<commit_msg>fix setting area to null in downloadOptionsModalView in case of polygon/point<commit_after>import turfBBox from '@turf/bbox';
import $ from 'jquery';
import _ from 'underscore';
import { transformExtent } from 'ol/proj';
import ModalView from '../../core/views/ModalView';

import template from './DownloadOptionsModalView.hbs';
import './DownloadOptionsModalView.css';

import FiltersModel from '../../core/models/FiltersModel';

import { downloadRecord, downloadMultipleRecords } from '../../download';
import { getProjectionOl } from '../../contrib/OpenLayers/utils';

export default ModalView.extend({
  template,
  templateHelpers() {
    return {
      records: this.records,
      downloadOptions: this.showDownloadOptions,
      bbox: this.bbox.map(v => v.toFixed(4)),
      projection_4326: this.mapProjection.getCode() === 'EPSG:4326',
    };
  },

  onRender() {
    const preferences = this.getPreferences();
    const preferredFormat = preferences.preferredFormat;
    const preferredPackage = preferences.preferredPackage;
    const preferredInterpolation = preferences.preferredInterpolation;
    const preferredProjection = preferences.preferredProjection;
    const preferredScalingMethod = preferences.preferredScalingMethod;
    const preferredSize = preferences.preferredSize;
    const preferredResolution = preferences.preferredResolution;
    const preferredScale = preferences.preferredScale;
    const subsetByBounds = preferences.subsetByBounds;
    const useMultipleDownload = preferences.UseMultipleDownload

    if (subsetByBounds) {
      this.$('.subset-by-bounds').prop('checked', true);
      this.model.set('subsetByBounds', subsetByBounds);
    }
    if (useMultipleDownload) {
      this.$('.use-multiple-download').prop('checked', true);
      this.model.set('useMultipleDownload', useMultipleDownload);
    }
    if (preferredPackage) {
      this.$('.select-package').val(preferredPackage);
      this.model.set('selectedDownloadPackage', preferredPackage);
    }
    if (preferredFormat) {
      this.$('.select-format').val(preferredFormat);
      this.model.set('selectedDownloadFormat', preferredFormat);
    }
    if (preferredInterpolation) {
      this.$('.select-interpolation').val(preferredInterpolation);
      this.model.set('selectedInterpolation', preferredInterpolation);
    }
    if (preferredProjection) {
      this.$('.select-projection').val(preferredProjection);
      this.model.set('selectedProjection', preferredProjection);
    }
    if (preferredScalingMethod) {
      this.$(`input[name="scale-method"][value=${preferredScalingMethod}]`).prop('checked', true);
      if (preferredScalingMethod === 'resolution' && !isNaN(preferredResolution[0]) && !isNaN(preferredResolution[1])) {
        this.$('[name="resolution-x"]').val(preferredResolution[0]);
        this.$('[name="resolution-y"]').val(preferredResolution[1]);
      } else if (preferredScalingMethod === 'size' && !isNaN(preferredSize[0]) && !isNaN(preferredSize[1])) {
        this.$('[name="size-x"]').val(preferredSize[0]);
        this.$('[name="size-y"]').val(preferredSize[1]);
      } else if (preferredScalingMethod === 'scale') {
        this.$('[name="scalefactor"]').val(preferredScale * 100);
      }
      this.onScaleMethodChange();
      this.onSizeOrResolutionChange();
    }
  },

  events: {
    'change .select-projection': 'onProjectionChange',
    'change .select-format': 'onFormatChange',
    'change .select-package': 'onPackageChange',
    'change .select-interpolation': 'onInterpolationChange',
    'change .subset-by-bounds': 'onSubsetByBoundsChange',
    'change .use-multiple-download': 'onUseMultipleDownload',
    'click .start-download': 'onStartDownloadClicked',
    'click .btn-draw-bbox': 'onDrawBBoxClicked',
    'change .show-bbox': 'onBBoxInputChange',
    'change [name="scale-method"]': 'onScaleMethodChange',
    [`change [name^='size-']`]: 'onSizeOrResolutionChange',
    [`change [name^='resolution-']`]: 'onSizeOrResolutionChange',
    'change [name="scalefactor"]': 'onSizeOrResolutionChange',
  },

  initialize(options) {
    this.mapModel = options.mapModel;
    this.mapProjection = getProjectionOl(this.mapModel.get('projection'));
    this.filtersModel = options.filtersModel;
    const filtersArea = options.mapModel.get('area');
    if (filtersArea) {
      if (Array.isArray(filtersArea)) {
        this.bbox = filtersArea;
      } else {
        this.bbox = turfBBox(filtersArea);
      }
    } else {
      this.bbox = options.mapModel.get('bbox');
    }
    this.bbox = transformExtent(this.bbox, 'EPSG:4326', this.mapProjection);

    this.listenTo(this.mapModel, 'change:area', () => {
      const bbox = this.mapModel.get('area');
      if (Array.isArray(bbox)) {
        this.bbox = transformExtent(bbox, 'EPSG:4326', this.mapProjection);
        this.render();
      } else if (bbox && typeof bbox === 'object') {
        this.bbox = transformExtent(turfBBox(bbox), 'EPSG:4326', this.mapProjection);
        this.render();
      }
    });

    if (options.records) {
      this.records = options.records;
    } else {
      const searchCollection = options.searchCollection;
      this.records = searchCollection.reduce((acc, searchModel) => (
        acc.concat(searchModel.get('downloadSelection')
          .map(recordModel => [recordModel, searchModel]))
      ), []);
    }
    this.showDownloadOptions = this.records.reduce((acc, record) => (
      acc || record[1].get('layerModel').get('download.protocol') === 'EO-WCS'
    ), false);
    this.defaultLabelsSet();
  },

  onProjectionChange() {
    const val = this.$('.select-projection').val();
    this.model.set('selectedProjection', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredProjection', (val !== '' && val !== '---') ? val : null);
  },

  onFormatChange() {
    const val = this.$('.select-format').val();
    this.model.set('selectedDownloadFormat', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredFormat', (val !== '' && val !== '---') ? val : null);
  },
  onPackageChange() {
    const val = this.$('.select-package').val();
    this.model.set('selectedDownloadPackage', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredPackage', (val !== '' && val !== '---') ? val : null);
  },

  onInterpolationChange() {
    const val = this.$('.select-interpolation').val();
    this.model.set('selectedInterpolation', (val !== '' && val !== '---') ? val : null);
    this.updatePreferences('preferredInterpolation', (val !== '' && val !== '---') ? val : null);
  },

  onScaleMethodChange() {
    switch (this.$('input[name="scale-method"]:checked').val()) {
      case 'full':
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', true);
        this.model.set({
          scaleMethod: 'none',
        });
        break;
      case 'resolution': {
        this.$(`input[name^='resolution']`).prop('disabled', false);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', true);

        this.model.set({
          scaleMethod: 'resolution',
          resolutionX: parseFloat(this.$('input[name="resolution-x"]').val()),
          resolutionY: parseFloat(this.$('input[name="resolution-y"]').val()),
        });
        break;
      }
      case 'size': {
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', false);
        this.$('input[name="scalefactor"]').prop('disabled', true);

        this.model.set({
          scaleMethod: 'size',
          sizeX: parseInt(this.$('input[name="size-x"]').val(), 10),
          sizeY: parseInt(this.$('input[name="size-y"]').val(), 10),
        });
        break;
      }
      case 'scale': {
        this.$(`input[name^='resolution']`).prop('disabled', true);
        this.$(`input[name^='size']`).prop('disabled', true);
        this.$('input[name="scalefactor"]').prop('disabled', false);

        this.model.set({
          scaleMethod: 'scale',
          scale: parseFloat(this.$('input[name="scalefactor"]').val()) / 100,
        });
        break;
      }
      default:
        break;
    }
    this.updatePreferences(
      'preferredScalingMethod',
      this.$('input[name="scale-method"]:checked').val()
    );
  },

  onSizeOrResolutionChange() {
    const resolution = [
      parseFloat(this.$('input[name="resolution-x"]').val()),
      parseFloat(this.$('input[name="resolution-y"]').val()),
    ];
    const size = [
      parseInt(this.$('input[name="size-x"]').val(), 10),
      parseInt(this.$('input[name="size-y"]').val(), 10),
    ];
    const scale = parseFloat(this.$('input[name="scalefactor"]').val()) / 100;

    this.model.set({
      resolutionX: resolution[0],
      resolutionY: resolution[1],
      sizeX: size[0],
      sizeY: size[1],
      scale,
    });
    this.updatePreferences('preferredResolution', resolution);
    this.updatePreferences('preferredSize', size);
    this.updatePreferences('preferredScale', scale);
  },

  onDrawBBoxClicked() {
    this.mapModel.set('tool', 'bbox');
    this.close();

    this.listenToOnce(this.mapModel, 'change:tool', () => {
      this.open();
    });
  },

  onSubsetByBoundsChange() {
    const checked = this.$('.subset-by-bounds').is(':checked');
    this.model.set('subsetByBounds', checked);
    this.updatePreferences('subsetByBounds', checked);
  },

  onUseMultipleDownload() {
    const checked = this.$('.use-multiple-download').is(':checked');
    this.model.set('useMultipleDownload', checked);
    this.updatePreferences('useMultipleDownload', checked);
    this.$('.select-package').prop('disabled', !checked);

    if (checked){
      this.$('.select-format').val('---');

      this.$('.select-interpolation').val('---');
    }

  },
  getPreferences() {
    try {
      return JSON.parse(localStorage.getItem(
        'download-options-view-preferences'
      ) || '{}');
    } catch (error) {
      return {};
    }
  },

  updatePreferences(key, value) {
    const preferences = this.getPreferences();
    preferences[key] = value;
    localStorage.setItem(
      'download-options-view-preferences',
      JSON.stringify(preferences),
    );
  },

  defaultLabelsSet() {
    _.each(this.model.get('availableDownloadFormats'), (format) => {
      if (typeof format.name === 'undefined' && format.mimeType !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        format.name = format.mimeType;
      }
    });
    _.each(this.model.get('availableProjections'), (proj) => {
      if (typeof proj.name === 'undefined' && proj.identifier !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        proj.name = proj.identifier;
      }
    });
    _.each(this.model.get('availableInterpolations'), (interpolation) => {
      if (typeof interpolation.name === 'undefined' && interpolation.identifier !== 'undefined') {
        // eslint-disable-next-line no-param-reassign
        interpolation.name = interpolation.identifier;
      }
    });
  },

  onBBoxInputChange() {
    const bbox = this.$('.show-bbox')
      .map((index, elem) => $(elem).val())
      .get()
      .map(parseFloat);

    if (bbox.reduce((prev, current) => prev && !isNaN(current), true)) {
      this.mapModel.set('drawnArea', null);
      this.mapModel.set('area', transformExtent(bbox, this.mapProjection, 'EPSG:4326'));
    }
  },

  onStartDownloadClicked() {
    this.onSizeOrResolutionChange();
    let subsetProj = this.mapProjection.getCode();
    // get numeric code and parse it into opengis def url
    if (subsetProj) {
      subsetProj = subsetProj.slice(subsetProj.lastIndexOf(':') + 1);
      subsetProj = `http://www.opengis.net/def/crs/EPSG/0/${subsetProj}`;
    }
    const options = {
      format: this.model.get('selectedDownloadFormat'),
      package: this.model.get('selectedDownloadPackage'),
      outputCRS: this.model.get('selectedProjection'),
      subsetCRS: subsetProj,
      interpolation: this.model.get('selectedInterpolation'),
    };

    const filtersModel = new FiltersModel();
    if (this.model.get('subsetByBounds')) {
      const bboxSubset = this.bbox;
      // min-max coordinates can not be the same for subsetting
      // do not modify the input forms & mapModel filter, only values for subset
      if (bboxSubset[0] === bboxSubset[2]) {
        bboxSubset[0] -= 0.001;
        bboxSubset[2] += 0.001;
      }
      if (bboxSubset[1] === bboxSubset[3]) {
        bboxSubset[1] -= 0.001;
        bboxSubset[3] += 0.001;
      }
      filtersModel.set('area', bboxSubset);
    }

    switch (this.model.get('scaleMethod')) {
      case 'resolution': {
        // size will be computed later per-record
        options.resolutionX = this.model.get('resolutionX');
        options.resolutionY = this.model.get('resolutionY');
        break;
      }
      case 'size':
        options.sizeX = this.model.get('sizeX');
        options.sizeY = this.model.get('sizeY');
        options.sizeX = options.sizeX < 1 ? 1 : options.sizeX;
        options.sizeY = options.sizeY < 1 ? 1 : options.sizeY;
        break;
      case 'scale':
        options.scale = this.model.get('scale');
        options.scale = options.scale < 0 ? 1 : options.scale;
        break;
      default:
        break;
    }

    const GetEOCoverageSet = this.model.get('useMultipleDownload');
    if (GetEOCoverageSet) {
      const eoids = [];
      let url;
      this.records.forEach(([recordModel, searchModel], i) => {
        if (i === 0) {
          url = searchModel.get('layerModel').get('download.url');
        }
        eoids.push(recordModel.id);
      });
      downloadMultipleRecords(eoids, url, filtersModel, options);
    } else {
    // if EO-WCS, use a timeout
      const timeout = this.showDownloadOptions ? 500 : 0;
      this.records.forEach(([recordModel, searchModel], i) => {
        setTimeout(() =>
          downloadRecord(
            searchModel.get('layerModel'), filtersModel, recordModel, options), i * timeout
        );
      });
    }
  }
});
<|endoftext|>


<commit_before>define(function(require){
    var PlasmaShader = require("PlasmaShader"),
        Timer = require("Timer");

    var scene = new THREE.Object3D();
    var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 1000);
    var cylinderMaterial;
    var cargoRoom;

    var title = new THREE.Mesh(
        new THREE.PlaneGeometry(8, 4),
        new THREE.MeshBasicMaterial({
            map: THREE.ImageUtils.loadTexture("images/titles/title-04.png"),
            transparent: true,
            depthWrite: false
        })
    );
    title.position.x = 4;

    scene.add(title);

    camera.position.z = 90;
    camera.position.x = 4;
    camera.lookAt(new THREE.Vector3());

    var loader = new THREE.JSONLoader(true);
    loader.load("models/cargo-room.js", function(geometry, materials){
        _.each(materials, function(mat, idx){
            if(mat.name == "Material")
                cylinderMaterial = materials[idx] = new THREE.ShaderMaterial(PlasmaShader);

        });
        cargoRoom = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        scene.add(cargoRoom);
    });

    var light = new THREE.PointLight(0x3366FF, 0.2, 90);
    light.position.set(30, 0, 0);
    var light2 = new THREE.PointLight(0xffbc2b, 0.2, 90);
    light2.position.set(-30, 0, 0);

    var warpLights = new THREE.Object3D();
    _.each([
        new THREE.Vector2(-14, -16),
        new THREE.Vector2(23, -16),
        new THREE.Vector2(-14, 21),
        new THREE.Vector2(23, 21),
        new THREE.Vector2(-14, 59),
        new THREE.Vector2(23, 59)
    ], function(coords){
        var lamp = new THREE.PointLight(0xCCCCFF, 0.4, 60);
        lamp.position.set(coords.x, -6, coords.y);
        warpLights.add(lamp);
    });
    scene.add(warpLights);

    var lightSystem = new THREE.Object3D();

    lightSystem.add(light);
    lightSystem.add(light2);

    scene.add(lightSystem);

    var lightTimer = new Timer();
    var flashTimer = new Timer();

    return {
        scene: scene,
        camera: camera,
        render: function(time){

            effectPass.uniforms.brightness.value = Math.max(0, 1 - flashTimer.getTime(time));

            cylinderMaterial.uniforms._time.value = time;
            cylinderMaterial.needsUpdate = true;

            var passed = lightTimer.getPassed(time);

            lightSystem.rotation.set(time, time, time);
            light.intensity = Math.max(0, light.intensity - passed * 2);
            light2.intensity = Math.max(0, light2.intensity - passed * 2);
            camera.position.z -=  0.2;
            camera.position.x +=  0.0003;
            camera.rotation.z -=  0.0001;
            title.position.z += 0.2;

            if(title.position.distanceTo(camera.position) < 20){
                title.material.opacity = Math.max(0, (title.position.distanceTo(camera.position) - 5) / 15);
            }

            _.each(warpLights.children, function(light){
                light.intensity = (Math.sin(time * 6 + light.position.x) * Math.sin((time + light.position.z + light.position.x) * 7.88)) * 0.1 + 0.5;
            });

            effectPass.uniforms.aberration.value = Math.random() * 0.001;

        },
        onEvent: function(ev){
            if(ev.note && ev.instrument == 1 && ev.note == 'C-3'){
                light.intensity = 2;
            }

            if(ev.note && ev.instrument == 1 && ev.note == 'D-3'){
                light2.intensity = 2;
            }
        }
    }

});<commit_msg>Make cargo room dependend on timers.<commit_after>define(function(require){
    var PlasmaShader = require("PlasmaShader"),
        Timer = require("Timer");

    var scene = new THREE.Object3D();
    var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 1000);
    var cylinderMaterial;
    var cargoRoom;

    var title = new THREE.Mesh(
        new THREE.PlaneGeometry(8, 4),
        new THREE.MeshBasicMaterial({
            map: THREE.ImageUtils.loadTexture("images/titles/title-04.png"),
            transparent: true,
            depthWrite: false
        })
    );
    title.position.x = 4;

    scene.add(title);

    camera.position.z = 90;
    camera.position.x = 4;
    camera.lookAt(new THREE.Vector3());

    var loader = new THREE.JSONLoader(true);
    loader.load("models/cargo-room.js", function(geometry, materials){
        _.each(materials, function(mat, idx){
            if(mat.name == "Material")
                cylinderMaterial = materials[idx] = new THREE.ShaderMaterial(PlasmaShader);

        });
        cargoRoom = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        scene.add(cargoRoom);
    });

    var light = new THREE.PointLight(0x3366FF, 0.2, 90);
    light.position.set(30, 0, 0);
    var light2 = new THREE.PointLight(0xffbc2b, 0.2, 90);
    light2.position.set(-30, 0, 0);

    var warpLights = new THREE.Object3D();
    _.each([
        new THREE.Vector2(-14, -16),
        new THREE.Vector2(23, -16),
        new THREE.Vector2(-14, 21),
        new THREE.Vector2(23, 21),
        new THREE.Vector2(-14, 59),
        new THREE.Vector2(23, 59)
    ], function(coords){
        var lamp = new THREE.PointLight(0xCCCCFF, 0.4, 60);
        lamp.position.set(coords.x, -6, coords.y);
        warpLights.add(lamp);
    });
    scene.add(warpLights);

    var lightSystem = new THREE.Object3D();

    lightSystem.add(light);
    lightSystem.add(light2);

    scene.add(lightSystem);

    var lightTimer = new Timer();
    var flashTimer = new Timer();

    return {
        scene: scene,
        camera: camera,
        render: function(time){

            effectPass.uniforms.brightness.value = Math.max(0, 1 - flashTimer.getTime(time));

            cylinderMaterial.uniforms._time.value = time;
            cylinderMaterial.needsUpdate = true;

            var passed = lightTimer.getPassed(time);

            lightSystem.rotation.set(time, time, time);
            light.intensity = Math.max(0, light.intensity - passed * 2);
            light2.intensity = Math.max(0, light2.intensity - passed * 2);
            camera.position.z -=  0.2;
            camera.position.x +=  0.0003 * passed;
            camera.rotation.z -=  0.0001 * passed;
            title.position.z += 0.2 * passed;

            if(title.position.distanceTo(camera.position) < 20){
                title.material.opacity = Math.max(0, (title.position.distanceTo(camera.position) - 5) / 15);
            }

            _.each(warpLights.children, function(light){
                light.intensity = (Math.sin(time * 6 + light.position.x) * Math.sin((time + light.position.z + light.position.x) * 7.88)) * 0.1 + 0.5;
            });

            effectPass.uniforms.aberration.value = Math.random() * 0.001;

        },
        onEvent: function(ev){
            if(ev.note && ev.instrument == 1 && ev.note == 'C-3'){
                light.intensity = 2;
            }

            if(ev.note && ev.instrument == 1 && ev.note == 'D-3'){
                light2.intensity = 2;
            }
        }
    }

});<|endoftext|>


<commit_before>(function () {

    var root = this;

    var defaults = {
        chart: {
            animations: true,
            // by default take the size of the parent container
            defaultWidth: 400,
            // height = width * ratio
            defaultAspect: 1 / 1.61803398875,
            // calculated at render time based on the options & container
            width: undefined,
            // if defined, height takes precedence over aspect
            height: undefined,
            // margin between the container and the chart (ie labels or axis title)
            margin: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            },
            // padding between the chart area and the inner plot area */
            padding: {
                top: null,
                right: null,
                bottom: 0,
                left: 0
            },
            // automatically false by default anyway; adding here to help generate docs
            rotatedFrame: false,
            // width in pixels of the plot area (area inside the axis if any). This gets calculated on render
            plotWidth: undefined,
            // height in pixels of the plot area (area inside the axis if any). This gets calculated on render
            plotHeight: undefined,
            // top edge in pixels (from the edge of the svg) of the plot area (area inside the axis if any). This gets calculated on render
            plotTop: undefined,
            // left edge in pixels (from the edge of the svg) of the plot area (area inside the axis if any). This gets calculated on render
            plotLeft: undefined,
        },

        xAxis: {
        },

        yAxis: {
        },

        tooltip: {
        }
    };

    /**
    * Creates a Contour instance, based on the core Contour object. This instance can contain a set of related visualizations.
    *
    *   * Pass the constructor any configuration options in the *options* parameter. Make sure the `el` option contains the selector of the container in which the Contour instance will be rendered.
    *   * Set the frame for this Contour instance (e.g. `.cartesian()`).
    *   * Add one or more specific visualizations to this Contour instance (e.g. `.scatter()`, `.trend-line()`). Pass each visualization constructor the data it displays. Pass configuration options if desired.
    *   * Invoke an action for this Contour instance (e.g. `.render()`).
    *
    * ### Example:
    *
    *     new Contour({el: 'myChart'})
    *       .cartesian()
    *       .line([1,3,2,5])
    *       .render()
    *
    *
    * @class Contour() visualizations object
    * @param {object} options The global configuration options object
    *
    */
    function Contour (options) {
        this.init(options);

        return this;
    }

    /**
    * Adds a new kind of visualization to the core Contour object.
    * The *renderer* function is called when you add this visualization to instances of Contour.
    *
    * ### Example:
    *
    *     Contour.export("exampleVisualization", function(data, layer) {
    *           //function body to create exampleVisualization
    *           //for example using SVG and/or D3
    *     });
    *
    *     //to include the visualization into a specific Contour instance
    *     new Contour(options)
    *           .exampleVisualization(data)
    *           .render()
    *
    * @param {String} ctorName Name of the visualization, used as a constructor name.
    * @param {Function} renderer Function called when this visualization is added to a Contour instance. This function receives the data that is passed in to the constructor.
    */
    Contour.export = function (ctorName, renderer) {

        if (typeof renderer !== 'function') throw new Error('Invalid render function for ' + ctorName + ' visualization');

        function sortSeries(data) {
            if(!data || !data.length) return [];

            if(data[0].data) {
                _.each(data, sortSeries);
            }

            var shouldSort = _.isObject(data[0]) && _.isDate(data[0].x);
            var sortFunc = function (a, b) { return a.x - b.x; };
            if(shouldSort) {
                data.sort(sortFunc);
            }

            return data;
        }

        Contour.prototype[ctorName] = function (data, options) {
            var categories = this.options ? this.options.xAxis ? this.options.xAxis.categories : undefined : undefined;
            var opt =  _.extend({}, this.options[ctorName], options);
            var vis;

            data = data || [];
            sortSeries(data);
            vis = new Contour.VisualizationContainer(_.nw.normalizeSeries(data, categories), opt, ctorName, renderer, this);
            this._visualizations.push(vis);

            return this;
        };
    };

    /**
    * Exposes functionality to the core Contour object.
    * Use this to add *functionality* that will be available for any visualizations.
    *
    * ###Example:
    *
    *     Contour.expose("example", {
    *          // when included in the instance, the function `.myFunction` is available in the visualizations
    *         myFunction: function(data) { .... }
    *     });
    *
    *     Contour.export("visualizationThatUsesMyFunction", function(data, layer) {
    *           //function body including call to this.myFunction(data)
    *     });
    *
    *     // to include the functionality into a specific instance
    *     new Contour(options)
    *           .example()
    *           .visualizationThatUsesMyFunction()
    *           .render()
    */
    Contour.expose = function (ctorName, functionalityConstructor) {
        var ctor = function () {
            var functionality = typeof functionalityConstructor === 'function' ? new functionalityConstructor() : functionalityConstructor;
            // extend the --instance-- we don't want all charts to be overriden...
            _.extend(this, _.omit(functionality, 'init'));

            if(functionality.init) functionality.init.call(this, this.options);

            return this;
        };

        Contour.prototype[ctorName] = ctor;

        return this;
    };

    Contour.prototype = _.extend(Contour.prototype, {
        _visualizations: undefined,

        _extraOptions: undefined,

        // Initializes the instance of Narwhal
        init: function (options) {
            // for now, just  store this options here...
            // the final set of options will be composed before rendering
            // after all components/visualizations have been added
            this.options = options || {};

            this._extraOptions = [];
            this._visualizations = [];

            return this;
        },

        calculateWidth: function () {
            var width = _.nw.getStyle(this.options.el, 'width');
            return this.options.el ? (parseInt(width, 10) || this.options.chart.defaultWidth) : this.options.chart.defaultWidth;
        },

        calculateHeight: function () {
            var height = _.nw.getStyle(this.options.el, 'height');
            var containerHeight = this.options.el ? parseInt(height, 10) : undefined;
            var calcWidth = this.options.chart.width;
            var ratio = this.options.chart.aspect || this.options.chart.defaultAspect;

            return !!containerHeight && containerHeight > 1 ?  containerHeight : Math.round(calcWidth * ratio);
        },

        calcMetrics: function () {
            var options = this.options;

            this.adjustPadding();

            this.adjustTitlePadding();

            options.chart.width = options.chart.width || this.calculateWidth();
            options.chart.height = options.chart.height || this.calculateHeight();

            this.options = _.merge(options, {
                chart: {
                    plotWidth: options.chart.width - options.chart.margin.left - options.chart.margin.right - options.chart.padding.left - options.chart.padding.right,
                    plotHeight: options.chart.height - options.chart.margin.top - options.chart.margin.bottom - options.chart.padding.top - options.chart.padding.bottom,
                    plotLeft: options.chart.margin.left + options.chart.padding.left,
                    plotTop: options.chart.margin.top + options.chart.padding.top
                }
            });
        },

        adjustPadding: function () {
            // overriden by components that need to adjust padding
            return this;
        },

        adjustTitlePadding: function () {
            // overriden by components that need to adjust padding
            return this;
        },

        composeOptions: function () {
            var allDefaults = _.merge({}, defaults);
            var mergeExtraOptions = function (opt) { _.merge(allDefaults, opt); };
            var mergeDefaults = function (vis) { _.merge(allDefaults, vis.renderer.defaults); };

            _.each(this._extraOptions, mergeExtraOptions);
            _.each(this._visualizations, mergeDefaults);

            // compose the final list of options right before start rendering
            this.options = _.merge({}, allDefaults, this.options);
        },

        baseRender: function () {
            this.plotArea();

            return this;
        },

        /**
        * Renders this Contour instance and all its visualizations into the DOM.
        *
        * Example:
        *
        *     new Contour({ el:'.myChart' })
        *           .pie([1,2,3])
        *           .render()
        *
        * @function render
        *
        */
        render: function () {
            this.composeOptions();

            this.calcMetrics();

            this.baseRender();

            this.renderVisualizations();

            return this;
        },

        update: function () {
            this.calcMetrics();
            return this;
        },

        plotArea: function () {

            var chartOpt = this.options.chart;

            this.container = d3.select(this.options.el);

            if(!this.svg) {
                this.svg = this.container
                    .append('svg')
                    .attr('viewBox', '0 0 ' + chartOpt.width + ' ' + chartOpt.height)
                    .attr('preserveAspectRatio', 'xMinYMin')
                    .attr('class', 'contour-chart')
                    .attr('height', chartOpt.height)
                    .append('g')
                        .attr('transform', 'translate(' + chartOpt.margin.left + ',' + chartOpt.margin.top + ')');
            }

            return this;
        },

        createVisualizationLayer: function (vis, id) {
            return this.svg.append('g')
                .attr('vis-id', id)
                .attr('vis-type', vis.type)
                .attr('transform', 'translate(' + this.options.chart.padding.left + ',' + this.options.chart.padding.top + ')');
        },

        renderVisualizations: function () {

            _.each(this._visualizations, function (visualization, index) {
                var id = index + 1;
                var layer = visualization.layer || this.createVisualizationLayer(visualization, id);
                var opt = _.merge({}, this.options, visualization.options);
                visualization.layer = layer;
                visualization.parent = this;
                visualization.render(layer, opt, this);
            }, this);

            return this;
        },

        /**
        * Sets the same data into all visualizations for a Contour instance. Useful for creating interactive
        * visualizations: call after getting the additional data from the user.
        *
        * ###Example:
        *
        *     var data = [1,2,3,4,5];
        *     var chart = new Contour({ el:'.myChart' })
        *           .scatter(data)
        *           .trendLine(data);
        *
        *     data.push(10);
        *     chart.setData(data)
        *           .render();
        *
        * @function setData
        *
        */
        setData: function (data) {
            _.invoke(this._visualizations, 'setData', data);

            return this;
        },

        /**
        * Returns a VisualizationContainer object for the visualization at a given index (0-based).
        *
        * ###Example:
        *
        *     var chart = new Contour({ el:'.myChart' })
        *           .pie([1,2,3])
        *           .render()
        *
        *     var myPie = chart.select(0)
        *
        *     // do something with the visualization, for example updating its data set
        *     myPie.setData([6,7,8,9]).render()
        *
        * @function select
        *
        */
        select: function (index) {
            return this._visualizations[index];
        },

        // place holder function for now
        data: function () {

        }
    });

    // export to our context
    root.Contour = Contour;

})();
<commit_msg>fix sample code - scatter requires cartesian<commit_after>(function () {

    var root = this;

    var defaults = {
        chart: {
            animations: true,
            // by default take the size of the parent container
            defaultWidth: 400,
            // height = width * ratio
            defaultAspect: 1 / 1.61803398875,
            // calculated at render time based on the options & container
            width: undefined,
            // if defined, height takes precedence over aspect
            height: undefined,
            // margin between the container and the chart (ie labels or axis title)
            margin: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 0
            },
            // padding between the chart area and the inner plot area */
            padding: {
                top: null,
                right: null,
                bottom: 0,
                left: 0
            },
            // automatically false by default anyway; adding here to help generate docs
            rotatedFrame: false,
            // width in pixels of the plot area (area inside the axis if any). This gets calculated on render
            plotWidth: undefined,
            // height in pixels of the plot area (area inside the axis if any). This gets calculated on render
            plotHeight: undefined,
            // top edge in pixels (from the edge of the svg) of the plot area (area inside the axis if any). This gets calculated on render
            plotTop: undefined,
            // left edge in pixels (from the edge of the svg) of the plot area (area inside the axis if any). This gets calculated on render
            plotLeft: undefined,
        },

        xAxis: {
        },

        yAxis: {
        },

        tooltip: {
        }
    };

    /**
    * Creates a Contour instance, based on the core Contour object. This instance can contain a set of related visualizations.
    *
    *   * Pass the constructor any configuration options in the *options* parameter. Make sure the `el` option contains the selector of the container in which the Contour instance will be rendered.
    *   * Set the frame for this Contour instance (e.g. `.cartesian()`).
    *   * Add one or more specific visualizations to this Contour instance (e.g. `.scatter()`, `.trend-line()`). Pass each visualization constructor the data it displays. Pass configuration options if desired.
    *   * Invoke an action for this Contour instance (e.g. `.render()`).
    *
    * ### Example:
    *
    *     new Contour({el: 'myChart'})
    *       .cartesian()
    *       .line([1,3,2,5])
    *       .render()
    *
    *
    * @class Contour() visualizations object
    * @param {object} options The global configuration options object
    *
    */
    function Contour (options) {
        this.init(options);

        return this;
    }

    /**
    * Adds a new kind of visualization to the core Contour object.
    * The *renderer* function is called when you add this visualization to instances of Contour.
    *
    * ### Example:
    *
    *     Contour.export("exampleVisualization", function(data, layer) {
    *           //function body to create exampleVisualization
    *           //for example using SVG and/or D3
    *     });
    *
    *     //to include the visualization into a specific Contour instance
    *     new Contour(options)
    *           .exampleVisualization(data)
    *           .render()
    *
    * @param {String} ctorName Name of the visualization, used as a constructor name.
    * @param {Function} renderer Function called when this visualization is added to a Contour instance. This function receives the data that is passed in to the constructor.
    */
    Contour.export = function (ctorName, renderer) {

        if (typeof renderer !== 'function') throw new Error('Invalid render function for ' + ctorName + ' visualization');

        function sortSeries(data) {
            if(!data || !data.length) return [];

            if(data[0].data) {
                _.each(data, sortSeries);
            }

            var shouldSort = _.isObject(data[0]) && _.isDate(data[0].x);
            var sortFunc = function (a, b) { return a.x - b.x; };
            if(shouldSort) {
                data.sort(sortFunc);
            }

            return data;
        }

        Contour.prototype[ctorName] = function (data, options) {
            var categories = this.options ? this.options.xAxis ? this.options.xAxis.categories : undefined : undefined;
            var opt =  _.extend({}, this.options[ctorName], options);
            var vis;

            data = data || [];
            sortSeries(data);
            vis = new Contour.VisualizationContainer(_.nw.normalizeSeries(data, categories), opt, ctorName, renderer, this);
            this._visualizations.push(vis);

            return this;
        };
    };

    /**
    * Exposes functionality to the core Contour object.
    * Use this to add *functionality* that will be available for any visualizations.
    *
    * ###Example:
    *
    *     Contour.expose("example", {
    *          // when included in the instance, the function `.myFunction` is available in the visualizations
    *         myFunction: function(data) { .... }
    *     });
    *
    *     Contour.export("visualizationThatUsesMyFunction", function(data, layer) {
    *           //function body including call to this.myFunction(data)
    *     });
    *
    *     // to include the functionality into a specific instance
    *     new Contour(options)
    *           .example()
    *           .visualizationThatUsesMyFunction()
    *           .render()
    */
    Contour.expose = function (ctorName, functionalityConstructor) {
        var ctor = function () {
            var functionality = typeof functionalityConstructor === 'function' ? new functionalityConstructor() : functionalityConstructor;
            // extend the --instance-- we don't want all charts to be overriden...
            _.extend(this, _.omit(functionality, 'init'));

            if(functionality.init) functionality.init.call(this, this.options);

            return this;
        };

        Contour.prototype[ctorName] = ctor;

        return this;
    };

    Contour.prototype = _.extend(Contour.prototype, {
        _visualizations: undefined,

        _extraOptions: undefined,

        // Initializes the instance of Narwhal
        init: function (options) {
            // for now, just  store this options here...
            // the final set of options will be composed before rendering
            // after all components/visualizations have been added
            this.options = options || {};

            this._extraOptions = [];
            this._visualizations = [];

            return this;
        },

        calculateWidth: function () {
            var width = _.nw.getStyle(this.options.el, 'width');
            return this.options.el ? (parseInt(width, 10) || this.options.chart.defaultWidth) : this.options.chart.defaultWidth;
        },

        calculateHeight: function () {
            var height = _.nw.getStyle(this.options.el, 'height');
            var containerHeight = this.options.el ? parseInt(height, 10) : undefined;
            var calcWidth = this.options.chart.width;
            var ratio = this.options.chart.aspect || this.options.chart.defaultAspect;

            return !!containerHeight && containerHeight > 1 ?  containerHeight : Math.round(calcWidth * ratio);
        },

        calcMetrics: function () {
            var options = this.options;

            this.adjustPadding();

            this.adjustTitlePadding();

            options.chart.width = options.chart.width || this.calculateWidth();
            options.chart.height = options.chart.height || this.calculateHeight();

            this.options = _.merge(options, {
                chart: {
                    plotWidth: options.chart.width - options.chart.margin.left - options.chart.margin.right - options.chart.padding.left - options.chart.padding.right,
                    plotHeight: options.chart.height - options.chart.margin.top - options.chart.margin.bottom - options.chart.padding.top - options.chart.padding.bottom,
                    plotLeft: options.chart.margin.left + options.chart.padding.left,
                    plotTop: options.chart.margin.top + options.chart.padding.top
                }
            });
        },

        adjustPadding: function () {
            // overriden by components that need to adjust padding
            return this;
        },

        adjustTitlePadding: function () {
            // overriden by components that need to adjust padding
            return this;
        },

        composeOptions: function () {
            var allDefaults = _.merge({}, defaults);
            var mergeExtraOptions = function (opt) { _.merge(allDefaults, opt); };
            var mergeDefaults = function (vis) { _.merge(allDefaults, vis.renderer.defaults); };

            _.each(this._extraOptions, mergeExtraOptions);
            _.each(this._visualizations, mergeDefaults);

            // compose the final list of options right before start rendering
            this.options = _.merge({}, allDefaults, this.options);
        },

        baseRender: function () {
            this.plotArea();

            return this;
        },

        /**
        * Renders this Contour instance and all its visualizations into the DOM.
        *
        * Example:
        *
        *     new Contour({ el:'.myChart' })
        *           .pie([1,2,3])
        *           .render()
        *
        * @function render
        *
        */
        render: function () {
            this.composeOptions();

            this.calcMetrics();

            this.baseRender();

            this.renderVisualizations();

            return this;
        },

        update: function () {
            this.calcMetrics();
            return this;
        },

        plotArea: function () {

            var chartOpt = this.options.chart;

            this.container = d3.select(this.options.el);

            if(!this.svg) {
                this.svg = this.container
                    .append('svg')
                    .attr('viewBox', '0 0 ' + chartOpt.width + ' ' + chartOpt.height)
                    .attr('preserveAspectRatio', 'xMinYMin')
                    .attr('class', 'contour-chart')
                    .attr('height', chartOpt.height)
                    .append('g')
                        .attr('transform', 'translate(' + chartOpt.margin.left + ',' + chartOpt.margin.top + ')');
            }

            return this;
        },

        createVisualizationLayer: function (vis, id) {
            return this.svg.append('g')
                .attr('vis-id', id)
                .attr('vis-type', vis.type)
                .attr('transform', 'translate(' + this.options.chart.padding.left + ',' + this.options.chart.padding.top + ')');
        },

        renderVisualizations: function () {

            _.each(this._visualizations, function (visualization, index) {
                var id = index + 1;
                var layer = visualization.layer || this.createVisualizationLayer(visualization, id);
                var opt = _.merge({}, this.options, visualization.options);
                visualization.layer = layer;
                visualization.parent = this;
                visualization.render(layer, opt, this);
            }, this);

            return this;
        },

        /**
        * Sets the same data into all visualizations for a Contour instance. Useful for creating interactive
        * visualizations: call after getting the additional data from the user.
        *
        * ###Example:
        *
        *     var data = [1,2,3,4,5];
        *     var chart = new Contour({ el:'.myChart' })
        *           .cartesian()
        *           .scatter(data)
        *           .trendLine(data);
        *
        *     data.push(10);
        *     chart.setData(data)
        *           .render();
        *
        * @function setData
        *
        */
        setData: function (data) {
            _.invoke(this._visualizations, 'setData', data);

            return this;
        },

        /**
        * Returns a VisualizationContainer object for the visualization at a given index (0-based).
        *
        * ###Example:
        *
        *     var chart = new Contour({ el:'.myChart' })
        *           .pie([1,2,3])
        *           .render()
        *
        *     var myPie = chart.select(0)
        *
        *     // do something with the visualization, for example updating its data set
        *     myPie.setData([6,7,8,9]).render()
        *
        * @function select
        *
        */
        select: function (index) {
            return this._visualizations[index];
        },

        // place holder function for now
        data: function () {

        }
    });

    // export to our context
    root.Contour = Contour;

})();
<|endoftext|>


<commit_before>var config =  require('../config.js');
var nano = require('nano')(config.couchAuthDbURL);
var maindb = nano.use('main');
var uuid = require('node-uuid');
var recordsToUpdate = [];

maindb.list({startkey: 'visit_', endkey: 'visit_\uffff', include_docs: true}, function(err, results) {
  if (!err) {
    results.rows.forEach(function(result) {
      var visitDoc = result.doc.data;
      if (visitDoc !== null && visitDoc.notes && !visitDoc.patientNotes) {
        var noteUuid = uuid.v4();
        var visitId = result.doc._id.substr(8);
        var patientNote = {
          _id: 'patientNote_2_' + noteUuid,
          data: {
            content: visitDoc.notes,
            createdBy: 'system',
            date: new Date(),
            noteType: 'General',
            patient: visitDoc.patient,
            visit: visitId
          }
        };
        recordsToUpdate.push(patientNote);
        result.doc.data.patientNotes = [noteUuid];
        recordsToUpdate.push(result.doc);
      }
    });
    if (recordsToUpdate.length > 0) {
      maindb.bulk({ docs: recordsToUpdate}, function(err, results) {
        if (err) {
          console.log('Error updating patient notes records.', err);
        } else {
          console.log('Success updating patient notes records.', JSON.stringify(results, null, 2));
        }
      });
    }
  } else {
    console.log('ERROR fetching visit records', err);
  }
});
<commit_msg>Update notes migration to use examiner and startDate<commit_after>var config =  require('../config.js');
var nano = require('nano')(config.couchAuthDbURL);
var maindb = nano.use('main');
var uuid = require('node-uuid');
var recordsToUpdate = [];

maindb.list({startkey: 'visit_', endkey: 'visit_\uffff', include_docs: true}, function(err, results) {
  if (!err) {
    results.rows.forEach(function(result) {
      var visitDoc = result.doc.data;
      if (visitDoc !== null && visitDoc.notes && !visitDoc.patientNotes) {
        var noteUuid = uuid.v4();
        var visitId = result.doc._id.substr(8);
        var patientNote = {
          _id: 'patientNote_2_' + noteUuid,
          data: {
            content: visitDoc.notes,
            createdBy: visitDoc.examiner || '',
            date: visitDoc.startDate,
            noteType: 'General',
            patient: visitDoc.patient,
            visit: visitId
          }
        };
        recordsToUpdate.push(patientNote);
        result.doc.data.patientNotes = [noteUuid];
        recordsToUpdate.push(result.doc);
      }
    });
    if (recordsToUpdate.length > 0) {
      maindb.bulk({ docs: recordsToUpdate}, function(err, results) {
        if (err) {
          console.log('Error updating patient notes records.', err);
        } else {
          console.log('Success updating patient notes records.', JSON.stringify(results, null, 2));
        }
      });
    }
  } else {
    console.log('ERROR fetching visit records', err);
  }
});
<|endoftext|>


<commit_before>import autoBind from 'auto-bind';
import m from 'mithril';
import SearchIconComponent from './search-icon';

// A generic autocomplete-based search field
class SearchFieldComponent {

  constructor(vnode) {
    this.searcher = vnode.attrs.searcher;
    autoBind(this);
  }

  // Handle keyboard shortcuts for navigating results
  handleKeyboardNav(keydownEvent) {

    let keyCode = keydownEvent.keyCode;
    // Do not proceed if no results are selected
    if (this.searcher.results.length === 0) {
      // Prevent Mithril from redrawing for irrelevant keydown events
      keydownEvent.redraw = false;
      return;
    }

    if (keyCode === 13) {
      // On enter key, action selected result (by default, view the reference)
      this.searcher.getSelectedResult().runDefaultAction();
      keydownEvent.preventDefault();
      keydownEvent.redraw = false;
    } else if (keyCode === 40) {
      // On down arrow, select next result
      this.searcher.selectNextResult();
      keydownEvent.preventDefault();
    } else if (keyCode === 38) {
      // On up arrow, select previous result
      this.searcher.selectPrevResult();
      keydownEvent.preventDefault();
    } else {
      keydownEvent.redraw = false;
    }

  }

  // Run the main search function as soon as the search field contents change
  triggerSearch(inputEvent) {
    this.searcher.search(inputEvent.target.value);
    inputEvent.redraw = false;
  }

  view(vnode) {
    return m('div.search-field-container', [
      m('input[type=text].search-field', {
        autofocus: vnode.attrs.autofocus,
        placeholder: vnode.attrs.placeholder,
        value: this.searcher.queryStr,
        onkeydown: this.handleKeyboardNav,
        oninput: this.triggerSearch
      }),
      m(SearchIconComponent)
    ]);
  }

}

export default SearchFieldComponent;
<commit_msg>Use destructuring to reference vnode attrs<commit_after>import autoBind from 'auto-bind';
import m from 'mithril';
import SearchIconComponent from './search-icon';

// A generic autocomplete-based search field
class SearchFieldComponent {

  constructor({attrs}) {
    this.searcher = attrs.searcher;
    autoBind(this);
  }

  // Handle keyboard shortcuts for navigating results
  handleKeyboardNav(keydownEvent) {

    let keyCode = keydownEvent.keyCode;
    // Do not proceed if no results are selected
    if (this.searcher.results.length === 0) {
      // Prevent Mithril from redrawing for irrelevant keydown events
      keydownEvent.redraw = false;
      return;
    }

    if (keyCode === 13) {
      // On enter key, action selected result (by default, view the reference)
      this.searcher.getSelectedResult().runDefaultAction();
      keydownEvent.preventDefault();
      keydownEvent.redraw = false;
    } else if (keyCode === 40) {
      // On down arrow, select next result
      this.searcher.selectNextResult();
      keydownEvent.preventDefault();
    } else if (keyCode === 38) {
      // On up arrow, select previous result
      this.searcher.selectPrevResult();
      keydownEvent.preventDefault();
    } else {
      keydownEvent.redraw = false;
    }

  }

  // Run the main search function as soon as the search field contents change
  triggerSearch(inputEvent) {
    this.searcher.search(inputEvent.target.value);
    inputEvent.redraw = false;
  }

  view({attrs}) {
    return m('div.search-field-container', [
      m('input[type=text].search-field', {
        autofocus: attrs.autofocus,
        placeholder: attrs.placeholder,
        value: this.searcher.queryStr,
        onkeydown: this.handleKeyboardNav,
        oninput: this.triggerSearch
      }),
      m(SearchIconComponent)
    ]);
  }

}

export default SearchFieldComponent;
<|endoftext|>