<commit_before>const Settings = require('../models/settings');
const Router = require('../models/router');
const LinkHandler = require('../models/linkHandler');
const IndexPage = require('../index/indexPage');
const SettingsPage = require('../settings/settingsPage');
const AboutPage = require('../about/aboutPage');
const FlashMessages = require('../models/flashMessages');
const AppMenu = require('../models/appMenu');
const ChromecastScanner = require('../models/chromecastScanner');
const Chromecast = require('../models/chromecast');

const __bind = function(fn, me) {
  return function() {
    return fn.apply(me, arguments);
  };
};

class PageLoader {
  constructor() {
    console.debug('page loader init');
    this.pageID = null;
    this.page = null;
    this.stationUrl = null;
    this.onPageLoad = __bind(this.onPageLoad, this);
    this.findElements();
    this.flashMessages = new FlashMessages(this.statusArea);
    Settings.load().then(this.onInitialSettingsLoad.bind(this));
    this.listenForCast();
    this.setupAppMenu();
  }

  findElements() {
    this.statusArea = document.getElementById('status-message');
    this.audioTag = document.querySelector('audio');
    this.chromecastWrapper = document.getElementById('chromecast-wrapper');
    this.chromecastLink = document.getElementById('chromecast-link');
    this.chromecastIcon = this.chromecastLink.querySelector('.material-icons');
    this.returnLinkWrapper = document.getElementById('return-link-wrapper');
    this.settingsLinkWrapper = document.getElementById('settings-wrapper');
    this.aboutLinkWrapper = document.getElementById('about-wrapper');
    this.chromecastList = document.getElementById('chromecast-list');
  }

  onInitialSettingsLoad(settings) {
    this.settings = settings;
    this.setupRouter();
  }

  listenForCast() {
    this.chromecastLink.addEventListener('click', this.onChromecast.bind(this));
  }

  setupAppMenu() {
    const menu = new AppMenu();
    menu.addListener('about-app', () => {
      this.router.loadPage('about/about.html', 'about');
    });
    menu.addListener('preferences', () => {
      this.router.loadPage('settings/settings.html', 'settings');
    });
  }

  setupRouter() {
    this.router = new Router();
    this.router.addListener('page:loaded', (id, d) => this.onPageLoaded(id, d));
    this.router.loadPage('index/index.html', 'player');
  }

  onPageLoaded(pageID, data) {
    if (this.page && pageID !== this.pageID) {
      this.page.removeListeners();
    }
    this.updatePageClass(pageID);
    document.getElementById('page-container').innerHTML = data;
    this.handleLinks();
    this.applyTheme(this.settings.theme);
    this.initPage(pageID);
  }

  initPage(pageID) {
    if (pageID === 'player') {
      this.onIndexPageLoaded();
    } else if (pageID === 'settings') {
      this.onSettingsPageLoaded();
    } else if (pageID === 'about') {
      this.onAboutPageLoaded();
    }
  }

  handleLinks() {
    if (this.linkHandler) {
      this.linkHandler.removeListener('page:load', this.onPageLoad);
    }
    this.linkHandler = new LinkHandler();
    this.linkHandler.addListener('page:load', this.onPageLoad);
  }

  onPageLoad(p, id) {
    this.router.loadPage(p, id);
  }

  updatePageClass(pageID) {
    if (this.pageID) {
      document.body.classList.remove(this.pageID);
    }
    this.pageID = pageID;
    document.body.classList.add(pageID);
  }

  applyTheme(theme) {
    document.body.classList.remove('theme-light');
    document.body.classList.remove('theme-dark');
    document.body.classList.add('theme-' + (theme || 'light'));
  }

  onIndexPageLoaded() {
    if (this.page && this.page instanceof IndexPage) {
      return;
    }
    this.page = new IndexPage(this.settings, this.audioTag);
    this.listenForPageMessages();
    this.page.addListener('play', this.onPlay.bind(this));
    this.page.addListener('pause', this.onPause.bind(this));
    this.returnLinkWrapper.classList.add('hidden');
    this.settingsLinkWrapper.classList.remove('hidden');
    this.aboutLinkWrapper.classList.remove('hidden');
  }

  onSettingsPageLoaded() {
    if (this.page && this.page instanceof SettingsPage) {
      return;
    }
    this.page = new SettingsPage(this.settings);
    this.listenForPageMessages();
    this.returnLinkWrapper.classList.remove('hidden');
    this.settingsLinkWrapper.classList.add('hidden');
    this.aboutLinkWrapper.classList.add('hidden');
  }

  onAboutPageLoaded() {
    if (this.page && this.page instanceof AboutPage) {
      return;
    }
    this.page = new AboutPage();
    this.listenForPageMessages();
    this.returnLinkWrapper.classList.remove('hidden');
    this.settingsLinkWrapper.classList.add('hidden');
    this.aboutLinkWrapper.classList.add('hidden');
  }

  listenForPageMessages() {
    this.page.addListener('settings:change', (s) => this.onSettingsChanged(s));
    this.page.addListener('error', (e) => this.flashMessages.error(e));
    this.page.addListener('notice', (m) => this.flashMessages.notice(m));
  }

  onPlay(url) {
    this.stationUrl = url;
    console.debug('playing', this.stationUrl);
    if (process.env.ENABLE_CHROMECAST) {
      this.chromecastWrapper.classList.remove('hidden');
    }
  }

  onPause(station) {
    this.stationUrl = null;
    if (process.env.ENABLE_CHROMECAST) {
      this.chromecastWrapper.classList.add('hidden');
    }
  }

  onChromecast() {
    if (!process.env.ENABLE_CHROMECAST) {
      return;
    }
    if (this.chromecastLink.classList.contains('disabled')) {
      return;
    }
    const listItems = Array.from(this.chromecastList.querySelectorAll('li'));
    listItems.forEach(li => li.remove());
    this.chromecastLink.classList.add('disabled');
    this.chromecastIcon.textContent = 'refresh';
    this.chromecastIcon.classList.add('spin');
    const scanner = new ChromecastScanner();
    scanner.addListener('chromecast', this.onChromecastFound.bind(this));
    scanner.addListener('error', this.onChromecastFindError.bind(this));
    scanner.addListener('finished', this.onChromecastScanComplete.bind(this));
    scanner.findChromecasts();
  }

  onChromecastFound(chromecast) {
    const listItem = document.createElement('li');
    const link = document.createElement('a');
    link.textContent = chromecast.name.replace(/\.local$/, '');
    link.href = '#';
    link.setAttribute('data-host', chromecast.data);
    link.addEventListener('click', this.onChromecastSelected.bind(this));
    listItem.appendChild(link);
    this.chromecastList.appendChild(listItem);
    this.chromecastList.classList.remove('hidden');
  }

  onChromecastScanComplete() {
    console.log('chromecast scan complete');
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    if (this.chromecastIcon.textContent === 'refresh') {
      this.chromecastIcon.textContent = 'cast';
    }
  }

  onChromecastFindError(error) {
    console.error('failed to find Chromecasts', error);
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    this.chromecastIcon.textContent = 'cast';
  }

  onChromecastSelected(event) {
    event.preventDefault();
    const link = event.target;
    link.blur();
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    this.chromecastIcon.textContent = 'cast';
    this.chromecastList.classList.add('hidden');
    this.chromecastLink.setAttribute('title', 'Casting to ' + link.textContent);
    const chromecast = new Chromecast({
      host: link.getAttribute('data-host'),
      url: this.stationUrl
    });
    chromecast.addListener('connected', this.onChromecastConnected.bind(this));
    chromecast.addListener('launched', this.onChromecastLaunched.bind(this));
    chromecast.addListener('launch-error',
                           this.onChromecastLaunchError.bind(this));
    chromecast.addListener('error', this.onChromecastError.bind(this));
    chromecast.addListener('client-error',
                           this.onChromecastClientError.bind(this));
    chromecast.addListener('status', this.onChromecastStatus.bind(this));
    chromecast.addListener('player-loaded',
                           this.onChromecastPlayerLoaded.bind(this));
    chromecast.addListener('player-load-error',
                           this.onChromecastPlayerLoadError.bind(this));
    chromecast.connect();
  }

  onChromecastConnected() {

  }

  onChromecastLaunched() {

  }

  onChromecastError(error) {

  }

  onChromecastPlayerLoadError(error) {

  }

  onChromecastClientError(error) {

  }

  onChromecastLaunchError(error) {

  }

  onChromecastStatus(status) {
    console.log(status.playerState, status.media ? status.media.contentId : 'unknown', 'volume ' + status.volume.level, status.volume.muted ? 'muted' : 'not muted');
    if (status.playerState === 'PLAYING') {
      this.chromecastIcon.textContent = 'cast_connected';
    }
    if (this.page && typeof this.page.onChromecastStatus === 'function') {

    }
  }

  onChromecastPlayerLoaded(status) {
    this.onChromecastStatus(status);
  }

  onSettingsChanged(settings) {
    this.settings = settings;
    this.applyTheme(settings.theme);
  }
}

document.addEventListener('DOMContentLoaded', function() {
  new PageLoader();
});
<commit_msg>Stop scanning for Chromecasts when one is selected<commit_after>const Settings = require('../models/settings');
const Router = require('../models/router');
const LinkHandler = require('../models/linkHandler');
const IndexPage = require('../index/indexPage');
const SettingsPage = require('../settings/settingsPage');
const AboutPage = require('../about/aboutPage');
const FlashMessages = require('../models/flashMessages');
const AppMenu = require('../models/appMenu');
const ChromecastScanner = require('../models/chromecastScanner');
const Chromecast = require('../models/chromecast');

