<commit_before>var baseKarma = require('./base-karma')

module.exports = function(config) {

  var baseConfig = baseKarma(config);

  config.set(Object.assign(baseConfig, {
    browsers: [
      'bs_firefox_android',
      'bs_firefox_windows',
      'bs_chrome_mac',
      'bs_safari_mac',
      'bs_ie_11',
      'bs_edge'
    ],
    reporters: [
      'mocha', 'BrowserStack'
    ],
    client: {
      mocha: {
        reporter: 'html'
      }
    },
    browserStack: {
      startTunnel: true
    },
    customLaunchers: {
      bs_firefox_android: {
        base: 'BrowserStack',
        browser: 'Android Browser',
        real_mobile: true,
        device: 'Samsung Galaxy S8',
        os: 'android',
        os_version: '7.0'
      },
      bs_firefox_windows: {
        base: 'BrowserStack',
        browser: 'firefox',
        browser_version: '60.0',
        os: 'Windows',
        os_version: '10'
      },
      bs_chrome_mac: {
        base: 'BrowserStack',
        browser: 'Chrome',
        browser_version: '66',
        os: 'OS X',
        os_version: 'High Sierra'
      },
      bs_safari_mac: {
        base: 'BrowserStack',
        browser: 'Safari',
        browser_version: '11.1',
        os: 'OS X',
        os_version: 'High Sierra'
      },
      bs_ie_11: {
        base: 'BrowserStack',
        browser: 'IE',
        browser_version: '11',
        os: 'Windows',
        os_version: '10'
      },
      bs_edge: {
        base: 'BrowserStack',
        browser: 'Edge',
        browser_version: '17',
        os: 'Windows',
        os_version: '10'
      }
    }
  }));

};
<commit_msg>Update testing to chrome v67<commit_after>var baseKarma = require('./base-karma')

module.exports = function(config) {

  var baseConfig = baseKarma(config);

  config.set(Object.assign(baseConfig, {
    browsers: [
      'bs_firefox_android',
      'bs_firefox_windows',
      'bs_chrome_mac',
      'bs_safari_mac',
      'bs_ie_11',
      'bs_edge'
    ],
    reporters: [
      'mocha', 'BrowserStack'
    ],
    client: {
      mocha: {
        reporter: 'html'
      }
    },
    browserStack: {
      startTunnel: true
    },
    customLaunchers: {
      bs_firefox_android: {
        base: 'BrowserStack',
        browser: 'Android Browser',
        real_mobile: true,
        device: 'Samsung Galaxy S8',
        os: 'android',
        os_version: '7.0'
      },
      bs_firefox_windows: {
        base: 'BrowserStack',
        browser: 'firefox',
        browser_version: '60.0',
        os: 'Windows',
        os_version: '10'
      },
      bs_chrome_mac: {
        base: 'BrowserStack',
        browser: 'Chrome',
        browser_version: '67',
        os: 'OS X',
        os_version: 'High Sierra'
      },
      bs_safari_mac: {
        base: 'BrowserStack',
        browser: 'Safari',
        browser_version: '11.1',
        os: 'OS X',
        os_version: 'High Sierra'
      },
      bs_ie_11: {
        base: 'BrowserStack',
        browser: 'IE',
        browser_version: '11',
        os: 'Windows',
        os_version: '10'
      },
      bs_edge: {
        base: 'BrowserStack',
        browser: 'Edge',
        browser_version: '17',
        os: 'Windows',
        os_version: '10'
      }
    }
  }));

};
<|endoftext|>


<commit_before>/**
 * Copyright 2020 Phenix Real Time Solutions, 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.
 */

define([
    'phenix-web-lodash-light'
], function(_) {
    'use strict';

    var environment = {};

    environment.getEnvironmentFromUrl = function(uri) {
        try {
            var baseURL = new URL(uri);

            return baseURL.origin;
        } catch (e) {
            return '';
        }
    };

    environment.parseEnvFromPcastBaseUri = function(uri) {
        uri = uri.toLowerCase();

        if (_.includes(uri, 'local')) {
            return 'local';
        } else if (_.includes(uri, 'stg')) {
            return 'staging';
        }

        return 'production';
    };

    environment.getTelemetryServerUri = function(baseUri) {
        if (!baseUri) {
            return '';
        }

        try {
            var baseURL = new URL(baseUri);
            var segments = baseURL.hostname.split('.');

            if (segments.length === 2 ||
                (segments.length === 3 && segments[segments.length - 2].length <= 2 && segments[segments.length - 1].length <= 3)
            ) {
                segments.unshift('telemetry');
            } else if (_.startsWith(segments[0], 'stg-') || _.endsWith(segments[0], '-stg') || _.includes(segments[0], '-stg-') || segments[0] === 'stg') {
                segments[0] = 'telemetry-stg';
            } else if (_.startsWith(segments[0], 'local') || _.endsWith(segments[0], 'local')) {
                // Leave URL unchanged
            } else {
                segments[0] = 'telemetry';
            }

            baseURL.hostname = segments.join('.');

            switch (baseURL.protocol) {
            case 'ws:':
                baseURL.protocol = 'http:';

                break;
            case 'wss:':
                baseURL.protocol = 'https:';

                break;

            default:
                break;
            }

            return baseURL.origin + '/telemetry';
        } catch (e) {
            return baseUri;
        }
    };

    return environment;
});<commit_msg>Fix telemetry issue for IE (#WSDK-667) Fixed<commit_after>/**
 * Copyright 2020 Phenix Real Time Solutions, 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.
 */

define([
    'phenix-web-lodash-light',
    'phenix-web-detect-browser'
], function(_, DetectBrowser) {
    'use strict';

    var environment = {};
    var browser = new DetectBrowser(navigator.userAgent).detect();

    environment.getEnvironmentFromUrl = function(uri) {
        try {
            var baseURL;

            if (URL && browser.browser !== 'IE') {
                baseURL = new URL(uri);
            } else {
                baseURL = getLocation(uri);
            }

            if (baseURL.port) {
                return baseURL.protocol + '//' + baseURL.hostname + ':' + baseURL.port;
            }

            return baseURL.protocol + '//' + baseURL.hostname;
        } catch (e) {
            return '';
        }
    };

    environment.parseEnvFromPcastBaseUri = function(uri) {
        uri = uri.toLowerCase();

        if (_.includes(uri, 'local')) {
            return 'local';
        } else if (_.includes(uri, 'stg')) {
            return 'staging';
        }

        return 'production';
    };

    environment.getTelemetryServerUri = function(baseUri) {
        if (!baseUri) {
            return '';
        }

        try {
            var baseURL;

            if (URL && browser.browser !== 'IE') {
                baseURL = new URL(baseUri);
            } else {
                baseURL = getLocation(baseUri);
            }

            var segments = baseURL.hostname.split('.');

            if (segments.length === 2 ||
                (segments.length === 3 && segments[segments.length - 2].length <= 2 && segments[segments.length - 1].length <= 3)
            ) {
                segments.unshift('telemetry');
            } else if (_.startsWith(segments[0], 'stg-') || _.endsWith(segments[0], '-stg') || _.includes(segments[0], '-stg-') || segments[0] === 'stg') {
                segments[0] = 'telemetry-stg';
            } else if (_.startsWith(segments[0], 'local') || _.endsWith(segments[0], 'local')) {
                // Leave URL unchanged
            } else {
                segments[0] = 'telemetry';
            }

            baseURL.hostname = segments.join('.');

            switch (baseURL.protocol) {
            case 'ws:':
                baseURL.protocol = 'http:';

                break;
            case 'wss:':
                baseURL.protocol = 'https:';

                break;

            default:
                break;
            }

            if (baseURL.port) {
                return baseURL.protocol + '//' + baseURL.hostname + ':' + baseURL.port + '/telemetry';
            }

            return baseURL.protocol + '//' + baseURL.hostname + '/telemetry';
        } catch (e) {
            return baseUri;
        }
    };

    function getLocation(url) {
        var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/); // eslint-disable-line

        return match && {
            href: url,
            protocol: match[1],
            host: match[2],
            hostname: match[3],
            port: match[4],
            pathname: match[5],
            search: match[6],
            hash: match[7],
            origin: match[1] + '//' + match[2]
        };
    }

    return environment;
});<|endoftext|>


