<commit_before>import React, { useState } from 'react';
import { storiesOf } from '@storybook/react';

import { Box, Grommet, CheckBox } from 'grommet';
import { grommet } from 'grommet/themes';

const IndeterminateCheckBox = () => {
  const [checked, setChecked] = useState([]);
  const checkboxes = ['fruits', 'vegetables', 'olive oil'];

  const onCheckAll = event => {
    if (event.target.checked) {
      setChecked(checkboxes);
    } else {
      setChecked([]);
    }
  };

  const onCheck = (event, value) => {
    if (event.target.checked) {
      setChecked([...checked, value]);
    } else {
      setChecked(checked.filter(item => item !== value));
    }
  };

  return (
    <Grommet theme={grommet}>
      <Box align="center" pad="large">
        <Box direction="row" gap="medium">
          <CheckBox
            checked={checked.length === 3}
            indeterminate={checked.length > 0 && checked.length < 3}
            label="All"
            onChange={onCheckAll}
          />
          {checkboxes.map(item => (
            <CheckBox
              key={item}
              checked={checked.includes(item)}
              label={item}
              onChange={e => onCheck(e, item)}
            />
          ))}
        </Box>
      </Box>
    </Grommet>
  );
};

storiesOf('CheckBox', module).add('Interminate', () => (
  <IndeterminateCheckBox />
));
<commit_msg>docs: fix indeterminate typo in Indeterminate story (#3754)<commit_after>import React, { useState } from 'react';
import { storiesOf } from '@storybook/react';

import { Box, Grommet, CheckBox } from 'grommet';
import { grommet } from 'grommet/themes';

const IndeterminateCheckBox = () => {
  const [checked, setChecked] = useState([]);
  const checkboxes = ['fruits', 'vegetables', 'olive oil'];

  const onCheckAll = event => {
    if (event.target.checked) {
      setChecked(checkboxes);
    } else {
      setChecked([]);
    }
  };

  const onCheck = (event, value) => {
    if (event.target.checked) {
      setChecked([...checked, value]);
    } else {
      setChecked(checked.filter(item => item !== value));
    }
  };

  return (
    <Grommet theme={grommet}>
      <Box align="center" pad="large">
        <Box direction="row" gap="medium">
          <CheckBox
            checked={checked.length === 3}
            indeterminate={checked.length > 0 && checked.length < 3}
            label="All"
            onChange={onCheckAll}
          />
          {checkboxes.map(item => (
            <CheckBox
              key={item}
              checked={checked.includes(item)}
              label={item}
              onChange={e => onCheck(e, item)}
            />
          ))}
        </Box>
      </Box>
    </Grommet>
  );
};

storiesOf('CheckBox', module).add('Indeterminate', () => (
  <IndeterminateCheckBox />
));
<|endoftext|>


<commit_before>(function () {
  var ns = $.namespace('pskl.controller.preview');

  var POPUP_TITLE = 'Piskel - preview';

  ns.PopupPreviewController = function (piskelController) {
    this.piskelController = piskelController;
    this.popup = null;
    this.renderer = null;
    this.renderFlag = false;
  };

  ns.PopupPreviewController.prototype.init = function () {
    pskl.utils.Event.addEventListener(window, 'unload', this.onMainWindowUnload_, this);
  };

  ns.PopupPreviewController.prototype.isOpen = function () {
    return !!this.popup;
  };

  ns.PopupPreviewController.prototype.open = function () {
    if (!this.isOpen()) {
      this.popup = window.open('about:blank', '', 'width=320,height=320');
      this.popup.document.body.innerHTML = pskl.utils.Template.get('popup-preview-partial');
      window.setTimeout(this.onPopupLoaded.bind(this), 500);
    }
  };

  ns.PopupPreviewController.prototype.onPopupLoaded = function () {
    this.popup.document.title = POPUP_TITLE;
    pskl.utils.Event.addEventListener(this.popup, 'resize', this.onWindowResize_, this);
    pskl.utils.Event.addEventListener(this.popup, 'unload', this.onPopupClosed_, this);
    var container = this.popup.document.querySelector('.preview-container');
    this.renderer = new pskl.rendering.frame.TiledFrameRenderer($(container));
    this.updateZoom_();
    this.renderFlag = true;
  };

  ns.PopupPreviewController.prototype.render = function (frame) {
    if (this.isOpen() && this.renderer) {
      this.renderer.render(frame);
      this.renderFlag = false;
    }
  };

  ns.PopupPreviewController.prototype.onWindowResize_ = function (frame) {
    this.updateZoom_();
    this.renderFlag = true;
  };

  ns.PopupPreviewController.prototype.updateZoom_ = function () {
    var documentElement = this.popup.document.documentElement;
    var wZoom = documentElement.clientWidth / this.piskelController.getWidth();
    var hZoom = documentElement.clientHeight / this.piskelController.getHeight();
    var zoom = Math.min(wZoom, hZoom);

    this.renderer.setZoom(zoom);

    var height = this.piskelController.getHeight() * zoom;
    var width = this.piskelController.getWidth() * zoom;

    var container = this.popup.document.querySelector('.preview-container');
    container.style.height = height + 'px';
    container.style.width = width + 'px';

    var horizontalMargin = (documentElement.clientHeight - height) / 2;
    container.style.marginTop = horizontalMargin + 'px';
    container.style.marginBottom = horizontalMargin + 'px';

    var verticalMargin = (documentElement.clientWidth - width) / 2;
    container.style.marginLeft = verticalMargin + 'px';
    container.style.marginRight = verticalMargin + 'px';
  };

  ns.PopupPreviewController.prototype.onPopupClosed_ = function () {
    var popup = this.popup;
    this.popup = null;
  };

  ns.PopupPreviewController.prototype.onMainWindowUnload_ = function () {
    if (this.isOpen()) {
      this.popup.close();
    }
  };
})();
<commit_msg>fix:focus preview popup if already opened<commit_after>(function () {
  var ns = $.namespace('pskl.controller.preview');

  var POPUP_TITLE = 'Piskel - preview';

  ns.PopupPreviewController = function (piskelController) {
    this.piskelController = piskelController;
    this.popup = null;
    this.renderer = null;
    this.renderFlag = false;
  };

  ns.PopupPreviewController.prototype.init = function () {
    pskl.utils.Event.addEventListener(window, 'unload', this.onMainWindowUnload_, this);
  };

  ns.PopupPreviewController.prototype.isOpen = function () {
    return !!this.popup;
  };

  ns.PopupPreviewController.prototype.open = function () {
    if (!this.isOpen()) {
      this.popup = window.open('about:blank', '', 'width=320,height=320');
      this.popup.document.body.innerHTML = pskl.utils.Template.get('popup-preview-partial');
      window.setTimeout(this.onPopupLoaded.bind(this), 500);
    } else {
      this.popup.focus();
    }
  };

  ns.PopupPreviewController.prototype.onPopupLoaded = function () {
    this.popup.document.title = POPUP_TITLE;
    pskl.utils.Event.addEventListener(this.popup, 'resize', this.onWindowResize_, this);
    pskl.utils.Event.addEventListener(this.popup, 'unload', this.onPopupClosed_, this);
    var container = this.popup.document.querySelector('.preview-container');
    this.renderer = new pskl.rendering.frame.TiledFrameRenderer($(container));
    this.updateZoom_();
    this.renderFlag = true;
  };

  ns.PopupPreviewController.prototype.render = function (frame) {
    if (this.isOpen() && this.renderer) {
      this.renderer.render(frame);
      this.renderFlag = false;
    }
  };

  ns.PopupPreviewController.prototype.onWindowResize_ = function (frame) {
    this.updateZoom_();
    this.renderFlag = true;
  };

  ns.PopupPreviewController.prototype.updateZoom_ = function () {
    var documentElement = this.popup.document.documentElement;
    var wZoom = documentElement.clientWidth / this.piskelController.getWidth();
    var hZoom = documentElement.clientHeight / this.piskelController.getHeight();
    var zoom = Math.min(wZoom, hZoom);

    this.renderer.setZoom(zoom);

    var height = this.piskelController.getHeight() * zoom;
    var width = this.piskelController.getWidth() * zoom;

    var container = this.popup.document.querySelector('.preview-container');
    container.style.height = height + 'px';
    container.style.width = width + 'px';

    var horizontalMargin = (documentElement.clientHeight - height) / 2;
    container.style.marginTop = horizontalMargin + 'px';
    container.style.marginBottom = horizontalMargin + 'px';

    var verticalMargin = (documentElement.clientWidth - width) / 2;
    container.style.marginLeft = verticalMargin + 'px';
    container.style.marginRight = verticalMargin + 'px';
  };

  ns.PopupPreviewController.prototype.onPopupClosed_ = function () {
    var popup = this.popup;
    this.popup = null;
  };

  ns.PopupPreviewController.prototype.onMainWindowUnload_ = function () {
    if (this.isOpen()) {
      this.popup.close();
    }
  };
})();
<|endoftext|>


<commit_before>import THREE from 'three';

import LightDescriptorBase from './LightDescriptorBase';

class AmbientLightDescriptor extends LightDescriptorBase {
  constructor(react3Instance) {
    super(react3Instance);

    this.hasColor();
  }

  construct(props) {
    const {
      color,
      } = props;

    return new THREE.AmbientLight(color);
  }
}

module.exports = AmbientLightDescriptor;
<commit_msg>#109 AmbientLight: add 'intensity' prop<commit_after>import THREE from 'three';

import PropTypes from 'react/lib/ReactPropTypes';

import LightDescriptorBase from './LightDescriptorBase';

class AmbientLightDescriptor extends LightDescriptorBase {
  constructor(react3Instance) {
    super(react3Instance);

    this.hasProp('intensity', {
      type: PropTypes.number,
      simple: true,
      default: 1,
    });

    this.hasColor();
  }

  construct(props) {
    const {
      color,
      intensity,
    } = props;

    return new THREE.AmbientLight(color, intensity);
  }
}

module.exports = AmbientLightDescriptor;
<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "platform";
	this.tests = [
		{name: "apiPoints"},
		{name: "displayCaps_platformHeight"},
		{name: "platform_id_A"},
		{name: "platform_id_B"},
		{name: "platform_Android_API_LEVEL"},
		{name: "displayCaps_platformWidth"},
		{name: "physicalSizeCategory"},
		{name: "platform_manufacturer"}
	]

	this.apiPoints = function(testRun) {
		valueOf(testRun, Ti.Platform.createUUID).shouldBeFunction();
		valueOf(testRun, Ti.Platform.openURL).shouldBeFunction();
		valueOf(testRun, Ti.Platform.is24HourTimeFormat).shouldBeFunction();
		valueOf(testRun, Ti.Platform.is24HourTimeFormat()).shouldBeBoolean();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_CHARGING).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_FULL).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_UNKNOWN).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_UNPLUGGED).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.address).shouldBeString();
		valueOf(testRun, Ti.Platform.architecture).shouldBeString();
    	valueOf(testRun, Ti.Platform.availableMemory).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.batteryMonitoring).shouldBeBoolean();
    	valueOf(testRun, Ti.Platform.displayCaps).shouldBeObject();
    	valueOf(testRun, Ti.Platform.displayCaps).shouldNotBeNull();
    	valueOf(testRun, Ti.Platform.displayCaps.dpi).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.displayCaps.density).shouldBeString();
    	valueOf(testRun, Ti.Platform.displayCaps.platformHeight).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.displayCaps.platformWidth).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.id).shouldBeString();
    	valueOf(testRun, Ti.Platform.locale).shouldBeString();
    	valueOf(testRun, Ti.Platform.macaddress).shouldBeString();
    	valueOf(testRun, Ti.Platform.model).shouldBeString();
    	valueOf(testRun, Ti.Platform.name).shouldBeString();
    	valueOf(testRun, Ti.Platform.netmask).shouldBeString();
    	valueOf(testRun, Ti.Platform.osname).shouldBeString();
    	valueOf(testRun, Ti.Platform.ostype).shouldBeString();
    	valueOf(testRun, Ti.Platform.processorCount).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.version).shouldBeString();
    	valueOf(testRun, Ti.Platform.runtime).shouldBeString();
    	if (Ti.Platform.osname === 'android') {
    		valueOf(testRun, Ti.Platform.runtime === 'rhino' || Ti.Platform.runtime === 'v8').shouldBeTrue();
    	} else if (Ti.Platform.osname === 'iphone' || Ti.Platform.osname === 'ipad') {
        	valueOf(testRun, Ti.Platform.runtime).shouldBe("javascriptcore");
    	} else {
        	valueOf(testRun, Ti.Platform.runtime.length).shouldBeGreaterThan(0);
    	}

		finish(testRun);
	}

	//TIMOB-2475
	this.displayCaps_platformHeight = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			valueOf(testRun, Titanium.Platform.displayCaps.platformHeight).shouldNotBeUndefined();
		}
		finish(testRun);
	}

	//TIMOB-5752
	var platform_id;

	this.platform_id_A = function(testRun) {
		platform_id=Ti.Platform.id;
		valueOf(testRun, platform_id).shouldNotBeNull();

		finish(testRun);
	}

	this.platform_id_B = function(testRun) {
		valueOf(testRun, Ti.Platform.id).shouldBe(platform_id);

		finish(testRun);
	}

	//TIMOB-7242
	this.platform_Android_API_LEVEL = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			valueOf(testRun, Ti.Platform.Android.API_LEVEL).shouldBeNumber();
		}
		finish(testRun);
	}

	//TIMOB-7917
	this.displayCaps_platformWidth = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			var result=Ti.Platform.displayCaps.platformWidth;
			var LastDPI=Ti.Platform.displayCaps.dpi;
			valueOf(testRun, Ti.Platform.displayCaps.platformWidth).shouldBe(result);
		}
		finish(testRun);
	}

	//TIMOB-10043
	this.physicalSizeCategory = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			valueOf(testRun, Ti.Platform.Android.physicalSizeCategory).shouldBeNumber();
		}
		finish(testRun);
	}

	//TIMOB-10482
	this.platform_manufacturer = function(testRun) {
		valueOf(testRun, Ti.Platform.getManufacturer()).shouldBe(Ti.Platform.manufacturer);

		finish(testRun);
	}
}
<commit_msg>updated suite<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "platform";
	this.tests = [
		{name: "apiPoints"},
		{name: "displayCaps_platformHeight"},
		{name: "platform_id_A"},
		{name: "platform_id_B"},
		{name: "platform_Android_API_LEVEL"},
		{name: "displayCaps_platformWidth"},
		{name: "physicalSizeCategory"},
		{name: "platform_manufacturer"}
	]

	this.apiPoints = function(testRun) {
		valueOf(testRun, Ti.Platform.createUUID).shouldBeFunction();
		valueOf(testRun, Ti.Platform.openURL).shouldBeFunction();
		valueOf(testRun, Ti.Platform.is24HourTimeFormat).shouldBeFunction();
		valueOf(testRun, Ti.Platform.is24HourTimeFormat()).shouldBeBoolean();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_CHARGING).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_FULL).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_UNKNOWN).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.BATTERY_STATE_UNPLUGGED).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.address).shouldBeString();
		valueOf(testRun, Ti.Platform.architecture).shouldBeString();
    	valueOf(testRun, Ti.Platform.availableMemory).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.batteryMonitoring).shouldBeBoolean();
    	valueOf(testRun, Ti.Platform.displayCaps).shouldBeObject();
    	valueOf(testRun, Ti.Platform.displayCaps).shouldNotBeNull();
    	valueOf(testRun, Ti.Platform.displayCaps.dpi).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.displayCaps.density).shouldBeString();
    	valueOf(testRun, Ti.Platform.displayCaps.platformHeight).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.displayCaps.platformWidth).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.id).shouldBeString();
    	valueOf(testRun, Ti.Platform.locale).shouldBeString();
    	valueOf(testRun, Ti.Platform.macaddress).shouldBeString();
    	valueOf(testRun, Ti.Platform.model).shouldBeString();
    	valueOf(testRun, Ti.Platform.name).shouldBeString();
    	valueOf(testRun, Ti.Platform.netmask).shouldBeString();
    	valueOf(testRun, Ti.Platform.osname).shouldBeString();
    	valueOf(testRun, Ti.Platform.ostype).shouldBeString();
    	valueOf(testRun, Ti.Platform.processorCount).shouldBeNumber();
    	valueOf(testRun, Ti.Platform.version).shouldBeString();
    	valueOf(testRun, Ti.Platform.runtime).shouldBeString();
    	if (Ti.Platform.osname === 'android') {
    		valueOf(testRun, Ti.Platform.runtime === 'rhino' || Ti.Platform.runtime === 'v8').shouldBeTrue();
    	} else if (Ti.Platform.osname === 'iphone' || Ti.Platform.osname === 'ipad') {
        	valueOf(testRun, Ti.Platform.runtime).shouldBe("javascriptcore");
    	} else {
        	valueOf(testRun, Ti.Platform.runtime.length).shouldBeGreaterThan(0);
    	}

		finish(testRun);
	}

	//TIMOB-2475
	this.displayCaps_platformHeight = function(testRun) {
		valueOf(testRun, Titanium.Platform.displayCaps.platformHeight).shouldNotBeUndefined();

		finish(testRun);
	}

	//TIMOB-5752
	var platform_id;

	this.platform_id_A = function(testRun) {
		platform_id=Ti.Platform.id;
		valueOf(testRun, platform_id).shouldNotBeNull();

		finish(testRun);
	}

	this.platform_id_B = function(testRun) {
		valueOf(testRun, Ti.Platform.id).shouldBe(platform_id);

		finish(testRun);
	}

	//TIMOB-7242
	this.platform_Android_API_LEVEL = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			valueOf(testRun, Ti.Platform.Android.API_LEVEL).shouldBeNumber();
		}
		finish(testRun);
	}

	//TIMOB-7917
	this.displayCaps_platformWidth = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			var result=Ti.Platform.displayCaps.platformWidth;
			var LastDPI=Ti.Platform.displayCaps.dpi;
			valueOf(testRun, Ti.Platform.displayCaps.platformWidth).shouldBe(result);
		}
		finish(testRun);
	}

	//TIMOB-10043
	this.physicalSizeCategory = function(testRun) {
		if (Ti.Platform.osname === 'android') {
			valueOf(testRun, Ti.Platform.Android.physicalSizeCategory).shouldBeNumber();
		}
		finish(testRun);
	}

	//TIMOB-10482
	this.platform_manufacturer = function(testRun) {
		valueOf(testRun, Ti.Platform.getManufacturer()).shouldBe(Ti.Platform.manufacturer);

		finish(testRun);
	}
}
<|endoftext|>