const __bind = function(fn, me) {
  return function() {
    return fn.apply(me, arguments);
  };
};

class PageLoader {
  constructor() {
    console.debug('page loader init');
    this.pageID = null;
    this.page = null;
    this.stationUrl = null;
    this.onPageLoad = __bind(this.onPageLoad, this);
    this.findElements();
    this.flashMessages = new FlashMessages(this.statusArea);
    Settings.load().then(this.onInitialSettingsLoad.bind(this));
    this.listenForCast();
    this.setupAppMenu();
  }

  findElements() {
    this.statusArea = document.getElementById('status-message');
    this.audioTag = document.querySelector('audio');
    this.chromecastWrapper = document.getElementById('chromecast-wrapper');
    this.chromecastLink = document.getElementById('chromecast-link');
    this.chromecastIcon = this.chromecastLink.querySelector('.material-icons');
    this.returnLinkWrapper = document.getElementById('return-link-wrapper');
    this.settingsLinkWrapper = document.getElementById('settings-wrapper');
    this.aboutLinkWrapper = document.getElementById('about-wrapper');
    this.chromecastList = document.getElementById('chromecast-list');
  }

  onInitialSettingsLoad(settings) {
    this.settings = settings;
    this.setupRouter();
  }

  listenForCast() {
    this.chromecastLink.addEventListener('click', this.onChromecast.bind(this));
  }

  setupAppMenu() {
    const menu = new AppMenu();
    menu.addListener('about-app', () => {
      this.router.loadPage('about/about.html', 'about');
    });
    menu.addListener('preferences', () => {
      this.router.loadPage('settings/settings.html', 'settings');
    });
  }

  setupRouter() {
    this.router = new Router();
    this.router.addListener('page:loaded', (id, d) => this.onPageLoaded(id, d));
    this.router.loadPage('index/index.html', 'player');
  }

  onPageLoaded(pageID, data) {
    if (this.page && pageID !== this.pageID) {
      this.page.removeListeners();
    }
    this.updatePageClass(pageID);
    document.getElementById('page-container').innerHTML = data;
    this.handleLinks();
    this.applyTheme(this.settings.theme);
    this.initPage(pageID);
  }

  initPage(pageID) {
    if (pageID === 'player') {
      this.onIndexPageLoaded();
    } else if (pageID === 'settings') {
      this.onSettingsPageLoaded();
    } else if (pageID === 'about') {
      this.onAboutPageLoaded();
    }
  }

  handleLinks() {
    if (this.linkHandler) {
      this.linkHandler.removeListener('page:load', this.onPageLoad);
    }
    this.linkHandler = new LinkHandler();
    this.linkHandler.addListener('page:load', this.onPageLoad);
  }

  onPageLoad(p, id) {
    this.router.loadPage(p, id);
  }

  updatePageClass(pageID) {
    if (this.pageID) {
      document.body.classList.remove(this.pageID);
    }
    this.pageID = pageID;
    document.body.classList.add(pageID);
  }

  applyTheme(theme) {
    document.body.classList.remove('theme-light');
    document.body.classList.remove('theme-dark');
    document.body.classList.add('theme-' + (theme || 'light'));
  }

  onIndexPageLoaded() {
    if (this.page && this.page instanceof IndexPage) {
      return;
    }
    this.page = new IndexPage(this.settings, this.audioTag);
    this.listenForPageMessages();
    this.page.addListener('play', this.onPlay.bind(this));
    this.page.addListener('pause', this.onPause.bind(this));
    this.returnLinkWrapper.classList.add('hidden');
    this.settingsLinkWrapper.classList.remove('hidden');
    this.aboutLinkWrapper.classList.remove('hidden');
  }

  onSettingsPageLoaded() {
    if (this.page && this.page instanceof SettingsPage) {
      return;
    }
    this.page = new SettingsPage(this.settings);
    this.listenForPageMessages();
    this.returnLinkWrapper.classList.remove('hidden');
    this.settingsLinkWrapper.classList.add('hidden');
    this.aboutLinkWrapper.classList.add('hidden');
  }

  onAboutPageLoaded() {
    if (this.page && this.page instanceof AboutPage) {
      return;
    }
    this.page = new AboutPage();
    this.listenForPageMessages();
    this.returnLinkWrapper.classList.remove('hidden');
    this.settingsLinkWrapper.classList.add('hidden');
    this.aboutLinkWrapper.classList.add('hidden');
  }

  listenForPageMessages() {
    this.page.addListener('settings:change', (s) => this.onSettingsChanged(s));
    this.page.addListener('error', (e) => this.flashMessages.error(e));
    this.page.addListener('notice', (m) => this.flashMessages.notice(m));
  }

  onPlay(url) {
    this.stationUrl = url;
    console.debug('playing', this.stationUrl);
    if (process.env.ENABLE_CHROMECAST) {
      this.chromecastWrapper.classList.remove('hidden');
    }
  }

  onPause(station) {
    this.stationUrl = null;
    if (process.env.ENABLE_CHROMECAST) {
      this.chromecastWrapper.classList.add('hidden');
    }
  }

  onChromecast() {
    if (!process.env.ENABLE_CHROMECAST) {
      return;
    }
    if (this.chromecastLink.classList.contains('disabled')) {
      return;
    }
    const listItems = Array.from(this.chromecastList.querySelectorAll('li'));
    listItems.forEach(li => li.remove());
    this.chromecastLink.classList.add('disabled');
    this.chromecastIcon.textContent = 'refresh';
    this.chromecastIcon.classList.add('spin');
    this.chromecastScanner = new ChromecastScanner();
    this.chromecastScanner.addListener('chromecast',
                                       this.onChromecastFound.bind(this));
    this.chromecastScanner.addListener('error',
                                       this.onChromecastFindError.bind(this));
    this.chromecastScanner.
         addListener('finished', this.onChromecastScanComplete.bind(this));
    this.chromecastScanner.findChromecasts();
  }

  onChromecastFound(chromecast) {
    const listItem = document.createElement('li');
    const link = document.createElement('a');
    link.textContent = chromecast.name.replace(/\.local$/, '');
    link.href = '#';
    link.setAttribute('data-host', chromecast.data);
    link.addEventListener('click', this.onChromecastSelected.bind(this));
    listItem.appendChild(link);
    this.chromecastList.appendChild(listItem);
    this.chromecastList.classList.remove('hidden');
  }

  onChromecastScanComplete() {
    console.log('chromecast scan complete');
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    if (this.chromecastIcon.textContent === 'refresh') {
      this.chromecastIcon.textContent = 'cast';
    }
  }

  onChromecastFindError(error) {
    console.error('failed to find Chromecasts', error);
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    this.chromecastIcon.textContent = 'cast';
  }

  onChromecastSelected(event) {
    event.preventDefault();
    const link = event.target;
    link.blur();
    this.chromecastLink.classList.remove('disabled');
    this.chromecastIcon.classList.remove('spin');
    this.chromecastIcon.textContent = 'cast';
    this.chromecastList.classList.add('hidden');
    if (this.chromecastScanner) {
      this.chromecastScanner.close();
    }
    this.chromecastLink.setAttribute('title', 'Casting to ' + link.textContent);
    const chromecast = new Chromecast({
      host: link.getAttribute('data-host'),
      url: this.stationUrl
    });
    chromecast.addListener('connected', this.onChromecastConnected.bind(this));
    chromecast.addListener('launched', this.onChromecastLaunched.bind(this));
    chromecast.addListener('launch-error',
                           this.onChromecastLaunchError.bind(this));
    chromecast.addListener('error', this.onChromecastError.bind(this));
    chromecast.addListener('client-error',
                           this.onChromecastClientError.bind(this));
    chromecast.addListener('status', this.onChromecastStatus.bind(this));
    chromecast.addListener('player-loaded',
                           this.onChromecastPlayerLoaded.bind(this));
    chromecast.addListener('player-load-error',
                           this.onChromecastPlayerLoadError.bind(this));
    chromecast.connect();
  }

  onChromecastConnected() {

  }

  onChromecastLaunched() {

  }

  onChromecastError(error) {

  }

  onChromecastPlayerLoadError(error) {

  }

  onChromecastClientError(error) {

  }

  onChromecastLaunchError(error) {

  }

  onChromecastStatus(status) {
    console.log(status.playerState, status.media ? status.media.contentId : 'unknown', 'volume ' + status.volume.level, status.volume.muted ? 'muted' : 'not muted');
    if (status.playerState === 'PLAYING') {
      this.chromecastIcon.textContent = 'cast_connected';
    }
    if (this.page && typeof this.page.onChromecastStatus === 'function') {

    }
  }

  onChromecastPlayerLoaded(status) {
    this.onChromecastStatus(status);
  }

  onSettingsChanged(settings) {
    this.settings = settings;
    this.applyTheme(settings.theme);
  }
}