<commit_before>(function() {
	var ThreeVRCameraPlugin = E2.plugins.three_vr_camera = function(core) {
		Plugin.apply(this, arguments)

		this.desc = 'THREE.js VR Camera'

		this.defaultFOV = 90

		// try to find out default fov from the device
		if (window.HMDVRDevice && window.HMDVRDevice.getEyeParameters) {
			var eyeParams = window.HMDVRDevice.getEyeParameters()

			if (eyeParams.recommendedFieldOfView) {
				this.defaultFOV = eyeParams.recommendedFieldOfView
			}
			else if (eyeParams.leftDegrees && eyeParams.rightDegrees) {
				this.defaultFOV = eyeParams.leftDegrees + eyeParams.rightDegrees
			}
		}

		this.input_slots = [
			{ name: 'position', dt: core.datatypes.VECTOR },
			{ name: 'rotation', dt: core.datatypes.VECTOR },
			{ name: 'fov', dt: core.datatypes.FLOAT, def: this.defaultFOV },
			{ name: 'aspectRatio', dt: core.datatypes.FLOAT, def: 1.0},
			{ name: 'near', dt: core.datatypes.FLOAT, def: 0.001 },
			{ name: 'far', dt: core.datatypes.FLOAT, def: 1000.0 }
		]

		this.output_slots = [
			{name: 'camera',	dt: core.datatypes.CAMERA},
			{name: 'position',	dt: core.datatypes.VECTOR},
			{name: 'rotation',	dt: core.datatypes.VECTOR}
		]

		this.always_update = true
		this.dirty = false

		this.state = {
			position: {x: 0, y: 0, z:0},

			// names with underscores have to match with THREE.Quaternion
			// member variable names because of to/from json serialisation
			quaternion: {_x: 0, _y: 0, _z:0, _w:1}
		}

		this.rotationFromGraph = new THREE.Euler()
	}

	ThreeVRCameraPlugin.prototype = Object.create(Plugin.prototype)

	ThreeVRCameraPlugin.prototype.reset = function() {
		Plugin.prototype.reset.apply(this, arguments)

		this.domElement = E2.dom.webgl_canvas[0]

		if (!this.perspectiveCamera) {
			this.perspectiveCamera = new THREE.PerspectiveCamera(
					this.defaultFOV,
					this.domElement.clientWidth / this.domElement.clientHeight,
					0.001,
					1000)
		}

		// create a object3d reference so that the world editor sees the camera
		// as an object3d
		this.object3d = this.perspectiveCamera

		this.perspectiveCamera.backReference = this

		if (!this.controls) {
			this.controls = new THREE.VRControls(this.perspectiveCamera)
		}

		this.perspectiveCamera.position.set(this.state.position.x, this.state.position.y, this.state.position.z)
		this.perspectiveCamera.quaternion.set(this.state.quaternion._x, this.state.quaternion._y, this.state.quaternion._z, this.state.quaternion._w)
	}

	ThreeVRCameraPlugin.prototype.play = function() {
		this.resize()
	}

	ThreeVRCameraPlugin.prototype.resize = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement);
		var wh = { width: window.innerWidth, height: window.innerHeight }

		if (!isFullscreen) {
			wh.width = this.domElement.clientWidth
			wh.height = this.domElement.clientHeight

			if (typeof(E2.app.calculateCanvasArea) !== 'undefined')
				wh = E2.app.calculateCanvasArea()
		}

		this.perspectiveCamera.aspect = wh.width / wh.height
		this.perspectiveCamera.updateProjectionMatrix()
	}

	ThreeVRCameraPlugin.prototype.update_state = function() {
		this.perspectiveCamera.position.set(this.state.position.x, this.state.position.y, this.state.position.z)
		this.perspectiveCamera.quaternion.set(this.state.quaternion._x, this.state.quaternion._y, this.state.quaternion._z, this.state.quaternion._w)

		var eulerRotation = new THREE.Euler().setFromQuaternion(this.perspectiveCamera.quaternion)
		this.rotationFromGraph.set(eulerRotation.x, eulerRotation.y, eulerRotation.z)

		if (this.dirty)
			this.perspectiveCamera.updateProjectionMatrix()

		this.perspectiveCamera.updateMatrixWorld()

		this.controls.update(this.positionFromGraph, this.rotationFromGraph)
	}

	ThreeVRCameraPlugin.prototype.update_input = function(slot, data) {
		if (!this.perspectiveCamera) {
			return
		}

		switch(slot.index) {
		case 0: // position
			this.positionFromGraph = data
			//this.perspectiveCamera.position.set(data.x, data.y, data.z)
			this.state.position.x = data.x
			this.state.position.y = data.y
			this.state.position.z = data.z
			this.dirty = true
			break
		case 1: // rotation
			var temp = new THREE.Quaternion().setFromEuler(new THREE.Euler(data.x, data.y, data.z))
			this.state.quaternion._x = temp._x
			this.state.quaternion._y = temp._y
			this.state.quaternion._z = temp._z
			this.state.quaternion._w = temp._w

			this.dirty = true
			break
		case 2: // fov
			this.perspectiveCamera.fov = data
			this.dirty = true
			break
		case 3: // aspect ratio
			this.perspectiveCamera.aspectRatio = data
			this.dirty = true
			break
		case 4: // near
			this.perspectiveCamera.near = data
			this.dirty = true
			break
		case 5: // far
			this.perspectiveCamera.far = data
			this.dirty = true
			break
		default:
			break
		}
	}

	ThreeVRCameraPlugin.prototype.update_output = function(slot) {
		if (slot.index === 0) { // camera
			return this.perspectiveCamera
		}
		else if (slot.index === 1) { // position
			return this.perspectiveCamera.position
		}
		else if (slot.index === 2) { // rotation
			var euler = new THREE.Euler().setFromQuaternion(this.perspectiveCamera.quaternion)
			return new THREE.Vector3(euler.x, euler.y, euler.z)
		}
	}

	ThreeVRCameraPlugin.prototype.state_changed = function(ui) {
		if (!ui) {
			E2.core.on('resize', this.resize.bind(this))
		}
	}

})()

<commit_msg>default positionFromGraph to empty Vec3<commit_after>(function() {
	var ThreeVRCameraPlugin = E2.plugins.three_vr_camera = function(core) {
		Plugin.apply(this, arguments)

		this.desc = 'THREE.js VR Camera'

		this.defaultFOV = 90

		// try to find out default fov from the device
		if (window.HMDVRDevice && window.HMDVRDevice.getEyeParameters) {
			var eyeParams = window.HMDVRDevice.getEyeParameters()

			if (eyeParams.recommendedFieldOfView) {
				this.defaultFOV = eyeParams.recommendedFieldOfView
			}
			else if (eyeParams.leftDegrees && eyeParams.rightDegrees) {
				this.defaultFOV = eyeParams.leftDegrees + eyeParams.rightDegrees
			}
		}

		this.input_slots = [
			{ name: 'position', dt: core.datatypes.VECTOR },
			{ name: 'rotation', dt: core.datatypes.VECTOR },
			{ name: 'fov', dt: core.datatypes.FLOAT, def: this.defaultFOV },
			{ name: 'aspectRatio', dt: core.datatypes.FLOAT, def: 1.0},
			{ name: 'near', dt: core.datatypes.FLOAT, def: 0.001 },
			{ name: 'far', dt: core.datatypes.FLOAT, def: 1000.0 }
		]

		this.output_slots = [
			{name: 'camera',	dt: core.datatypes.CAMERA},
			{name: 'position',	dt: core.datatypes.VECTOR},
			{name: 'rotation',	dt: core.datatypes.VECTOR}
		]

		this.always_update = true
		this.dirty = false

		this.state = {
			position: {x: 0, y: 0, z:0},

			// names with underscores have to match with THREE.Quaternion
			// member variable names because of to/from json serialisation
			quaternion: {_x: 0, _y: 0, _z:0, _w:1}
		}

		this.rotationFromGraph = new THREE.Euler()
		this.positionFromGraph = new THREE.Vector3()
	}

	ThreeVRCameraPlugin.prototype = Object.create(Plugin.prototype)

	ThreeVRCameraPlugin.prototype.reset = function() {
		Plugin.prototype.reset.apply(this, arguments)

		this.domElement = E2.dom.webgl_canvas[0]

		if (!this.perspectiveCamera) {
			this.perspectiveCamera = new THREE.PerspectiveCamera(
					this.defaultFOV,
					this.domElement.clientWidth / this.domElement.clientHeight,
					0.001,
					1000)
		}

		// create a object3d reference so that the world editor sees the camera
		// as an object3d
		this.object3d = this.perspectiveCamera

		this.perspectiveCamera.backReference = this

		if (!this.controls) {
			this.controls = new THREE.VRControls(this.perspectiveCamera)
		}

		this.perspectiveCamera.position.set(this.state.position.x, this.state.position.y, this.state.position.z)
		this.perspectiveCamera.quaternion.set(this.state.quaternion._x, this.state.quaternion._y, this.state.quaternion._z, this.state.quaternion._w)
	}

	ThreeVRCameraPlugin.prototype.play = function() {
		this.resize()
	}

	ThreeVRCameraPlugin.prototype.resize = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement);
		var wh = { width: window.innerWidth, height: window.innerHeight }

		if (!isFullscreen) {
			wh.width = this.domElement.clientWidth
			wh.height = this.domElement.clientHeight

			if (typeof(E2.app.calculateCanvasArea) !== 'undefined')
				wh = E2.app.calculateCanvasArea()
		}

		this.perspectiveCamera.aspect = wh.width / wh.height
		this.perspectiveCamera.updateProjectionMatrix()
	}

	ThreeVRCameraPlugin.prototype.update_state = function() {
		this.perspectiveCamera.position.set(this.state.position.x, this.state.position.y, this.state.position.z)
		this.perspectiveCamera.quaternion.set(this.state.quaternion._x, this.state.quaternion._y, this.state.quaternion._z, this.state.quaternion._w)

		var eulerRotation = new THREE.Euler().setFromQuaternion(this.perspectiveCamera.quaternion)
		this.rotationFromGraph.set(eulerRotation.x, eulerRotation.y, eulerRotation.z)

		if (this.dirty)
			this.perspectiveCamera.updateProjectionMatrix()

		this.perspectiveCamera.updateMatrixWorld()

		this.controls.update(this.positionFromGraph, this.rotationFromGraph)
	}

	ThreeVRCameraPlugin.prototype.update_input = function(slot, data) {
		if (!this.perspectiveCamera) {
			return
		}

		switch(slot.index) {
		case 0: // position
			this.positionFromGraph = data
			//this.perspectiveCamera.position.set(data.x, data.y, data.z)
			this.state.position.x = data.x
			this.state.position.y = data.y
			this.state.position.z = data.z
			this.dirty = true
			break
		case 1: // rotation
			var temp = new THREE.Quaternion().setFromEuler(new THREE.Euler(data.x, data.y, data.z))
			this.state.quaternion._x = temp._x
			this.state.quaternion._y = temp._y
			this.state.quaternion._z = temp._z
			this.state.quaternion._w = temp._w

			this.dirty = true
			break
		case 2: // fov
			this.perspectiveCamera.fov = data
			this.dirty = true
			break
		case 3: // aspect ratio
			this.perspectiveCamera.aspectRatio = data
			this.dirty = true
			break
		case 4: // near
			this.perspectiveCamera.near = data
			this.dirty = true
			break
		case 5: // far
			this.perspectiveCamera.far = data
			this.dirty = true
			break
		default:
			break
		}
	}

	ThreeVRCameraPlugin.prototype.update_output = function(slot) {
		if (slot.index === 0) { // camera
			return this.perspectiveCamera
		}
		else if (slot.index === 1) { // position
			return this.perspectiveCamera.position
		}
		else if (slot.index === 2) { // rotation
			var euler = new THREE.Euler().setFromQuaternion(this.perspectiveCamera.quaternion)
			return new THREE.Vector3(euler.x, euler.y, euler.z)
		}
	}

	ThreeVRCameraPlugin.prototype.state_changed = function(ui) {
		if (!ui) {
			E2.core.on('resize', this.resize.bind(this))
		}
	}

})()