<commit_before>describe("Browser API", function() {
});<commit_msg>Unit tests: Browser API<commit_after>describe("Browser API", function() {

	it("tells me what browser I'm using", function() {
		var possibilities = ["Firefox", "Chrome", "Safari", "Opera", "Explorer", "Opera", "RockMelt", "OmniWeb", "iCab", "KDE", "Camino", "Netscape"];
		expect(possibilities).toContain(Fiesta.getBrowser());
	});

	it("tells me the browser's version", function() {
		expect(typeof Fiesta.getBrowserVersion()).toEqual(typeof 1);
	});

	it("tells me what OS I'm using", function() {
		var possibilities = ["Windows", "Mac", "iPhone/iPod", "Linux"];
		expect(possibilities).toContain(Fiesta.getOS());
	});

});<|endoftext|>


<commit_before>(function (db, describe, it, expect, beforeEach, afterEach) {
    'use strict';
    describe('web workers', function () {
        var initialVersion = 1;
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.oIndexedDB || window.msIndexedDB;

        beforeEach(function (done) {
            this.dbName = guid();
            var req = indexedDB.deleteDatabase(this.dbName);

            req.onsuccess = function () {
                done();
            };

            req.onerror = function (e) {
                console.log('error deleting db', arguments);
                done(e);
            };

            req.onblocked = function (e) {
                console.log('db blocked on delete', arguments);
                done(e);
            };
        }, 10000);

        afterEach(function (done) {
            if (this.server && !this.server.isClosed()) {
                this.server.close();
            }
            var req = indexedDB.deleteDatabase(this.dbName);

            req.onsuccess = function (/* e */) {
                done();
            };

            req.onerror = function (e) {
                console.log('failed to delete db', arguments);
                done(e);
            };

            req.onblocked = function (e) {
                console.log('db blocked', arguments);
                done(e);
            };
        });

        it('should open a created db in a web worker', function (done) {
            var tw = new Worker('../test-worker.js');
            tw.onmessage = function (e) {
                expect(e.data).to.be.true;
                tw.terminate();
                done();
            };
            tw.postMessage({dbName: this.dbName, message: 'web worker open', version: initialVersion});
        });

        it('should open a created db in a service worker', function (done) {
            var spec = this;
            navigator.serviceWorker.register('../test-worker.js').then(function() {
                return navigator.serviceWorker.ready;
            }).then(function () {
                var messageChannel = new MessageChannel();
                messageChannel.port1.onmessage = function(e) {
                    expect(e.data).to.be.true;
                    done();
                };
                navigator.serviceWorker.controller.postMessage(
                    {dbName: spec.dbName, message: 'service worker open', version: initialVersion},
                    [messageChannel.port2]
                );
            }).catch(function (err) {
                console.log('Service worker error: ' + err);
            });
        });
    });
})(window.db, window.describe, window.it, window.expect, window.beforeEach, window.afterEach);
<commit_msg>relying on the service worker provided in<commit_after>(function (db, describe, it, expect, beforeEach, afterEach) {
    'use strict';
    describe('web workers', function () {
        var initialVersion = 1;
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.oIndexedDB || window.msIndexedDB;

        beforeEach(function (done) {
            this.dbName = guid();
            var req = indexedDB.deleteDatabase(this.dbName);

            req.onsuccess = function () {
                done();
            };

            req.onerror = function (e) {
                console.log('error deleting db', arguments);
                done(e);
            };

            req.onblocked = function (e) {
                console.log('db blocked on delete', arguments);
                done(e);
            };
        }, 10000);

        afterEach(function (done) {
            if (this.server && !this.server.isClosed()) {
                this.server.close();
            }
            var req = indexedDB.deleteDatabase(this.dbName);

            req.onsuccess = function (/* e */) {
                done();
            };

            req.onerror = function (e) {
                console.log('failed to delete db', arguments);
                done(e);
            };

            req.onblocked = function (e) {
                console.log('db blocked', arguments);
                done(e);
            };
        });

        it('should open a created db in a web worker', function (done) {
            var tw = new Worker('../test-worker.js');
            tw.onmessage = function (e) {
                expect(e.data).to.be.true;
                tw.terminate();
                done();
            };
            tw.postMessage({dbName: this.dbName, message: 'web worker open', version: initialVersion});
        });

        it('should open a created db in a service worker', function (done) {
            var spec = this;
            navigator.serviceWorker.register('../test-worker.js').then(function() {
                return navigator.serviceWorker.ready;
            }).then(function (serviceWorker) {
                var messageChannel = new MessageChannel();
                messageChannel.port1.onmessage = function(e) {
                    expect(e.data).to.be.true;
                    done();
                };

                var controller = navigator.serviceWorker.controller || serviceWorker.active;

                controller.postMessage(
                    {dbName: spec.dbName, message: 'service worker open', version: initialVersion},
                    [messageChannel.port2]
                );
            }).catch(function (err) {
                console.log('Service worker error: ' + err);
            });
        });
    });
})(window.db, window.describe, window.it, window.expect, window.beforeEach, window.afterEach);
<|endoftext|>