document.addEventListener('DOMContentLoaded', function() {
  new PageLoader();
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Custom configuration object for RoTercera configuration configuration
 * @author Roy Braam
 */
Ext.define("viewer.components.CustomConfiguration",{
    extend: "viewer.components.SelectionWindowConfig",
    constructor: function (parentId,configObject){
        viewer.components.CustomConfiguration.superclass.constructor.call(this, parentId,configObject);
        //this.createCheckBoxes(this.configObject.layers);
        this.addFormItems(configObject);
        this.createCheckBoxes(this.configObject.layers,{editable:true});
    },
    addFormItems: function(){
        var me =this;
        this.form.add([{
                xtype: "textfield",
                name: "width",
                value: me.configObject.width ? me.configObject.width : 280,
                fieldLabel: "width",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "height",
                value: me.configObject.height ? me.configObject.height: 580,
                fieldLabel: "height",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roServiceUrl",
                value: me.configObject.roServiceUrl,
                fieldLabel: "roServiceUrl",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "terceraRequestPage",
                value: me.configObject.terceraRequestPage? me.configObject.terceraRequestPage : "https://tercera.provincie-utrecht.nl/RequestPage.aspx",
                fieldLabel: "terceraRequestPage",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roonlineLayers",
                value: me.configObject.roonlineLayers? me.configObject.roonlineLayers : "BP:Bestemmingsplangebied,BP:Wijzigingsplangebied,BP:Enkelbestemming,\
BP:Figuur,BP:Lettertekenaanduiding,BP:Maatvoering,BP:Dubbelbestemming,BP:Bouwvlak,\
BP:Gebiedsaanduiding,BP:Inpassingsplangebied,BP:Bouwaanduiding,BP:Functieaanduiding,\
PP:ProvinciaalPlangebied,PP:ProvinciaalGebied,PP:ProvinciaalComplex,\
PP:ProvinciaalVerbinding,NP:NationaalPlangebied,XGB:Besluitvlak,XGB:Besluitsubvlak,\
XGB:Exploitatieplangebied,XGB:Gerechtelijkeuitspraakgebied,XGB:Projectbesluitgebied,\
XGB:Tijdelijkeontheffingbuitenplansgebied,XGB:Voorbereidingsbesluitgebied,PCP:Plangebied",
                fieldLabel: "roonlineLayers",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roonlineServiceUrl",
                value: me.configObject.roonlineServiceUrl ? me.configObject.roonlineServiceUrl : "http://afnemers.ruimtelijkeplannen.nl/afnemers/services",
                fieldLabel: "roonlineServiceUrl",
                labelWidth: this.labelWidth
            }
        ]);

    }
});

<commit_msg>Changes for #15<commit_after>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Custom configuration object for RoTercera configuration configuration
 * @author Roy Braam
 */
Ext.define("viewer.components.CustomConfiguration",{
    extend: "viewer.components.SelectionWindowConfig",
    constructor: function (parentId, configObject, configPage){
        viewer.components.CustomConfiguration.superclass.constructor.call(this, parentId, configObject, configPage);
        //this.createCheckBoxes(this.configObject.layers);
        this.addFormItems(configObject);
        this.createCheckBoxes(this.configObject.layers,{editable:true});
    },
    addFormItems: function(){
        var me =this;
        this.form.add([{
                xtype: "textfield",
                name: "width",
                value: me.configObject.width ? me.configObject.width : 280,
                fieldLabel: "width",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "height",
                value: me.configObject.height ? me.configObject.height: 580,
                fieldLabel: "height",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roServiceUrl",
                value: me.configObject.roServiceUrl,
                fieldLabel: "roServiceUrl",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "terceraRequestPage",
                value: me.configObject.terceraRequestPage? me.configObject.terceraRequestPage : "https://tercera.provincie-utrecht.nl/RequestPage.aspx",
                fieldLabel: "terceraRequestPage",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roonlineLayers",
                value: me.configObject.roonlineLayers? me.configObject.roonlineLayers : "BP:Bestemmingsplangebied,BP:Wijzigingsplangebied,BP:Enkelbestemming,\
BP:Figuur,BP:Lettertekenaanduiding,BP:Maatvoering,BP:Dubbelbestemming,BP:Bouwvlak,\
BP:Gebiedsaanduiding,BP:Inpassingsplangebied,BP:Bouwaanduiding,BP:Functieaanduiding,\
PP:ProvinciaalPlangebied,PP:ProvinciaalGebied,PP:ProvinciaalComplex,\
PP:ProvinciaalVerbinding,NP:NationaalPlangebied,XGB:Besluitvlak,XGB:Besluitsubvlak,\
XGB:Exploitatieplangebied,XGB:Gerechtelijkeuitspraakgebied,XGB:Projectbesluitgebied,\
XGB:Tijdelijkeontheffingbuitenplansgebied,XGB:Voorbereidingsbesluitgebied,PCP:Plangebied",
                fieldLabel: "roonlineLayers",
                labelWidth: this.labelWidth
            },{
                xtype: "textfield",
                name: "roonlineServiceUrl",
                value: me.configObject.roonlineServiceUrl ? me.configObject.roonlineServiceUrl : "http://afnemers.ruimtelijkeplannen.nl/afnemers/services",
                fieldLabel: "roonlineServiceUrl",
                labelWidth: this.labelWidth
            }
        ]);

    }
});

<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/DeveloperError',
        '../Core/Iso8601',
        '../Core/JulianDate',
        '../Core/TimeInterval',
        '../Core/TimeIntervalCollection',
        '../Core/binarySearch',
        '../Core/HermitePolynomialApproximation',
        '../Core/LinearApproximation',
        '../Core/LagrangePolynomialApproximation'
    ], function(
        DeveloperError,
        Iso8601,
        JulianDate,
        TimeInterval,
        TimeIntervalCollection,
        binarySearch,
        HermitePolynomialApproximation,
        LinearApproximation,
        LagrangePolynomialApproximation) {
    "use strict";

    //CZML_TODO This is more of an idea than a to-do, but currently DynamicProperty requires
    //you know the type of data being loaded up-front by passing valueType.  We could take
    //a similar approach to DynamicMaterialProperty and have a list of potential valueTypes
    //that we check for when we encounter data.  This would make it possible to support
    //properties that are defined in a CZML document but not part of the official spec.  This
    //would be helpful in cases where a CZML document has $ or # links to other properties,
    //but that property itself is not part of another to-spec CZML object.  We could still
    //allow the user to pass a default valueType if they want to make sure the data
    //being processed is only the data of the expected type.

    //Map CZML interval types to their implementation.
    var interpolators = {
        HERMITE : HermitePolynomialApproximation,
        LAGRANGE : LagrangePolynomialApproximation,
        LINEAR : LinearApproximation
    };

    //The data associated with each DynamicProperty interval.
    function IntervalData() {
        this.interpolationAlgorithm = LinearApproximation;
        this.numberOfPoints = LinearApproximation.getRequiredDataPoints(1);
        this.interpolationDegree = 1;
        this.times = undefined;
        this.values = undefined;
        this.isSampled = false;
        this.xTable = undefined;
        this.yTable = undefined;
    }

    //Converts a CZML defined data into a JulianDate, regardless of whether it was
    //specified in epoch seconds or as an ISO8601 string.
    function czmlDateToJulianDate(date, epoch) {
        if (typeof date === 'string') {
            return JulianDate.fromIso8601(date);
        }
        return epoch.addSeconds(date);
    }

    /**
     *

     * DynamicProperty represents a single value that changes over time.
     * Rather than creating instances of this object directly, it's typically
     * created and managed via loading CZML data into a DynamicObjectCollection.
     * Instances of this type are exposed via DynamicObject and it's sub-objects
     * and are responsible for interpreting and interpolating the data for visualization.
     *

     *

     * The type of value exposed by this property must be provided during construction
     * by passing in an object which performs all the necessary operations needed to
     * properly store, retrieve, and interpolate the data.  For more specialized needs
     * other types of dynamic properties exist, such as DynamicMaterialProperty,
     * which as the name implies, handles materials.
     *

     *
     * @alias DynamicProperty
     * @constructor
     *
     * @param {Object} valueType A CZML type object which contains the methods needed to interpret and interpolate CZML data of the same type.
     *
     * @see CzmlBoolean
     * @see CzmlCartesian2
     * @see CzmlCartesian3
     * @see CzmlPosition
     * @see CzmlColor
     * @see CzmlHorizontalOrigin
     * @see CzmlLabelStyle
     * @see CzmlNumber
     * @see CzmlString
     * @see CzmlUnitCartesian3
     * @see CzmlUnitQuaternion
     * @see CzmlUnitSpherical
     * @see CzmlVerticalOrigin
     * @see DynamicObject
     * @see ReferenceProperty
     * @see DynamicMaterialProperty
     * @see DynamicPositionProperty
     * @see DynamicDirectionsProperty
     * @see DynamicVertexPositionsProperty
     */
    var DynamicProperty = function(valueType) {
        if (typeof valueType === 'undefined') {
            throw new DeveloperError('valueType is required.');
        }
        this.valueType = valueType;
        this._intervals = new TimeIntervalCollection();
        this._cachedTime = undefined;
        this._cachedInterval = undefined;
    };

    /**
     * Processes the provided CZML interval or intervals into this property.
     *
     * @memberof DynamicProperty
     *
     * @param {Object} czmlIntervals The CZML data to process.
     * @param {TimeInterval} [constrainedInterval] Constrains the processing so that any times outside of this interval are ignored.
     * @param {String} [sourceUri] The originating url of the CZML being processed.
     */
    DynamicProperty.prototype.processCzmlIntervals = function(czmlIntervals, constrainedInterval, sourceUri) {
        if (Array.isArray(czmlIntervals)) {
            for ( var i = 0, len = czmlIntervals.length; i < len; i++) {
                this._addCzmlInterval(czmlIntervals[i], constrainedInterval, sourceUri);
            }
        } else {
            this._addCzmlInterval(czmlIntervals, constrainedInterval, sourceUri);
        }
    };

    var interpolationScratch;

    /**
     * Returns the value of the property at the specified time.
     * @memberof DynamicProperty
     *
     * @param {JulianDate} time The time for which to retrieve the value.
     * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
     * @returns The modified result parameter or a new instance if the result parameter was not supplied.
     */
    DynamicProperty.prototype.getValue = function(time, result) {
        var valueType = this.valueType;

        if (typeof this._staticValue !== 'undefined') {
            return valueType.getValue(this._staticValue, result);
        }

        var interval = this._cachedInterval;
        if (!JulianDate.equals(this._cachedTime, time)) {
            this._cachedTime = JulianDate.clone(time, this._cachedTime);
            if (typeof interval === 'undefined' || !interval.contains(time)) {
                interval = this._intervals.findIntervalContainingDate(time);
                this._cachedInterval = interval;
            }
        }

        if (typeof interval === 'undefined') {
            return undefined;
        }

        var intervalData = interval.data;
        var times = intervalData.times;
        var values = intervalData.values;
        if (intervalData.isSampled && times.length >= 0 && values.length > 0) {
            var doublesPerValue = valueType.doublesPerValue;
            var index = binarySearch(times, time, JulianDate.compare);
            if (index < 0) {
                if (intervalData.numberOfPoints < 2) {
                    return undefined;
                }
                index = ~index;

                if (index >= times.length) {
                    index = times.length - 1;
                }

                var firstIndex = 0;
                var lastIndex = times.length - 1;

                var degree = intervalData.numberOfPoints - 1;
                var pointsInCollection = lastIndex - firstIndex + 1;

                if (pointsInCollection < degree + 1) {
                    // Use the entire range.
                } else {
                    var computedFirstIndex = index - ((degree / 2) | 0) - 1;
                    if (computedFirstIndex < firstIndex) {
                        computedFirstIndex = firstIndex;
                    }
                    var computedLastIndex = computedFirstIndex + degree;
                    if (computedLastIndex > lastIndex) {
                        computedLastIndex = lastIndex;
                        computedFirstIndex = computedLastIndex - degree;
                        if (computedFirstIndex < firstIndex) {
                            computedFirstIndex = firstIndex;
                        }
                    }

                    firstIndex = computedFirstIndex;
                    lastIndex = computedLastIndex;
                }

                var length = lastIndex - firstIndex + 1;

                var doublesPerInterpolationValue = valueType.doublesPerInterpolationValue;
                var xTable = intervalData.xTable;
                var yTable = intervalData.yTable;

                if (typeof xTable === 'undefined') {
                    xTable = intervalData.xTable = new Array(intervalData.numberOfPoints);
                    yTable = intervalData.yTable = new Array(intervalData.numberOfPoints * doublesPerInterpolationValue);
                }

                // Build the tables
                for ( var i = 0; i < length; ++i) {
                    xTable[i] = times[lastIndex].getSecondsDifference(times[firstIndex + i]);
                }
                var specializedPackFunction = valueType.packValuesForInterpolation;
                if (typeof specializedPackFunction === 'undefined') {
                    var destinationIndex = 0;
                    var sourceIndex = firstIndex * doublesPerValue;
                    var stop = (lastIndex + 1) * doublesPerValue;

                    while (sourceIndex < stop) {
                        yTable[destinationIndex] = values[sourceIndex];
                        sourceIndex++;
                        destinationIndex++;
                    }
                } else {
                    specializedPackFunction(values, yTable, firstIndex, lastIndex);
                }

                // Interpolate!
                var x = times[lastIndex].getSecondsDifference(time);
                interpolationScratch = intervalData.interpolationAlgorithm.interpolateOrderZero(x, xTable, yTable, doublesPerInterpolationValue, interpolationScratch);

                var specializedGetFunction = valueType.getValueFromInterpolationResult;
                if (typeof specializedGetFunction === 'undefined') {
                    return valueType.getValueFromArray(interpolationScratch, 0, result);
                }
                return specializedGetFunction(interpolationScratch, result, values, firstIndex, lastIndex);
            }
            return valueType.getValueFromArray(intervalData.values, index * doublesPerValue, result);
        }
        return valueType.getValue(intervalData.values, result);
    };

    DynamicProperty._mergeNewSamples = function(epoch, times, values, newData, doublesPerValue) {
        var newDataIndex = 0, i, prevItem, timesInsertionPoint, valuesInsertionPoint, timesSpliceArgs, valuesSpliceArgs, currentTime, nextTime;
        while (newDataIndex < newData.length) {
            currentTime = czmlDateToJulianDate(newData[newDataIndex], epoch);
            timesInsertionPoint = binarySearch(times, currentTime, JulianDate.compare);

            if (timesInsertionPoint < 0) {
                //Doesn't exist, insert as many additional values as we can.
                timesInsertionPoint = ~timesInsertionPoint;
                timesSpliceArgs = [timesInsertionPoint, 0];

                valuesInsertionPoint = timesInsertionPoint * doublesPerValue;
                valuesSpliceArgs = [valuesInsertionPoint, 0];
                prevItem = undefined;
                nextTime = times[timesInsertionPoint];
                while (newDataIndex < newData.length) {
                    currentTime = czmlDateToJulianDate(newData[newDataIndex], epoch);
                    if ((typeof prevItem !== 'undefined' && JulianDate.compare(prevItem, currentTime) >= 0) ||
                        (typeof nextTime !== 'undefined' && JulianDate.compare(currentTime, nextTime) >= 0)) {
                        break;
                    }
                    timesSpliceArgs.push(currentTime);
                    newDataIndex = newDataIndex + 1;
                    for (i = 0; i < doublesPerValue; i++) {
                        valuesSpliceArgs.push(newData[newDataIndex]);
                        newDataIndex = newDataIndex + 1;
                    }
                    prevItem = currentTime;
                }

                Array.prototype.splice.apply(values, valuesSpliceArgs);
                Array.prototype.splice.apply(times, timesSpliceArgs);
            } else {
                //Found an exact match
                for (i = 0; i < doublesPerValue; i++) {
                    newDataIndex++;
                    values[(timesInsertionPoint * doublesPerValue) + i] = newData[newDataIndex];
                }
                newDataIndex++;
            }
        }
    };

    DynamicProperty.prototype._addCzmlInterval = function(czmlInterval, constrainedInterval, sourceUri) {
        var iso8601Interval = czmlInterval.interval;
        if (typeof iso8601Interval === 'undefined') {
            iso8601Interval = Iso8601.MAXIMUM_INTERVAL;
        } else {
            iso8601Interval = TimeInterval.fromIso8601(iso8601Interval);
        }

        if (typeof constrainedInterval !== 'undefined') {
            iso8601Interval = iso8601Interval.intersect(constrainedInterval);
        }

        var unwrappedInterval = this.valueType.unwrapInterval(czmlInterval, sourceUri);
        if (typeof unwrappedInterval !== 'undefined') {
            this._addCzmlIntervalUnwrapped(iso8601Interval.start, iso8601Interval.stop, unwrappedInterval, czmlInterval.epoch, czmlInterval.interpolationAlgorithm, czmlInterval.interpolationDegree);
        }
    };

    DynamicProperty.prototype._addCzmlIntervalUnwrapped = function(start, stop, unwrappedInterval, epoch, interpolationAlgorithmType, interpolationDegree) {
        var thisIntervals = this._intervals;
        var existingInterval = thisIntervals.findInterval(start, stop);
        this._cachedTime = undefined;
        this._cachedInterval = undefined;

        var intervalData;
        if (typeof existingInterval === 'undefined') {
            intervalData = new IntervalData();
            existingInterval = new TimeInterval(start, stop, true, true, intervalData);
            thisIntervals.addInterval(existingInterval);
        } else {
            intervalData = existingInterval.data;
        }

        var valueType = this.valueType;
        if (valueType.isSampled(unwrappedInterval)) {
            var interpolationAlgorithm;
            if (typeof interpolationAlgorithmType !== 'undefined') {
                interpolationAlgorithm = interpolators[interpolationAlgorithmType];
                intervalData.interpolationAlgorithm = interpolationAlgorithm;
            }
            if (typeof interpolationAlgorithm !== 'undefined' && typeof interpolationDegree !== 'undefined') {
                intervalData.interpolationDegree = interpolationDegree;
                intervalData.xTable = undefined;
                intervalData.yTable = undefined;
            }

            if (!intervalData.isSampled) {
                intervalData.times = [];
                intervalData.values = [];
                intervalData.isSampled = true;
            }
            if (typeof epoch !== 'undefined') {
                epoch = JulianDate.fromIso8601(epoch);
            }
            DynamicProperty._mergeNewSamples(epoch, intervalData.times, intervalData.values, unwrappedInterval, valueType.doublesPerValue, valueType);
            intervalData.numberOfPoints = Math.min(intervalData.interpolationAlgorithm.getRequiredDataPoints(intervalData.interpolationDegree), intervalData.times.length);
            this._staticValue = undefined;
        } else {
            //Packet itself is a constant value
            intervalData.times = undefined;
            intervalData.values = unwrappedInterval;
            intervalData.isSampled = false;

            if (existingInterval.equals(Iso8601.MAXIMUM_INTERVAL)) {
                this._staticValue = unwrappedInterval;
            } else {
                this._staticValue = undefined;
            }
        }
    };

    return DynamicProperty;
});<commit_msg>Work around stack overflow in Chrome caused by a large number of arguments to splice.apply.<commit_after>/*global define*/
define([
        '../Core/DeveloperError',
        '../Core/Iso8601',
        '../Core/JulianDate',
        '../Core/TimeInterval',
        '../Core/TimeIntervalCollection',
        '../Core/binarySearch',
        '../Core/HermitePolynomialApproximation',
        '../Core/LinearApproximation',
        '../Core/LagrangePolynomialApproximation'
    ], function(
        DeveloperError,
        Iso8601,
        JulianDate,
        TimeInterval,
        TimeIntervalCollection,
        binarySearch,
        HermitePolynomialApproximation,
        LinearApproximation,
        LagrangePolynomialApproximation) {
    "use strict";

    //CZML_TODO This is more of an idea than a to-do, but currently DynamicProperty requires
    //you know the type of data being loaded up-front by passing valueType.  We could take
    //a similar approach to DynamicMaterialProperty and have a list of potential valueTypes
    //that we check for when we encounter data.  This would make it possible to support
    //properties that are defined in a CZML document but not part of the official spec.  This
    //would be helpful in cases where a CZML document has $ or # links to other properties,
    //but that property itself is not part of another to-spec CZML object.  We could still
    //allow the user to pass a default valueType if they want to make sure the data
    //being processed is only the data of the expected type.

    //Map CZML interval types to their implementation.
    var interpolators = {
        HERMITE : HermitePolynomialApproximation,
        LAGRANGE : LagrangePolynomialApproximation,
        LINEAR : LinearApproximation
    };

    //The data associated with each DynamicProperty interval.
    function IntervalData() {
        this.interpolationAlgorithm = LinearApproximation;
        this.numberOfPoints = LinearApproximation.getRequiredDataPoints(1);
        this.interpolationDegree = 1;
        this.times = undefined;
        this.values = undefined;
        this.isSampled = false;
        this.xTable = undefined;
        this.yTable = undefined;
    }

    //Converts a CZML defined data into a JulianDate, regardless of whether it was
    //specified in epoch seconds or as an ISO8601 string.
    function czmlDateToJulianDate(date, epoch) {
        if (typeof date === 'string') {
            return JulianDate.fromIso8601(date);
        }
        return epoch.addSeconds(date);
    }

    //We can't use splice for inserting new elements because function apply can't handle
    //a huge number of arguments.  See https://code.google.com/p/chromium/issues/detail?id=56588
    function arrayInsert(array, startIndex, items) {
        var i;
        var itemsLength = items.length;
        var itemsToMove = array.length - startIndex;

        if (itemsToMove > 0) {
            var tmp = array.splice(startIndex, itemsToMove);
            array.length += itemsLength;
            for (i = 0; i < itemsLength; i++) {
                array[startIndex++] = items[i];
            }
            for (i = 0; i < itemsToMove; i++) {
                array[startIndex++] = tmp[i];
            }
        } else {
            for (i = 0; i < itemsLength; i++) {
                array.push(items[i]);
            }
        }
    }

    /**
     *

     * DynamicProperty represents a single value that changes over time.
     * Rather than creating instances of this object directly, it's typically
     * created and managed via loading CZML data into a DynamicObjectCollection.
     * Instances of this type are exposed via DynamicObject and it's sub-objects
     * and are responsible for interpreting and interpolating the data for visualization.
     *

     *

     * The type of value exposed by this property must be provided during construction
     * by passing in an object which performs all the necessary operations needed to
     * properly store, retrieve, and interpolate the data.  For more specialized needs
     * other types of dynamic properties exist, such as DynamicMaterialProperty,
     * which as the name implies, handles materials.
     *

     *
     * @alias DynamicProperty
     * @constructor
     *
     * @param {Object} valueType A CZML type object which contains the methods needed to interpret and interpolate CZML data of the same type.
     *
     * @see CzmlBoolean
     * @see CzmlCartesian2
     * @see CzmlCartesian3
     * @see CzmlPosition
     * @see CzmlColor
     * @see CzmlHorizontalOrigin
     * @see CzmlLabelStyle
     * @see CzmlNumber
     * @see CzmlString
     * @see CzmlUnitCartesian3
     * @see CzmlUnitQuaternion
     * @see CzmlUnitSpherical
     * @see CzmlVerticalOrigin
     * @see DynamicObject
     * @see ReferenceProperty
     * @see DynamicMaterialProperty
     * @see DynamicPositionProperty
     * @see DynamicDirectionsProperty
     * @see DynamicVertexPositionsProperty
     */
    var DynamicProperty = function(valueType) {
        if (typeof valueType === 'undefined') {
            throw new DeveloperError('valueType is required.');
        }
        this.valueType = valueType;
        this._intervals = new TimeIntervalCollection();
        this._cachedTime = undefined;
        this._cachedInterval = undefined;
    };

    /**
     * Processes the provided CZML interval or intervals into this property.
     *
     * @memberof DynamicProperty
     *
     * @param {Object} czmlIntervals The CZML data to process.
     * @param {TimeInterval} [constrainedInterval] Constrains the processing so that any times outside of this interval are ignored.
     * @param {String} [sourceUri] The originating url of the CZML being processed.
     */
    DynamicProperty.prototype.processCzmlIntervals = function(czmlIntervals, constrainedInterval, sourceUri) {
        if (Array.isArray(czmlIntervals)) {
            for ( var i = 0, len = czmlIntervals.length; i < len; i++) {
                this._addCzmlInterval(czmlIntervals[i], constrainedInterval, sourceUri);
            }
        } else {
            this._addCzmlInterval(czmlIntervals, constrainedInterval, sourceUri);
        }
    };

    var interpolationScratch;

    /**
     * Returns the value of the property at the specified time.
     * @memberof DynamicProperty
     *
     * @param {JulianDate} time The time for which to retrieve the value.
     * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned.
     * @returns The modified result parameter or a new instance if the result parameter was not supplied.
     */
    DynamicProperty.prototype.getValue = function(time, result) {
        var valueType = this.valueType;

        if (typeof this._staticValue !== 'undefined') {
            return valueType.getValue(this._staticValue, result);
        }

        var interval = this._cachedInterval;
        if (!JulianDate.equals(this._cachedTime, time)) {
            this._cachedTime = JulianDate.clone(time, this._cachedTime);
            if (typeof interval === 'undefined' || !interval.contains(time)) {
                interval = this._intervals.findIntervalContainingDate(time);
                this._cachedInterval = interval;
            }
        }

        if (typeof interval === 'undefined') {
            return undefined;
        }

        var intervalData = interval.data;
        var times = intervalData.times;
        var values = intervalData.values;
        if (intervalData.isSampled && times.length >= 0 && values.length > 0) {
            var doublesPerValue = valueType.doublesPerValue;
            var index = binarySearch(times, time, JulianDate.compare);
            if (index < 0) {
                if (intervalData.numberOfPoints < 2) {
                    return undefined;
                }
                index = ~index;

                if (index >= times.length) {
                    index = times.length - 1;
                }

                var firstIndex = 0;
                var lastIndex = times.length - 1;

                var degree = intervalData.numberOfPoints - 1;
                var pointsInCollection = lastIndex - firstIndex + 1;

                if (pointsInCollection < degree + 1) {
                    // Use the entire range.
                } else {
                    var computedFirstIndex = index - ((degree / 2) | 0) - 1;
                    if (computedFirstIndex < firstIndex) {
                        computedFirstIndex = firstIndex;
                    }
                    var computedLastIndex = computedFirstIndex + degree;
                    if (computedLastIndex > lastIndex) {
                        computedLastIndex = lastIndex;
                        computedFirstIndex = computedLastIndex - degree;
                        if (computedFirstIndex < firstIndex) {
                            computedFirstIndex = firstIndex;
                        }
                    }

                    firstIndex = computedFirstIndex;
                    lastIndex = computedLastIndex;
                }

                var length = lastIndex - firstIndex + 1;

                var doublesPerInterpolationValue = valueType.doublesPerInterpolationValue;
                var xTable = intervalData.xTable;
                var yTable = intervalData.yTable;

                if (typeof xTable === 'undefined') {
                    xTable = intervalData.xTable = new Array(intervalData.numberOfPoints);
                    yTable = intervalData.yTable = new Array(intervalData.numberOfPoints * doublesPerInterpolationValue);
                }

                // Build the tables
                for ( var i = 0; i < length; ++i) {
                    xTable[i] = times[lastIndex].getSecondsDifference(times[firstIndex + i]);
                }
                var specializedPackFunction = valueType.packValuesForInterpolation;
                if (typeof specializedPackFunction === 'undefined') {
                    var destinationIndex = 0;
                    var sourceIndex = firstIndex * doublesPerValue;
                    var stop = (lastIndex + 1) * doublesPerValue;

                    while (sourceIndex < stop) {
                        yTable[destinationIndex] = values[sourceIndex];
                        sourceIndex++;
                        destinationIndex++;
                    }
                } else {
                    specializedPackFunction(values, yTable, firstIndex, lastIndex);
                }

                // Interpolate!
                var x = times[lastIndex].getSecondsDifference(time);
                interpolationScratch = intervalData.interpolationAlgorithm.interpolateOrderZero(x, xTable, yTable, doublesPerInterpolationValue, interpolationScratch);

                var specializedGetFunction = valueType.getValueFromInterpolationResult;
                if (typeof specializedGetFunction === 'undefined') {
                    return valueType.getValueFromArray(interpolationScratch, 0, result);
                }
                return specializedGetFunction(interpolationScratch, result, values, firstIndex, lastIndex);
            }
            return valueType.getValueFromArray(intervalData.values, index * doublesPerValue, result);
        }
        return valueType.getValue(intervalData.values, result);
    };

    DynamicProperty._mergeNewSamples = function(epoch, times, values, newData, doublesPerValue) {
        var newDataIndex = 0;
        var i;
        var prevItem;
        var timesInsertionPoint;
        var valuesInsertionPoint;
        var timesSpliceArgs;
        var valuesSpliceArgs;
        var currentTime;
        var nextTime;

        while (newDataIndex < newData.length) {
            currentTime = czmlDateToJulianDate(newData[newDataIndex], epoch);
            timesInsertionPoint = binarySearch(times, currentTime, JulianDate.compare);

            if (timesInsertionPoint < 0) {
                //Doesn't exist, insert as many additional values as we can.
                timesInsertionPoint = ~timesInsertionPoint;
                timesSpliceArgs = [];

                valuesInsertionPoint = timesInsertionPoint * doublesPerValue;
                valuesSpliceArgs = [];
                prevItem = undefined;
                nextTime = times[timesInsertionPoint];
                while (newDataIndex < newData.length) {
                    currentTime = czmlDateToJulianDate(newData[newDataIndex], epoch);
                    if ((typeof prevItem !== 'undefined' && JulianDate.compare(prevItem, currentTime) >= 0) ||
                        (typeof nextTime !== 'undefined' && JulianDate.compare(currentTime, nextTime) >= 0)) {
                        break;
                    }
                    timesSpliceArgs.push(currentTime);
                    newDataIndex = newDataIndex + 1;
                    for (i = 0; i < doublesPerValue; i++) {
                        valuesSpliceArgs.push(newData[newDataIndex]);
                        newDataIndex = newDataIndex + 1;
                    }
                    prevItem = currentTime;
                }

                arrayInsert(values, valuesInsertionPoint, valuesSpliceArgs);
                arrayInsert(times, timesInsertionPoint, timesSpliceArgs);
            } else {
                //Found an exact match
                for (i = 0; i < doublesPerValue; i++) {
                    newDataIndex++;
                    values[(timesInsertionPoint * doublesPerValue) + i] = newData[newDataIndex];
                }
                newDataIndex++;
            }
        }
    };

    DynamicProperty.prototype._addCzmlInterval = function(czmlInterval, constrainedInterval, sourceUri) {
        var iso8601Interval = czmlInterval.interval;
        if (typeof iso8601Interval === 'undefined') {
            iso8601Interval = Iso8601.MAXIMUM_INTERVAL;
        } else {
            iso8601Interval = TimeInterval.fromIso8601(iso8601Interval);
        }

        if (typeof constrainedInterval !== 'undefined') {
            iso8601Interval = iso8601Interval.intersect(constrainedInterval);
        }

        var unwrappedInterval = this.valueType.unwrapInterval(czmlInterval, sourceUri);
        if (typeof unwrappedInterval !== 'undefined') {
            this._addCzmlIntervalUnwrapped(iso8601Interval.start, iso8601Interval.stop, unwrappedInterval, czmlInterval.epoch, czmlInterval.interpolationAlgorithm, czmlInterval.interpolationDegree);
        }
    };

    DynamicProperty.prototype._addCzmlIntervalUnwrapped = function(start, stop, unwrappedInterval, epoch, interpolationAlgorithmType, interpolationDegree) {
        var thisIntervals = this._intervals;
        var existingInterval = thisIntervals.findInterval(start, stop);
        this._cachedTime = undefined;
        this._cachedInterval = undefined;

        var intervalData;
        if (typeof existingInterval === 'undefined') {
            intervalData = new IntervalData();
            existingInterval = new TimeInterval(start, stop, true, true, intervalData);
            thisIntervals.addInterval(existingInterval);
        } else {
            intervalData = existingInterval.data;
        }

        var valueType = this.valueType;
        if (valueType.isSampled(unwrappedInterval)) {
            var interpolationAlgorithm;
            if (typeof interpolationAlgorithmType !== 'undefined') {
                interpolationAlgorithm = interpolators[interpolationAlgorithmType];
                intervalData.interpolationAlgorithm = interpolationAlgorithm;
            }
            if (typeof interpolationAlgorithm !== 'undefined' && typeof interpolationDegree !== 'undefined') {
                intervalData.interpolationDegree = interpolationDegree;
                intervalData.xTable = undefined;
                intervalData.yTable = undefined;
            }

            if (!intervalData.isSampled) {
                intervalData.times = [];
                intervalData.values = [];
                intervalData.isSampled = true;
            }
            if (typeof epoch !== 'undefined') {
                epoch = JulianDate.fromIso8601(epoch);
            }
            DynamicProperty._mergeNewSamples(epoch, intervalData.times, intervalData.values, unwrappedInterval, valueType.doublesPerValue, valueType);
            intervalData.numberOfPoints = Math.min(intervalData.interpolationAlgorithm.getRequiredDataPoints(intervalData.interpolationDegree), intervalData.times.length);
            this._staticValue = undefined;
        } else {
            //Packet itself is a constant value
            intervalData.times = undefined;
            intervalData.values = unwrappedInterval;
            intervalData.isSampled = false;

            if (existingInterval.equals(Iso8601.MAXIMUM_INTERVAL)) {
                this._staticValue = unwrappedInterval;
            } else {
                this._staticValue = undefined;
            }
        }
    };

    return DynamicProperty;
});<|endoftext|>