<|endoftext|>


<commit_before>#! /usr/bin/env node

'use strict'

const minimist = require('minimist')
const fs = require('fs')
const path = require('path')
const help = fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf8')
const run = require('./lib/run')
const track = require('./lib/progressTracker')

module.exports = run
module.exports.track = track

function start () {
  const argv = minimist(process.argv.slice(2), {
    boolean: ['json', 'n', 'help', 'renderLatencyTable', 'renderProgressBar'],
    alias: {
      connections: 'c',
      pipelining: 'p',
      timeout: 't',
      duration: 'd',
      amount: 'a',
      json: 'j',
      renderLatencyTable: ['l', 'latency'],
      method: 'm',
      headers: ['H', 'header'],
      body: 'b',
      bailout: 'B',
      input: 'i',
      maxConnectionRequests: 'M',
      maxOverallRequests: 'O',
      connectionRate: 'r',
      overallRate: 'R',
      reconnectRate: 'D',
      renderProgressBar: 'progress',
      title: 'T',
      version: 'v',
      help: 'h'
    },
    default: {
      connections: 10,
      timeout: 10,
      pipelining: 1,
      duration: 10,
      reconnectRate: 0,
      renderLatencyTable: false,
      renderProgressBar: true,
      json: false,
      method: 'GET'
    }
  })

  argv.url = argv._[0]

  // support -n to disable the progress bar
  if (argv.n) {
    argv.renderProgressBar = false
  }

  if (argv.version) {
    console.log('autocannon', 'v' + require('./package').version)
    console.log('node', process.version)
    return
  }

  if (!argv.url || argv.help) {
    console.error(help)
    return
  }

  if (argv.input) {
    argv.body = fs.readFileSync(argv.input)
  }

  if (argv.headers) {
    if (!Array.isArray(argv.headers)) {
      argv.headers = [argv.headers]
    }

    argv.headers = argv.headers.reduce((obj, header) => {
      const split = header.split('=')
      obj[split[0]] = split[1]
      return obj
    }, {})
  }

  const tracker = run(argv, (err, result) => {
    if (err) {
      throw err
    }

    if (argv.json) {
      console.log(JSON.stringify(result))
    }
  })

  // if not rendering json, or if std isn't a tty, track progress
  if (!argv.json || !process.stdout.isTTY) track(tracker, argv)

  process.once('SIGINT', () => {
    tracker.stop()
  })
}

if (require.main === module) {
  start()
}
<commit_msg>don't render results table when -n arg is passed<commit_after>#! /usr/bin/env node

'use strict'

const minimist = require('minimist')
const fs = require('fs')
const path = require('path')
const help = fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf8')
const run = require('./lib/run')
const track = require('./lib/progressTracker')

module.exports = run
module.exports.track = track

function start () {
  const argv = minimist(process.argv.slice(2), {
    boolean: ['json', 'n', 'help', 'renderLatencyTable', 'renderProgressBar'],
    alias: {
      connections: 'c',
      pipelining: 'p',
      timeout: 't',
      duration: 'd',
      amount: 'a',
      json: 'j',
      renderLatencyTable: ['l', 'latency'],
      method: 'm',
      headers: ['H', 'header'],
      body: 'b',
      bailout: 'B',
      input: 'i',
      maxConnectionRequests: 'M',
      maxOverallRequests: 'O',
      connectionRate: 'r',
      overallRate: 'R',
      reconnectRate: 'D',
      renderProgressBar: 'progress',
      title: 'T',
      version: 'v',
      help: 'h'
    },
    default: {
      connections: 10,
      timeout: 10,
      pipelining: 1,
      duration: 10,
      reconnectRate: 0,
      renderLatencyTable: false,
      renderProgressBar: true,
      json: false,
      method: 'GET'
    }
  })

  argv.url = argv._[0]

  // support -n to disable the progress bar and results table
  if (argv.n) {
    argv.renderProgressBar = false
    opts.renderResultsTable = false
  }

  if (argv.version) {
    console.log('autocannon', 'v' + require('./package').version)
    console.log('node', process.version)
    return
  }

  if (!argv.url || argv.help) {
    console.error(help)
    return
  }

  if (argv.input) {
    argv.body = fs.readFileSync(argv.input)
  }

  if (argv.headers) {
    if (!Array.isArray(argv.headers)) {
      argv.headers = [argv.headers]
    }

    argv.headers = argv.headers.reduce((obj, header) => {
      const split = header.split('=')
      obj[split[0]] = split[1]
      return obj
    }, {})
  }

  const tracker = run(argv, (err, result) => {
    if (err) {
      throw err
    }

    if (argv.json) {
      console.log(JSON.stringify(result))
    }
  })

  // if not rendering json, or if std isn't a tty, track progress
  if (!argv.json || !process.stdout.isTTY) track(tracker, argv)

  process.once('SIGINT', () => {
    tracker.stop()
  })
}

if (require.main === module) {
  start()
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore')
  , async = require('async')
  , glob = require('glob')
  , util = require('gulp-util')
  , format = require('./tasks/format')
  , clean = require('./tasks/clean')
  , build = require('./tasks/build')
  , server = require('./tasks/server')
  , complexity = require('./tasks/complexity')
  , coveralls = require('./tasks/coveralls')
  , tag = require('./tasks/tag')
  , karma = require('karma');

module.exports = function(gulp, options) {
  var options = format(options);

  function error(err) {
    if (err) {
      util.log(util.colors.red(err));
      process.exit(1);
    }
  }

  gulp.task('dev', function(cb) {
    async.series({
      'clean': clean.bind(null, {src: options.dirs.build})
    , 'build': build.all.bind(null, {dest: options.dirs.build, watch: true}, options)
    , 'notifier': server.bind(null, _.extend(options.server, {src: options.dirs.build}))
    }, function(err, r) {
      if (err) return error(err);

      gulp.watch(
        options.css.src
      , build.css.bind(null, _.extend(options.css, {dest: options.dirs.build, name: options.name}), null)
      );
      gulp.watch(
        options.html.src
      , build.html.bind(null, {src: options.html.src, dest: options.dirs.build}, null)
      );

      gulp.watch(options.dirs.build + '**/*', r.notifier);

      cb();
    });
  });

  gulp.task('dev:unit', ['dev'], function(cb) {
    build.js(_.extend(options.test.unit, {dest: options.dirs.build, watch: true}), function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: false
      , autoWatch: true
      , files: [options.dirs.build + '/*.js']
      };

      karma.server.start(_.extend(options.karma, karmaOptions), cb);
    });
  });

  gulp.task('dist:build', function(cb) {
    async.series([
      clean.bind(null, {src: options.dirs.dist})
    , build.all.bind(null, {dest: options.dirs.dist, min: true}, options)
    ], function(err) {
      if (err) return error(err);

      util.log(util.colors.green('Distribution ready in ' + options.dirs.dist));

      cb();
    });
  });

  gulp.task('dist:serve', ['dist:build'], function(cb) {
    server(_.extend(options.server, {src: options.dirs.dist}), cb);
  });

  gulp.task('complexity:report', function() {
    complexity(_.extend(options.js, {dest: options.dirs.complexity}));
  });

  gulp.task('complexity:serve', ['complexity:report'], function(cb) {
    server(_.extend(options.server, {src: options.dirs.complexity}), cb);
  });

  gulp.task('coverage:report', function(cb) {
    async.parallel([
      clean.bind(null, {src: options.dirs.coverage})
    , build.js.bind(null, _.extend(options.js, {dest: options.dirs.build, coverage: true}))
    , build.js.bind(null, _.extend(options.test.unit, {dest: options.dirs.build}))
    ], function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: true
      , autoWatch: false
      , files: [options.dirs.build + '/*.js']
      , reporters: ['progress', 'coverage']
      , coverageReporter: {type : 'html', dir : options.dirs.coverage}
      };

      karma.server.start(_.extend(options.karma, karmaOptions), cb);
    });
  });

  gulp.task('coverage:serve', ['coverage:report'], function(cb) {
    glob(options.dirs.coverage + '/PhantomJS*', function(err, files) {
      if (err || files.length !== 1) return error(err);

      server(_.extend(options.server, {src: _.first(files)}), cb);
    });
  });

  gulp.task('ci', function(cb) {
    async.series([
      clean.bind(null, {src: options.dirs.dist})
    , build.all.bind(null, {dest: options.dirs.dist, min: true, coverage: true}, options)
    , clean.bind(null, {src: options.dirs.coverage})
    , build.js.bind(null, _.extend(options.test.unit, {dest: options.dirs.dist}))
    ], function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: true
      , autoWatch: false
      , files: [options.dirs.dist + '/*.js']
      , reporters: ['progress', 'coverage']
      , coverageReporter: {type : 'lcov', dir : options.dirs.coverage}
      };

      karma.server.start(
        _.extend(options.karma, karmaOptions)
      , coveralls.bind(null, {src: options.dirs.coverage + '/**/lcov.info'}, cb)
      );
    });
  });

  gulp.task('release', ['dist:build'], function(cb) {
    build.js(_.extend(options.test.unit, {dest: options.dirs.dist}), function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: true
      , autoWatch: false
      , files: [options.dirs.dist + '/*.js']
      };

      karma.server.start(_.extend(options.karma, karmaOptions), function(err) {
        if (err) return error(err);

        var version = options.version;
        tag({src: './**/*', version: version}, function(err) {
          if (err) return error(err);

          util.log(util.colors.green('Release '+ option.version +' committed, tagged & pushed'));

          cb();
        });
      });
    });
  });
};
<commit_msg>rm release task<commit_after>'use strict';