<commit_before>var test = require('tape');
var template = require('template-utils.js');
var tapeTemplates = require('tape-templates.js');

// TEST FIXTURE

test('tape template function', function (t) {
    t.plan(2); // How many tests?
    //Dummy data for parsed comment
    var emptyTestObj = {
      specType : 'tape',
      specFileSrc : 'app.js',
      tests : [
        { testTitle: 'sum function',
          assertions: []
        }
       ]
    };

    var singleTestObj = {
      specType : 'tape',
      specFileSrc : 'app.js',
      tests : [
      { testTitle: 'sum function',
        assertions: [
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(6, 7)',
            assertionOutput: '13'
          },
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(8, 9)',
            assertionOutput: '17'
          }
        ]
      }
     ]
    };
    var singleTestBlock = "test('sum function', function (t) {" +
                            "t.equal(sum(6, 7), 13, 'return the sum of both params')" +
                            "t.equal(sum(8, 9), 17, 'return the sum of both params')"+
                          ")}";
    var emptyTestBlock = "test('sum function', function (t) {" +
                          "})";
    //It takes an empty object and outputs an empty test block
    t.equal(template.addTestDataToBaseTemplate(tapeTemplates.baseTemplate, emptyTestObj), emptyTestBlock, 'Takes an test with 0 assertion and outputs a base template');
    //It takes one test block and produces a properly formatted tape test
    t.equal(template.addTestDataToBaseTemplate(tapeTemplates.baseTemplate, singleTestObj), emptyTestBlock, 'Takes an test with 0 assertion and outputs a base template');
    //It takes multiple test blocks and produces a properly formatted tape test
    //If a field is missing, return error, missing field
});
<commit_msg>Added template utility function tape test for object with multiple tests<commit_after>var test = require('tape');
var template = require('template-utils.js');
var tapeTemplates = require('tape-templates.js');

// TEST FIXTURE

test('tape template function', function (t) {
    t.plan(2); // How many tests?
    //Dummy data for parsed comment
    var dataObj = {
    specType : 'tape',
    specFileSrc : 'app.js',
    tests : [
      { testTitle: 'sum function',
        assertions: [
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(6, 7)',
            assertionOutput: '13'
          },
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(8, 9)',
            assertionOutput: '17'
          }
        ]
      },
      { testTitle: 'multiply function',
        assertions: [
          { assertionMessage: 'return the product of both params',
            assertionType: 'equals',
            assertionInput: 'mult(4, 5)',
            assertionOutput: '20'
          }
        ]
      }
    ]
    };
    var emptyTestObj = {
      specType : 'tape',
      specFileSrc : 'app.js',
      tests : [
        { testTitle: 'sum function',
          assertions: []
        }
       ]
    };

    var singleTestObj = {
      specType : 'tape',
      specFileSrc : 'app.js',
      tests : [
      { testTitle: 'sum function',
        assertions: [
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(6, 7)',
            assertionOutput: '13'
          },
          { assertionMessage: 'return the sum of both params',
            assertionType: 'equals',
            assertionInput: 'sum(8, 9)',
            assertionOutput: '17'
          }
        ]
      }
     ]
    };
    var normalTestBlock = "test('sum function', function (t) {" +
                            "t.equal(sum(6, 7), 13, 'return the sum of both params')" +
                            "t.equal(sum(8, 9), 17, 'return the sum of both params')"+
                          ")}" +
                          "test('multiply function', function (t) {" +
                            "t.equal(multiply(4, 5), 20, 'return the product of both params')" +
                          ")}";
    var singleTestBlock = "test('sum function', function (t) {" +
                            "t.equal(sum(6, 7), 13, 'return the sum of both params')" +
                            "t.equal(sum(8, 9), 17, 'return the sum of both params')"+
                          ")}";
    var emptyTestBlock = "test('sum function', function (t) {" +
                          "})";
    //It takes an empty object and outputs an empty test block
    t.equal(template.addTestDataToBaseTemplate(tapeTemplates.baseTemplate, emptyTestObj), emptyTestBlock, 'Takes an test with 0 assertion and outputs a base template');
    //It takes one test block and produces a properly formatted tape test
    t.equal(template.addTestDataToBaseTemplate(tapeTemplates.baseTemplate, singleTestObj), emptyTestBlock, 'Takes an test with 0 assertion and outputs a base template');
    //It takes multiple test blocks and produces a properly formatted tape test
    t.equal(template.addTestDataToBaseTemplate(tapeTemplates.baseTemplate, dataObj), normalTestBlock, 'Takes a properly formatted object and outputs a formatted test block');
    //If a field is missing, return error, missing field
});
<|endoftext|>