<commit_before>(function($) {
	$.fn.dribbbleshot = function(options) {

		// Sanitize options
		$.fn.dribbbleshot.settings = $.extend({}, $.fn.dribbbleshot.defaults, options);

		var settings = $.fn.dribbbleshot.settings;

		// Player is required
		if(!settings.player || (typeof(settings.player) != "string" && typeof(settings.player) != "number")) {
			throw new TypeError("Required setting 'player' must be a string or a number.");
		}

		// Shots per page
		settings.per_page = parseInt(settings.per_page);
		if(settings.per_page > 30 || settings.per_page < 1) {
			settings.per_page = 30;
		}

		// Current page
		settings.page = parseInt(settings.page);

		// Request URL
		settings.url = "//api.dribbble.com/players/" + settings.player + "/shots?page=" + settings.page + "&per_page=" + settings.per_page + "&callback=?";

		// Allow chaining
		return this.each(function() {

			var $container = $(this);

			$container.addClass("dribbbleshot-container");

			var request = $.ajax({
				crossDomain: true,
				url: settings.url,
				dataType: "jsonp"
			});

			if(typeof(settings.always) == "function") {
				request.always(settings.always);
			}

			if(typeof(settings.fail) == "function") {
				request.fail(settings.fail);
			}

			if(typeof(settings.done) == "function") {
				request.done(settings.done);
			}
			else {
				request.done(function(response, textStatus, jqxhr) {

					if(jqxhr.status != 200) {
						return false;
					}

					$container.attr({
						"data-page" : response.page,
						"data-pages" : response.pages
					});

					// Shots

					$.each(response.shots, function(index, element) {
						$container.append(settings.format(element));
					});

					// Pagination

					if($container.find(".dribbbleshot-pagination").length > 0) {
						$container.find(".dribbbleshot-pagination").detach().appendTo($container);
					}
					else {
						$container.append($.fn.dribbbleshot.pagination(response.pages, response.page));
					}

					$container.find(".dribbbleshot-pagination .disabled").removeClass("disabled");

					if(parseInt(response.page) >= parseInt(response.pages)) {
						response.page = response.pages;
						$container.find(".dribbbleshot-pagination-next").addClass("disabled");
					}

					if(parseInt(response.page) <= 1) {
						response.page = 1;
						$container.find(".dribbbleshot-pagination-previous").addClass("disabled");
					}

					// Pagination events

					$container.find(".dribbbleshot-pagination-previous:not(.disabled)").one("click", function(e) {
						settings["page"] = parseInt(response.page) - 1;
						$container.dribbbleshot(settings);
					});

					$container.find(".dribbbleshot-pagination-page").one("click", function(e) {
						settings["page"] = $(this).attr("data-page");
						$container.dribbbleshot(settings);
					});

					$container.find(".dribbbleshot-pagination-next:not(.disabled)").one("click", function(e) {
						settings["page"] = parseInt(response.page) + 1;
						$container.dribbbleshot(settings);
					});
				});
			}

		});

	};

	$.fn.dribbbleshot.format = function(shot) {
		var markup = '
';

		// Shot image
		markup += '
';
		markup += '';

		// Shot title
		markup += '';
		markup += '
' + shot.title + '
';
		markup += '';

		markup += '
';

		// Extra stats
		markup += '
';
		if(parseInt(shot.rebounds_count) > 0) {
			markup += '';
		}
		markup += '';
		markup += '';
		markup += '';
		markup += '
';

		markup += '
';

		return $.parseHTML(markup);
	};

	$.fn.dribbbleshot.pagination = function(pages, currentPage) {
		var markup = '
';
		markup += '' + $.fn.dribbbleshot.settings.paginationPreviousText + '';

		var currentClass = '';
		for(var p = 1; p <= pages; p++) {

			if(p == currentPage) {
				currentClass = ' dribbbleshot-pagination-current';
			}
			else {
				currentClass = '';
			}

			markup += '';

			if($.fn.dribbbleshot.settings.showPaginationPages) {
				markup += p;
			}

			markup += '';
		}

		markup += '' + $.fn.dribbbleshot.settings.paginationNextText + '';
		markup += '
';

		return $.parseHTML(markup);
	};

	$.fn.dribbbleshot.defaults = {
		format : $.fn.dribbbleshot.format,
		page : 1,
		per_page : 15,
		shotClass : "dribbble-shot",
		showPaginationControls : true,
		showPaginationPages : false,
		paginationPreviousText : "Previous",
		paginationNextText : "Next"
	};

}(jQuery));
<commit_msg>Added pagination events setting<commit_after>(function($) {
	$.fn.dribbbleshot = function(options) {

		// Sanitize options
		$.fn.dribbbleshot.settings = $.extend({}, $.fn.dribbbleshot.defaults, options);

		var settings = $.fn.dribbbleshot.settings;

		// Player is required
		if(!settings.player || (typeof(settings.player) != "string" && typeof(settings.player) != "number")) {
			throw new TypeError("Required setting 'player' must be a string or a number.");
		}

		// Shots per page
		settings.per_page = parseInt(settings.per_page);
		if(settings.per_page > 30 || settings.per_page < 1) {
			settings.per_page = 30;
		}

		// Current page
		settings.page = parseInt(settings.page);

		// Request URL
		settings.url = "//api.dribbble.com/players/" + settings.player + "/shots?page=" + settings.page + "&per_page=" + settings.per_page + "&callback=?";

		// Allow chaining
		return this.each(function() {

			var $container = $(this);

			$container.addClass("dribbbleshot-container");

			var request = $.ajax({
				crossDomain: true,
				url: settings.url,
				dataType: "jsonp"
			});

			if(typeof(settings.always) == "function") {
				request.always(settings.always);
			}

			if(typeof(settings.fail) == "function") {
				request.fail(settings.fail);
			}

			if(typeof(settings.done) == "function") {
				request.done(settings.done);
			}
			else {
				request.done(function(response, textStatus, jqxhr) {

					if(jqxhr.status != 200) {
						return false;
					}

					$container.attr({
						"data-page" : response.page,
						"data-pages" : response.pages
					});

					// Shots

					$.each(response.shots, function(index, element) {
						$container.append(settings.format(element));
					});

					// Pagination

					if($container.find(".dribbbleshot-pagination").length > 0) {
						$container.find(".dribbbleshot-pagination").detach().appendTo($container);
					}
					else {
						$container.append($.fn.dribbbleshot.pagination(response.pages, response.page));
					}

					$container.find(".dribbbleshot-pagination .disabled").removeClass("disabled");

					if(parseInt(response.page) >= parseInt(response.pages)) {
						response.page = response.pages;
						$container.find(".dribbbleshot-pagination-next").addClass("disabled");
					}

					if(parseInt(response.page) <= 1) {
						response.page = 1;
						$container.find(".dribbbleshot-pagination-previous").addClass("disabled");
					}

					// Pagination events

					if(settings.bindPaginationEvents) {
						$container.find(".dribbbleshot-pagination-previous:not(.disabled)").one("click", function(e) {
							settings["page"] = parseInt(response.page) - 1;
							$container.dribbbleshot(settings);
						});

						$container.find(".dribbbleshot-pagination-page").one("click", function(e) {
							settings["page"] = $(this).attr("data-page");
							$container.dribbbleshot(settings);
						});

						$container.find(".dribbbleshot-pagination-next:not(.disabled)").one("click", function(e) {
							settings["page"] = parseInt(response.page) + 1;
							$container.dribbbleshot(settings);
						});
					}
				});
			}

		});

	};

	$.fn.dribbbleshot.format = function(shot) {
		var markup = '
';

		// Shot image
		markup += '
';
		markup += '';

		// Shot title
		markup += '';
		markup += '
' + shot.title + '
';
		markup += '';

		markup += '
';

		// Extra stats
		markup += '
';
		if(parseInt(shot.rebounds_count) > 0) {
			markup += '';
		}
		markup += '';
		markup += '';
		markup += '';
		markup += '
';

		markup += '
';

		return $.parseHTML(markup);
	};

	$.fn.dribbbleshot.pagination = function(pages, currentPage) {
		var markup = '
';
		markup += '' + $.fn.dribbbleshot.settings.paginationPreviousText + '';

		var currentClass = '';
		for(var p = 1; p <= pages; p++) {

			if(p == currentPage) {
				currentClass = ' dribbbleshot-pagination-current';
			}
			else {
				currentClass = '';
			}

			markup += '';

			if($.fn.dribbbleshot.settings.showPaginationPages) {
				markup += p;
			}

			markup += '';
		}

		markup += '' + $.fn.dribbbleshot.settings.paginationNextText + '';
		markup += '
';

		return $.parseHTML(markup);
	};

	$.fn.dribbbleshot.defaults = {
		format : $.fn.dribbbleshot.format,
		page : 1,
		per_page : 15,
		shotClass : "dribbble-shot",
		bindPaginationEvents : true,
		showPaginationControls : true,
		showPaginationPages : false,
		paginationPreviousText : "Previous",
		paginationNextText : "Next"
	};

}(jQuery));
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