var _ = require('underscore')
  , async = require('async')
  , glob = require('glob')
  , util = require('gulp-util')
  , format = require('./tasks/format')
  , clean = require('./tasks/clean')
  , build = require('./tasks/build')
  , server = require('./tasks/server')
  , complexity = require('./tasks/complexity')
  , coveralls = require('./tasks/coveralls')
  , karma = require('karma');

module.exports = function(gulp, options) {
  var options = format(options);

  function error(err) {
    if (err) {
      util.log(util.colors.red(err));
      process.exit(1);
    }
  }

  gulp.task('dev', function(cb) {
    async.series({
      'clean': clean.bind(null, {src: options.dirs.build})
    , 'build': build.all.bind(null, {dest: options.dirs.build, watch: true}, options)
    , 'notifier': server.bind(null, _.extend(options.server, {src: options.dirs.build}))
    }, function(err, r) {
      if (err) return error(err);

      gulp.watch(
        options.css.src
      , build.css.bind(null, _.extend(options.css, {dest: options.dirs.build, name: options.name}), null)
      );
      gulp.watch(
        options.html.src
      , build.html.bind(null, {src: options.html.src, dest: options.dirs.build}, null)
      );

      gulp.watch(options.dirs.build + '**/*', r.notifier);

      cb();
    });
  });

  gulp.task('dev:unit', ['dev'], function(cb) {
    build.js(_.extend(options.test.unit, {dest: options.dirs.build, watch: true}), function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: false
      , autoWatch: true
      , files: [options.dirs.build + '/*.js']
      };

      karma.server.start(_.extend(options.karma, karmaOptions), cb);
    });
  });

  gulp.task('dist:build', function(cb) {
    async.series([
      clean.bind(null, {src: options.dirs.dist})
    , build.all.bind(null, {dest: options.dirs.dist, min: true}, options)
    ], function(err) {
      if (err) return error(err);

      util.log(util.colors.green('Distribution ready in ' + options.dirs.dist));

      cb();
    });
  });

  gulp.task('dist:serve', ['dist:build'], function(cb) {
    server(_.extend(options.server, {src: options.dirs.dist}), cb);
  });

  gulp.task('complexity:report', function() {
    complexity(_.extend(options.js, {dest: options.dirs.complexity}));
  });

  gulp.task('complexity:serve', ['complexity:report'], function(cb) {
    server(_.extend(options.server, {src: options.dirs.complexity}), cb);
  });

  gulp.task('coverage:report', function(cb) {
    async.parallel([
      clean.bind(null, {src: options.dirs.coverage})
    , build.js.bind(null, _.extend(options.js, {dest: options.dirs.build, coverage: true}))
    , build.js.bind(null, _.extend(options.test.unit, {dest: options.dirs.build}))
    ], function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: true
      , autoWatch: false
      , files: [options.dirs.build + '/*.js']
      , reporters: ['progress', 'coverage']
      , coverageReporter: {type : 'html', dir : options.dirs.coverage}
      };

      karma.server.start(_.extend(options.karma, karmaOptions), cb);
    });
  });

  gulp.task('coverage:serve', ['coverage:report'], function(cb) {
    glob(options.dirs.coverage + '/PhantomJS*', function(err, files) {
      if (err || files.length !== 1) return error(err);

      server(_.extend(options.server, {src: _.first(files)}), cb);
    });
  });

  gulp.task('ci', function(cb) {
    async.series([
      clean.bind(null, {src: options.dirs.dist})
    , build.all.bind(null, {dest: options.dirs.dist, min: true, coverage: true}, options)
    , clean.bind(null, {src: options.dirs.coverage})
    , build.js.bind(null, _.extend(options.test.unit, {dest: options.dirs.dist}))
    ], function(err) {
      if (err) return error(err);

      var karmaOptions = {
        singleRun: true
      , autoWatch: false
      , files: [options.dirs.dist + '/*.js']
      , reporters: ['progress', 'coverage']
      , coverageReporter: {type : 'lcov', dir : options.dirs.coverage}
      };

      karma.server.start(
        _.extend(options.karma, karmaOptions)
      , coveralls.bind(null, {src: options.dirs.coverage + '/**/lcov.info'}, cb)
      );
    });
  });
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    this.taigaContribPlugins = this.taigaContribPlugins || [];

    var pingFederateAuthInfo = {
        slug: "pingfederate-auth",
        name: "Ping Federate Auth",
        type: "auth",
        module: "taigaContrib.pingfederateAuth",
        template: "contrib/ping_federate_auth"
    };

    this.taigaContribPlugins.push(pingFederateAuthInfo);

    var module = angular.module('taigaContrib.pingfederateAuth', []);

    var PingFederateLoginButtonDirective = function(
        $window,
        $params,
        $location,
        $config,
        $events,
        $confirm,
        $auth,
        $navUrls,
        $loader
    ) {
        /**
         *
         */
        var link = function($scope, $el, $attrs) {

            var clientId = $config.get("", null);
            var loginOnSuccess = function(response) {
                var nextUrl = $navUrls.resolve("home");
                if (
                    $params.next &&
                    $params.next !== $navUrls.resolve("login")
                ) {
                    nextUrl = $params.next;
                }

                $events.setupConnection();
                $location.search("next", null);
                $location.search("REF", null);
                $location.search("TargetResource", null);

                var redirectToUri = $location.url(nextUrl).absUrl();
                return $window.location.href = redirectToUri;

            };

            var loginOnError = function(response) {
                $location.search("TargetResource", null);
                $location.search("REF", null);
                $loader.pageLoaded();
                if (response.data.error_message) {
                    return $confirm.notify(
                        "light-error",
                        response.data.error_message
                    );
                }
                return $confirm.notify(
                    "light-error",
                    "Our Oompa Loompas have not been able to get you credentials from Ping Federate."
                );
            };

            var loginWithPingFederateAccount = function() {
                var targetResource = $params.TargetResource;
                var ref = $params.REF;

                if (!(targetResource && ref)) {
                    return;
                }
                $loader.start();
                var data = {
                    targetResource: targetResource,
                    REF: ref
                };
                return $auth.
                    login(data, "pingfederate").
                    then(
                        loginOnSuccess,
                        loginOnError
                    )
                ;
            };

            loginWithPingFederateAccount();
            $el.on(
                "click",
                ".button-auth",
                function(event) {
                    var redirectToUri = $location.url($location.path()).absUrl();

                    var PING_FEDERATE_AUTH_SERVICE_URL = $config.get("pingfederateAuthServiceURL", null);
                    var PING_FEDERATE_TARGET_RESOURCE = $config.get("pingfederateTargetResource", null);
                    var url = "" + PING_FEDERATE_AUTH_SERVICE_URL +
                        "/pf/adapter2adapter" +
                        "?TargetResource=" + PING_FEDERATE_TARGET_RESOURCE
                    ;
                    console.log(redirectToUri);

                    return $window.location.href = url;
                }
            );

            return $scope.$on(
                "$destroy",
                function() { return $el.off(); }
            );
        };

        return {
            link: link,
            restrict: "EA",
            template: ""
        }
    };

    module.directive(
        "tgPingFederateLoginButton",
        [
            "$window",
            '$routeParams',
            "$tgLocation",
            "$tgConfig",
            "$tgEvents",
            "$tgConfirm",
            "$tgAuth",
            "$tgNavUrls",
            "tgLoader",
            PingFederateLoginButtonDirective
        ]
    );

    module.run([
        '$templateCache',
        function($templateCache) {
            return $templateCache.put(
                'contrib/ping_federate_auth',
                '
' +
                    ''+
                        '' +
                        'Login with Ping Federate' +
                    '' +
                '
'
            );
        }
    ]);

}).call(this);
<commit_msg>Update ping_federate_auth.js<commit_after>(function() {
    'use strict';

    this.taigaContribPlugins = this.taigaContribPlugins || [];

    var pingFederateAuthInfo = {
        slug: "pingfederate-auth",
        name: "Ping Federate Auth",
        type: "auth",
        module: "taigaContrib.pingfederateAuth",
        template: "contrib/ping_federate_auth"
    };

    this.taigaContribPlugins.push(pingFederateAuthInfo);

    var module = angular.module('taigaContrib.pingfederateAuth', []);

    var PingFederateLoginButtonDirective = function(
        $window,
        $params,
        $location,
        $config,
        $events,
        $confirm,
        $auth,
        $navUrls,
        $loader
    ) {
        /**
         *
         */
        var link = function($scope, $el, $attrs) {

            var clientId = $config.get("", null);
            var loginOnSuccess = function(response) {
                var nextUrl = $navUrls.resolve("home");
                if (
                    $params.next &&
                    $params.next !== $navUrls.resolve("login")
                ) {
                    nextUrl = $params.next;
                }

                $events.setupConnection();
                $location.search("next", null);
                $location.search("REF", null);
                $location.search("TargetResource", null);

                var redirectToUri = $location.url(nextUrl).absUrl();
                return $window.location.href = redirectToUri;

            };

            var loginOnError = function(response) {
                $location.search("TargetResource", null);
                $location.search("REF", null);
                $loader.pageLoaded();
                if (response.data.error_message) {
                    return $confirm.notify(
                        "light-error",
                        response.data.error_message
                    );
                }
                return $confirm.notify(
                    "light-error",
                    "Our Oompa Loompas have not been able to get you credentials from Ping Federate."
                );
            };

            var loginWithPingFederateAccount = function() {
                var targetResource = $params.TargetResource;
                var ref = $params.REF;

                if (!(targetResource && ref)) {
                    return;
                }
                $loader.start();
                var data = {
                    targetResource: targetResource,
                    REF: ref
                };
                return $auth.
                    login(data, "pingfederate").
                    then(
                        loginOnSuccess,
                        loginOnError
                    )
                ;
            };

            loginWithPingFederateAccount();
            $el.on(
                "click",
                ".button-auth",
                function(event) {
                    var redirectToUri = $location.url($location.path()).absUrl();

                    var PING_FEDERATE_AUTH_SERVICE_URL = $config.get("pingfederateAuthServiceURL", null);
                    var PING_FEDERATE_TARGET_RESOURCE = $config.get("pingfederateTargetResource", null);
                    var url = "" + PING_FEDERATE_AUTH_SERVICE_URL +
                        "/pf/adapter2adapter" +
                        "?TargetResource=" + PING_FEDERATE_TARGET_RESOURCE
                    ;
                    console.log(redirectToUri);

                    return $window.location.href = url;
                }
            );

            return $scope.$on(
                "$destroy",
                function() { return $el.off(); }
            );
        };

        return {
            link: link,
            restrict: "EA",
            template: ""
        }
    };

    module.directive(
        "tgPingFederateLoginButton",
        [
            "$window",
            '$routeParams',
            "$tgLocation",
            "$tgConfig",
            "$tgEvents",
            "$tgConfirm",
            "$tgAuth",
            "$tgNavUrls",
            "tgLoader",
            PingFederateLoginButtonDirective
        ]
    );

    module.run([
        '$templateCache',
        function($templateCache) {
            return $templateCache.put(
                'contrib/ping_federate_auth',
                '
' +
                    ''+
                        '' +
                        'Login with SSO' +
                    '' +
                '
'
            );
        }
    ]);

}).call(this);
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('./proof')(4, function (step, Strata, tmp, load, serialize, objectify, gather, say, assert) {
    var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 })
    step(function () {
        serialize(__dirname + '/fixtures/merge.before.json', tmp, step())
    }, function () {
        strata.open(step())
    }, function () {
        strata.mutator('a', step())
    }, function (cursor) {
        step(function () {
            cursor.remove(cursor.index, step())
        }, function () {
            assert(cursor.index, 0, 'unghostable')
            cursor.unlock()
        })
    }, function () {
        gather(step, strata)
    }, function (records) {
        assert(records, [ 'b', 'c', 'd' ], 'records')
        strata.balance(step())
    }, function () {
        gather(step, strata)
    }, function (records) {
        assert(records, [ 'b', 'c', 'd' ], 'merged')
        objectify(tmp, step())
        load(__dirname + '/fixtures/left-most-unghostable.after.json', step())
    }, function (actual, expected) {
        say(expected)
        say(actual)

        assert(actual, expected, 'after')
        strata.close(step())
    })
})
<commit_msg>Use `vivify` in `left-most-unghostable.t.js`.<commit_after>#!/usr/bin/env node