<commit_before>//namespace
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * @class  Dialog
	 * @constructor
	 */
	var Dialog = function(page, message, x, y, params) {
		var hasParam = GNOVEL.Util.hasParam;

		this._page = page;
		this._params = params || {};
		this._x = x;
		this._y = y;
		this._type = params.type;
		this._hasTransition = true;
		this._mouseDownListener = null;
		this._tweenComplete = false;
		this._showSpeaker = hasParam(params.showSpeaker, true);
		this._charLine = params.charLine || 72;
		this._font = params.font;
		this._bgWidth = params.bgWidth || 900;
		this._bgHeight = params.bgHeight || 145.5;
		this._bgPath = params.bgPath || "/static/gnovel/res/textures/blue_box.png";
		this._dontRemove = params.dontRemove || false;
		this._bgOffsetX = params.bgOffsetX || 0;
		this._bgOffsetY = params.bgOffsetY || 0;
		this._msgOffsetZ = params.msgOffsetZ || 0;
		this._msgOffsetY = params.msgOffsetY || 0;
		this._speakerOffsetX = params.speakerOffsetX || 0;
		this._speakerOffsetY = params.speakerOffsetY || 0;
		this._textBg = null; // private copy(might be shallow, might be referenced by Dialog.textBg)
		this._message = message;
		this._messageText = null;
		this._nameText = null;
		this._messageAlign = params.messageAlign || "center";
		var curspk = params.speaker;
		var prespk = Dialog._prevSpeaker;
		if (curspk == prespk) {
			this._hasTransition = false;
		}

		if (params.hasOwnProperty('createNewBg')) {
			this._hasTransition = params.createNewBg;
		}

		this._init();

		var dialog = this;
		this._mouseDownListener = function(event) {
			if (dialog._tweenComplete == false) {
				dialog._tweenComplete = true;
				dialog._onComplete();
			}
		}

		this._page.getOwner().addMouseDownListener(this._mouseDownListener);
	};

	// static class variable
	Dialog._textBg = null;
	Dialog._prevSpeaker = null;

	Dialog.prototype._init = function() {
		var x = this._x;
		var y = this._y;
		var z = this._page.getDialogLayer();

		if (Dialog._textBg != null && this._hasTransition && !this._dontRemove) {
			// if current speaker is different than the previous speaker, then we need to
			// close the previous dialog box if it still exists
			this._textBg = Dialog._textBg; // because this._textBg is null because of the ctor
			this._closeDialog();
		}
		else if(this._temp==true){
			// if current speaker is different than the previous speaker, then we need to
			// close the previous dialog box if it still exists
			this._textBg = Dialog._textBg; // because this._textBg is null because of the ctor
			this._closeDialog();
		}

		this._messageText = this._page.createTextBox(this._message, {
			align: this._messageAlign,
			charLine: this._charLine,
			font: this._font,
		});

		this._nameText = this._page.createTextBox(this._params.speaker, {
			align: "left",
			charLine: this._charLine
		});

		var textHeight = this._messageText.canvas.textHeight;
		if (textHeight > 23) {
			if (textHeight > 46) {
				this._messageText.position.set(x, y + 50 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
				this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 20 + this._speakerOffsetY, z + 20);
			}else {
				this._messageText.position.set(x, y + 45 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
				this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 25 + this._speakerOffsetY, z + 20);
			}
		}else {
			this._messageText.position.set(x, y + 40 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
			this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 30 + this._speakerOffsetY, z + 20);
		}

		// add background textbox
		if (typeof Dialog._textBg === "undefined" || Dialog._textBg === null || this._hasTransition) {
			Dialog._textBg = this._page.createImage(
				this._bgPath,
				new THREE.Vector3(this._messageText.position.x + this._bgOffsetX, y + this._bgOffsetY, z - 20),
				this._bgWidth, this._bgHeight);

			var opacityDest = 1;
			if(this._params.dontShowBg) {
				opacityDest = 0;
			}else{
				this._page._addToScene(Dialog._textBg);
			}

			//slide in animation for context box
			if(this._type == "context") {
			/*	this._page.tweenPos(Dialog._textBg,{
					duration:1000,
					toX: -520,
					toY: 230,
				});*/

				this._textBg = Dialog._textBg;
			}
			else {
				Dialog._textBg.material.opacity = 0;
				this._page.tweenMat(Dialog._textBg, {
					duration: 800,
					opacity: opacityDest,
					easing: TWEEN.Easing.Cubic.Out
				});

				this._textBg = Dialog._textBg;
			}
		}

		//slide in animation for context box
		if(this._type == "context") {
			this._page.tweenPos(this._messageText,{
				duration:1000,
				toX: -520,
			//toY: 230,
			});
		}
		else {

		// fade in text and speaker
		this._messageText.material.opacity = 0;
		this._page.tweenMat(this._messageText, {
			duration: 800,
			opacity: 1,
			easing: TWEEN.Easing.Cubic.Out
		});
		this._nameText.material.opacity = 0;
		this._page.tweenMat(this._nameText, {
			duration: 800,
			opacity: 1,
			easing: TWEEN.Easing.Cubic.Out
		});

	}

		this._page._addToScene(this._messageText);

		if (this._showSpeaker)
			this._page._addToScene(this._nameText);
	};

	Dialog.prototype._onComplete = function() {
		Dialog._prevSpeaker = this._params.speaker;

		//remove mousedown listener
		this._page.getOwner().removeMouseDownListener(this._mouseDownListener);

		var messageTextObj = this._messageText;
		var nameTextObj = this._nameText;
		var dialog = this;

		if (!dialog._dontRemove) {

			// fade out dialog speaker
			this._page.tweenMat(this._messageText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(messageTextObj);

					if (dialog._params.onComplete != null) {
						dialog._params.onComplete(dialog);
					}
				},
			});

			// fade out dialog text
			this._page.tweenMat(this._nameText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(nameTextObj);
				},
			});

			this._nameText = null;
			this._messageText = null;

			// if the next flow is not dialog, or it has different speaker, then we need to close the
			// dialog
			if (!this._isDialogNext() || this._isDifferentSpeakerNext()) {
				if(this._textBg != null) {
					this._closeDialog();
				}
				if(Dialog._textBg != null) {
					this._textBg =Dialog._textBg;
					this._closeDialog();
				}
			}
		} else {
			if (dialog._params.onComplete != null) {
				dialog._params.onComplete(dialog);
			}
		}
	};

	Dialog.prototype._isDialogNext = function() {
		if (this._page._getFlow()._peekNext() == null) {
			return false;
		}

		return this._page._getFlow()._peekNext().type == GNOVEL.Flow.DIALOG;
	};

	Dialog.prototype._isDifferentSpeakerNext = function() {
		if (this._page._getFlow()._peekNext() == null) {
			return false;
		}

		return this._page._getFlow()._peekNext().speaker !== this._params.speaker;
	}

	Dialog.prototype._closeDialog = function() {
		var dialog = this;
		var textBgObj = this._textBg;

		if(this._textBg != null){
			this._page.tweenMat(this._textBg, {
			duration: 800,
			opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(textBgObj);
				},
			});
		}

		if (this._messageText !== null) {
			var msgTextObj = this._messageText;
			this._page.tweenMat(this._messageText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(msgTextObj);
				},
			});
			this._messageText = null;
		}

		if (this._nameText !== null) {
			var nameTextObj = this._nameText;
			this._page.tweenMat(this._nameText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(nameTextObj);
				},
			});
			this._nameText = null;
		}

		Dialog._textBg = null;
		Dialog._prevSpeaker = null;
		this._textBg = null;
	};

	Dialog.prototype.getImage = function() {
			return this._textBg;
	};

	GNOVEL.Dialog = Dialog;
}());
<commit_msg>"temp" parameter for dialog boxes of timer responses added to dialog.js<commit_after>//namespace
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * @class  Dialog
	 * @constructor
	 */
	var Dialog = function(page, message, x, y, params) {
		var hasParam = GNOVEL.Util.hasParam;

		this._page = page;
		this._params = params || {};
		this._x = x;
		this._y = y;
		this._type = params.type;
		this._hasTransition = true;
		this._mouseDownListener = null;
		this._tweenComplete = false;
		this._showSpeaker = hasParam(params.showSpeaker, true);
		this._charLine = params.charLine || 72;
		this._font = params.font;
		this._bgWidth = params.bgWidth || 900;
		this._bgHeight = params.bgHeight || 145.5;
		this._bgPath = params.bgPath || "/static/gnovel/res/textures/blue_box.png";
		this._dontRemove = params.dontRemove || false;
		this._bgOffsetX = params.bgOffsetX || 0;
		this._bgOffsetY = params.bgOffsetY || 0;
		this._msgOffsetZ = params.msgOffsetZ || 0;
		this._msgOffsetY = params.msgOffsetY || 0;
		this._speakerOffsetX = params.speakerOffsetX || 0;
		this._speakerOffsetY = params.speakerOffsetY || 0;
		this._textBg = null; // private copy(might be shallow, might be referenced by Dialog.textBg)
		this._message = message;
		this._messageText = null;
		this._nameText = null;
		this._messageAlign = params.messageAlign || "center";
		this._temp = params.temp;
		var curspk = params.speaker;
		var prespk = Dialog._prevSpeaker;
		if (curspk == prespk) {
			this._hasTransition = false;
		}

		if (params.hasOwnProperty('createNewBg')) {
			this._hasTransition = params.createNewBg;
		}

		this._init();

		var dialog = this;
		this._mouseDownListener = function(event) {
			if (dialog._tweenComplete == false) {
				dialog._tweenComplete = true;
				dialog._onComplete();
			}
		}

		this._page.getOwner().addMouseDownListener(this._mouseDownListener);
	};

	// static class variable
	Dialog._textBg = null;
	Dialog._prevSpeaker = null;

	Dialog.prototype._init = function() {
		var x = this._x;
		var y = this._y;
		var z = this._page.getDialogLayer();

		if (Dialog._textBg != null && this._hasTransition && !this._dontRemove) {
			// if current speaker is different than the previous speaker, then we need to
			// close the previous dialog box if it still exists
			this._textBg = Dialog._textBg; // because this._textBg is null because of the ctor
			this._closeDialog();
		}
		else if(this._temp==true){
			// if current speaker is different than the previous speaker, then we need to
			// close the previous dialog box if it still exists
			this._textBg = Dialog._textBg; // because this._textBg is null because of the ctor
			this._closeDialog();
		}

		this._messageText = this._page.createTextBox(this._message, {
			align: this._messageAlign,
			charLine: this._charLine,
			font: this._font,
		});

		this._nameText = this._page.createTextBox(this._params.speaker, {
			align: "left",
			charLine: this._charLine
		});

		var textHeight = this._messageText.canvas.textHeight;
		if (textHeight > 23) {
			if (textHeight > 46) {
				this._messageText.position.set(x, y + 50 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
				this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 20 + this._speakerOffsetY, z + 20);
			}else {
				this._messageText.position.set(x, y + 45 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
				this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 25 + this._speakerOffsetY, z + 20);
			}
		}else {
			this._messageText.position.set(x, y + 40 + this._msgOffsetY, z + 20 + this._msgOffsetZ);
			this._nameText.position.set(this._messageText.position.x + this._speakerOffsetX, this._messageText.position.y + 30 + this._speakerOffsetY, z + 20);
		}

		// add background textbox
		if (typeof Dialog._textBg === "undefined" || Dialog._textBg === null || this._hasTransition) {
			Dialog._textBg = this._page.createImage(
				this._bgPath,
				new THREE.Vector3(this._messageText.position.x + this._bgOffsetX, y + this._bgOffsetY, z - 20),
				this._bgWidth, this._bgHeight);

			var opacityDest = 1;
			if(this._params.dontShowBg) {
				opacityDest = 0;
			}else{
				this._page._addToScene(Dialog._textBg);
			}

			//slide in animation for context box
			if(this._type == "context") {
			/*	this._page.tweenPos(Dialog._textBg,{
					duration:1000,
					toX: -520,
					toY: 230,
				});*/

				this._textBg = Dialog._textBg;
			}
			else {
				Dialog._textBg.material.opacity = 0;
				this._page.tweenMat(Dialog._textBg, {
					duration: 800,
					opacity: opacityDest,
					easing: TWEEN.Easing.Cubic.Out
				});

				this._textBg = Dialog._textBg;
			}
		}

		//slide in animation for context box
		if(this._type == "context") {
			this._page.tweenPos(this._messageText,{
				duration:1000,
				toX: -520,
			//toY: 230,
			});
		}
		else {

		// fade in text and speaker
		this._messageText.material.opacity = 0;
		this._page.tweenMat(this._messageText, {
			duration: 800,
			opacity: 1,
			easing: TWEEN.Easing.Cubic.Out
		});
		this._nameText.material.opacity = 0;
		this._page.tweenMat(this._nameText, {
			duration: 800,
			opacity: 1,
			easing: TWEEN.Easing.Cubic.Out
		});

	}

		this._page._addToScene(this._messageText);

		if (this._showSpeaker)
			this._page._addToScene(this._nameText);
	};

	Dialog.prototype._onComplete = function() {
		Dialog._prevSpeaker = this._params.speaker;

		//remove mousedown listener
		this._page.getOwner().removeMouseDownListener(this._mouseDownListener);

		var messageTextObj = this._messageText;
		var nameTextObj = this._nameText;
		var dialog = this;

		if (!dialog._dontRemove) {

			// fade out dialog speaker
			this._page.tweenMat(this._messageText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(messageTextObj);

					if (dialog._params.onComplete != null) {
						dialog._params.onComplete(dialog);
					}
				},
			});

			// fade out dialog text
			this._page.tweenMat(this._nameText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(nameTextObj);
				},
			});

			this._nameText = null;
			this._messageText = null;

			// if the next flow is not dialog, or it has different speaker, then we need to close the
			// dialog
			if (!this._isDialogNext() || this._isDifferentSpeakerNext()) {
				if(this._textBg != null) {
					this._closeDialog();
				}
				if(Dialog._textBg != null) {
					this._textBg =Dialog._textBg;
					this._closeDialog();
				}
			}
		} else {
			if (dialog._params.onComplete != null) {
				dialog._params.onComplete(dialog);
			}
		}
	};

	Dialog.prototype._isDialogNext = function() {
		if (this._page._getFlow()._peekNext() == null) {
			return false;
		}

		return this._page._getFlow()._peekNext().type == GNOVEL.Flow.DIALOG;
	};

	Dialog.prototype._isDifferentSpeakerNext = function() {
		if (this._page._getFlow()._peekNext() == null) {
			return false;
		}

		return this._page._getFlow()._peekNext().speaker !== this._params.speaker;
	}

	Dialog.prototype._closeDialog = function() {
		var dialog = this;
		var textBgObj = this._textBg;

		if(this._textBg != null){
			this._page.tweenMat(this._textBg, {
			duration: 800,
			opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(textBgObj);
				},
			});
		}

		if (this._messageText !== null) {
			var msgTextObj = this._messageText;
			this._page.tweenMat(this._messageText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(msgTextObj);
				},
			});
			this._messageText = null;
		}

		if (this._nameText !== null) {
			var nameTextObj = this._nameText;
			this._page.tweenMat(this._nameText, {
				duration: 800,
				opacity: 0,
				easing: TWEEN.Easing.Cubic.Out,
				onComplete: function() {
					dialog._page._removeFromScene(nameTextObj);
				},
			});
			this._nameText = null;
		}

		Dialog._textBg = null;
		Dialog._prevSpeaker = null;
		this._textBg = null;
	};

	Dialog.prototype.getImage = function() {
			return this._textBg;
	};

	GNOVEL.Dialog = Dialog;
}());
<|endoftext|>