exports.createTypeMeta = function(opts, metadata, callback) {
    console.log('Storing type mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        type : opts.sourceType,
        index : opts.sourceIndex,
        metadata: metadata
    }, callback);
};

exports.createIndexMeta = function(opts, metadata,  callback) {
    console.log('Storing index mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        index : opts.sourceIndex,
        metadata: metadata
    }, callback);
};

exports.createAllMeta = function(opts, metadata, callback) {
    console.log('Storing entire index mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        metadata: metadata
    }, callback);
};

function createParentDir(opts) {
	var dir = '';
    path.dirname(opts.targetFile).split(path.sep).forEach(function(dirPart){
        dir += dirPart + path.sep;
        console.log(dir)
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
    });
}

var targetStream = null;

function createMeta(opts, data, callback) {
    createParentDir(opts);
    fs.writeFile(opts.targetFile + '.meta', JSON.stringify(data, null, 2), { encoding:'utf8' }, function (err) {
        if (err) throw err;
        if (!opts.targetCompression) {
            fs.writeFile(opts.targetFile + '.data', '', function() {
                if (err) throw err;
                callback();
            });
        } else {
            var zlib = require('zlib');
            var through = require('through');
            targetStream = through().pause();
            var out = fs.createWriteStream(opts.targetFile + '.data');
            targetStream.pipe(zlib.createGzip()).pipe(out);
            callback();
        }
    });
}