require('./proof')(4, function (step, Strata, tmp, load, serialize, vivify, gather, say, assert) {
    var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 })
    step(function () {
        serialize(__dirname + '/fixtures/merge.before.json', tmp, step())
    }, function () {
        strata.open(step())
    }, function () {
        strata.mutator('a', step())
    }, function (cursor) {
        step(function () {
            cursor.remove(cursor.index, step())
        }, function () {
            assert(cursor.index, 0, 'unghostable')
            cursor.unlock()
        })
    }, function () {
        gather(step, strata)
    }, function (records) {
        assert(records, [ 'b', 'c', 'd' ], 'records')
        strata.balance(step())
    }, function () {
        gather(step, strata)
    }, function (records) {
        assert(records, [ 'b', 'c', 'd' ], 'merged')
        vivify(tmp, step())
        load(__dirname + '/fixtures/left-most-unghostable.after.json', step())
    }, function (actual, expected) {
        say(expected)
        say(actual)

        assert(actual, expected, 'after')
        strata.close(step())
    })
})
<|endoftext|>


<commit_before>export default function factory () {
  return {
    require: ['esm'],
    files: [
      'test/*.js'
    ],
    sources: [
      'src/**/*.js'
    ],
    cache: true,
    concurrency: 5,
    failFast: false,
    timeout: '10s'
  }
}
<commit_msg>increase timeout from 10s to 30s<commit_after>export default function factory () {
  return {
    require: ['esm'],
    files: [
      'test/*.js'
    ],
    sources: [
      'src/**/*.js'
    ],
    cache: true,
    concurrency: 5,
    failFast: false,
    timeout: '30s'
  }
}
<|endoftext|>


<commit_before>import React from 'react'

export default function makeMultiOrganism(
  Parent,
  cells,
  {
    onChange,
    adjustArgs
  } = {}
) {
  return class OrganismMulticelled extends React.Component {
    state = Object.keys(cells).reduce((state, cellKey) => {
      state[cellKey] = cells[cellKey].initial(this.props)
      return state
    }, {})

    changeStateForCell(stateChanger, cellKey) {
      // Can either be a plain object or a callback to transform the existing state
      this.setState(
        (prevState, props) => {
          let changes = {}
          // Check if stateChanger is a function
          if (typeof(stateChanger) === typeof(stateChanger.call)) { // TODO: better function check?
            changes[cellKey] = stateChanger(prevState[cellKey], props)
          }
          // Else just an object with changes
          else {
            changes[cellKey] = stateChanger
          }
          return changes
        },
        // Call onChange once updated with current version of state
        onChange ? () => { onChange(this.state) } : undefined
      )
    }

    // Uses `load` handler, if present, to asynchronously load initial state
    loadAsync(nextProps, prevProps) {
      Object.keys(cells).map(cellKey => {
        const handlersIn = cells[cellKey]
        if (handlersIn.load) {
          // Wrap in Promise to safely catch any errors thrown by `load`
          Promise.resolve(true).then(() => handlersIn.load(nextProps, prevProps, { handlers: this.cellsProxy[cellKey].handlers }))
            .then(updater => updater && this.changeStateForCell(updater, cellKey))
            .catch(error => this.setState({ loadError: error }))
        }
      })
    }

    componentDidMount() {
      this.loadAsync(this.props, null)
    }

    componentWillReceiveProps(nextProps) {
      this.loadAsync(nextProps, this.props)
    }

    cellsProxy = Object.keys(cells).reduce((cellsProxy, cellKey) => {
      const handlersIn = cells[cellKey]
      const handlers = Object.keys(handlersIn).reduce((out, key) => {
        // Special case for `load` handler to reload fresh
        if (key === 'load') {
          out.load = () => {
            // FIXME
            this.loadAsync(this.props, null)
          }
          return out
        }

        out[key] = (...args) => {
          if (adjustArgs) {
            args = adjustArgs(args)
          }

          // Call handler function, props first, then rest of args
          // Note: that this should only be given its own handlers, as that’s all it knows about
          const stateChanger = handlersIn[key].apply(null, [ Object.assign({}, this.props, { handlers }) ].concat(args));
          // Can return multiple state changers, ensure array, and then loop through
          [].concat(result).forEach(stateChanger => {
            // Check if thenable (i.e. a Promise)
            if (!!stateChanger && (typeof stateChanger.then === typeof Object.assign)) {
              stateChanger
                .then(stateChanger => {
                  stateChanger && this.changeStateForCell(stateChanger, cellKey)
                })
                .catch(error => {
                  this.setState({ handlerError: error })
                })
            }
            // Otherwise, change state immediately
            // Required for things like <textarea> onChange to keep cursor in correct position
            else {
              stateChanger && this.changeStateForCell(stateChanger, cellKey)
            }
          })
        }
        return out
      }, {})

      Object.defineProperty(cellsProxy, cellKey, {
        get: () => {
          // Track which cells are used
          //this.usedCells[cellKey] = true
          return Object.assign({}, this.state[cellKey], { handlers })
        }
      })
      return cellsProxy
    }, {})

    render() {
      // Render the pure component, passing both props and cells
      return <Parent { ...this.props } cells={ this.cellsProxy } />
    }
  }
}
<commit_msg>Add comments to multi<commit_after>import React from 'react'