<commit_before>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page8_2
	 * @augments MPlay.MPlayPage
	 */
	var Page8_2 = function() {
		MPLAY.MPlayPage.call(this);
	};

	Page8_2.prototype = Object.create(MPLAY.MPlayPage.prototype);
	Page8_2.prototype.constructor = Page8_2;

	/**
	 * @override
	 */
	Page8_2.prototype._onLoad = function() {
		MPLAY.MPlayPage.prototype._onLoad.call(this);

		this.setupOfficeBackground();
	};

	Page8_2.prototype._createFlowElements = function() {

		var priya = "%" + this._priya;
		var ryan = "%" + this._ryan;
		var professor = "%" + this._professor;
		var player = this._player;
		var closephone = "%" + this._closephone;

		var o = null;

		o = [
			{type: "show_context", text: "A few days after the test,"},
			{type: "show_context", text: "Professor Sweeny calls you and Ryan to his office"},
			{type: "show", img: professor, expression: "sad"},
			{type: "dialog", speaker: this._professor, text: "I noticed a very strange mistake that only you two made on the exam.  You see, last year there was an error on one of the prompts."},

			{type: "choices", choices : [
				{text: "I can explain-"},
				{text: "But Professor-"},
				],
			seconds: 5},

			{type: "dialog", speaker: this._professor, text: "Now, I know that wasn't the case on this year's exam.  Can you both explain how you made last year's mistake on this year's exam?"},

			{type: "choices", choices : [
				{text: "You see-"},
				{text: "We just-"},
				],
			seconds: 5},

			{type: "dialog", speaker: this._professor, text: "Potential consequences of an academic violation are failing the exam, the course and possible expulsion from your graduate programs."},
			{type: "dialog", speaker: this._professor, text: "There is an appeals process as well, but before we go down that road, I'd like to hear from you."},
			{type: "dialog", speaker: this._professor, text: "RYAN, " + this._player + ", please tell me your side of the story."},
			{type: "hide", img: this._professor},

			{type: "nothing", label: "email"},
			{type: "show_phone_notif"},

			// phone email exchange begins
			{type: "show", img: closephone, waitUntilShown: false},
			{type: "phone_textbox",
				label: "phone_bg",
				bgOffsetY: -230,
				bgOffsetX: -15,
				bgHeight: 800,
				bgWidth: 1460,
				y: 250,
				charLine: 37,
				bgPath: "/static/gnovel/res/textures/Email-graphic.png",
				waitUntilShown: false,
				text: ""},
			{type: "phone_textbox",
				label: "address_from",
				bgHeight: 10,
				bgWidth: 10,
				x: -200,
				y: 230,
				dontShowBg: true,
				text: "From: Prof. Sweeney",
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "address_to",
				bgHeight: 10,
				bgWidth: 10,
				x: -200,
				y: 200,
				dontShowBg: true,
				text: "To: " + player,
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "email_subject",
				bgHeight: 10,
				bgWidth: 10,
				x: -200,
				y: 100,
				dontShowBg: true,
				charLine: 40,
				text: "Subject: ",
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "email_textbox",
				bgHeight: 10,
				bgWidth: 10,
				y: 40,
				charLine: 37,
				dontShowBg: true,
				text: "After much deliberation, I have made up my own solution to address your violation. As a consequence of unauthorized possession and use of last year’s exam, you will need to retake the final, with the highest possible grade starting at the class average, an 80%. As we discussed in our meeting, I will cut you some slack though I am extremely disappointed.  Since I believe you did not consciously act in bad faith, I will not be moving forward with proceedings for this violation.  Please take this as a learning experience to reflect on your actions. - Prof. Sweeney"},
			{type: "hide_phone_textbox", dialog: "$phone_bg"},
			{type: "hide_phone_textbox", dialog: "$address_from"},
			{type: "hide_phone_textbox", dialog: "$address_to"},
			{type: "hide_phone_textbox", dialog: "$email_subject"},
			{type: "hide_phone_textbox", dialog: "$email_textbox"},
			{type: "hide", img: closephone},

			{type: "show_context", text: "You receive a text from Ryan"},

			{type: "custom", func: function(page){
				return page.getRelationshipManager().getRelationship("Ryan");
			}, label: "ryanRelationshipScore1"},
			{type: "compare", leftop: "$ryanRelationshipScore1", operator: "greater", rightop: 0, goTrue: "#pos-ryan1", goFalse: "#compareryan1"},

			{type: "nothing", label: "pos-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Woo!!  I passed too!  I got a C.  Happy it turned out ok for us.  Definitely not taking any more advice from my bro anytime soon…"},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			{type: "nothing", label: "compareryan1"},
			{type: "compare", leftop: "$ryanRelationshipScore1", operator: "equal", rightop: 0, goTrue: "#zero-ryan1", goFalse: "#neg-ryan1"},

			{type: "nothing", label: "zero-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Did you pass?  I got a C."},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			{type: "nothing", label: "neg-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Got a C, this sucks."},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			];

		return o;
	};

	Page8_2.prototype._onUnload = function() {
		if (this._owner._ambient != null) {
			this._tweenVolumeOut();
		}
	};

	Page8_2.prototype._onStart = function() {
		this._owner._ambient = this._owner.getSoundManager().play("Office-bg", {interrupt: this._owner.getSoundManager().INTERRUPT_ANY, loop: -1, offset: 1000, volume: 0.0});
		this._tweenVolumeIn();
	};

	MPLAY.Page8_2 = Page8_2;
}());
<commit_msg>Fix phone interaction in page8_2.js<commit_after>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page8_2
	 * @augments MPlay.MPlayPage
	 */
	var Page8_2 = function() {
		MPLAY.MPlayPage.call(this);
	};

	Page8_2.prototype = Object.create(MPLAY.MPlayPage.prototype);
	Page8_2.prototype.constructor = Page8_2;

	/**
	 * @override
	 */
	Page8_2.prototype._onLoad = function() {
		MPLAY.MPlayPage.prototype._onLoad.call(this);

		this.setupOfficeBackground();
	};

	Page8_2.prototype._createFlowElements = function() {

		var priya = "%" + this._priya;
		var ryan = "%" + this._ryan;
		var professor = "%" + this._professor;
		var player = this._player;
		var closephone = "%" + this._closephone;

		var o = null;

		o = [
			{type: "show_context", text: "A few days after the test,"},
			{type: "show_context", text: "Professor Sweeny calls you and Ryan to his office"},
			{type: "show", img: professor, expression: "sad"},
			{type: "dialog", speaker: this._professor, text: "I noticed a very strange mistake that only you two made on the exam.  You see, last year there was an error on one of the prompts."},

			{type: "choices", choices : [
				{text: "I can explain-"},
				{text: "But Professor-"},
				],
			seconds: 5},

			{type: "dialog", speaker: this._professor, text: "Now, I know that wasn't the case on this year's exam.  Can you both explain how you made last year's mistake on this year's exam?"},

			{type: "choices", choices : [
				{text: "You see-"},
				{text: "We just-"},
				],
			seconds: 5},

			{type: "dialog", speaker: this._professor, text: "Potential consequences of an academic violation are failing the exam, the course and possible expulsion from your graduate programs."},
			{type: "dialog", speaker: this._professor, text: "There is an appeals process as well, but before we go down that road, I'd like to hear from you."},
			{type: "dialog", speaker: this._professor, text: "RYAN, " + this._player + ", please tell me your side of the story."},
			{type: "hide", img: this._professor},

			{type: "nothing", label: "email"},
			{type: "show_phone_notif"},

			// phone email exchange begins
			{type: "show", img: closephone, waitUntilShown: false},
			{type: "phone_textbox",
				label: "phone_bg",
				bgOffsetY: -230,
				bgOffsetX: -15,
				bgHeight: 790,
				bgWidth: 1230,
				y: 250,
				charLine: 37,
				bgPath: "/static/gnovel/res/textures/Email-graphic.png",
				waitUntilShown: false,
				text: ""},
			{type: "phone_textbox",
				label: "address_from",
				bgHeight: 10,
				bgWidth: 10,
				x: -170,
				y: 230,
				dontShowBg: true,
				text: "From: Prof. Sweeney",
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "address_to",
				bgHeight: 10,
				bgWidth: 10,
				x: -170,
				y: 200,
				dontShowBg: true,
				text: "To: " + player,
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "email_subject",
				bgHeight: 10,
				bgWidth: 10,
				x: -170,
				y: 100,
				dontShowBg: true,
				charLine: 40,
				text: "Subject: Academic Violation",
				messageAlign: "left",
				waitUntilShown: false,
				},
			{type: "phone_textbox",
				label: "email_textbox",
				bgHeight: 10,
				bgWidth: 10,
				y: 40,
				charLine: 37,
				dontShowBg: true,
				text: "After much deliberation, I have made up my own solution to address your violation. As a consequence of unauthorized possession and use of last year’s exam, you will need to retake the final, with the highest possible grade starting at the class average, an 80%. As we discussed in our meeting, I will cut you some slack though I am extremely disappointed.  Since I believe you did not consciously act in bad faith, I will not be moving forward with proceedings for this violation. "},
			{type: "hide_phone_textbox", dialog: "$phone_bg"},
			{type: "hide_phone_textbox", dialog: "$address_from"},
			{type: "hide_phone_textbox", dialog: "$address_to"},
			{type: "hide_phone_textbox", dialog: "$email_subject"},
			{type: "hide_phone_textbox", dialog: "$email_textbox"},
			{type: "hide", img: closephone},

			{type: "show_context", text: "You receive a text from Ryan"},

			{type: "custom", func: function(page){
				return page.getRelationshipManager().getRelationship("Ryan");
			}, label: "ryanRelationshipScore1"},
			{type: "compare", leftop: "$ryanRelationshipScore1", operator: "greater", rightop: 0, goTrue: "#pos-ryan1", goFalse: "#compareryan1"},

			{type: "nothing", label: "pos-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Woo!!  I passed too!  I got a C.  Happy it turned out ok for us.  Definitely not taking any more advice from my bro anytime soon…"},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			{type: "nothing", label: "compareryan1"},
			{type: "compare", leftop: "$ryanRelationshipScore1", operator: "equal", rightop: 0, goTrue: "#zero-ryan1", goFalse: "#neg-ryan1"},

			{type: "nothing", label: "zero-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Did you pass?  I got a C."},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			{type: "nothing", label: "neg-ryan1"},
			// phone exchange begins
			{type: "show", img: closephone},
			{type: "phone_textbox",
				label: "text1",
				bgOffsetY: 10,
				bgHeight: 60,
				bgWidth: 330,
				y: 250,
				charLine: 37,
				text: "Got a C, this sucks."},
			{type: "hide_phone_textbox", dialog: "$text1"},
			{type: "hide", img: closephone},
			{type: "goto", page: "scene ending"},

			];

		return o;
	};

	Page8_2.prototype._onUnload = function() {
		if (this._owner._ambient != null) {
			this._tweenVolumeOut();
		}
	};

	Page8_2.prototype._onStart = function() {
		this._owner._ambient = this._owner.getSoundManager().play("Office-bg", {interrupt: this._owner.getSoundManager().INTERRUPT_ANY, loop: -1, offset: 1000, volume: 0.0});
		this._tweenVolumeIn();
	};

	MPLAY.Page8_2 = Page8_2;
}());
<|endoftext|>