exports.getMeta = function(opts, callback) {
    console.log('Reading mapping from meta file ' + opts.sourceFile + '.meta');
    fs.readFile(opts.sourceFile + '.meta', { encoding:'utf8' }, function (err, data) {
        if (err) throw err;
        data = JSON.parse(data);
        if (data.type) {
            opts.sourceType = data.type;
            if (!opts.targetType) {
                opts.targetType = opts.sourceType;
            }
        }
        if (data.index) {
            opts.sourceIndex = data.index;
            if (!opts.targetIndex) {
                opts.targetIndex = opts.sourceIndex;
            }
        }
        callback(data.metadata);
    });
};

var fileReader = null;
var readable = true;
var end = false;
var lineProgress = 0;
var lineCount = null;
var buffer = '';
var items = [];
var end = false;

function getLineCount(file, callback) {
    if (lineCount !== null) {
        callback(lineCount);
        return;
    }
    var count = 0;
    var stream = fs.createReadStream(file);
    stream.on('readable', function(chunk) {
    	try {
        	count += (''+ stream.read()).match(/\n/g).length;
    	} catch (e) {}
    });
    stream.on('end', function() {
        lineCount = Math.ceil(count/2);
        callback(lineCount);
    });
}

function getNewlineMatches(buffer) {
	var matches = buffer.match(/\n/g);
	return matches != null && buffer.match(/\n/g).length > 1
}