export default function makeMultiOrganism(
  Parent,
  cells,
  {
    onChange,
    adjustArgs
  } = {}
) {
  return class OrganismMulticelled extends React.Component {
    state = Object.keys(cells).reduce((state, cellKey) => {
      // Grab each cell’s initial value
      state[cellKey] = cells[cellKey].initial(this.props)
      return state
    }, {})

    changeStateForCell(stateChanger, cellKey) {
      // Can either be a plain object or a callback to transform the existing state
      this.setState(
        (prevState, props) => {
          let changes = {}
          // Check if stateChanger is a function
          if (typeof(stateChanger) === typeof(stateChanger.call)) { // TODO: better function check?
            changes[cellKey] = stateChanger(prevState[cellKey], props)
          }
          // Else just an object with changes
          else {
            changes[cellKey] = stateChanger
          }
          return changes
        },
        // Call onChange once updated with current version of state
        onChange ? () => { onChange(this.state) } : undefined
      )
    }

    // Uses `load` handler, if present, to asynchronously load initial state
    loadAsync(nextProps, prevProps) {
      Object.keys(cells).map(cellKey => {
        const handlersIn = cells[cellKey]
        if (handlersIn.load) {
          // Wrap in Promise to safely catch any errors thrown by `load`
          Promise.resolve(true).then(() => handlersIn.load(nextProps, prevProps, { handlers: this.cellsProxy[cellKey].handlers }))
            .then(updater => updater && this.changeStateForCell(updater, cellKey))
            .catch(error => this.setState({ loadError: error }))
        }
      })
    }

    componentDidMount() {
      this.loadAsync(this.props, null)
    }

    componentWillReceiveProps(nextProps) {
      this.loadAsync(nextProps, this.props)
    }

    cellsProxy = Object.keys(cells).reduce((cellsProxy, cellKey) => {
      const handlersIn = cells[cellKey]
      const handlers = Object.keys(handlersIn).reduce((out, key) => {
        // Special case for `load` handler to reload fresh
        if (key === 'load') {
          out.load = () => {
            // FIXME
            this.loadAsync(this.props, null)
          }
          return out
        }

        out[key] = (...args) => {
          if (adjustArgs) {
            args = adjustArgs(args)
          }

          // Call handler function, props first, then rest of args
          // Note: that this should only be given its own handlers, as that’s all it knows about
          const stateChanger = handlersIn[key].apply(null, [ Object.assign({}, this.props, { handlers }) ].concat(args));
          // Can return multiple state changers, ensure array, and then loop through
          [].concat(result).forEach(stateChanger => {
            // Check if thenable (i.e. a Promise)
            if (!!stateChanger && (typeof stateChanger.then === typeof Object.assign)) {
              stateChanger
                .then(stateChanger => {
                  stateChanger && this.changeStateForCell(stateChanger, cellKey)
                })
                .catch(error => {
                  this.setState({ handlerError: error })
                })
            }
            // Otherwise, change state immediately
            // Required for things like <textarea> onChange to keep cursor in correct position
            else {
              stateChanger && this.changeStateForCell(stateChanger, cellKey)
            }
          })
        }
        return out
      }, {})

      Object.defineProperty(cellsProxy, cellKey, {
        get: () => {
          // Track which cells are used
          //this.usedCells[cellKey] = true
          return Object.assign({}, this.state[cellKey], { handlers })
        }
      })
      return cellsProxy
    }, {})

    render() {
      // Render the pure component, passing both props and cells
      return <Parent { ...this.props } cells={ this.cellsProxy } />
    }
  }
}
<|endoftext|>


<commit_before>// mv-if plugin
(function($, $$) {

Mavo.Expressions.directive("mv-if", {
	extend: {
		"Primitive": {
			live: {
				"hidden": function(value) {
					if (this._hidden !== value) {
						this._hidden = value;
						this.dataChanged();
					}
				}
			}
		},
		"DOMExpression": {
			lazy: {
				"childProperties": function() {
					var properties = $$(Mavo.selectors.property, this.element)
									.filter(el => el.closest("[mv-if]") == this.element)
									.map(el => Mavo.Node.get(el));

					// When the element is detached, datachange events from properties
					// do not propagate up to the group so expressions do not recalculate.
					// We must do this manually.
					this.element.addEventListener("mv-change", evt => {
						// Cannot redispatch synchronously [why??]
						requestAnimationFrame(() => {
							if (!this.element.parentNode) { // out of the DOM?
							this.item.element.dispatchEvent(evt);
						}
						});
					});

					return properties;
				}
			}
		}
	},
	hooks: {
		"domexpression-init-start": function() {
			if (this.attribute != "mv-if") {
				return;
			}

			this.expression = this.element.getAttribute("mv-if");
			this.parsed = [new Mavo.Expression(this.expression)];
			this.expression = this.syntax.start + this.expression + this.syntax.end;

			this.parentIf = this.element.parentNode && Mavo.DOMExpression.search(this.element.parentNode.closest("[mv-if]"), "mv-if");

			if (this.parentIf) {
				this.parentIf.childIfs = (this.parentIf.childIfs || new Set()).add(this);
			}
		},
		"domexpression-update-end": function() {
			if (this.attribute != "mv-if") {
				return;
			}

			var value = this.value[0];
			var oldValue = this.oldValue[0];

			// Only apply this after the tree is built, otherwise any properties inside the if will go missing!
			this.item.mavo.treeBuilt.then(() => {
				if (this.parentIf) {
					var parentValue = this.parentIf.value[0];
					this.value[0] = value = value && parentValue;
				}

				if (value === oldValue) {
					return;
				}

				if (parentValue !== false) { // If parent if was false, it wouldn't matter whether this is in the DOM or not
					if (value) {
						// Is removed from the DOM and needs to get back
						Mavo.revocably.add(this.element);
					}
					else if (this.element.parentNode) {
						// Is in the DOM and needs to be removed
						Mavo.revocably.remove(this.element, "mv-if");
					}
				}

				// Mark any properties inside as hidden or not
				if (this.childProperties) {
					for (let property of this.childProperties) {
						property.hidden = !value;
					}
				}

				if (this.childIfs) {
					for (let childIf of this.childIfs) {
						childIf.update();
					}
				}
			});
		},
		"unit-isdatanull": function(env) {
			env.result = env.result || (this.hidden && env.options.live);
		}
	}
});

})(Bliss, Bliss.$);
<commit_msg>Fix weird mv-if bug<commit_after>// mv-if plugin
(function($, $$) {

Mavo.Expressions.directive("mv-if", {
	extend: {
		"Primitive": {
			live: {
				"hidden": function(value) {
					if (this._hidden !== value) {
						this._hidden = value;
						this.dataChanged();
					}
				}
			}
		},
		"DOMExpression": {
			lazy: {
				"childProperties": function() {
					var properties = $$(Mavo.selectors.property, this.element)
									.filter(el => el.closest("[mv-if]") == this.element)
									.map(el => Mavo.Node.get(el));

					// When the element is detached, datachange events from properties
					// do not propagate up to the group so expressions do not recalculate.
					// We must do this manually.
					this.element.addEventListener("mv-change", evt => {
						// Cannot redispatch synchronously [why??]
						requestAnimationFrame(() => {
							if (!this.element.parentNode) { // out of the DOM?
							this.item.element.dispatchEvent(evt);
						}
						});
					});

					return properties;
				}
			}
		}
	},
	hooks: {
		"domexpression-init-start": function() {
			if (this.attribute != "mv-if") {
				return;
			}

			this.expression = this.element.getAttribute("mv-if");
			this.parsed = [new Mavo.Expression(this.expression)];
			this.expression = this.syntax.start + this.expression + this.syntax.end;

			this.parentIf = this.element.parentNode && Mavo.DOMExpression.search(this.element.parentNode.closest("[mv-if]"), "mv-if");

			if (this.parentIf) {
				this.parentIf.childIfs = (this.parentIf.childIfs || new Set()).add(this);
			}
		},
		"domexpression-update-end": function() {
			if (this.attribute != "mv-if") {
				return;
			}

			var value = this.value[0];
			var oldValue = this.oldValue[0];

			// Only apply this after the tree is built, otherwise any properties inside the if will go missing!
			this.item.mavo.treeBuilt.then(() => {
				if (this.parentIf) {
					var parentValue = this.parentIf.value[0];
					this.value[0] = value = value && parentValue;
				}

				if (parentValue !== false) { // If parent if was false, it wouldn't matter whether this is in the DOM or not
					if (value) {
						// Is removed from the DOM and needs to get back
						Mavo.revocably.add(this.element);
					}
					else if (this.element.parentNode) {
						// Is in the DOM and needs to be removed
						Mavo.revocably.remove(this.element, "mv-if");
					}
				}

				if (value !== oldValue) {
					// Mark any properties inside as hidden or not
					if (this.childProperties) {
						for (let property of this.childProperties) {
							property.hidden = !value;
						}
					}

					if (this.childIfs) {
						for (let childIf of this.childIfs) {
							childIf.update();
						}
					}
				}
			});
		},
		"unit-isdatanull": function(env) {
			env.result = env.result || (this.hidden && env.options.live);
		}
	}
});

})(Bliss, Bliss.$);
<|endoftext|>


<commit_before><commit_msg>feat: yaml prettyErrors in resolver too<commit_after><|endoftext|>


<commit_before>/**
 * Terrific Nitro App
 * Copyright (c) 2016 Robert Vogt <robert.vogt@namics.com>
 * MIT Licensed
 */

'use strict';

var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
var router = require('./router');
var hbs = require('hbs');

/**
 * Express App Instance
 * @private
 */
var app = express();

/**
 * nitro/config Instance
 * @private
 */
var config;

/**
 * Creates express app with default middleware.
 *
 * @param port
 * @param callback {fn(app)}
 */
function createApp(port, callback) {
	app.use(router(config));
	app.use(compression());
	app.use(bodyParser.urlencoded({ extended: true }));

	app.set('view engine', config.nitro.view_file_extension);
	app.set('views', config.nitro.view_directory);

	app.listen(port, callback.apply(undefined, [ app ]));
}

/**
 * Adds a custom handlebars helper to the hbs instance
 * @param name
 */
function addHelper(name) {
	hbs.registerHelper(name, require(config.nitro.helpers_directory + name));
}

/**
 * @param cfg nitro/config Object
 * @returns {{start: createApp, addHelper: addHelper}}
 */
module.exports = function(cfg) {
	config = cfg;
	return {
		__app: app,
		start: createApp,
		addHelper: addHelper
	}
}<commit_msg>Enable simple helpers (closures)<commit_after>/**
 * Terrific Nitro App
 * Copyright (c) 2016 Robert Vogt <robert.vogt@namics.com>
 * MIT Licensed
 */

'use strict';

var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
var router = require('./router');
var hbs = require('hbs');

/**
 * Express App Instance
 * @private
 */
var app = express();

/**
 * nitro/config Instance
 * @private
 */
var config;

/**
 * Creates express app with default middleware.
 *
 * @param port
 * @param callback {fn(app)}
 */
function createApp(port, callback) {
	app.use(router(config));
	app.use(compression());
	app.use(bodyParser.urlencoded({ extended: true }));

	app.set('view engine', config.nitro.view_file_extension);
	app.set('views', config.nitro.view_directory);

	app.listen(port, callback.apply(undefined, [ app ]));
}

/**
 * Adds a custom handlebars helper to the hbs instance
 * @param name
 * @param callback
 */