<commit_before>
$(document).ready(function(){
  var all = document.getElementsByTagName("*");
  alert("scanning");
  scanfill();
  alert("scan over");
})

function scanfill(){
	var re = new RegExp("[#_]*(.*)(.|\r|\n)*?![\n|#]?");
	var str = readfile();
	var m;
	alert(str);
	if ((m = re.exec(str)) !== null) {
	    if (m.index === re.lastIndex) {
	        re.lastIndex++;
	    }
	    alert('hi: '+m[0]);
	}
}

function readfile(){
	var txtFile = new XMLHttpRequest();
	txtFile.open("GET", "definition.kml", true);//finds the kode markup lang definition
	txtFile.onreadystatechange = function() {
  		if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
    		if (txtFile.status === 200) {  // Makes sure it's found the file.
    			var allText = txtFile.responseText;
    	  		return allText;
  			}
		}
	}
	txtFile.send(null);
}
<commit_msg>minor<commit_after>
$(document).ready(function(){
  var all = document.getElementsByTagName("*");
  alert("scanning");
  scanfill();
  alert("scan over");
})

function scanfill(){
	var re = new RegExp("[#_]*(.*)(.|\r|\n)*?![\n|#]?");
	var str = readfile();
	var m;
	alert(str);
	if ((m = re.exec(str)) !== null) {
	    if (m.index === re.lastIndex) {
	        re.lastIndex++;
	    }
	    alert('hi: '+m[0]);
	}
}

function readfile(){
	var thetext = "";
	var txtFile = new XMLHttpRequest();
	txtFile.open("GET", "definition.kml", true);//finds the kode markup lang definition
	txtFile.onreadystatechange = function() {
  		if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
    		if (txtFile.status === 200) {  // Makes sure it's found the file.
    			thetext = txtFile.responseText;
    			alert("file found");
  			}
  			else
  			{
  				alert("file not found");
  			}
		}
	}
	txtFile.send(null);
	return thetext;
}
<|endoftext|>


<commit_before>var jwt = require('jsonwebtoken');
var cookie = require('cookie');
var debug = require('debug')('upcache:scope');

var headerRestriction = 'X-Cache-Restriction';
var headerHandshake = 'X-Cache-Key-Handshake';

var publicKeySent = false;

var config;
exports = module.exports = function(obj) {
	config = Object.assign({
		algorithm: 'RS256',
		forbidden: function(res) {
			res.sendStatus(403);
		},
		unauthorized: function(res) {
			res.sendStatus(401);
		}

	}, obj);
	return exports;
};

// facility for checking request against some scopes
exports.allowed = function(req) {
	var action = getAction(method);
	var list = restrictionsByAction(action, Array.from(arguments).slice(1));
	sendHeaders(req.res, list);
	return authorize(action, list, initScopes(req));
};

function restrictionsByAction(action, list) {
	if (!action) return [];
	if (!Array.isArray(list)) list = [list];
	var metaAction = action == "read" ? "read" : "write";
	var restrictions = [];
	list.forEach(function(item) {
		if (typeof item != "string") {
			if (item[action]) item = item[action];
			else if (item[metaAction]) item = item[metaAction];
			else return;
		}
		restrictions.push(item);
	});
	return restrictions;
}

function authorize(action, restrictions, scopes) {
	if (!action) return false;
	var failure = false;
	var i, label, grant, scope, mandatory, regstr;
	var grants = [];
	for (i=0; i < restrictions.length; i++) {
		grant = label = restrictions[i];
		if (label == "*") {
			grants.push(grant);
			continue;
		}
		if (!scopes) continue;
		mandatory = false;
		if (label[0] == "&") {
			mandatory = true;
			label = label.substring(1);
		}
		regstr = label.replace(/\*/g, '.*');
		if (regstr.length != label.length) {
			// wildcard
			var reg = new RegExp("^" + regstr + "$");
			if (Object.keys(scopes).some(function(scope) {
				var scopeObj = scopes[scope];
				if (scopeObj == true || scopeObj != null && scopeObj[action] == true) {
					return reg.test(scope);
				}
			})) {
				grants.push(grant);
				continue;
			}
		} else {
			scope = scopes[label];
			if (scope === true || scope && scope[action]) {
				grants.push(grant);
				continue;
			}
		}
		if (mandatory) {
			failure = true;
			break;
		}
	}
	if (failure || !grants.length) return false;
	// might be useful for optimizing first proxy response key
	// by sending actual scopes being granted, since the response key
	// will do the same job, given request bearer and restrictions list
	return grants;
}

function sendHeaders(res, list) {
	// an empty list does not have same meaning as no list at all
	if (list) {
		res.set(headerRestriction, list);
		debug("send header", headerRestriction, list);
	} else {
		debug("not sending header", headerRestriction);
	}
};

exports.restrict = function() {
	var restrictions = Array.from(arguments);
	// TODO memoize restrictionsByAction
	return function(req, res, next) {
		if (req.get(headerHandshake) == '1' || !publicKeySent) {
			debug("sending public key to proxy");
			publicKeySent = true;
			res.set(headerHandshake, encodeURIComponent(config.publicKey));
		}
		var scopes = initScopes(req);
		var action = getAction(req.method);
		var list = restrictionsByAction(action, restrictions);
		sendHeaders(res, list);
		var grants = authorize(action, list, scopes);
		if (grants) {
			debug("grants", grants);
			next();
		} else if (!scopes) {
			config.unauthorized(res);
		} else {
			config.forbidden(res);
		}
	};
};