function parseBuffer() {
	var nlIndex1 = buffer.indexOf('\n');
	var nlIndex2 = buffer.indexOf('\n', nlIndex1 + 1);
	var metaData = JSON.parse(buffer.substr(0, nlIndex1));
	var data = JSON.parse(buffer.substr(nlIndex1 + 1, nlIndex2 - nlIndex1));
	buffer = buffer.substr(nlIndex2 + 1);
	items.push({
		_id : metaData.index._id,
		_index : metaData.index._index,
		_type : metaData.index._type,
		fields : {
			_timestamp : metaData.index._timestamp,
			_version : metaData.index._version,
			_percolate : metaData.index._percolate,
			_routing : metaData.index._routing,
			_parent : metaData.index._parent,
			_ttl : metaData.index._ttl
		},
		_source : data
	});
}

exports.getData = function(opts, callback) {
    if (fileReader === null) {
        getLineCount(opts.sourceFile + '.data', function(lineCount) {
            fileReader = fs.createReadStream(opts.sourceFile + '.data', { encoding:'utf8' });
            fileReader.on('data', function(chunk) {
            	fileReader.pause();
            	buffer += chunk;
            	while (getNewlineMatches(buffer)) {
					parseBuffer();
					if (items.length >= 100) {
						callback(items, lineCount);
						items = [];
					}
            	}
            	fileReader.resume();
            });
            fileReader.on('end', function() {
            	end = true;
            	if (buffer.length) {
            		buffer += '\n';
            		parseBuffer();
            	}
                callback(items, lineCount);
            });
        });
    }
};

exports.storeHits = function(opts, data, callback) {
    if (targetStream) {
        targetStream.queue(data).resume();
        callback();
    } else {
        fs.appendFile(opts.targetFile + '.data', data, { encoding: 'utf8' }, function (err) {
            if (err) throw err;
            callback();
        });
    }
};

exports.end = function() {
    if (targetStream) {
        targetStream.end();
    } else {
        process.exit(0);
    }
}<commit_msg>file driver now also decompresses compressed data files<commit_after>var fs = require('fs');
var through = require('through');
var zlib = require('zlib');
var path = require('path');

exports.createTypeMeta = function(opts, metadata, callback) {
    console.log('Storing type mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        type : opts.sourceType,
        index : opts.sourceIndex,
        metadata: metadata
    }, callback);
};

exports.createIndexMeta = function(opts, metadata,  callback) {
    console.log('Storing index mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        index : opts.sourceIndex,
        metadata: metadata
    }, callback);
};

exports.createAllMeta = function(opts, metadata, callback) {
    console.log('Storing entire index mapping in meta file ' + opts.targetFile + '.meta');
    createMeta(opts, {
        metadata: metadata
    }, callback);
};

function createParentDir(opts) {
	var dir = '';
    path.dirname(opts.targetFile).split(path.sep).forEach(function(dirPart){
        dir += dirPart + path.sep;
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
    });
}

var targetStream = null;