function addHelper(name, callback) {
	if (typeof callback === 'undefined') {
		callback = require(config.nitro.helpers_directory + name);
	}
	hbs.registerHelper(name, callback);
}

/**
 * @param cfg nitro/config Object
 * @returns {{start: createApp, addHelper: addHelper}}
 */
module.exports = function(cfg) {
	config = cfg;
	return {
		__app: app,
		start: createApp,
		addHelper: addHelper
	}
}<|endoftext|>


<commit_before>'use strict';

var CopyUtils = require('../utils/CopyUtils'),
    path = require('path'),
    _ = require('lodash'),
    nodeunit = require('nodeunit'),
    TestStatus = require('../lib/TestStatus'),
    log4js = require('log4js'),
    logger = log4js.getLogger('mutation-testing-nodeunit'),
    Promise = require('bluebird'),
    globAsync = Promise.promisify(require("glob"));

Promise.longStackTraces();
var cp = require("child_process");
var fs = Promise.promisifyAll(require("fs"));
var fsExtra = require('fs-extra');
var E = require("core-error-predicates");
var rimrafAsync = Promise.promisify(require("rimraf"));

function runAsync(execStr) {
    return new Promise(function(resolve, reject) {
        var stdout = [];
        var stderr = [];
        var elements = execStr.split(/\s+/g);
        var command = elements.shift();
        var args = elements;

        var newProcess = cp.spawn(command, args);
        newProcess.stdout.on("data", function(buffer) {
            process.stdout.write(buffer);
            stdout.push(buffer);
        });
        newProcess.stderr.on("data", function(buffer) {
            process.stderr.write(buffer);
            stderr.push(buffer);
        });
        newProcess.on("close", function(code) {
            stdout = Buffer.concat(stdout).toString("utf8");
            stderr = Buffer.concat(stderr).toString("utf8");
            if (code === 0) {
                resolve({
                    stdout: stdout,
                    stderr: stderr
                });
            } else {
                var error = new Error(execStr + " exited with failure code: " + code);
                error.stdout = stdout;
                error.stderr = stderr;
                error.command = execStr;
                reject(error);
            }
        });
    }).catch(function(e) {
        e.command = execStr;
        throw e;
    });
}

exports.init = function(grunt, opts) {
    if(opts.testFramework !== 'nodeunit') {
        return;
    }

    var commandLineOptMutate = grunt.option("mutationTest:options:mutate");
    var commandLineOptCode = grunt.option("mutationTest:options:code");
    var commandLineOptCodeAdditional = grunt.option("mutationTest:options:code:additional");
    var originalBasePath = process.cwd();
    var tmpBasePath;

    if(commandLineOptMutate){
        opts.mutate = grunt.file.expand(commandLineOptMutate);
        logger.info('Overriding opts.mutate with %s', opts.mutate);
    };

    if(commandLineOptCode){
        opts.code = grunt.file.expand(commandLineOptCode);
        logger.info('Overriding opts.code with %s', opts.code);
    };

    if(commandLineOptCodeAdditional){
        commandLineOptCodeAdditional = commandLineOptCodeAdditional.split(',');
        commandLineOptCodeAdditional.forEach(function(minimaxExpr){
            var expanded = grunt.file.expand(minimaxExpr);
            logger.info('Appending opts.code with %s', expanded);
            opts.code = opts.code.concat(expanded);
        })
        logger.info('Overriding opts.code with %s', opts.code);
    };

    function expandSpecs() {
        var specPattern = grunt.option("mutationTest:options:specs") || "test/**/*.js";
        var globResult = globAsync(specPattern);
        return Promise
            .join(globResult)
            .return(globResult);
    }

    var expandedSpecs = expandSpecs();

    function runTests(specs, tmpDir){
        return specs.each(function(file) {
            var name = path.basename(file).replace(path.extname(file), "");
            var p = path.join(tmpDir, file);
            // var p = file;
            // logger.error(p);
            return runAsync("nodeunit --reporter minimal " + p);
        });
    }

    opts.before = function(doneBefore) {
        if(opts.mutateProductionCode) {
            doneBefore();
        } else {
            // Find which files are used in the unit test such that they can be copied
            CopyUtils.copyToTemp(opts.code.concat(opts.specs), 'mutation-testing')
            .done(function(tempDirPath) {
                tmpBasePath = tempDirPath;
                logger.trace('Copied %j to %s', opts.code.concat(opts.specs), tempDirPath);

                // create symlinks in tmpDirPath, if set
                if (opts.symlinks) {
                    opts.symlinks.forEach(function(folder) {
                        var srcPath = path.resolve(path.join(opts.basePath, folder));
                        var tgtPath = path.join(tempDirPath, folder);
                        fs.symlinkSync(srcPath, tgtPath);
                        logger.info('Created symbolik link: %s -> %s', srcPath, tgtPath);
                    })
                };

                // Set the basePath relative to the temp dir
                opts.basePath = path.join(tempDirPath, opts.basePath);

                // Set the paths to the files to be mutated relative to the temp dir
                opts.mutate = _.map(opts.mutate, function(file) {
                    return path.join(tempDirPath, file);
                });

                runTests(expandedSpecs, tempDirPath).then(function(){
                    doneBefore();
                })
                .catch(function(error) {
                    logger.error('Tests don\'t pass without mutations!');
                    process.exit(-1);
                });
            });
        }
    };

    opts.test = function(done) {
        runTests(expandedSpecs, tmpBasePath).then(function(){
            done(TestStatus.SURVIVED);
        })
        .catch(function(error) {
            // logger.error(error.stdout);
            done(TestStatus.KILLED);
        });
    };

    opts.after = function() {
        var srcPath = path.join(tmpBasePath, 'reports');
        var tgtPath = path.join(originalBasePath, 'reports');
        fsExtra.copy(srcPath, tgtPath, function (err) {
            if (err) {
                logger.error(err);
            } else {
                logger.info('Copied ' + srcPath + ' to ' + tgtPath);
            }
        })
        logger.info('Copied ' + srcPath + ' to ' + tgtPath);
    };
}
<commit_msg>remove redundant code<commit_after>'use strict';

var CopyUtils = require('../utils/CopyUtils'),
    path = require('path'),
    _ = require('lodash'),
    nodeunit = require('nodeunit'),
    TestStatus = require('../lib/TestStatus'),
    log4js = require('log4js'),
    logger = log4js.getLogger('mutation-testing-nodeunit'),
    Promise = require('bluebird'),
    globAsync = Promise.promisify(require("glob"));

Promise.longStackTraces();
var cp = require("child_process");
var fs = Promise.promisifyAll(require("fs"));
var fsExtra = require('fs-extra');
var E = require("core-error-predicates");
var rimrafAsync = Promise.promisify(require("rimraf"));

function runAsync(execStr) {
    return new Promise(function(resolve, reject) {
        var stdout = [];
        var stderr = [];
        var elements = execStr.split(/\s+/g);
        var command = elements.shift();
        var args = elements;

        var newProcess = cp.spawn(command, args);
        newProcess.stdout.on("data", function(buffer) {
            process.stdout.write(buffer);
            stdout.push(buffer);
        });
        newProcess.stderr.on("data", function(buffer) {
            process.stderr.write(buffer);
            stderr.push(buffer);
        });
        newProcess.on("close", function(code) {
            stdout = Buffer.concat(stdout).toString("utf8");
            stderr = Buffer.concat(stderr).toString("utf8");
            if (code === 0) {
                resolve({
                    stdout: stdout,
                    stderr: stderr
                });
            } else {
                var error = new Error(execStr + " exited with failure code: " + code);
                error.stdout = stdout;
                error.stderr = stderr;
                error.command = execStr;
                reject(error);
            }
        });
    }).catch(function(e) {
        e.command = execStr;
        throw e;
    });
}

exports.init = function(grunt, opts) {
    if(opts.testFramework !== 'nodeunit') {
        return;
    }

    var commandLineOptMutate = grunt.option("mutationTest:options:mutate");
    var commandLineOptCode = grunt.option("mutationTest:options:code");
    var commandLineOptCodeAdditional = grunt.option("mutationTest:options:code:additional");
    var originalBasePath = process.cwd();
    var tmpBasePath;

    if(commandLineOptMutate){
        opts.mutate = grunt.file.expand(commandLineOptMutate);
        logger.info('Overriding opts.mutate with %s', opts.mutate);
    };

    if(commandLineOptCode){
        opts.code = grunt.file.expand(commandLineOptCode);
        logger.info('Overriding opts.code with %s', opts.code);
    };

    if(commandLineOptCodeAdditional){
        commandLineOptCodeAdditional = commandLineOptCodeAdditional.split(',');
        commandLineOptCodeAdditional.forEach(function(minimaxExpr){
            var expanded = grunt.file.expand(minimaxExpr);
            logger.info('Appending opts.code with %s', expanded);
            opts.code = opts.code.concat(expanded);
        })
        logger.info('Overriding opts.code with %s', opts.code);
    };

    function expandSpecs() {
        var specPattern = grunt.option("mutationTest:options:specs") || "test/**/*.js";
        var globResult = globAsync(specPattern);
        return Promise
            .join(globResult)
            .return(globResult);
    }

    var expandedSpecs = expandSpecs();

    function runTests(specs, tmpDir){
        return specs.each(function(file) {
            var name = path.basename(file).replace(path.extname(file), "");
            var p = path.join(tmpDir, file);
            // var p = file;
            // logger.error(p);
            return runAsync("nodeunit --reporter minimal " + p);
        });
    }

    opts.before = function(doneBefore) {
        if(opts.mutateProductionCode) {
            doneBefore();
        } else {
            // Find which files are used in the unit test such that they can be copied
            CopyUtils.copyToTemp(opts.code.concat(opts.specs), 'mutation-testing')
            .done(function(tempDirPath) {
                tmpBasePath = tempDirPath;
                logger.trace('Copied %j to %s', opts.code.concat(opts.specs), tempDirPath);

                // create symlinks in tmpDirPath, if set
                if (opts.symlinks) {
                    opts.symlinks.forEach(function(folder) {
                        var srcPath = path.resolve(path.join(opts.basePath, folder));
                        var tgtPath = path.join(tempDirPath, folder);
                        fs.symlinkSync(srcPath, tgtPath);
                        logger.info('Created symbolik link: %s -> %s', srcPath, tgtPath);
                    })
                };

                // Set the basePath relative to the temp dir
                opts.basePath = path.join(tempDirPath, opts.basePath);

                // Set the paths to the files to be mutated relative to the temp dir
                opts.mutate = _.map(opts.mutate, function(file) {
                    return path.join(tempDirPath, file);
                });

                runTests(expandedSpecs, tempDirPath).then(function(){
                    doneBefore();
                })
                .catch(function(error) {
                    logger.error('Tests don\'t pass without mutations!');
                    process.exit(-1);
                });
            });
        }
    };

    opts.test = function(done) {
        runTests(expandedSpecs, tmpBasePath).then(function(){
            done(TestStatus.SURVIVED);
        })
        .catch(function(error) {
            // logger.error(error.stdout);
            done(TestStatus.KILLED);
        });
    };
}
<|endoftext|>