exports.login = function(res, user, opts) {
	if (!user.scopes) debug("login user without scopes");
	var bearer = jwt.sign(user, config.privateKey, {
		expiresIn: config.maxAge,
		algorithm: config.algorithm,
		issuer: config.issuer
	});
	res.cookie('bearer', bearer, Object.assign({
		maxAge: config.maxAge * 1000,
		httpOnly: true,
		path: '/'
	}, opts);
	return bearer;
};

exports.logout = function(res, opts) {
	res.clearCookie('bearer', Object.assign({
		httpOnly: true,
		path: '/'
	}, opts));
};

function getAction(method) {
	return {
		GET: "read",
		HEAD: "read",
		PUT: "save",
		PATCH: "save",
		POST: "add",
		DELETE: "del"
	}[method];
}

function initScopes(req) {
	var prop = config.userProperty;
	if (prop && req[prop]) return req[prop].scopes;
	if (!req.cookies) req.cookies = cookie.parse(req.headers.cookie || "") || {};

	var bearer = req.cookies.bearer;
	if (!bearer) {
		return;
	}
	var obj;
	try {
		obj = jwt.verify(bearer, config.publicKey, {
			algorithm: config.algorithm,
			issuer: config.issuer
		});
	} catch(ex) {
		debug(ex, bearer);
	}
	if (!obj) return;
	if (prop) req[prop] = obj;
	return obj.scopes;
}

<commit_msg>Missing closing parens<commit_after>var jwt = require('jsonwebtoken');
var cookie = require('cookie');
var debug = require('debug')('upcache:scope');

var headerRestriction = 'X-Cache-Restriction';
var headerHandshake = 'X-Cache-Key-Handshake';

var publicKeySent = false;

var config;
exports = module.exports = function(obj) {
	config = Object.assign({
		algorithm: 'RS256',
		forbidden: function(res) {
			res.sendStatus(403);
		},
		unauthorized: function(res) {
			res.sendStatus(401);
		}

	}, obj);
	return exports;
};

// facility for checking request against some scopes
exports.allowed = function(req) {
	var action = getAction(method);
	var list = restrictionsByAction(action, Array.from(arguments).slice(1));
	sendHeaders(req.res, list);
	return authorize(action, list, initScopes(req));
};

function restrictionsByAction(action, list) {
	if (!action) return [];
	if (!Array.isArray(list)) list = [list];
	var metaAction = action == "read" ? "read" : "write";
	var restrictions = [];
	list.forEach(function(item) {
		if (typeof item != "string") {
			if (item[action]) item = item[action];
			else if (item[metaAction]) item = item[metaAction];
			else return;
		}
		restrictions.push(item);
	});
	return restrictions;
}

function authorize(action, restrictions, scopes) {
	if (!action) return false;
	var failure = false;
	var i, label, grant, scope, mandatory, regstr;
	var grants = [];
	for (i=0; i < restrictions.length; i++) {
		grant = label = restrictions[i];
		if (label == "*") {
			grants.push(grant);
			continue;
		}
		if (!scopes) continue;
		mandatory = false;
		if (label[0] == "&") {
			mandatory = true;
			label = label.substring(1);
		}
		regstr = label.replace(/\*/g, '.*');
		if (regstr.length != label.length) {
			// wildcard
			var reg = new RegExp("^" + regstr + "$");
			if (Object.keys(scopes).some(function(scope) {
				var scopeObj = scopes[scope];
				if (scopeObj == true || scopeObj != null && scopeObj[action] == true) {
					return reg.test(scope);
				}
			})) {
				grants.push(grant);
				continue;
			}
		} else {
			scope = scopes[label];
			if (scope === true || scope && scope[action]) {
				grants.push(grant);
				continue;
			}
		}
		if (mandatory) {
			failure = true;
			break;
		}
	}
	if (failure || !grants.length) return false;
	// might be useful for optimizing first proxy response key
	// by sending actual scopes being granted, since the response key
	// will do the same job, given request bearer and restrictions list
	return grants;
}

function sendHeaders(res, list) {
	// an empty list does not have same meaning as no list at all
	if (list) {
		res.set(headerRestriction, list);
		debug("send header", headerRestriction, list);
	} else {
		debug("not sending header", headerRestriction);
	}
};

exports.restrict = function() {
	var restrictions = Array.from(arguments);
	// TODO memoize restrictionsByAction
	return function(req, res, next) {
		if (req.get(headerHandshake) == '1' || !publicKeySent) {
			debug("sending public key to proxy");
			publicKeySent = true;
			res.set(headerHandshake, encodeURIComponent(config.publicKey));
		}
		var scopes = initScopes(req);
		var action = getAction(req.method);
		var list = restrictionsByAction(action, restrictions);
		sendHeaders(res, list);
		var grants = authorize(action, list, scopes);
		if (grants) {
			debug("grants", grants);
			next();
		} else if (!scopes) {
			config.unauthorized(res);
		} else {
			config.forbidden(res);
		}
	};
};

exports.login = function(res, user, opts) {
	if (!user.scopes) debug("login user without scopes");
	var bearer = jwt.sign(user, config.privateKey, {
		expiresIn: config.maxAge,
		algorithm: config.algorithm,
		issuer: config.issuer
	});
	res.cookie('bearer', bearer, Object.assign({
		maxAge: config.maxAge * 1000,
		httpOnly: true,
		path: '/'
	}, opts));
	return bearer;
};

exports.logout = function(res, opts) {
	res.clearCookie('bearer', Object.assign({
		httpOnly: true,
		path: '/'
	}, opts));
};

function getAction(method) {
	return {
		GET: "read",
		HEAD: "read",
		PUT: "save",
		PATCH: "save",
		POST: "add",
		DELETE: "del"
	}[method];
}

function initScopes(req) {
	var prop = config.userProperty;
	if (prop && req[prop]) return req[prop].scopes;
	if (!req.cookies) req.cookies = cookie.parse(req.headers.cookie || "") || {};

	var bearer = req.cookies.bearer;
	if (!bearer) {
		return;
	}
	var obj;
	try {
		obj = jwt.verify(bearer, config.publicKey, {
			algorithm: config.algorithm,
			issuer: config.issuer
		});
	} catch(ex) {
		debug(ex, bearer);
	}
	if (!obj) return;
	if (prop) req[prop] = obj;
	return obj.scopes;
}

<|endoftext|>


<commit_before>// Copyright 2012 Rackspace Hosting, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var trace = require('..').trace;
var node_tracers = require('..').node_tracers;

var express = require('express');
var http = require('http');
var util = require('util');

var mockKeystoneClient = {
  getTenantIdAndToken: function(cb) {
    cb('1', 2, '3');
  }
};

// Asserts (via a nodeunit test object) that the result is a base64 string
var assert_is_base64 = function(test, string) {
  test.ok(string.search(/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/) >= 0);
};

// Asserts (via a nodeunit test object) that the result is a json array - if
// it is a string representing a json array, parses the string
var assert_is_json_array = function(test, json) {
  if (typeof json === typeof "") {
    json = JSON.parse(json);
  }
  test.ok(util.isArray(json));
  test.ok(json.length >= 1);
};

// A fake scribe client for testing purposes - rather than send data to scribe,
// it saves the category and message sent to it and allows assertions to be
// made on the data (via a nodeunit test object)
var FakeScribe = function(test) {
  var self = this;
  self.test = test;
  self.results = [];
  self.send = function(category, message) {
    self.results.push([category, message]);
  };
  self.assert_sent = function() {
    self.test.equal(self.results.length, 1);
    self.test.equal(self.results[0].length, 2);
  };
  self.assert_category = function(category) {
    self.test.equal(self.results[0][0], category);
  };
  self.assert_json = function() {
    assert_is_json_array(self.test, self.results[0][1]);
  };
  self.assert_base64 = function() {
    assert_is_base64(self.test, self.results[0][1]);
  };
};

module.exports = {
  setUp: function(cb) {
    var self = this;
    self.trace = new trace.Trace('clientRecv');
    self.annotation = trace.Annotation.clientRecv(2);
    cb();
  },
  test_restkin_tracer: function(test){
    var self = this;
    var app = express();
    var server = http.createServer(app);
    var tracer1, tracer2;
    var i = 0;

    app.use(express.bodyParser());

    app.post('/3/trace', function(request, response) {
      i++;
      test.equal(request.headers['x-auth-token'], '1');
      test.equal(request.headers['x-tenant-id'], '3');
      test.equal(request.headers['content-type'], 'application/json');
      test.notEqual(request.headers['content-length'], '0');
      assert_is_json_array(test, request.body);

      response.end('done');

      if (i === 2) {
        server.close();
      }
    });

    server.on('close', function(){
      test.done();
    });

    server.listen(22222, 'localhost');

    // Valid URL
    tracer1 = new node_tracers.RESTkinTracer('http://localhost:22222',
                                             mockKeystoneClient);

    // Valid URL with trailing slash
    tracer2 = new node_tracers.RESTkinTracer('http://localhost:22222/',
                                             mockKeystoneClient);

    tracer1.record(self.trace, self.annotation);
    tracer2.record(self.trace, self.annotation);
  },
  test_restkin_tracer_server_: function(test) {
    var tracer;

    tracer = new node_tracers.RESTkinTracer('http://localhost:1898/',
                                            mockKeystoneClient);

    tracer.record(this.trace, this.annotation);
    test.done();
  },
  test_zipkin_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('zipkin');
    s.assert_base64();
    test.done();
  },
  test_zipkin_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_base64();
    test.done();
  },
  test_restkin_scribe_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('restkin');
    s.assert_json();
    test.done();
  },
  test_restkin_scribe_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_json();
    test.done();
  }
};
<commit_msg>fix the test name.<commit_after>// Copyright 2012 Rackspace Hosting, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var trace = require('..').trace;
var node_tracers = require('..').node_tracers;

var express = require('express');
var http = require('http');
var util = require('util');

var mockKeystoneClient = {
  getTenantIdAndToken: function(cb) {
    cb('1', 2, '3');
  }
};

// Asserts (via a nodeunit test object) that the result is a base64 string
var assert_is_base64 = function(test, string) {
  test.ok(string.search(/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/) >= 0);
};

// Asserts (via a nodeunit test object) that the result is a json array - if
// it is a string representing a json array, parses the string
var assert_is_json_array = function(test, json) {
  if (typeof json === typeof "") {
    json = JSON.parse(json);
  }
  test.ok(util.isArray(json));
  test.ok(json.length >= 1);
};

// A fake scribe client for testing purposes - rather than send data to scribe,
// it saves the category and message sent to it and allows assertions to be
// made on the data (via a nodeunit test object)
var FakeScribe = function(test) {
  var self = this;
  self.test = test;
  self.results = [];
  self.send = function(category, message) {
    self.results.push([category, message]);
  };
  self.assert_sent = function() {
    self.test.equal(self.results.length, 1);
    self.test.equal(self.results[0].length, 2);
  };
  self.assert_category = function(category) {
    self.test.equal(self.results[0][0], category);
  };
  self.assert_json = function() {
    assert_is_json_array(self.test, self.results[0][1]);
  };
  self.assert_base64 = function() {
    assert_is_base64(self.test, self.results[0][1]);
  };
};

module.exports = {
  setUp: function(cb) {
    var self = this;
    self.trace = new trace.Trace('clientRecv');
    self.annotation = trace.Annotation.clientRecv(2);
    cb();
  },
  test_restkin_tracer: function(test){
    var self = this;
    var app = express();
    var server = http.createServer(app);
    var tracer1, tracer2;
    var i = 0;

    app.use(express.bodyParser());

    app.post('/3/trace', function(request, response) {
      i++;
      test.equal(request.headers['x-auth-token'], '1');
      test.equal(request.headers['x-tenant-id'], '3');
      test.equal(request.headers['content-type'], 'application/json');
      test.notEqual(request.headers['content-length'], '0');
      assert_is_json_array(test, request.body);

      response.end('done');

      if (i === 2) {
        server.close();
      }
    });

    server.on('close', function(){
      test.done();
    });

    server.listen(22222, 'localhost');

    // Valid URL
    tracer1 = new node_tracers.RESTkinTracer('http://localhost:22222',
                                             mockKeystoneClient);

    // Valid URL with trailing slash
    tracer2 = new node_tracers.RESTkinTracer('http://localhost:22222/',
                                             mockKeystoneClient);

    tracer1.record(self.trace, self.annotation);
    tracer2.record(self.trace, self.annotation);
  },
  test_restkin_tracer_server_connection_to_server_refused: function(test) {
    var tracer;

    tracer = new node_tracers.RESTkinTracer('http://localhost:1898/',
                                            mockKeystoneClient);

    tracer.record(this.trace, this.annotation);
    test.done();
  },
  test_zipkin_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('zipkin');
    s.assert_base64();
    test.done();
  },
  test_zipkin_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.ZipkinTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_base64();
    test.done();
  },
  test_restkin_scribe_tracer_default_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s);
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('restkin');
    s.assert_json();
    test.done();
  },
  test_restkin_scribe_tracer_provided_category: function(test){
    var self = this;
    var s = new FakeScribe(test);
    var t = new node_tracers.RESTkinScribeTracer(s, 'mycategory');
    t.record(self.trace, self.annotation);
    s.assert_sent();
    s.assert_category('mycategory');
    s.assert_json();
    test.done();
  }
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var jsonStableStringify = require('json-stable-stringify');
var glob = require('glob');
var timeout = require('connect-timeout');

var jsonStableStringifyConfig = {
  space: '  ',
  cmp: function(a, b) {
    return a.key < b.key ? -1 : 1;
  },
};
function stringify(data) {
  return jsonStableStringify(data, jsonStableStringifyConfig);
}

var NameRewriter = require('object-graph-js').NameRewriter;

var app = express();
var nameRewriter = new NameRewriter();

app.use(bodyParser.urlencoded({extended: false, limit: '500mb'}));

app.use(express.static('static'));

var DATA_DIR = './data';
var OG_DATA_DIR = './data/og';
var HTML_HEAD = '' +
      '<meta name="viewport" content="width=500, initial-scale=1">' +
      '';
var HTML_FOOT = '';

var list;
try {
  list = JSON.parse(fs.readFileSync(DATA_DIR + '/list.json'));
} catch (e) {
  list = {};
  fs.writeFileSync(DATA_DIR + '/list.json', stringify(list));
}

/**
 * Browser product info.
 * @constructor
 * @param {(Array|Object)} opts - [nameStr, versionStr] or { name, version }
 */