function createMeta(opts, data, callback) {
    createParentDir(opts);
    fs.writeFile(opts.targetFile + '.meta', JSON.stringify(data, null, 2), { encoding:'utf8' }, function (err) {
        if (err) throw err;
        if (!opts.targetCompression) {
            fs.writeFile(opts.targetFile + '.data', '', function() {
                if (err) throw err;
                callback();
            });
        } else {
            targetStream = through().pause();
            var out = fs.createWriteStream(opts.targetFile + '.data');
            targetStream.pipe(zlib.createGzip()).pipe(out);
            callback();
        }
    });
}

exports.getMeta = function(opts, callback) {
    console.log('Reading mapping from meta file ' + opts.sourceFile + '.meta');
    fs.readFile(opts.sourceFile + '.meta', { encoding:'utf8' }, function (err, data) {
        if (err) throw err;
        data = JSON.parse(data);
        if (data.type) {
            opts.sourceType = data.type;
            if (!opts.targetType) {
                opts.targetType = opts.sourceType;
            }
        }
        if (data.index) {
            opts.sourceIndex = data.index;
            if (!opts.targetIndex) {
                opts.targetIndex = opts.sourceIndex;
            }
        }
        callback(data.metadata);
    });
};

var lineCount = null;

function getLineCount(file, callback) {
    if (lineCount !== null) {
        callback(lineCount);
        return;
    }
    var count = 0;
    var stream = fs.createReadStream(file).pipe(zlib.createGunzip());
    stream.on('readable', function() {
    	try {
        	count += (''+ stream.read()).match(/\n/g).length;
    	} catch (e) {}
    });
    stream.on('end', function() {
        lineCount = Math.ceil(count/2);
        callback(lineCount);
    });
}

function getNewlineMatches(buffer) {
	var matches = buffer.match(/\n/g);
	return matches != null && buffer.match(/\n/g).length > 1
}

var buffer = '';
var items = [];

function parseBuffer() {
	var nlIndex1 = buffer.indexOf('\n');
	var nlIndex2 = buffer.indexOf('\n', nlIndex1 + 1);
	var metaData = JSON.parse(buffer.substr(0, nlIndex1));
	var data = JSON.parse(buffer.substr(nlIndex1 + 1, nlIndex2 - nlIndex1));
	buffer = buffer.substr(nlIndex2 + 1);
	items.push({
		_id : metaData.index._id,
		_index : metaData.index._index,
		_type : metaData.index._type,
		fields : {
			_timestamp : metaData.index._timestamp,
			_version : metaData.index._version,
			_percolate : metaData.index._percolate,
			_routing : metaData.index._routing,
			_parent : metaData.index._parent,
			_ttl : metaData.index._ttl
		},
		_source : data
	});
}

var fileReader = null;
var end = false;

exports.getData = function(opts, callback) {
    if (fileReader === null) {
        getLineCount(opts.sourceFile + '.data', function(lineCount) {
            fileReader = fs.createReadStream(opts.sourceFile + '.data').pipe(zlib.createGunzip());
            fileReader.on('data', function(chunk) {
            	fileReader.pause();
            	buffer += chunk;
            	while (getNewlineMatches(buffer)) {
					parseBuffer();
					if (items.length >= 100) {
						callback(items, lineCount);
						items = [];
					}
            	}
            	fileReader.resume();
            });
            fileReader.on('end', function() {
            	end = true;
            	if (buffer.length) {
            		buffer += '\n';
            		parseBuffer();
            	}
                callback(items, lineCount);
            });
        });
    }
};

exports.storeHits = function(opts, data, callback) {
    if (targetStream) {
        targetStream.queue(data).resume();
        callback();
    } else {
        fs.appendFile(opts.targetFile + '.data', data, { encoding: 'utf8' }, function (err) {
            if (err) throw err;
            callback();
        });
    }
};

exports.end = function() {
    if (targetStream) {
        targetStream.end();
    } else {
        process.exit(0);
    }
};<|endoftext|>


<commit_before>var exec = require('child_process').exec;

NodeDriver  = function(server_vars) {
    this.server = server_vars;
};

NodeDriver.prototype.onGet = function(file, params, callback) {
    this.execute(file, callback, params, {});
};

NodeDriver.prototype.onPost = function(file, params, callback) {
    this.execute(file, callback, {}, params);
};

NodeDriver.prototype.execute = function(file, callback, getParams, postParams) {
    var self = this;
    var cmd  = '';

    exec('cat ' + file + ' | head -n 1', function(error, stdout, stderr) {
        var isNodeFile = (stdout && stdout.substring(0,6) == '//NODE');

        if(isNodeFile) {
            if(getParams && Object.keys(getParams).length > 0) {
                cmd  = 'node ' + file + ' \'' + JSON.stringify({mode:"GET", params:getParams}) + '\'';
            }
            else if(postParams && Object.keys(postParams).length > 0) {
                cmd  = 'node ' + file + ' \'' + JSON.stringify({mode:"POST", params:postParams}) + '\'';
            }
            else cmd = 'node ' + file + ' \'' + JSON.stringify({mode:"GET"}) + '\'';

            exec(cmd, function(error, stdout, stderr) {
                callback(self.getMimeType(), stdout, stderr);
            });
        }
        else {
            if(callback)
                callback('NOT_SUPPORTED_FILE', file);
        }
    });
};

NodeDriver.prototype.getMimeType = function() {
    return 'text/html';
};

module.exports = NodeDriver;<commit_msg>Cleaned up NodeJS driver, using newer server configurations.<commit_after>var exec = require('child_process').exec;

NodeDriver  = function(server_vars) {
    this.server = server_vars;
};

NodeDriver.prototype.onGet = function(file, params, callback) {
    this.execute(file, callback, params, {});
};

NodeDriver.prototype.onPost = function(file, params, callback) {
    this.execute(file, callback, {}, params);
};

NodeDriver.prototype.execute = function(file, callback, getParams, postParams) {
    var self   = this;
    var params = {
        server:this.server,
        get   :getParams,
        post  :postParams
    };
    var cmd  = '';

    exec('cat ' + file + ' | head -n 1', function(error, stdout, stderr) {
        var isNodeFile = (stdout && stdout.substring(0,6) == '//NODE');

        if(isNodeFile) {
            cmd = 'node ' + file + ' \'' + JSON.stringify(params) + '\'';

            exec(cmd, function(error, stdout, stderr) {
                callback(self.getMimeType(), stdout, stderr);
            });
        }
        else {
            if(callback)
                callback('NOT_SUPPORTED_FILE', file);
        }
    });
};

NodeDriver.prototype.getMimeType = function() {
    return 'text/html';
};

module.exports = NodeDriver;<|endoftext|>


<commit_before>describe('the palindrome canary spec', () => {
  it('shows the infrastructure works', () => {
    true.should.be.true();
  });

  describe('palindrome should be', () => {
    it('true for mom');
    it('false for dude');
  });
});
<commit_msg>design palindrome<commit_after>describe('the palindrome canary spec', () => {
  it('shows the infrastructure works', () => {
    true.should.be.true();
  });

  describe('palindrome should be', () => {
    it('true for mom');
    it('false for dude');
    it('true for mom mom');
    it('false for dad mom');
    it('true for whitespaces');
    it('error for empty string');
    it('error for not a string');
  });
});
<|endoftext|>


<commit_before>import Router from 'koa-router'
import logger from '../../lib/logger'
import { connect } from '../../lib/salesforce'
import {
  getEventRegistration,
  getEventRegistrationByAccount,
  updateEventRegistration,
  createEventRegistration
} from '../../lib/salesforce/event-registration'

function handleError (ctx, error) {
  // TODO: Differentiate different types of errors, and return different codes accordingly.
  logger.error(`${error.message}`)
  ctx.throw(error.message, 503)
}

const router = Router()

router
  .get('/:id', (ctx, next) => {
    return connect()
      .then(res => getEventRegistration(res.connection, ctx.params.id))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .get('/', (ctx, next) => {
    return connect()
      .then(res => getEventRegistrationByAccount(res.connection, ctx.query.accountId))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .put('/:id', (ctx, next) => {
    return connect()
      .then(res => updateEventRegistration(res.connection, ctx.params.id, ctx.request.body.fields))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .post('/', (ctx, next) => {
    return connect()
      .then(res => createEventRegistration(res.connection, ctx.request.body.fields))
      .then(res => (ctx.body = res))
      // .catch(error => handleError(ctx, error))
  })

export default router
<commit_msg>un-comment out code<commit_after>import Router from 'koa-router'
import logger from '../../lib/logger'
import { connect } from '../../lib/salesforce'
import {
  getEventRegistration,
  getEventRegistrationByAccount,
  updateEventRegistration,
  createEventRegistration
} from '../../lib/salesforce/event-registration'

function handleError (ctx, error) {
  // TODO: Differentiate different types of errors, and return different codes accordingly.
  logger.error(`${error.message}`)
  ctx.throw(error.message, 503)
}

const router = Router()

router
  .get('/:id', (ctx, next) => {
    return connect()
      .then(res => getEventRegistration(res.connection, ctx.params.id))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .get('/', (ctx, next) => {
    return connect()
      .then(res => getEventRegistrationByAccount(res.connection, ctx.query.accountId))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .put('/:id', (ctx, next) => {
    return connect()
      .then(res => updateEventRegistration(res.connection, ctx.params.id, ctx.request.body.fields))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })
  .post('/', (ctx, next) => {
    return connect()
      .then(res => createEventRegistration(res.connection, ctx.request.body.fields))
      .then(res => (ctx.body = res))
      .catch(error => handleError(ctx, error))
  })

export default router
<|endoftext|>