<commit_before>/**
 * @file From raw serialization
 * @since 0.2.8
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*global _gpfSerialGet*/ // Collect gpf.typedef.serializableProperty defined for the object / class
/*global _gpfSerialIdentityConverter*/ // Identity converter, returns passed value
/*#endif*/

function _gpfSerialRawFromProperties (instance, raw, converter) {
    var properties = _gpfSerialGet(instance);
    _gpfObjectForEach(properties, function (property, member) {
        if (raw.hasOwnProperty(property.name)) {
            instance[member] = converter.call(instance, raw[property.name], property, member);
        }
    });
}

function _gpfSerialRawFrom (instance, raw, converter) {
    _gpfSerialRawFromProperties(instance, raw, converter || _gpfSerialIdentityConverter);
}

/**
 * Initialize the given instance from a dictionary containing serializable properties' value.
 *
 * @param {Object} instance Instance of a class containing {@ling gpf.attributes.Serializable} attributes
 * @param {Object} raw Dictionary with all serializable properties (indexed by property names)
 * @param {gpf.typedef.serialConverter} [converter] Converter function for properties' value
 * @return {Object} instance
 * @throws {gpf.Error.InvalidParameter}
 * @since 0.2.8
 */
gpf.serial.fromRaw = function (instance, raw, converter) {
    if ("function" === typeof instance) {
        gpf.Error.invalidParameter();
    }
    _gpfSerialRawFrom(instance, raw, converter);
    return instance;
};
<commit_msg>!yoda style (#280)<commit_after>/**
 * @file From raw serialization
 * @since 0.2.8
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*global _gpfSerialGet*/ // Collect gpf.typedef.serializableProperty defined for the object / class
/*global _gpfSerialIdentityConverter*/ // Identity converter, returns passed value
/*#endif*/

function _gpfSerialRawFromProperties (instance, raw, converter) {
    var properties = _gpfSerialGet(instance);
    _gpfObjectForEach(properties, function (property, member) {
        if (raw.hasOwnProperty(property.name)) {
            instance[member] = converter.call(instance, raw[property.name], property, member);
        }
    });
}

function _gpfSerialRawFrom (instance, raw, converter) {
    _gpfSerialRawFromProperties(instance, raw, converter || _gpfSerialIdentityConverter);
}

/**
 * Initialize the given instance from a dictionary containing serializable properties' value.
 *
 * @param {Object} instance Instance of a class containing {@ling gpf.attributes.Serializable} attributes
 * @param {Object} raw Dictionary with all serializable properties (indexed by property names)
 * @param {gpf.typedef.serialConverter} [converter] Converter function for properties' value
 * @return {Object} instance
 * @throws {gpf.Error.InvalidParameter}
 * @since 0.2.8
 */
gpf.serial.fromRaw = function (instance, raw, converter) {
    if (typeof instance === "function") {
        gpf.Error.invalidParameter();
    }
    _gpfSerialRawFrom(instance, raw, converter);
    return instance;
};
<|endoftext|>


<commit_before>var w = screen.width * 0.3,
h = screen.width * 0.3,
r = 380,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
node,
root;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

var pack = d3.layout.pack()
    .size([r, r])
    .value(function(d) { return d.size;})
    .padding(p);

function load_data(chartnode,json_data)
{
d3.json(json_data, function(data) {
    node = root = data;
    var nodes = pack.nodes(root);
    chartnode.selectAll("circle")
        .remove();
    chartnode.selectAll("circle")
        .data(nodes)
        .enter().append("svg:circle")
        .attr("class", function(d) { return d.children ? "parent" : "child"; })
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return d.r; })
        .style("fill", function(d){return colorPicker(d.name)});

    chartnode.selectAll("text")
        .remove();
    chartnode.selectAll("text")
        .data(nodes)
        .enter().append("svg:text")
        .attr("class", function(d) { return d.children ? "parent" : "child"; })
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("opacity", function(d) { return d.r > 20 ? 1 : 0; })
        .text(function(d) { return d.name; })
        .call(wrap);
});
}

function add_info(chart_id,json_data)
{

var fc1 = d3.select(chart_id + " svg")
    .attr("width", w)
    .attr("height", h)
    .append("svg:g")
    .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    load_data(fc1,json_data);

}

function info(dynamic,json_data1,json_data2,json_data3)
{

    add_info("#chart1",json_data1);
    add_info("#chart2",json_data2);
    add_info("#chart3",json_data3);
}

function getTypeOrg() {

    var parser = document.createElement("a");
    parser.href = document.URL;
    searchList = parser.search.substring(1).split("&");

    var dynamic =false;

    for (var i=0;i<searchList.length;i++)
    {
        if (searchList[i] == "dynamic")
        {
            dynamic = true;
        }

    }

    for (var i=0;i<searchList.length;i++)
    {
        var divList = document.querySelectorAll("#" + searchList[i]);
        for (var j=0;j<divList.length;j++)
        {
            divList[j].style.display="block";
        }
        if (searchList[i] == "cost")
        {
            info(dynamic,
                 "info-raw-data-run1-2000_2050_2100-cost.json",
                 "info-raw-data-run3-2000_2050_2100-cost.json",
                 "info-raw-data-run5-2000_2050_2100-cost.json");

        }
        if (searchList[i] == "waste")
        {
            info(dynamic,
                 "info-raw-data-run1-2000_2050_2100-waste.json",
                 "info-raw-data-run3-2000_2050_2100-waste.json",
                 "info-raw-data-run5-2000_2050_2100-waste.json");
        }

    }

}
<commit_msg>made chart nodes global<commit_after>var w = screen.width * 0.3,
h = screen.width * 0.3,
r = 380,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
node,
root,
fc1,fc2,fc3;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

var pack = d3.layout.pack()
    .size([r, r])
    .value(function(d) { return d.size;})
    .padding(p);

function load_data(chartnode,json_data)
{
d3.json(json_data, function(data) {
    node = root = data;
    var nodes = pack.nodes(root);
    chartnode.selectAll("circle")
        .remove();
    chartnode.selectAll("circle")
        .data(nodes)
        .enter().append("svg:circle")
        .attr("class", function(d) { return d.children ? "parent" : "child"; })
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return d.r; })
        .style("fill", function(d){return colorPicker(d.name)});

    chartnode.selectAll("text")
        .remove();
    chartnode.selectAll("text")
        .data(nodes)
        .enter().append("svg:text")
        .attr("class", function(d) { return d.children ? "parent" : "child"; })
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("opacity", function(d) { return d.r > 20 ? 1 : 0; })
        .text(function(d) { return d.name; })
        .call(wrap);
});
}

function add_info(chart_node,chart_id,json_data)
{

var chart_node = d3.select(chart_id + " svg")
    .attr("width", w)
    .attr("height", h)
    .append("svg:g")
    .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    load_data(chart_node,json_data);

}

function info(dynamic,json_data1,json_data2,json_data3)
{

    add_info(fc1,"#chart1",json_data1);
    add_info(fc2,"#chart2",json_data2);
    add_info(fc3,"#chart3",json_data3);
}

function getTypeOrg() {

    var parser = document.createElement("a");
    parser.href = document.URL;
    searchList = parser.search.substring(1).split("&");

    var dynamic =false;

    for (var i=0;i<searchList.length;i++)
    {
        if (searchList[i] == "dynamic")
        {
            dynamic = true;
        }

    }

    for (var i=0;i<searchList.length;i++)
    {
        var divList = document.querySelectorAll("#" + searchList[i]);
        for (var j=0;j<divList.length;j++)
        {
            divList[j].style.display="block";
        }
        if (searchList[i] == "cost")
        {
            info(dynamic,
                 "info-raw-data-run1-2000_2050_2100-cost.json",
                 "info-raw-data-run3-2000_2050_2100-cost.json",
                 "info-raw-data-run5-2000_2050_2100-cost.json");

        }
        if (searchList[i] == "waste")
        {
            info(dynamic,
                 "info-raw-data-run1-2000_2050_2100-waste.json",
                 "info-raw-data-run3-2000_2050_2100-waste.json",
                 "info-raw-data-run5-2000_2050_2100-waste.json");
        }

    }

}

function load_fcs(year) {
  load_data(fc1,"years/info-raw-data-run1-" + year + "-cost.json");
  load_data(fc2,"years/info-raw-data-run3-" + year + "-cost.json");
  load_data(fc3,"years/info-raw-data-run5-" + year + "-cost.json");
}

function yearUpdate(year) {
  document.querySelector('#yearlabel').value = year;
  load_fcs(year);
}
<|endoftext|>


<commit_before>'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})
<commit_msg>fix history fallback for windows.<commit_after>'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})
<|endoftext|>