function ProductInfo(opts) {
  opts = opts || {};
  if (Array.isArray(opts)) {
    this.name = opts[0] || '';
    this.version = opts[1] || '';
  } else {
    this.name = opts.name || '';
    this.version = opts.version || '';
  }
}

ProductInfo.prototype.toArray = function() {
  return [this.name, this.version];
};

/**
 * Browser environment info.
 * @constructor
 * @param {(Array|Object)} opts - [browserNameStr, browserVersionStr,
 *                                platformNameStr, platformNameStr] or
 *                                { browser: { name, version },
 *                                  platform: { name, version } }
 */
function Environment(opts) {
  opts = opts || {};
  if (Array.isArray(opts)) {
    this.browser = new ProductInfo(opts.slice(0, 2));
    this.platform = new ProductInfo(opts.slice(2));
  } else {
    this.browser = new ProductInfo(opts.browser);
    this.platform = new ProductInfo(opts.platform);
  }
}

Environment.prototype.toArray = function() {
  return this.browser.toArray().concat(this.platform.toArray());
};

Environment.prototype.getJSONFileName = function() {
  return 'window_' + this.browser.name + '_' + this.browser.version +
    '_' + this.platform.name + '_' + this.platform.version + '.json';
};

function declFromJSON(ctor) {
  ctor.fromJSON = function(data) {
    var o = Object.create(ctor.prototype);
    ctor.apply(o, JSON.parse(data));
  };
}
declFromJSON(ProductInfo);
declFromJSON(Environment);

function hasPath(data, keys) {
  for (var i = 0; i < keys.length - 1; i++) {
    data = data[keys[i]];
    if (!data) return false;
  }
  return Boolean(data);
}

function ensurePath(data, keys) {
  for (var i = 0; i < keys.length - 1; i++) {
    data = data[keys[i]] = data[keys[i]] || {};
  }
  if (data[keys[keys.length - 1]])
    return true;

  data[keys[keys.length - 1]] = 1;
  return false;
}

/**
 * Respond to request with JSON data.
 * @param {Object} data - The data to send
 * @param {Response} res - The express response object for server request
 */
function sendJSON(data, res) {
  var str = (typeof data === 'string' || data instanceof Buffer) ?
        stringify(JSON.parse(data)) :
        stringify(data);
  res.setHeader('Content-Type', 'application/json');
  res.send(str);
}

/**
 * Respond to request with HTML data.
 * @param {String} str - The HTML to send
 * @param {Response} res - The express response object for server request
 */
function sendHTML(str, res) {
  res.send(HTML_HEAD + str + HTML_FOOT);
}

/**
 * Update internal list of object graph data stored by this server.
 * @param {Object} env - The environment for which data has been added
 * @return {Boolean} - Whether or not the list was updated successfully
 */
function updateList(env) {
  try {
    var dataExists = ensurePath(list, env.toArray());
    fs.writeFileSync(DATA_DIR + '/list.json', stringify(list));
    return !dataExists;
  } catch (e) {
    console.error(e);
    return false;
  }
}

/**
 * Get object graph data.
 * @param {Environment} info - The requested browser environment
 * @return {Buffer} - The requested data in a JSON string buffer
 */
function getData(info) {
  return fs.readFileSync(OG_DATA_DIR + '/' + info.getJSONFileName());
}

app.post('/save', timeout('30s'), function(req, res) {
  if (!(req.body && req.body.data)) {
    sendHTML('No data saved: No data found.', res);
    return;
  }

  var ua = req.headers['user-agent'];
  var env = new Environment(nameRewriter.userAgentAsPlatformInfo(ua));
  var jsonFileName = env.getJSONFileName();
  var path = OG_DATA_DIR + '/' + jsonFileName;

  fs.stat(path, function(err) {
    if (err && err.code !== 'ENOENT') {
      console.error(err);
      sendHTML('Error: ' + err.toString(), res);
    } else if (err) {
      var dataStr = stringify(JSON.parse(req.body.data));
      fs.writeFileSync(path, dataStr);
      updateList(env);
      sendHTML('Saved data (' + dataStr.length + ' characters of JSON)',
               res);
    } else {
      sendHTML('No data saved: Data for this platform already recorded', res);
    }
  });
});

app.get('/list', function(req, res) {
  glob('./data/og/window_*.json', function(err, files) {
    if (err) {
      console.error(err);
      sendJSON([], res);
      return;
    }

    sendJSON(files.map(function(file) {
      var parts = file.split('_');
      // 4 platform/browser/version parts.
      parts = parts.slice(parts.length - 4);
      // Drop ".json".
      var last = parts[parts.length - 1];
      last = last.substr(0, last.length - '.json'.length);
      parts[parts.length - 1] = last;
      return parts.join(' ');
    }), res);
  });
});

app.get(
    /^\/data\/og\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/?$/,
  function(req, res) {
    var parts = req.url.split('/');
    var env = new Environment(parts.slice(3));

    fs.stat(
      OG_DATA_DIR + '/' + env.getJSONFileName(),
      function(err) {
        if (err) sendJSON(null, res);
        else sendJSON(getData(env), res);
      }
    );
  });

app.listen(8000, function() {
  console.log('Listening...');
});
<commit_msg>Get rid of leftover data/list.json stuff in serve.js<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var jsonStableStringify = require('json-stable-stringify');
var glob = require('glob');
var timeout = require('connect-timeout');

var jsonStableStringifyConfig = {
  space: '  ',
  cmp: function(a, b) {
    return a.key < b.key ? -1 : 1;
  },
};
function stringify(data) {
  return jsonStableStringify(data, jsonStableStringifyConfig);
}

var NameRewriter = require('object-graph-js').NameRewriter;

var app = express();
var nameRewriter = new NameRewriter();

app.use(bodyParser.urlencoded({extended: false, limit: '500mb'}));

app.use(express.static('static'));

var DATA_DIR = './data';
var OG_DATA_DIR = './data/og';
var HTML_HEAD = '' +
      '<meta name="viewport" content="width=500, initial-scale=1">' +
      '';
var HTML_FOOT = '';

/**
 * Browser product info.
 * @constructor
 * @param {(Array|Object)} opts - [nameStr, versionStr] or { name, version }
 */
function ProductInfo(opts) {
  opts = opts || {};
  if (Array.isArray(opts)) {
    this.name = opts[0] || '';
    this.version = opts[1] || '';
  } else {
    this.name = opts.name || '';
    this.version = opts.version || '';
  }
}

ProductInfo.prototype.toArray = function() {
  return [this.name, this.version];
};

/**
 * Browser environment info.
 * @constructor
 * @param {(Array|Object)} opts - [browserNameStr, browserVersionStr,
 *                                platformNameStr, platformNameStr] or
 *                                { browser: { name, version },
 *                                  platform: { name, version } }
 */
function Environment(opts) {
  opts = opts || {};
  if (Array.isArray(opts)) {
    this.browser = new ProductInfo(opts.slice(0, 2));
    this.platform = new ProductInfo(opts.slice(2));
  } else {
    this.browser = new ProductInfo(opts.browser);
    this.platform = new ProductInfo(opts.platform);
  }
}

Environment.prototype.toArray = function() {
  return this.browser.toArray().concat(this.platform.toArray());
};

Environment.prototype.getJSONFileName = function() {
  return 'window_' + this.browser.name + '_' + this.browser.version +
    '_' + this.platform.name + '_' + this.platform.version + '.json';
};

function declFromJSON(ctor) {
  ctor.fromJSON = function(data) {
    var o = Object.create(ctor.prototype);
    ctor.apply(o, JSON.parse(data));
  };
}
declFromJSON(ProductInfo);
declFromJSON(Environment);

function hasPath(data, keys) {
  for (var i = 0; i < keys.length - 1; i++) {
    data = data[keys[i]];
    if (!data) return false;
  }
  return Boolean(data);
}

function ensurePath(data, keys) {
  for (var i = 0; i < keys.length - 1; i++) {
    data = data[keys[i]] = data[keys[i]] || {};
  }
  if (data[keys[keys.length - 1]])
    return true;

  data[keys[keys.length - 1]] = 1;
  return false;
}

/**
 * Respond to request with JSON data.
 * @param {Object} data - The data to send
 * @param {Response} res - The express response object for server request
 */
function sendJSON(data, res) {
  var str = (typeof data === 'string' || data instanceof Buffer) ?
        stringify(JSON.parse(data)) :
        stringify(data);
  res.setHeader('Content-Type', 'application/json');
  res.send(str);
}

/**
 * Respond to request with HTML data.
 * @param {String} str - The HTML to send
 * @param {Response} res - The express response object for server request
 */
function sendHTML(str, res) {
  res.send(HTML_HEAD + str + HTML_FOOT);
}

/**
 * Get object graph data.
 * @param {Environment} info - The requested browser environment
 * @return {Buffer} - The requested data in a JSON string buffer
 */
function getData(info) {
  return fs.readFileSync(OG_DATA_DIR + '/' + info.getJSONFileName());
}

app.post('/save', timeout('30s'), function(req, res) {
  if (!(req.body && req.body.data)) {
    sendHTML('No data saved: No data found.', res);
    return;
  }

  var ua = req.headers['user-agent'];
  var env = new Environment(nameRewriter.userAgentAsPlatformInfo(ua));
  var jsonFileName = env.getJSONFileName();
  var path = OG_DATA_DIR + '/' + jsonFileName;

  fs.stat(path, function(err) {
    if (err && err.code !== 'ENOENT') {
      console.error(err);
      sendHTML('Error: ' + err.toString(), res);
    } else if (err) {
      var dataStr = stringify(JSON.parse(req.body.data));
      fs.writeFileSync(path, dataStr);
      sendHTML('Saved data (' + dataStr.length + ' characters of JSON)',
               res);
    } else {
      sendHTML('No data saved: Data for this platform already recorded', res);
    }
  });
});

app.get('/list', function(req, res) {
  glob('./data/og/window_*.json', function(err, files) {
    if (err) {
      console.error(err);
      sendJSON([], res);
      return;
    }

    sendJSON(files.map(function(file) {
      var parts = file.split('_');
      // 4 platform/browser/version parts.
      parts = parts.slice(parts.length - 4);
      // Drop ".json".
      var last = parts[parts.length - 1];
      last = last.substr(0, last.length - '.json'.length);
      parts[parts.length - 1] = last;
      return parts.join(' ');
    }), res);
  });
});

app.get(
    /^\/data\/og\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/[A-Za-z0-9.]+\/?$/,
  function(req, res) {
    var parts = req.url.split('/');
    var env = new Environment(parts.slice(3));

    fs.stat(
      OG_DATA_DIR + '/' + env.getJSONFileName(),
      function(err) {
        if (err) sendJSON(null, res);
        else sendJSON(getData(env), res);
      }
    );
  });

app.listen(8000, function() {
  console.log('Listening...');
});
<|endoftext|>