<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

// @flow

import PropTypes from "prop-types";
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { createSelector } from "reselect";

import { get } from "lodash";
import type { Frame } from "debugger-html";
import type { SourcesMap } from "../../../reducers/sources";

import FrameComponent from "./Frame";
import Group from "./Group";

import renderWhyPaused from "./WhyPaused";

import actions from "../../../actions";
import {
  annotateFrame,
  collapseFrames,
  formatCopyName
} from "../../../utils/frame";
import { copyToTheClipboard } from "../../../utils/clipboard";

import {
  getFrames,
  getFrameworkGroupingState,
  getSelectedFrame,
  getSourceInSources,
  getSources,
  getPause
} from "../../../selectors";

import type { LocalFrame } from "./types";

import "./Frames.css";

const NUM_FRAMES_SHOWN = 7;

type Props = {
  frames: Array<Frame>,
  frameworkGroupingOn: boolean,
  toggleFrameworkGrouping: Function,
  selectedFrame: Object,
  selectFrame: Function,
  toggleBlackBox: Function,
  pause: Object
};

type State = {
  showAllFrames: boolean
};

class Frames extends Component<Props, State> {
  renderFrames: Function;
  toggleFramesDisplay: Function;
  truncateFrames: Function;
  copyStackTrace: Function;
  toggleFrameworkGrouping: Function;
  renderToggleButton: Function;

  constructor(props) {
    super(props);

    this.state = {
      showAllFrames: false
    };

    this.toggleFramesDisplay = this.toggleFramesDisplay.bind(this);
    this.copyStackTrace = this.copyStackTrace.bind(this);
    this.toggleFrameworkGrouping = this.toggleFrameworkGrouping.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { frames, selectedFrame, frameworkGroupingOn } = this.props;
    const { showAllFrames } = this.state;
    return (
      frames !== nextProps.frames ||
      selectedFrame !== nextProps.selectedFrame ||
      showAllFrames !== nextState.showAllFrames ||
      frameworkGroupingOn !== nextProps.frameworkGroupingOn
    );
  }

  toggleFramesDisplay() {
    this.setState({
      showAllFrames: !this.state.showAllFrames
    });
  }

  collapseFrames(frames) {
    const { frameworkGroupingOn } = this.props;
    if (!frameworkGroupingOn) {
      return frames;
    }

    return collapseFrames(frames);
  }

  truncateFrames(frames) {
    const numFramesToShow = this.state.showAllFrames
      ? frames.length
      : NUM_FRAMES_SHOWN;

    return frames.slice(0, numFramesToShow);
  }

  copyStackTrace() {
    const { frames } = this.props;
    const framesToCopy = frames.map(f => formatCopyName(f)).join("\n");
    copyToTheClipboard(framesToCopy);
  }

  toggleFrameworkGrouping() {
    const { toggleFrameworkGrouping, frameworkGroupingOn } = this.props;
    toggleFrameworkGrouping(!frameworkGroupingOn);
  }

  renderFrames(frames: LocalFrame[]) {
    const {
      selectFrame,
      selectedFrame,
      toggleBlackBox,
      frameworkGroupingOn
    } = this.props;

    const framesOrGroups = this.truncateFrames(this.collapseFrames(frames));
    type FrameOrGroup = LocalFrame | LocalFrame[];

    return (

        {framesOrGroups.map(
          (frameOrGroup: FrameOrGroup) =>
            frameOrGroup.id ? (
              <FrameComponent
                frame={frameOrGroup}
                toggleFrameworkGrouping={this.toggleFrameworkGrouping}
                copyStackTrace={this.copyStackTrace}
                frameworkGroupingOn={frameworkGroupingOn}
                selectFrame={selectFrame}
                selectedFrame={selectedFrame}
                toggleBlackBox={toggleBlackBox}
                key={String(frameOrGroup.id)}
              />
            ) : (
              <Group
                group={frameOrGroup}
                toggleFrameworkGrouping={this.toggleFrameworkGrouping}
                copyStackTrace={this.copyStackTrace}
                frameworkGroupingOn={frameworkGroupingOn}
                selectFrame={selectFrame}
                selectedFrame={selectedFrame}
                toggleBlackBox={toggleBlackBox}
                key={frameOrGroup[0].id}
              />
            )
        )}

    );
  }

  renderToggleButton(frames: LocalFrame[]) {
    const buttonMessage = this.state.showAllFrames
      ? L10N.getStr("callStack.collapse")
      : L10N.getStr("callStack.expand");

    frames = this.collapseFrames(frames);
    if (frames.length <= NUM_FRAMES_SHOWN) {
      return null;
    }

    return (

        {buttonMessage}

    );
  }

  render() {
    const { frames, pause } = this.props;

    if (!frames) {
      return (

            {L10N.getStr("callStack.notPaused")}

      );
    }

    return (

        {this.renderFrames(frames)}
        {renderWhyPaused({ pause })}
        {this.renderToggleButton(frames)}

    );
  }
}

Frames.propTypes = {
  frames: PropTypes.array,
  frameworkGroupingOn: PropTypes.bool.isRequired,
  toggleFrameworkGrouping: PropTypes.func.isRequired,
  selectedFrame: PropTypes.object,
  selectFrame: PropTypes.func.isRequired,
  toggleBlackBox: PropTypes.func,
  pause: PropTypes.object
};

function getSourceForFrame(sources, frame) {
  return getSourceInSources(sources, frame.location.sourceId);
}

function appendSource(sources, frame) {
  return { ...frame, source: getSourceForFrame(sources, frame).toJS() };
}

export function getAndProcessFrames(frames: Frame[], sources: SourcesMap) {
  if (!frames) {
    return null;
  }

  const processedFrames = frames
    .filter(frame => getSourceForFrame(sources, frame))
    .map(frame => appendSource(sources, frame))
    .filter(frame => !get(frame, "source.isBlackBoxed"))
    .map(annotateFrame);

  return processedFrames;
}

const getAndProcessFramesSelector = createSelector(
  getFrames,
  getSources,
  getAndProcessFrames
);

export default connect(
  state => ({
    frames: getAndProcessFramesSelector(state),
    frameworkGroupingOn: getFrameworkGroupingState(state),
    selectedFrame: getSelectedFrame(state),
    pause: getPause(state)
  }),
  dispatch => bindActionCreators(actions, dispatch)
)(Frames);
<commit_msg>Removed PropTypes for Frames/index.js (#4826)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

// @flow

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { createSelector } from "reselect";

import { get } from "lodash";
import type { Frame } from "debugger-html";
import type { SourcesMap } from "../../../reducers/sources";

import FrameComponent from "./Frame";
import Group from "./Group";

import renderWhyPaused from "./WhyPaused";

import actions from "../../../actions";
import {
  annotateFrame,
  collapseFrames,
  formatCopyName
} from "../../../utils/frame";
import { copyToTheClipboard } from "../../../utils/clipboard";

import {
  getFrames,
  getFrameworkGroupingState,
  getSelectedFrame,
  getSourceInSources,
  getSources,
  getPause
} from "../../../selectors";

import type { LocalFrame } from "./types";

import "./Frames.css";

const NUM_FRAMES_SHOWN = 7;

type Props = {
  frames: Array<Frame>,
  frameworkGroupingOn: boolean,
  toggleFrameworkGrouping: Function,
  selectedFrame: Object,
  selectFrame: Function,
  toggleBlackBox: Function,
  pause: Object
};

type State = {
  showAllFrames: boolean
};

class Frames extends Component<Props, State> {
  renderFrames: Function;
  toggleFramesDisplay: Function;
  truncateFrames: Function;
  copyStackTrace: Function;
  toggleFrameworkGrouping: Function;
  renderToggleButton: Function;

  constructor(props) {
    super(props);

    this.state = {
      showAllFrames: false
    };

    this.toggleFramesDisplay = this.toggleFramesDisplay.bind(this);
    this.copyStackTrace = this.copyStackTrace.bind(this);
    this.toggleFrameworkGrouping = this.toggleFrameworkGrouping.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState): boolean {
    const { frames, selectedFrame, frameworkGroupingOn } = this.props;
    const { showAllFrames } = this.state;
    return (
      frames !== nextProps.frames ||
      selectedFrame !== nextProps.selectedFrame ||
      showAllFrames !== nextState.showAllFrames ||
      frameworkGroupingOn !== nextProps.frameworkGroupingOn
    );
  }

  toggleFramesDisplay(): void {
    this.setState({
      showAllFrames: !this.state.showAllFrames
    });
  }

  collapseFrames(frames) {
    const { frameworkGroupingOn } = this.props;
    if (!frameworkGroupingOn) {
      return frames;
    }

    return collapseFrames(frames);
  }

  truncateFrames(frames) {
    const numFramesToShow = this.state.showAllFrames
      ? frames.length
      : NUM_FRAMES_SHOWN;

    return frames.slice(0, numFramesToShow);
  }

  copyStackTrace() {
    const { frames } = this.props;
    const framesToCopy = frames.map(f => formatCopyName(f)).join("\n");
    copyToTheClipboard(framesToCopy);
  }

  toggleFrameworkGrouping() {
    const { toggleFrameworkGrouping, frameworkGroupingOn } = this.props;
    toggleFrameworkGrouping(!frameworkGroupingOn);
  }

  renderFrames(frames: LocalFrame[]) {
    const {
      selectFrame,
      selectedFrame,
      toggleBlackBox,
      frameworkGroupingOn
    } = this.props;

    const framesOrGroups = this.truncateFrames(this.collapseFrames(frames));
    type FrameOrGroup = LocalFrame | LocalFrame[];

    return (

        {framesOrGroups.map(
          (frameOrGroup: FrameOrGroup) =>
            frameOrGroup.id ? (
              <FrameComponent
                frame={frameOrGroup}
                toggleFrameworkGrouping={this.toggleFrameworkGrouping}
                copyStackTrace={this.copyStackTrace}
                frameworkGroupingOn={frameworkGroupingOn}
                selectFrame={selectFrame}
                selectedFrame={selectedFrame}
                toggleBlackBox={toggleBlackBox}
                key={String(frameOrGroup.id)}
              />
            ) : (
              <Group
                group={frameOrGroup}
                toggleFrameworkGrouping={this.toggleFrameworkGrouping}
                copyStackTrace={this.copyStackTrace}
                frameworkGroupingOn={frameworkGroupingOn}
                selectFrame={selectFrame}
                selectedFrame={selectedFrame}
                toggleBlackBox={toggleBlackBox}
                key={frameOrGroup[0].id}
              />
            )
        )}

    );
  }

  renderToggleButton(frames: LocalFrame[]) {
    const buttonMessage = this.state.showAllFrames
      ? L10N.getStr("callStack.collapse")
      : L10N.getStr("callStack.expand");

    frames = this.collapseFrames(frames);
    if (frames.length <= NUM_FRAMES_SHOWN) {
      return null;
    }

    return (

        {buttonMessage}

    );
  }

  render() {
    const { frames, pause } = this.props;

    if (!frames) {
      return (

            {L10N.getStr("callStack.notPaused")}

      );
    }

    return (

        {this.renderFrames(frames)}
        {renderWhyPaused({ pause })}
        {this.renderToggleButton(frames)}

    );
  }
}

function getSourceForFrame(sources, frame) {
  return getSourceInSources(sources, frame.location.sourceId);
}

function appendSource(sources, frame) {
  return { ...frame, source: getSourceForFrame(sources, frame).toJS() };
}

export function getAndProcessFrames(frames: Frame[], sources: SourcesMap) {
  if (!frames) {
    return null;
  }

  const processedFrames = frames
    .filter(frame => getSourceForFrame(sources, frame))
    .map(frame => appendSource(sources, frame))
    .filter(frame => !get(frame, "source.isBlackBoxed"))
    .map(annotateFrame);

  return processedFrames;
}

const getAndProcessFramesSelector = createSelector(
  getFrames,
  getSources,
  getAndProcessFrames
);

export default connect(
  state => ({
    frames: getAndProcessFramesSelector(state),
    frameworkGroupingOn: getFrameworkGroupingState(state),
    selectedFrame: getSelectedFrame(state),
    pause: getPause(state)
  }),
  dispatch => bindActionCreators(actions, dispatch)
)(Frames);
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/signal/Signal"], function(Tone){

	"use strict";

	/**
	 *  @class  a sample accurate clock built on an oscillator.
	 *          Invokes the onTick method at the set rate
	 *          NB: can cause audio glitches. use sparingly.
	 *
	 * 	@internal
	 * 	@constructor
	 * 	@extends {Tone}
	 * 	@param {number} rate the number of
	 */
	Tone.Clock = function(rate, callback){

		/**
		 *  the oscillator
		 *  @type {OscillatorNode}
		 */
		this._oscillator = null;

		/**
		 *  the script processor which listens to the oscillator
		 *  @type {[type]}
		 *  @private
		 */
		this._jsNode = this.context.createScriptProcessor(this.bufferSize, 1, 1);
		this._jsNode.onaudioprocess = this._processBuffer.bind(this);

		/**
		 *  the rate control signal
		 *  @type {Tone.Signal}
		 *  @private
		 */
		this._controlSignal = new Tone.Signal(1);

		/**
		 *  whether the tick is on the up or down
		 *  @type {boolean}
		 *  @private
		 */
		this._upTick = false;

		/**
		 *  the callback which is invoked on every tick
		 *  with the time of that tick as the argument
		 *  @type {function(number)}
		 */
		this.tick = this.defaultArg(callback, function(){});

		//setup
		this._jsNode.noGC();
		this.setRate(rate);
	};

	Tone.extend(Tone.Clock);

	/**
	 *  set the rate of the clock
	 *  optionally ramp to the rate over the rampTime
	 *  @param {Tone.Time} rate
	 *  @param {Tone.Time=} rampTime
	 */
	Tone.Clock.prototype.setRate = function(rate, rampTime){
		//convert the time to a to frequency
		var freqVal = this.secondsToFrequency(this.toSeconds(rate));
		if (!rampTime){
			this._controlSignal.cancelScheduledValues(0);
			this._controlSignal.setValue(freqVal);
		} else {
			this._controlSignal.exponentialRampToValueNow(freqVal, rampTime);
		}
	};

	/**
	 *  return the current rate
	 *
	 *  @return {number}
	 */
	Tone.Clock.prototype.getRate = function(){
		return this._controlSignal.getValue();
	};

	/**
	 *  start the clock
	 *  @param {Tone.Time} time the time when the clock should start
	 */
	Tone.Clock.prototype.start = function(time){
		//reset the oscillator
		this._oscillator = this.context.createOscillator();
		this._oscillator.type = "square";
		this._oscillator.connect(this._jsNode);
		//connect it up
		this._controlSignal.connect(this._oscillator.frequency);
		this._upTick = false;
		var startTime = this.toSeconds(time);
		this._oscillator.start(startTime);
	};

	/**
	 *  stop the clock
	 *  @param {Tone.Time} time the time when the clock should stop
	 */
	Tone.Clock.prototype.stop = function(time){
		var stopTime = this.toSeconds(time);
		this._oscillator.stop(stopTime);
	};

	/**
	 *  @private
	 *  @param  {AudioProcessingEvent} event
	 */
	Tone.Clock.prototype._processBuffer = function(event){
		var now = this.defaultArg(event.playbackTime, this.now());
		var bufferSize = this._jsNode.bufferSize;
		var incomingBuffer = event.inputBuffer.getChannelData(0);
		var upTick = this._upTick;
		for (var i = 0; i < bufferSize; i++){
			var sample = incomingBuffer[i];
			if (sample > 0 && !upTick){
				upTick = true;
				this.tick(now + this.samplesToSeconds(i));
			} else if (sample < 0 && upTick){
				upTick = false;
			}
		}
		this._upTick = upTick;
	};

	/**
	 *  clean up
	 */
	Tone.Clock.prototype.dispose = function(){
		this._jsNode.disconnect();
		this._controlSignal.dispose();
		if (this._oscillator){
			this._oscillator.disconnect();
		}
		this._jsNode.onaudioprocess = function(){};
		this._jsNode = null;
		this._controlSignal = null;
		this._oscillator = null;
	};

	return Tone.Clock;
});<commit_msg>fixes jsdoc error<commit_after>define(["Tone/core/Tone", "Tone/signal/Signal"], function(Tone){

	"use strict";

	/**
	 *  @class  a sample accurate clock built on an oscillator.
	 *          Invokes the onTick method at the set rate
	 *          NB: can cause audio glitches. use sparingly.
	 *
	 * 	@internal
	 * 	@constructor
	 * 	@extends {Tone}
	 * 	@param {number} rate the number of
	 */
	Tone.Clock = function(rate, callback){

		/**
		 *  the oscillator
		 *  @type {OscillatorNode}
		 */
		this._oscillator = null;

		/**
		 *  the script processor which listens to the oscillator
		 *  @type {ScriptProcessorNode}
		 *  @private
		 */
		this._jsNode = this.context.createScriptProcessor(this.bufferSize, 1, 1);
		this._jsNode.onaudioprocess = this._processBuffer.bind(this);

		/**
		 *  the rate control signal
		 *  @type {Tone.Signal}
		 *  @private
		 */
		this._controlSignal = new Tone.Signal(1);

		/**
		 *  whether the tick is on the up or down
		 *  @type {boolean}
		 *  @private
		 */
		this._upTick = false;

		/**
		 *  the callback which is invoked on every tick
		 *  with the time of that tick as the argument
		 *  @type {function(number)}
		 */
		this.tick = this.defaultArg(callback, function(){});

		//setup
		this._jsNode.noGC();
		this.setRate(rate);
	};

	Tone.extend(Tone.Clock);

	/**
	 *  set the rate of the clock
	 *  optionally ramp to the rate over the rampTime
	 *  @param {Tone.Time} rate
	 *  @param {Tone.Time=} rampTime
	 */
	Tone.Clock.prototype.setRate = function(rate, rampTime){
		//convert the time to a to frequency
		var freqVal = this.secondsToFrequency(this.toSeconds(rate));
		if (!rampTime){
			this._controlSignal.cancelScheduledValues(0);
			this._controlSignal.setValue(freqVal);
		} else {
			this._controlSignal.exponentialRampToValueNow(freqVal, rampTime);
		}
	};

	/**
	 *  return the current rate
	 *
	 *  @return {number}
	 */
	Tone.Clock.prototype.getRate = function(){
		return this._controlSignal.getValue();
	};

	/**
	 *  start the clock
	 *  @param {Tone.Time} time the time when the clock should start
	 */
	Tone.Clock.prototype.start = function(time){
		//reset the oscillator
		this._oscillator = this.context.createOscillator();
		this._oscillator.type = "square";
		this._oscillator.connect(this._jsNode);
		//connect it up
		this._controlSignal.connect(this._oscillator.frequency);
		this._upTick = false;
		var startTime = this.toSeconds(time);
		this._oscillator.start(startTime);
	};

	/**
	 *  stop the clock
	 *  @param {Tone.Time} time the time when the clock should stop
	 */
	Tone.Clock.prototype.stop = function(time){
		var stopTime = this.toSeconds(time);
		this._oscillator.stop(stopTime);
	};

	/**
	 *  @private
	 *  @param  {AudioProcessingEvent} event
	 */
	Tone.Clock.prototype._processBuffer = function(event){
		var now = this.defaultArg(event.playbackTime, this.now());
		var bufferSize = this._jsNode.bufferSize;
		var incomingBuffer = event.inputBuffer.getChannelData(0);
		var upTick = this._upTick;
		for (var i = 0; i < bufferSize; i++){
			var sample = incomingBuffer[i];
			if (sample > 0 && !upTick){
				upTick = true;
				this.tick(now + this.samplesToSeconds(i));
			} else if (sample < 0 && upTick){
				upTick = false;
			}
		}
		this._upTick = upTick;
	};

	/**
	 *  clean up
	 */
	Tone.Clock.prototype.dispose = function(){
		this._jsNode.disconnect();
		this._controlSignal.dispose();
		if (this._oscillator){
			this._oscillator.disconnect();
		}
		this._jsNode.onaudioprocess = function(){};
		this._jsNode = null;
		this._controlSignal = null;
		this._oscillator = null;
	};

	return Tone.Clock;
});<|endoftext|>


<commit_before>var Class = require('./Class')

var mobileRegex = /mobile/i;

var Client = Class(function() {

	this.init = function(userAgent) {
		this._userAgent = userAgent
		this._parseClient()
		this._parseOS()
	}

	this._parseClient = function() {
		(this.isChrome = this._isClient('Chrome'))
			|| (this.isFirefox = this._isClient('Firefox'))
			|| (this.isIE = this._isClient('MSIE'))
			|| (this.isSafari = this._isClient('Safari', 'Version'))
			|| (this.isOpera = this._isClient('Opera', 'Version'))

		if (this.isSafari) {
			(this.isIPhone = this._isClient('iPhone', 'Version'))
				|| (this.isIPad = this._isClient('iPad', 'Version'))
				|| (this.isIPod = this._isClient('iPod', 'Version'))
				|| (this.isAndroid = this._isClient('Android', 'Version'))
		}

		if (this.isOpera) {
			if (this._userAgent.match('Opera Mini')) { this.isOperaMini = true } // Opera mini is a cloud browser - Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/ADR-1110171336; U; en) Presto/2.9.201 Version/11.50
			if (this._userAgent.match('Opera Mobi')) { this.isMobile = true } // Opera mobile is a proper mobile browser - Opera/9.80 (Android; Opera Mini/6.5.26571/ 26.1069; U; en) Presto/2.8.119 Version/10.54
		}

		if (this._userAgent.match('Skyfire')) {
			this.isSkyFire = this._isClient('Skyfire', 'Version') // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Safari/530.17 Skyfire/2.0
		}

		if (this.isIPhone) { this.isMobile = true }
		if (this.isAndroid) {
			if (this._userAgent.match(mobileRegex)) { this.isMobile = true }
			if (this.isFirefox) { this.isMobile = true } // Firefox Android browsers do not seem to have an indication that it's a phone vs a tablet: Mozilla/5.0 (Android; Linux armv7l; rv:7.0.1) Gecko/20110928 Firefox/7.0.1 Fennec/7.0.1
		}

		this.isTablet = this.isIPad || (this.isAndroid && !this.isMobile)
		try {
			document.createEvent("TouchEvent")
			this.isTouch = true
		} catch (e) {
			this.isTouch = false
		}
	}

	this._parseOS = function() {
		if (this.isSafari) {
			this.isIOS = (this.isIPhone || this.isIPad || this.isIPod)
			if (this.isIOS) { this.osVersion = parseFloat(this._userAgent.match(/ OS (\d+_\d+)/)[1].replace('_', '.'), 10) }
		}
		return this
	}

	this.isQuirksMode = function(doc) {
		// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
		return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
	}

	this._isClient = function(name, versionString) {
		var agent = this._userAgent,
			index = agent.indexOf(name)
		if (index < 0) { return false }
		if (versionString) { index = agent.indexOf(versionString) }
		this.version = parseFloat(agent.substr(index + (versionString || name).length + 1))
		this.name = name
		return true
	}

})

if (typeof window != 'undefined') { module.exports = new Client(window.navigator.userAgent) }
else { module.exports = {} }

module.exports.parse = function(userAgent) { return new Client(userAgent) }
<commit_msg>Detect android and skyfire better<commit_after>var Class = require('./Class')

var mobileRegex = /mobile/i;

var Client = Class(function() {

	this.init = function(userAgent) {
		this._userAgent = userAgent
		this._parseClient()
		this._parseOS()
	}

	this._parseClient = function() {
		(this.isChrome = this._isClient('Chrome'))
			|| (this.isFirefox = this._isClient('Firefox'))
			|| (this.isIE = this._isClient('MSIE'))
			|| (this.isSafari = this._isClient('Safari', 'Version'))
			|| (this.isOpera = this._isClient('Opera', 'Version'))
			|| (this.isSkyFire = this._isClient('Skyfire', 'Version')) // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Safari/530.17 Skyfire/2.0

		this.isAndroid = this._isClient('Android', 'Version')

		if (this.isSafari) {
			(this.isIPhone = this._isClient('iPhone', 'Version'))
				|| (this.isIPad = this._isClient('iPad', 'Version'))
				|| (this.isIPod = this._isClient('iPod', 'Version'))
				|| (this.isAndroid = this._isClient('Android', 'Version'))
		}

		if (this.isOpera) {
			if (this._userAgent.match('Opera Mini')) { this.isOperaMini = true } // Opera mini is a cloud browser - Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/ADR-1110171336; U; en) Presto/2.9.201 Version/11.50
			if (this._userAgent.match('Opera Mobi')) { this.isMobile = true } // Opera mobile is a proper mobile browser - Opera/9.80 (Android; Opera Mini/6.5.26571/ 26.1069; U; en) Presto/2.8.119 Version/10.54
		}

		if (this.isSkyFire) { this.isMobile = true }

		if (this.isIPhone) { this.isMobile = true }
		if (this.isAndroid) {
			if (this._userAgent.match(mobileRegex)) { this.isMobile = true }
			if (this.isFirefox) { this.isMobile = true } // Firefox Android browsers do not seem to have an indication that it's a phone vs a tablet: Mozilla/5.0 (Android; Linux armv7l; rv:7.0.1) Gecko/20110928 Firefox/7.0.1 Fennec/7.0.1
		}

		this.isTablet = this.isIPad || (this.isAndroid && !this.isMobile)
		try {
			document.createEvent("TouchEvent")
			this.isTouch = true
		} catch (e) {
			this.isTouch = false
		}
	}

	this._parseOS = function() {
		if (this.isSafari) {
			this.isIOS = (this.isIPhone || this.isIPad || this.isIPod)
			if (this.isIOS) { this.osVersion = parseFloat(this._userAgent.match(/ OS (\d+_\d+)/)[1].replace('_', '.'), 10) }
		}
		return this
	}

	this.isQuirksMode = function(doc) {
		// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
		return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
	}

	this._isClient = function(name, versionString) {
		var agent = this._userAgent,
			index = agent.indexOf(name)
		if (index < 0) { return false }
		if (versionString) { index = agent.indexOf(versionString) }
		this.version = parseFloat(agent.substr(index + (versionString || name).length + 1))
		this.name = name
		return true
	}

})

if (typeof window != 'undefined') { module.exports = new Client(window.navigator.userAgent) }
else { module.exports = {} }

module.exports.parse = function(userAgent) { return new Client(userAgent) }
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. 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.
 */

foam.CLASS({
  package: 'foam.core',
  name: 'Static',
  extends: 'foam.core.AbstractMethod',

  documentation: 'An Axiom for defining static methods.',

  properties: [
    //get prop from foam.core.AbstractMethod
  ],

  methods: [
    function exportAs(obj) {
    },
    function isStatic(){ return true;},
    function installInClass(cls) {
      Object.defineProperty(
        cls,
        foam.String.constantize(this.name),
        {
          value: this.value,
          configurable: false
        });
    },
    function installInProto(proto) {
      this.installInClass(proto);
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',

  properties: [
    {
      class: 'AxiomArray',
      of: 'Static',
      name: 'static',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          var name = foam.Function.getName(o);
          foam.assert(name, 'Static must be named');
          return foam.core.Static.create({name: name, code: o});
        }

        return foam.core.Static.isInstance(o) ?
            o :
            foam.core.Static.create(o) ;
      }
    }
  ]
});
<commit_msg>Update header<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.core',
  name: 'Static',
  extends: 'foam.core.AbstractMethod',

  documentation: 'An Axiom for defining static methods.',

  properties: [
    //get prop from foam.core.AbstractMethod
  ],

  methods: [
    function exportAs(obj) {
    },
    function isStatic(){ return true;},
    function installInClass(cls) {
      Object.defineProperty(
        cls,
        foam.String.constantize(this.name),
        {
          value: this.value,
          configurable: false
        });
    },
    function installInProto(proto) {
      this.installInClass(proto);
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',

  properties: [
    {
      class: 'AxiomArray',
      of: 'Static',
      name: 'static',
      adaptArrayElement: function(o) {
        if ( typeof o === 'function' ) {
          var name = foam.Function.getName(o);
          foam.assert(name, 'Static must be named');
          return foam.core.Static.create({name: name, code: o});
        }

        return foam.core.Static.isInstance(o) ?
            o :
            foam.core.Static.create(o) ;
      }
    }
  ]
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import Icon from 'components/Icon'
import VolumeSlider from './VolumeSlider'
import NoPlayer from './NoPlayer'
import './PlaybackCtrl.css'

const PlaybackCtrl = (props) => {
  if (!props.isInRoom) {
    return null
  }

  if (props.isAdmin && !props.isPlayerPresent) {
    return <NoPlayer />
  }

  const { isPlaying, isAtQueueEnd } = props

  return (

      {isPlaying &&

          <Icon icon='PAUSE' size={42} styleName='pause' />

      }
      {!isPlaying &&

          <Icon icon='PLAY' size={42} styleName='play' />

      }

        <Icon icon='PLAY_NEXT' size={48} styleName={'next ' + (isAtQueueEnd ? ' disabled' : '')} />

      <VolumeSlider
        styleName='volume'
        volume={props.volume}
        onVolumeChange={props.requestVolume}
      />

  )
}

PlaybackCtrl.propTypes = {
  isAdmin: PropTypes.bool.isRequired,
  isInRoom: PropTypes.bool.isRequired,
  isPlaying: PropTypes.bool.isRequired,
  isAtQueueEnd: PropTypes.bool.isRequired,
  volume: PropTypes.number.isRequired,
  isPlayerPresent: PropTypes.bool.isRequired,
  // actions
  requestPlay: PropTypes.func.isRequired,
  requestPlayNext: PropTypes.func.isRequired,
  requestPause: PropTypes.func.isRequired,
  requestVolume: PropTypes.func.isRequired,
}

export default PlaybackCtrl
<commit_msg>Only show Player link if fullscreen is possible<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import screenfull from 'screenfull'
import Icon from 'components/Icon'
import VolumeSlider from './VolumeSlider'
import NoPlayer from './NoPlayer'
import './PlaybackCtrl.css'

const PlaybackCtrl = (props) => {
  if (!props.isInRoom) {
    return null
  }

  if (props.isAdmin && !props.isPlayerPresent && screenfull.enabled) {
    return <NoPlayer />
  }

  const { isPlaying, isAtQueueEnd } = props

  return (

      {isPlaying &&

          <Icon icon='PAUSE' size={42} styleName='pause' />

      }
      {!isPlaying &&

          <Icon icon='PLAY' size={42} styleName='play' />

      }

        <Icon icon='PLAY_NEXT' size={48} styleName={'next ' + (isAtQueueEnd ? ' disabled' : '')} />

      <VolumeSlider
        styleName='volume'
        volume={props.volume}
        onVolumeChange={props.requestVolume}
      />

  )
}

PlaybackCtrl.propTypes = {
  isAdmin: PropTypes.bool.isRequired,
  isInRoom: PropTypes.bool.isRequired,
  isPlaying: PropTypes.bool.isRequired,
  isAtQueueEnd: PropTypes.bool.isRequired,
  volume: PropTypes.number.isRequired,
  isPlayerPresent: PropTypes.bool.isRequired,
  // actions
  requestPlay: PropTypes.func.isRequired,
  requestPlayNext: PropTypes.func.isRequired,
  requestPause: PropTypes.func.isRequired,
  requestVolume: PropTypes.func.isRequired,
}

export default PlaybackCtrl
<|endoftext|>


<commit_before>import HasManyRelation from './has-many';
import RelationLoader from './util/relation-loader';
import QueryFindMixin from '../../util/query-find-mixin';
import RelationQueryMixin from './query/relation';
import RelationFindQueryMixin from './query/relation-find';

export default class HasManyLoadedRelation extends HasManyRelation {

  constructor() {
    super(...arguments);
    this.loader = new RelationLoader(this);
  }

  createArrayProxy(owner, content) {
    let _relation = this;
    return owner.factoryFor('sofa:has-many-loaded').create({ _relation, content });
  }

  createQuery() {
    return this.relationship.createQuery(this, 'relation-find', Query => {
      return Query.extend(QueryFindMixin, RelationQueryMixin, RelationFindQueryMixin);
    });
  }

  relationLoaderDidLoad(array) {
    this.setValue(array);
  }

  serialize(type) {
    let isLoaded = this.loader.state.isLoaded;
    let content = this.serializeInternalModelsToDocIds(this.getContent(), type);
    return { isLoaded, content };
  }

  deserialize(value, changed) {
    let internals = this.deserializeDocIdsToModels(value.content);
    let isLoaded = value.isLoaded;
    this.setValue(internals, changed);
    this.loader.setState({ isLoaded }, false);
  }

}
<commit_msg>fixes for has-many-loaded fastboot<commit_after>import HasManyRelation from './has-many';
import RelationLoader from './util/relation-loader';
import QueryFindMixin from '../../util/query-find-mixin';
import RelationQueryMixin from './query/relation';
import RelationFindQueryMixin from './query/relation-find';

export default class HasManyLoadedRelation extends HasManyRelation {

  constructor() {
    super(...arguments);
    this.loader = new RelationLoader(this);
  }

  createArrayProxy(owner, content) {
    let _relation = this;
    return owner.factoryFor('sofa:has-many-loaded').create({ _relation, content });
  }

  createQuery() {
    return this.relationship.createQuery(this, 'relation-find', Query => {
      return Query.extend(QueryFindMixin, RelationQueryMixin, RelationFindQueryMixin);
    });
  }

  relationLoaderDidLoad(array) {
    this.setValue(array);
  }

  serialize(type) {
    let isLoaded = this.loader.state.isLoaded;
    let content = this.serializeInternalModelsToDocIds(this.getContent(), type);
    return { isLoaded, content };
  }

  deserialize(value, changed) {
    let internals = this.deserializeDocIdsToModels(value.content);
    this.setValue(internals, changed);
    if(value.isLoaded) {
      this.loader.setLoaded();
    }
  }

}
<|endoftext|>


<commit_before>"use strict";
var Item = require('./transactions').item,
  List = require('./transactions').list,
  moment = require('moment'),
  _ = require('lodash'),
  when = require('when'),
  stripe = require('stripe')(process.env.STRIPE_KEY);

// Model interactions

module.exports = {

  save: function (trans) {
    var promise, actions = [], list = new List();

    promise = when.promise(function (resolve, reject) {

      stripe.balance.retrieveTransaction(
        trans.data.object.balance_transaction,
        function(err, balanceTransaction) {

          if (err) {
            console.log(err);
            reject(err);
            return false;
          }

          var date = moment.unix(balanceTransaction.available_on).format('YYYY.MM.DD'),
              time = moment(balanceTransaction.available_on).format('HH:MM');

          _.forEach(balanceTransaction.fee_details, function (fee) {
            var obj;

            obj = {
              date: date,
              time: time,
              name: trans.data.object.source.name,
              amount: fee.amount
            };

            list.transactions.push(new Item(obj));
          });

          list.save()
          .catch(function (err) {
            reject(err);
          })
          .then(function (reply) {
            resolve(reply);
          });
        }
      );

    });

    return promise;
  },

  report: function () {
    var promise, list = new List(), week = 'w' + moment().isoWeek();

    return list.fetch(week)
    .then(function (result) {
      return list;
    });
  }

};
<commit_msg>Update events.js<commit_after>"use strict";
var Item = require('./transactions').item,
  List = require('./transactions').list,
  moment = require('moment'),
  _ = require('lodash'),
  when = require('when'),
  stripe = require('stripe')(process.env.STRIPE_KEY);

// Model interactions

module.exports = {

  save: function (trans) {
    var promise, actions = [], list = new List();

    promise = when.promise(function (resolve, reject) {

      stripe.balance.retrieveTransaction(
        trans.data.object.balance_transaction,
        function(err, balanceTransaction) {

          if (err) {
            console.log(err);
            reject(err);
            return false;
          }

          var date = moment.unix(balanceTransaction.available_on).format('YYYY.MM.DD'),
              time = moment.unix(balanceTransaction.available_on).format('HH:MM');

          _.forEach(balanceTransaction.fee_details, function (fee) {
            var obj;

            obj = {
              date: date,
              time: time,
              name: trans.data.object.source.name,
              amount: fee.amount
            };

            list.transactions.push(new Item(obj));
          });

          list.save()
          .catch(function (err) {
            reject(err);
          })
          .then(function (reply) {
            resolve(reply);
          });
        }
      );

    });

    return promise;
  },

  report: function () {
    var promise, list = new List(), week = 'w' + moment().isoWeek();

    return list.fetch(week)
    .then(function (result) {
      return list;
    });
  }

};
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import {Touchable} from '../touchable'
import {rightButtonStyles as styles} from './styles'

type State = {
  favorited: boolean,
}

export class FavoriteButton extends React.PureComponent<Props, State> {
  constructor(props) {
    super(props);
    this.onPress = this.onPress.bind(this);
  }

  state = {
    favorited: this.props.favorited,
  }

  render() {
    if (this.state.favorited) {
      // console.log("Favorited")
      return (
        <Touchable
          highlight={false}
          onPress={() => {this.onPress(); this.props.onFavorite();}}
          style={styles.button}
        >
          {Platform.OS === 'ios' ? (
            <Icon name="ios-heart" style={styles.icon} />
          ) : (
            <Icon name="md-heart" style={styles.icon} />
          )}
        </Touchable>
      )
    } else {
      // console.log("Not favorited")
      return (
        <Touchable
          highlight={false}
          onPress={() => {this.onPress(); this.props.onFavorite();}}
          style={styles.button}
        >
          {Platform.OS === 'ios' ? (
            <Icon name="ios-heart-outline" style={styles.icon} />
          ) : (
            <Icon name="md-heart-outline" style={styles.icon} />
          )}
        </Touchable>
      )
    }
  }
  onPress () {
    if (this.state.favorited) {
      this.setState({favorited: false});
    } else {
      this.setState({favorited: true});
    }
  }
}
<commit_msg>removed console.logs<commit_after>// @flow

import * as React from 'react'
import {Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import {Touchable} from '../touchable'
import {rightButtonStyles as styles} from './styles'

type State = {
  favorited: boolean,
}

export class FavoriteButton extends React.PureComponent<Props, State> {
  constructor(props) {
    super(props);
    this.onPress = this.onPress.bind(this);
  }

  state = {
    favorited: this.props.favorited,
  }

  render() {
    if (this.state.favorited) {
      return (
        <Touchable
          highlight={false}
          onPress={() => {this.onPress(); this.props.onFavorite();}}
          style={styles.button}
        >
          {Platform.OS === 'ios' ? (
            <Icon name="ios-heart" style={styles.icon} />
          ) : (
            <Icon name="md-heart" style={styles.icon} />
          )}
        </Touchable>
      )
    } else {
      return (
        <Touchable
          highlight={false}
          onPress={() => {this.onPress(); this.props.onFavorite();}}
          style={styles.button}
        >
          {Platform.OS === 'ios' ? (
            <Icon name="ios-heart-outline" style={styles.icon} />
          ) : (
            <Icon name="md-heart-outline" style={styles.icon} />
          )}
        </Touchable>
      )
    }
  }
  onPress () {
    if (this.state.favorited) {
      this.setState({favorited: false});
    } else {
      this.setState({favorited: true});
    }
  }
}
<|endoftext|>


<commit_before>import * as yup from 'yup';
import i18next from '../../core/language';

const t = i18next.t.bind(i18next);

export default yup.object().shape({
  type: yup.string().oneOf(['caregiver', 'patient'], 'Please select a valid option'),
  firstName: yup.string().required(t('First name is required')),
  lastName: yup.string().required(t('Last name is required')),
  birthday: yup.date().required(t('Patient\'s birthday is required')),
  email: yup.string().email(t('Please enter a valid email address')).required(t('Email address is required')),
  emailConfirm: yup.string()
    .oneOf([yup.ref('email')], 'Email address confirmation does not match')
    .required('Email confirmation is required'),
});
<commit_msg>[WEB-819] Add required validation to prescription account type<commit_after>import * as yup from 'yup';
import i18next from '../../core/language';

const t = i18next.t.bind(i18next);

export default yup.object().shape({
  type: yup.string().oneOf(['caregiver', 'patient'], 'Please select a valid option').required(t('Account type is required')),
  firstName: yup.string().required(t('First name is required')),
  lastName: yup.string().required(t('Last name is required')),
  birthday: yup.date().required(t('Patient\'s birthday is required')),
  email: yup.string().email(t('Please enter a valid email address')).required(t('Email address is required')),
  emailConfirm: yup.string()
    .oneOf([yup.ref('email')], 'Email address confirmation does not match')
    .required('Email confirmation is required'),
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var onlineSGDRegression = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof onlineSGDRegression, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if the `options` object is not a simple object', function test( t ) {
	var values;
	var i;

	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		[],
		function(){}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			onlineSGDRegression( value );
		};
	}
});

tape( 'the `loss` option of the function specifies the used loss function', function test( t ) {
	var values;
	var model;
	var len;
	var i;

	values = [
		'epsilonInsensitive',
		'huber',
		'squaredError'
	];
	len = values.length;

	for ( i = 0; i < len; i++ ) {
		model = onlineSGDRegression({
			'loss': values[ i ]
		});
	}

	t.end();
});

tape( 'the function throws an error if supplied an unknown `loss` option', function test( t ) {
	t.throws( badValue, Error, 'throws an error when provided unknown loss' );
	t.end();

	function badValue() {
		onlineSGDRegression({
			'loss': 'hilbert'
		});
	}
});

tape( 'the `learningRate` option can be used to set the strength schedule of the gradient descent algorithm', function test( t ) {
	var values;
	var len;
	var i;

	values = [
		'basic',
		'constant',
		'pegasos'
	];
	for ( i = 0; i < len; i++ ) {
		onlineSGDRegression({
			'learningRate': values[ i ]
		});
	}
	t.end();
});

tape( 'the constructor throws an error if supplied an unknown `learningRate` option', function test( t ) {
	t.throws( badValue, Error, 'throws an error when provided unknown learning rate' );
	t.end();

	function badValue() {
		onlineSGDRegression({
			'learningRate': 'scaling'
		});
	}
});

tape( 'the function has an `intercept` option determining whether the regression model should include an implicit intercept / bias term', function test( t ) {
	var model;

	model = onlineSGDRegression({
		'intercept': true
	});
	model.update( [1.0,1.0,1.0], 2.0 );
	t.equal( model.coefs.length, 4, 'the model contains a regression coefficient for the intercept' );

	model = onlineSGDRegression({
		'intercept': false
	});
	model.update( [1.0,1.0,1.0], 2.0 );
	t.equal( model.coefs.length, 3, 'the model does not contain an intercept regression coefficient' );

	t.end();
});

tape( 'the `update` method throws an error if the `x` value is not an array', function test( t ) {
	var values;
	var model;
	var i;
	var y;

	model = onlineSGDRegression();
	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		{},
		function(){}
	];
	y = 2.0;

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			model.update( value, y );
		};
	}
});

tape( 'the `update` method throws an error if the `x` is an array with an invalid number of elements', function test( t ) {
	var model;
	var i;
	var y;
	var x;

	model = onlineSGDRegression();
	y = 2.0;
	x = [1.0,1.0];
	model.update( x, y );

	for ( i = 0; i < 10; i++ ) {
		x.push( 1.0 );
		t.throws( badValue, TypeError, 'throws an error when provided an array of any length other than two' );
	}
	t.end();

	function badValue() {
		model.update( x, y );
	}
});

tape( 'the `predict` method calculates the inner product of the weights and feature vector `x`', function test( t ) {
	var expected;
	var weights;
	var actual;
	var model;
	var i;
	var x;

	model = onlineSGDRegression();
	model.update( [0.0,0.0], 2.0 );
	weights = model.coefs;

	x = [ 2.0, 2.0 ];
	actual = model.predict( x );
	expected = 0;
	for ( i = 0; i < weights.length; i++ ) {
		expected += x[ i ] * weights[ i ];
	}

	t.end();
});

tape( 'the `predict` method throws an error if the `x` value is not an array', function test( t ) {
	var values;
	var model;
	var i;

	model = onlineSGDRegression();
	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		{},
		function(){}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			model.predict( value );
		};
	}
});

tape( 'the `predict` method throws an error if the `x` is an array with an invalid number of elements', function test( t ) {
	var model;
	var i;
	var x;

	model = onlineSGDRegression();
	x = [1.0,1.0];
	model.update( x, 2.0 );

	for ( i = 0; i < 10; i++ ) {
		x.push( 1.0 );
		t.throws( badValue, TypeError, 'throws an error when provided an array of any length other than two' );
	}
	t.end();

	function badValue() {
		model.predict( x );
	}
});
<commit_msg>Finish tests<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var onlineSGDRegression = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof onlineSGDRegression, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if the `options` object is not a simple object', function test( t ) {
	var values;
	var i;

	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		[],
		function(){}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			onlineSGDRegression( value );
		};
	}
});

tape( 'the `loss` option of the function specifies the used loss function', function test( t ) {
	var values;
	var model;
	var len;
	var i;

	values = [
		'epsilonInsensitive',
		'huber',
		'squaredError'
	];
	len = values.length;

	for ( i = 0; i < len; i++ ) {
		model = onlineSGDRegression({
			'loss': values[ i ]
		});
	}

	t.end();
});

tape( 'the function throws an error if supplied an unknown `loss` option', function test( t ) {
	t.throws( badValue, Error, 'throws an error when provided unknown loss' );
	t.end();

	function badValue() {
		onlineSGDRegression({
			'loss': 'hilbert'
		});
	}
});

tape( 'the `learningRate` option can be used to set the strength schedule of the gradient descent algorithm', function test( t ) {
	var values;
	var len;
	var i;

	values = [
		'basic',
		'constant',
		'pegasos'
	];
	for ( i = 0; i < len; i++ ) {
		onlineSGDRegression({
			'learningRate': values[ i ]
		});
	}
	t.end();
});

tape( 'the constructor throws an error if supplied an unknown `learningRate` option', function test( t ) {
	t.throws( badValue, Error, 'throws an error when provided unknown learning rate' );
	t.end();

	function badValue() {
		onlineSGDRegression({
			'learningRate': 'scaling'
		});
	}
});

tape( 'the function has an `intercept` option determining whether the regression model should include an implicit intercept / bias term', function test( t ) {
	var model;

	model = onlineSGDRegression({
		'intercept': true
	});
	model.update( [1.0,1.0,1.0], 2.0 );
	t.equal( model.coefs.length, 4, 'the model contains a regression coefficient for the intercept' );

	model = onlineSGDRegression({
		'intercept': false
	});
	model.update( [1.0,1.0,1.0], 2.0 );
	t.equal( model.coefs.length, 3, 'the model does not contain an intercept regression coefficient' );

	t.end();
});

tape( 'the `update` method throws an error if the `x` value is not an array', function test( t ) {
	var values;
	var model;
	var i;
	var y;

	model = onlineSGDRegression();
	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		{},
		function(){}
	];
	y = 2.0;

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			model.update( value, y );
		};
	}
});

tape( 'the `update` method throws an error if the `x` is an array with an invalid number of elements', function test( t ) {
	var model;
	var i;
	var y;
	var x;

	model = onlineSGDRegression();
	y = 2.0;
	x = [1.0,1.0];
	model.update( x, y );

	for ( i = 0; i < 10; i++ ) {
		x.push( 1.0 );
		t.throws( badValue, TypeError, 'throws an error when provided an array of any length other than two' );
	}
	t.end();

	function badValue() {
		model.update( x, y );
	}
});

tape( 'the `predict` method calculates the inner product of the weights and feature vector `x`', function test( t ) {
	var expected;
	var weights;
	var actual;
	var model;
	var i;
	var x;

	model = onlineSGDRegression();
	model.update( [0.0,0.0], 2.0 );
	weights = model.coefs;

	x = [ 2.0, 2.0 ];
	actual = model.predict( x );

	// Add intercept...
	x.push( 1.0 );
	expected = 0;
	for ( i = 0; i < weights.length; i++ ) {
		expected += x[ i ] * weights[ i ];
	}
	t.deepEqual( actual, expected, 'deep equal' );

	t.end();
});

tape( 'the `predict` method throws an error if the `x` value is not an array', function test( t ) {
	var values;
	var model;
	var i;

	model = onlineSGDRegression();
	values = [
		'abc',
		5,
		null,
		true,
		undefined,
		NaN,
		{},
		function(){}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			model.predict( value );
		};
	}
});

tape( 'the `predict` method throws an error if the `x` is an array with an invalid number of elements', function test( t ) {
	var model;
	var i;
	var x;

	model = onlineSGDRegression();
	x = [1.0,1.0];
	model.update( x, 2.0 );

	for ( i = 0; i < 10; i++ ) {
		x.push( 1.0 );
		t.throws( badValue, TypeError, 'throws an error when provided an array of any length other than two' );
	}
	t.end();

	function badValue() {
		model.predict( x );
	}
});
<|endoftext|>


<commit_before>import test from 'ava';
import React from 'react';
import {shallow, mount} from 'enzyme';
import ReactDOM from 'react-dom';

import { MyPage } from '../MyPage'

test('component renders', t => {
  const wrapper = shallow(
    <MyPage />
  )

  t.deepEqual(wrapper.find('div').length, 1);
});
<commit_msg>fix test<commit_after>import test from 'ava';
import React from 'react';
import {shallow, mount} from 'enzyme';
import ReactDOM from 'react-dom';

import { MyPage } from '../MyPage'

test('component renders', t => {
  const wrapper = shallow(
    <MyPage />
  )

  t.deepEqual(wrapper.find('.center').length, 1);
});
<|endoftext|>


<commit_before>'use strict';

// Necessary Plugins
var gulp     = require('gulp')
    ,paths   = require('../paths')
    ,stylint = require('gulp-stylint');

// Call Stylus Linter
module.exports = gulp.task('stylint', function () {
  return gulp.src('paths.source.styl')
      .pipe(stylint({config: '.stylintrc'}))
});
<commit_msg>Remove old stylus linting task<commit_after><|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { AddressList, Select } from '@folio/stripes/smart-components';
import { toAddressTypeOptions } from '../../converters/address_type';

class UserAddresses extends React.Component {
  static propTypes = {
    addresses: PropTypes.arrayOf(PropTypes.object),
    addressTypes: PropTypes.arrayOf(PropTypes.object),
    onUpdate: PropTypes.func,
    expanded: PropTypes.bool,
    editable: PropTypes.bool,
    intl: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.onUpdate = this.onUpdate.bind(this);
    this.onDelete = this.onDelete.bind(this);

    this.addressList = null;
  }

  onDelete(addr) {
    this.removeAddress(addr);
    this.props.onUpdate(this.props.addresses);
  }

  onUpdate(addr) {
    this.addAddress(addr);
    this.props.onUpdate(this.props.addresses);
  }

  addAddress(addr) {
    const addresses = this.props.addresses;
    let index = 0;

    /* eslint-disable no-param-reassign */
    addr.id = addr.id || _.uniqueId();

    if (addresses.length) {
      index = _.findIndex(addresses, a => a.id === addr.id);
      if (index === -1) index = addresses.length;
    }

    addresses[index] = addr;
  }

  removeAddress(id) {
    const addresses = this.props.addresses;
    const index = _.findIndex(addresses, addr => addr.id === id);
    addresses.splice(index, 1);
  }

  render() {
    const { addresses, addressTypes, intl } = this.props;

    if (!addresses) return (<div />);

    const addressFields = {
      addressType: {
        component: Select,
        props: {
          dataOptions: toAddressTypeOptions(addressTypes),
          fullWidth: true,
          placeholder: intl.formatMessage({ id: 'ui-users.contact.selectAddressType' }),
        },
      },
    };

    return (<AddressList
      label={intl.formatMessage({ id: 'ui-users.contact.addresses' })}
      onUpdate={this.onUpdate}
      onCreate={this.onUpdate}
      onDelete={this.onDelete}
      fieldComponents={addressFields}
      addresses={this.props.addresses}
      expanded={this.props.expanded}
      canEdit={this.props.editable}
      canDelete={this.props.editable}
    />);
  }
}

export default UserAddresses;
<commit_msg>fix Select import<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { AddressList } from '@folio/stripes/smart-components';
import { Select } from '@folio/stripes/components';
import { toAddressTypeOptions } from '../../converters/address_type';

class UserAddresses extends React.Component {
  static propTypes = {
    addresses: PropTypes.arrayOf(PropTypes.object),
    addressTypes: PropTypes.arrayOf(PropTypes.object),
    onUpdate: PropTypes.func,
    expanded: PropTypes.bool,
    editable: PropTypes.bool,
    intl: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.onUpdate = this.onUpdate.bind(this);
    this.onDelete = this.onDelete.bind(this);

    this.addressList = null;
  }

  onDelete(addr) {
    this.removeAddress(addr);
    this.props.onUpdate(this.props.addresses);
  }

  onUpdate(addr) {
    this.addAddress(addr);
    this.props.onUpdate(this.props.addresses);
  }

  addAddress(addr) {
    const addresses = this.props.addresses;
    let index = 0;

    /* eslint-disable no-param-reassign */
    addr.id = addr.id || _.uniqueId();

    if (addresses.length) {
      index = _.findIndex(addresses, a => a.id === addr.id);
      if (index === -1) index = addresses.length;
    }

    addresses[index] = addr;
  }

  removeAddress(id) {
    const addresses = this.props.addresses;
    const index = _.findIndex(addresses, addr => addr.id === id);
    addresses.splice(index, 1);
  }

  render() {
    const { addresses, addressTypes, intl } = this.props;

    if (!addresses) return (<div />);

    const addressFields = {
      addressType: {
        component: Select,
        props: {
          dataOptions: toAddressTypeOptions(addressTypes),
          fullWidth: true,
          placeholder: intl.formatMessage({ id: 'ui-users.contact.selectAddressType' }),
        },
      },
    };

    return (<AddressList
      label={intl.formatMessage({ id: 'ui-users.contact.addresses' })}
      onUpdate={this.onUpdate}
      onCreate={this.onUpdate}
      onDelete={this.onDelete}
      fieldComponents={addressFields}
      addresses={this.props.addresses}
      expanded={this.props.expanded}
      canEdit={this.props.editable}
      canDelete={this.props.editable}
    />);
  }
}

export default UserAddresses;
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/signal/WaveShaper"], function(Tone){

	"use strict";

	/**
	 *  @class Pow applies an exponent to the incoming signal. The incoming signal
	 *         must be AudioRange.
	 *
	 *  @extends {Tone.SignalBase}
	 *  @constructor
	 *  @param {number} exp The exponent to apply to the incoming signal, must be at least 2.
	 *  @example
	 * var pow = new Tone.Pow(2);
	 * var sig = new Tone.Signal(0.5).connect(pow);
	 * //output of pow is 0.25.
	 */
	Tone.Pow = function(exp){

		/**
		 * the exponent
		 * @private
		 * @type {number}
		 */
		this._exp = this.defaultArg(exp, 1);

		/**
		 *  @type {WaveShaperNode}
		 *  @private
		 */
		this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192);
	};

	Tone.extend(Tone.Pow, Tone.SignalBase);

	/**
	 * The value of the exponent.
	 * @memberOf Tone.Pow#
	 * @type {number}
	 * @name value
	 */
	Object.defineProperty(Tone.Pow.prototype, "value", {
		get : function(){
			return this._exp;
		},
		set : function(exp){
			this._exp = exp;
			this._expScaler.setMap(this._expFunc(this._exp));
		}
	});

	/**
	 *  the function which maps the waveshaper
	 *  @param   {number} exp
	 *  @return {function}
	 *  @private
	 */
	Tone.Pow.prototype._expFunc = function(exp){
		return function(val){
			return Math.pow(Math.abs(val), exp);
		};
	};

	/**
	 *  Clean up.
	 *  @returns {Tone.Pow} this
	 */
	Tone.Pow.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this._expScaler.dispose();
		this._expScaler = null;
		return this;
	};

	return Tone.Pow;
});<commit_msg>updating doc<commit_after>define(["Tone/core/Tone", "Tone/signal/WaveShaper"], function(Tone){

	"use strict";

	/**
	 *  @class Pow applies an exponent to the incoming signal. The incoming signal
	 *         must be AudioRange.
	 *
	 *  @extends {Tone.SignalBase}
	 *  @constructor
	 *  @param {Positive} exp The exponent to apply to the incoming signal, must be at least 2.
	 *  @example
	 * var pow = new Tone.Pow(2);
	 * var sig = new Tone.Signal(0.5).connect(pow);
	 * //output of pow is 0.25.
	 */
	Tone.Pow = function(exp){

		/**
		 * the exponent
		 * @private
		 * @type {number}
		 */
		this._exp = this.defaultArg(exp, 1);

		/**
		 *  @type {WaveShaperNode}
		 *  @private
		 */
		this._expScaler = this.input = this.output = new Tone.WaveShaper(this._expFunc(this._exp), 8192);
	};

	Tone.extend(Tone.Pow, Tone.SignalBase);

	/**
	 * The value of the exponent.
	 * @memberOf Tone.Pow#
	 * @type {number}
	 * @name value
	 */
	Object.defineProperty(Tone.Pow.prototype, "value", {
		get : function(){
			return this._exp;
		},
		set : function(exp){
			this._exp = exp;
			this._expScaler.setMap(this._expFunc(this._exp));
		}
	});

	/**
	 *  the function which maps the waveshaper
	 *  @param   {number} exp
	 *  @return {function}
	 *  @private
	 */
	Tone.Pow.prototype._expFunc = function(exp){
		return function(val){
			return Math.pow(Math.abs(val), exp);
		};
	};

	/**
	 *  Clean up.
	 *  @returns {Tone.Pow} this
	 */
	Tone.Pow.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this._expScaler.dispose();
		this._expScaler = null;
		return this;
	};

	return Tone.Pow;
});<|endoftext|>


<commit_before>'use strict';

function HomeWorld() {
    this.__init__();
}

const MONTH_VIEW_RADIUS = 3000;

HomeWorld.prototype = {

    //
    entity_walls: null,

    //
    loaded_entities: null,

    create_month_day_wall: function(day, index, total_number_of_days) {
        var w = 500;
        var h = 1000;

        var percentage = index / total_number_of_days;
        var x_position = cos(percentage * TWO_PIE) * MONTH_VIEW_RADIUS;
        var z_position = sin(percentage * TWO_PIE) * MONTH_VIEW_RADIUS;

        var p = new THREE.Vector3(x_position, 1000, z_position);
        var n = new THREE.Vector3(-x_position, 1000, -z_position);

        var month_day_wall = new FloatingWall(w, h, p, n, this, false);
        month_day_wall.add_3d_title(day.to_string_without_year());

        return month_day_wall;
    },

    __init__: function() {

        World.call(this, 'HomeWorld');

        this.loaded_entities = false;

        this.entity_walls = [];

        // TODO : What is this for?
        this.players = [];

        // The 360 schedule view.
        this.month_day_walls = [];
        this.month_days = new MyDates(THIS_MONTH);

        for (var md = 0; md < this.month_days.length; md++) {
            this.month_day_walls.push(this.create_month_day_wall(this.month_days[md], md, this.month_days.length));
        }

        // Create a seperate class for this!

        /*   __   __        ___  __             ___            ___
            /__` /  ` |__| |__  |  \ |  | |    |__     \  / | |__  |  |    .
            .__/ \__, |  | |___ |__/ \__/ |___ |___     \/  | |___ |/\|    .*/
        /*
        var schedule_view_height = 1000;

        this.test_positions = [];
        this.schedule_floating_day_titles = [];

        var today = get_today_with_n_days_offset(0);

        for (var i = 0; i < 15; i++) {
            this.test_positions.push([cos((i / 15) * TWO_PIE), sin((i / 15) * TWO_PIE)]);

            var magnitude_value = 2500;

            var p = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height, sin((i / 15) * TWO_PIE) * magnitude_value);
            var p2 = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height - 200, sin((i / 15) * TWO_PIE) * magnitude_value);
            var p3 = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height - 400, sin((i / 15) * TWO_PIE) * magnitude_value);
            var look_at = new THREE.Vector3(0, schedule_view_height, 0);
            var look_at2 = new THREE.Vector3(0, schedule_view_height - 200, 0);
            var look_at3 = new THREE.Vector3(0, schedule_view_height - 400, 0);

            //this.make_entity_wall_public_button = new Floating2DText(this.width, 'Make Entity Wall Public', TYPE_BUTTON, this.scene);

            var color = null;

            switch(i-7) {
            case -7:
                color = COLOR_DAY_PAST_SEVEN;
                break;
            case -6:
                color = COLOR_DAY_PAST_SIX;
                break;
            case -5:
                color = COLOR_DAY_PAST_FIVE;
                break;
            case -4:
                color = COLOR_DAY_PAST_FOUR;
                break;
            case -3:
                color = COLOR_DAY_PAST_THREE;
                break;
            case -2:
                color = COLOR_DAY_PAST_TWO;
                break;
            case -1:
                color = COLOR_DAY_PAST_ONE;
                break;
            case 0:
                color = COLOR_DAY_PRESENT;
                break;
            case 1:
                color = COLOR_DAY_FUTURE_ONE;
                break;
            case 2:
                color = COLOR_DAY_FUTURE_TWO;
                break;
            case 3:
                color = COLOR_DAY_FUTURE_THREE;
                break;
            case 4:
                color = COLOR_DAY_FUTURE_FOUR;
                break;
            case 5:
                color = COLOR_DAY_FUTURE_FIVE;
                break;
            case 6:
                color = COLOR_DAY_FUTURE_SIX;
                break;
            case 7:
                color = COLOR_DAY_FUTURE_SEVEN;
                break;
            }

            var day_of_week_word = get_day_of_week_as_word(get_just_date_object_of_date_of_n_days_offset(i - 7));
            var full_date_of_day = get_today_with_n_days_offset(i - 7);

            if (get_day_of_week_as_word(today) === get_day_of_week_as_word(full_date_of_day)) {
                var floating_3d_subtitle_2 = new Floating3DText(schedule_view_height - 400, 'Today', TYPE_TITLE, this.scene, color);
                floating_3d_subtitle_2.update_position_and_look_at(p3, look_at3);
            }

            var floating_3d_text = new Floating3DText(schedule_view_height, day_of_week_word, TYPE_SUPER_TITLE, this.scene, color);
            floating_3d_text.update_position_and_look_at(p, look_at);

            var floating_3d_subtitle = new Floating3DText(schedule_view_height - 200, full_date_of_day, TYPE_TITLE, this.scene, color);
            floating_3d_subtitle.update_position_and_look_at(p2, look_at2);

            this.schedule_floating_day_titles.push(floating_3d_text);
        }
        */
    },

    //remove_entity: function()

    create_entity_wall_command_entered: function() {
        // The wall will be generated 100 units away from the player and looking at the player (while perpendicular to the y-axis).
        var player_position = CURRENT_PLAYER.get_position();
        var player_normal = CURRENT_PLAYER.get_direction();
        var wall_normal = new THREE.Vector3(-player_normal.x, 0, -player_normal.z);
        var wall_position = new THREE.Vector3(player_position.x + player_normal.x * 100, player_position.y, player_position.z + player_normal.z * 100);
        var wall_width = 512;
        var wall_height = 512;
        var wall_normal_depth = 2;

        // Create the entity wall entity.
        var save_data = {};
        save_data[ENTITY_PROPERTY_POSITION] = '[' + wall_position.x + ',' + wall_position.y + ',' + wall_position.z + ']';
        save_data[ENTITY_PROPERTY_NORMAL] = '[' + wall_normal.x + ',' + wall_normal.y + ',' + wall_normal.z + ']';
        save_data[ENTITY_PROPERTY_WIDTH] = wall_width;
        save_data[ENTITY_PROPERTY_HEIGHT] = wall_height;
        save_data[ENTITY_PROPERTY_NORMAL_DEPTH] = wall_normal_depth;
        save_data[ENTITY_PROPERTY_NAME] = 'generic entity group';
        save_data[ENTITY_DEFAULT_PROPERTY_TYPE] = ENTITY_TYPE_WALL;
        var entity_wall_entity = new Entity(save_data);

        var entity_wall = new EntityWall(this, entity_wall_entity);
        this.entity_walls.push(entity_wall);
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event);
    },

    prepare_for_save: function() {
        for (var i = 0; i < this.entity_walls.length; i++) {
            this.entity_walls[i].prepare_for_save();
        }
    },

    load_entity_walls: function() {
        var wall_entities = MANAGER_ENTITY.get_all_entities_of_type(ENTITY_TYPE_WALL);
        for (var w = 0; w < wall_entities.length; w++) {
            // FOR_DEV_START
            if (!is_defined(wall_entities[w])) {
                GUI_PAUSED_MENU.add_server_message('Entity wall is not defined? Investigate.');
                l('There is non-defined entity wall being processed! Investigate!');
            }
            // FOR_DEV_END

            //var save_data = wall_entities[w].get_all_properties();

            // Get the matching entity from the Entity Manager.

            //l(save_data);
            //var entity_wall_entity = new Entity(save_data);

            // TODO : Optimize later.
            //MANAGER_ENTITY.link_entities();

            //var entity_wall = new EntityWall(this, entity_wall_entity);
            this.entity_walls.push(new EntityWall(this, wall_entities[w]));
        }
    },

    update: function() {
        // Get the task entities once all entities have been loaded.
        if (!this.loaded_entities) {
            if (!MANAGER_ENTITY.currently_loading()) {
                // Now create the entity walls from the entities.
                this.load_entity_walls();

                this.loaded_entities = true;
            }
        } else {

            // TODO : Fix this system so only one floating wall at a time gets grabbed.

            // Update all the FloatingWalls.
            for (var i = 0; i < this.entity_walls.length; i++) {
                this.entity_walls[i].update();
            }

            // Now that all the entity walls have been updated check for the closest intersection point if any.
            for (i = 0; i < this.entity_walls.length; i++) {
                // TODO : This!!
            }
        }

        // World function.
        this.update_interactive_objects();
    },

    enter_world: function() {
        CURRENT_PLAYER.disengage();
        if (!GUI_PAUSED_MENU.currently_displayed) {
            CURRENT_PLAYER.enable_controls();
        }
        CURRENT_PLAYER.set_position_xyz(0, 100, 0);
    },

    exit_world: function() {
    }

};

<commit_msg>general updating 116<commit_after>'use strict';

function HomeWorld() {
    this.__init__();
}

const MONTH_VIEW_RADIUS = 3000;

HomeWorld.prototype = {

    //
    entity_walls: null,

    //
    loaded_entities: null,

    create_month_day_wall: function(day, index, total_number_of_days) {
        var w = 500;
        var h = 1000;

        var percentage = index / total_number_of_days;
        var x_position = cos(percentage * TWO_PIE) * MONTH_VIEW_RADIUS;
        var z_position = sin(percentage * TWO_PIE) * MONTH_VIEW_RADIUS;

        var p = new THREE.Vector3(x_position, 1000, z_position);
        var n = new THREE.Vector3(-x_position, 1000, -z_position);

        var month_day_wall = new FloatingWall(w, h, p, n, this, false);

        l('Created ' + day.to_string_without_year());

        month_day_wall.add_3d_title(day.to_string_without_year());

        return month_day_wall;
    },

    __init__: function() {

        World.call(this, 'HomeWorld');

        this.loaded_entities = false;

        this.entity_walls = [];

        // TODO : What is this for?
        this.players = [];

        // The 360 schedule view.
        this.month_day_walls = [];
        this.month_days = new MyDates(THIS_MONTH);

        for (var md = 0; md < this.month_days.length; md++) {
            this.month_day_walls.push(this.create_month_day_wall(this.month_days[md], md, this.month_days.length));
        }

        // Create a seperate class for this!

        /*   __   __        ___  __             ___            ___
            /__` /  ` |__| |__  |  \ |  | |    |__     \  / | |__  |  |    .
            .__/ \__, |  | |___ |__/ \__/ |___ |___     \/  | |___ |/\|    .*/
        /*
        var schedule_view_height = 1000;

        this.test_positions = [];
        this.schedule_floating_day_titles = [];

        var today = get_today_with_n_days_offset(0);

        for (var i = 0; i < 15; i++) {
            this.test_positions.push([cos((i / 15) * TWO_PIE), sin((i / 15) * TWO_PIE)]);

            var magnitude_value = 2500;

            var p = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height, sin((i / 15) * TWO_PIE) * magnitude_value);
            var p2 = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height - 200, sin((i / 15) * TWO_PIE) * magnitude_value);
            var p3 = new THREE.Vector3(cos((i / 15) * TWO_PIE) * magnitude_value, schedule_view_height - 400, sin((i / 15) * TWO_PIE) * magnitude_value);
            var look_at = new THREE.Vector3(0, schedule_view_height, 0);
            var look_at2 = new THREE.Vector3(0, schedule_view_height - 200, 0);
            var look_at3 = new THREE.Vector3(0, schedule_view_height - 400, 0);

            //this.make_entity_wall_public_button = new Floating2DText(this.width, 'Make Entity Wall Public', TYPE_BUTTON, this.scene);

            var color = null;

            switch(i-7) {
            case -7:
                color = COLOR_DAY_PAST_SEVEN;
                break;
            case -6:
                color = COLOR_DAY_PAST_SIX;
                break;
            case -5:
                color = COLOR_DAY_PAST_FIVE;
                break;
            case -4:
                color = COLOR_DAY_PAST_FOUR;
                break;
            case -3:
                color = COLOR_DAY_PAST_THREE;
                break;
            case -2:
                color = COLOR_DAY_PAST_TWO;
                break;
            case -1:
                color = COLOR_DAY_PAST_ONE;
                break;
            case 0:
                color = COLOR_DAY_PRESENT;
                break;
            case 1:
                color = COLOR_DAY_FUTURE_ONE;
                break;
            case 2:
                color = COLOR_DAY_FUTURE_TWO;
                break;
            case 3:
                color = COLOR_DAY_FUTURE_THREE;
                break;
            case 4:
                color = COLOR_DAY_FUTURE_FOUR;
                break;
            case 5:
                color = COLOR_DAY_FUTURE_FIVE;
                break;
            case 6:
                color = COLOR_DAY_FUTURE_SIX;
                break;
            case 7:
                color = COLOR_DAY_FUTURE_SEVEN;
                break;
            }

            var day_of_week_word = get_day_of_week_as_word(get_just_date_object_of_date_of_n_days_offset(i - 7));
            var full_date_of_day = get_today_with_n_days_offset(i - 7);

            if (get_day_of_week_as_word(today) === get_day_of_week_as_word(full_date_of_day)) {
                var floating_3d_subtitle_2 = new Floating3DText(schedule_view_height - 400, 'Today', TYPE_TITLE, this.scene, color);
                floating_3d_subtitle_2.update_position_and_look_at(p3, look_at3);
            }

            var floating_3d_text = new Floating3DText(schedule_view_height, day_of_week_word, TYPE_SUPER_TITLE, this.scene, color);
            floating_3d_text.update_position_and_look_at(p, look_at);

            var floating_3d_subtitle = new Floating3DText(schedule_view_height - 200, full_date_of_day, TYPE_TITLE, this.scene, color);
            floating_3d_subtitle.update_position_and_look_at(p2, look_at2);

            this.schedule_floating_day_titles.push(floating_3d_text);
        }
        */
    },

    //remove_entity: function()

    create_entity_wall_command_entered: function() {
        // The wall will be generated 100 units away from the player and looking at the player (while perpendicular to the y-axis).
        var player_position = CURRENT_PLAYER.get_position();
        var player_normal = CURRENT_PLAYER.get_direction();
        var wall_normal = new THREE.Vector3(-player_normal.x, 0, -player_normal.z);
        var wall_position = new THREE.Vector3(player_position.x + player_normal.x * 100, player_position.y, player_position.z + player_normal.z * 100);
        var wall_width = 512;
        var wall_height = 512;
        var wall_normal_depth = 2;

        // Create the entity wall entity.
        var save_data = {};
        save_data[ENTITY_PROPERTY_POSITION] = '[' + wall_position.x + ',' + wall_position.y + ',' + wall_position.z + ']';
        save_data[ENTITY_PROPERTY_NORMAL] = '[' + wall_normal.x + ',' + wall_normal.y + ',' + wall_normal.z + ']';
        save_data[ENTITY_PROPERTY_WIDTH] = wall_width;
        save_data[ENTITY_PROPERTY_HEIGHT] = wall_height;
        save_data[ENTITY_PROPERTY_NORMAL_DEPTH] = wall_normal_depth;
        save_data[ENTITY_PROPERTY_NAME] = 'generic entity group';
        save_data[ENTITY_DEFAULT_PROPERTY_TYPE] = ENTITY_TYPE_WALL;
        var entity_wall_entity = new Entity(save_data);

        var entity_wall = new EntityWall(this, entity_wall_entity);
        this.entity_walls.push(entity_wall);
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event);
    },

    prepare_for_save: function() {
        for (var i = 0; i < this.entity_walls.length; i++) {
            this.entity_walls[i].prepare_for_save();
        }
    },

    load_entity_walls: function() {
        var wall_entities = MANAGER_ENTITY.get_all_entities_of_type(ENTITY_TYPE_WALL);
        for (var w = 0; w < wall_entities.length; w++) {
            // FOR_DEV_START
            if (!is_defined(wall_entities[w])) {
                GUI_PAUSED_MENU.add_server_message('Entity wall is not defined? Investigate.');
                l('There is non-defined entity wall being processed! Investigate!');
            }
            // FOR_DEV_END

            //var save_data = wall_entities[w].get_all_properties();

            // Get the matching entity from the Entity Manager.

            //l(save_data);
            //var entity_wall_entity = new Entity(save_data);

            // TODO : Optimize later.
            //MANAGER_ENTITY.link_entities();

            //var entity_wall = new EntityWall(this, entity_wall_entity);
            this.entity_walls.push(new EntityWall(this, wall_entities[w]));
        }
    },

    update: function() {
        // Get the task entities once all entities have been loaded.
        if (!this.loaded_entities) {
            if (!MANAGER_ENTITY.currently_loading()) {
                // Now create the entity walls from the entities.
                this.load_entity_walls();

                this.loaded_entities = true;
            }
        } else {

            // TODO : Fix this system so only one floating wall at a time gets grabbed.

            // Update all the FloatingWalls.
            for (var i = 0; i < this.entity_walls.length; i++) {
                this.entity_walls[i].update();
            }

            // Now that all the entity walls have been updated check for the closest intersection point if any.
            for (i = 0; i < this.entity_walls.length; i++) {
                // TODO : This!!
            }
        }

        // World function.
        this.update_interactive_objects();
    },

    enter_world: function() {
        CURRENT_PLAYER.disengage();
        if (!GUI_PAUSED_MENU.currently_displayed) {
            CURRENT_PLAYER.enable_controls();
        }
        CURRENT_PLAYER.set_position_xyz(0, 100, 0);
    },

    exit_world: function() {
    }

};

<|endoftext|>


<commit_before>'use babel';

function getClassLocalFields(tokens, editor) {
  return tokens
    .map(row => row.filter(token =>
      !token.scopes.includes('meta.method.body.java') &&
      token.scopes.includes('meta.definition.variable.java') &&
      (
        token.scopes.includes('storage.type.java') ||
        token.scopes.includes('storage.type.primitive.java') ||
        token.scopes.includes('variable.definition.java')
      )
    ))
    .filter(row => row.length >= 2) // Storage type and variable name
    .map(([ { value: type }, { value: name } ]) => ({
      type: this.getFullyQualifiedClass(editor, type) || type,
      name
    }));
}

export { getClassLocalFields };
<commit_msg>Support primitive arrays for class local fields<commit_after>'use babel';

import { tokenIsSquareBrackets, tokenIsStorageType, tokenIsVariableName } from '../util/tokens';

function getClassLocalFields(tokens, editor) {
  return tokens
    .map(row => row.filter(token =>
      !token.scopes.includes('meta.method.body.java') &&
      token.scopes.includes('meta.definition.variable.java') && (
        tokenIsSquareBrackets(token) ||
        tokenIsStorageType(token) ||
        tokenIsVariableName(token)
      )
    ))
    .filter(row => row.length >= 2) // Storage type and variable name
    .map(matchedTokens => {
      const brackets = matchedTokens.filter(token => -1 !== [ '[', ']' ].indexOf(token.value)).length;
      const type = matchedTokens.find(token => tokenIsStorageType(token)).value;
      const name = matchedTokens.find(token => tokenIsVariableName(token)).value;
      return {
        type: brackets > 0 ? `${type}${'[]'.repeat(brackets / 2)}` : (this.getFullyQualifiedClass(editor, type) || type),
        name: name
      };
    });
}

export { getClassLocalFields };
<|endoftext|>


<commit_before><commit_msg>allowing manual input to the initialising<commit_after><|endoftext|>


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

import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
} from 'react-native';

import I18n from 'react-native-i18n'

class Login extends Component{
  constructor(){
    super();

    this.state = {
      name: "",
      username: "",
      password_digest: "",
      location: "",
      bio: "",
      preferred_contact: "",
      skills: "",
      seeking: "",
      errors: [],
    }
  }

  async _onPressLogin() {

    try {
      let response = await fetch('http:///simulnos.herokuapp.com/api/users', {
                      method: 'POST',
                      headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify({
                        session:{
                          username: this.state.username,
                          password_digest: this.state.password_digest,
                        }
                      })
      });

      let res = await response.text();
      console.log("res is: " + res)
    } catch(errors){

    }

  }

  render() {
    return (
      <View style={styles.container}>

        <TextInput
          onChangeText={ (val)=> this.setState({username: val}) }
          style={styles.input} placeholder={I18n.t('username')}
        />

        <TextInput
          onChangeText={ (val)=> this.setState({password_digest: val}) }
          style={styles.input} placeholder={I18n.t('password')}
        />

        <TouchableHighlight onPress={this._onPressLogin.bind(this)} style={styles.button}>
          <Text style={styles.buttonText}>
          {I18n.t('login')}
          </Text>
        </TouchableHighlight>

      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: "#29c5da",
  },
  title: {
   fontSize: 20,
   alignSelf: 'center',
   margin: 40
  },
  input: {
    height: 50,
    marginTop: 10,
    padding: 4,
    fontSize: 15,
    borderWidth: 1,
    borderColor: 'white'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
});

module.exports = Login;
<commit_msg>Change login color<commit_after>import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
} from 'react-native';

import I18n from 'react-native-i18n'

class Login extends Component{
  constructor(){
    super();

    this.state = {
      name: "",
      username: "",
      password_digest: "",
      location: "",
      bio: "",
      preferred_contact: "",
      skills: "",
      seeking: "",
      errors: [],
    }
  }

  async _onPressLogin() {

    try {
      let response = await fetch('http:///simulnos.herokuapp.com/api/users', {
                      method: 'POST',
                      headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify({
                        session:{
                          username: this.state.username,
                          password_digest: this.state.password_digest,
                        }
                      })
      });

      let res = await response.text();
      console.log("res is: " + res)
    } catch(errors){

    }

  }

  render() {
    return (
      <View style={styles.container}>

        <TextInput
          onChangeText={ (val)=> this.setState({username: val}) }
          style={styles.input} placeholder={I18n.t('username')}
        />

        <TextInput
          onChangeText={ (val)=> this.setState({password_digest: val}) }
          style={styles.input} placeholder={I18n.t('password')}
        />

        <TouchableHighlight onPress={this._onPressLogin.bind(this)} style={styles.button}>
          <Text style={styles.buttonText}>
          {I18n.t('login')}
          </Text>
        </TouchableHighlight>

      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: "#29c5da",
  },
  title: {
   fontSize: 20,
   alignSelf: 'center',
   margin: 40
  },
  input: {
    height: 50,
    marginTop: 10,
    padding: 4,
    fontSize: 15,
    borderWidth: 1,
    color: 'white',
    borderColor: 'white'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
});

module.exports = Login;
<|endoftext|>


<commit_before>import Page from './Page';

class SideNav extends Page {
	get directMessageTarget() { return browser.element('.flex-nav input#who'); }
	get saveDirectMessageBtn() { return browser.element('.save-direct-message'); }

	get channelType() { return browser.element('label[for="channel-type"]'); }
	get channelReadOnly() { return browser.element('label[for="channel-ro"]'); }
	get channelName() { return browser.element('#channel-name'); }
	get saveChannelBtn() { return browser.element('.save-channel'); }

	get messageInput() { return browser.element('.input-message'); }

	get accountBoxUserName() { return browser.element('.account-box .data h4'); }
	get accountBoxUserAvatar() { return browser.element('.account-box .avatar-image'); }

	get newChannelBtn() { return browser.element('.rooms-list .add-room:nth-of-type(1)'); }
	get newChannelIcon() { return browser.element('.rooms-list .add-room:nth-of-type(1) .icon-plus'); }
	get moreChannels() { return browser.element('.rooms-list .more-channels'); }

	get newDirectMessageBtn() { return browser.element('.rooms-list .add-room:nth-of-type(2)'); }
	get newDirectMessageIcon() { return browser.element('.rooms-list .add-room:nth-of-type(2) .icon-plus'); }
	get moreDirectMessages() { return browser.element('.rooms-list .more-direct-messages'); }

	get general() { return browser.element('.rooms-list > .wrapper > ul [title="general"]'); }
	get channelHoverIcon() { return browser.element('.rooms-list > .wrapper > ul [title="general"] .icon-eye-off'); }

	get userOptions() { return browser.element('.options'); }
	get statusOnline() { return browser.element('.online'); }
	get statusAway() { return browser.element('.away'); }
	get statusBusy() { return browser.element('.busy'); }
	get statusOffline() { return browser.element('.offline'); }
	get account() { return browser.element('#account'); }
	get logout() { return browser.element('#logout'); }
	get sideNavBar() { return browser.element('.side-nav '); }
	get sideNavBtn() { return browser.element('.fixed-title .burger'); }

	get preferences() { return browser.element('.account-link:nth-of-type(1)'); }
	get profile() { return browser.element('.account-link:nth-of-type(2)'); }
	get avatar() { return browser.element('.account-link:nth-of-type(3)'); }
	get preferencesClose() { return browser.element('.side-nav .arrow.close'); }

	openChannel(channelName) {
		browser.click('.rooms-list > .wrapper > ul [title="'+channelName+'"]');
		this.messageInput.waitForExist(5000);
		browser.waitUntil(function() {
			return browser.getText('.room-title') === channelName;
		}, 5000);
	}

	getChannelFromList(channelName) {
		return browser.element('.rooms-list > .wrapper > ul [title="'+channelName+'"]');
	}

	createChannel(channelName, isPrivate, isReadOnly) {
		this.newChannelBtn.waitForVisible(10000);
		this.newChannelBtn.click();
		this.channelType.waitForVisible(10000);
		this.channelName.setValue(channelName);
		if (isPrivate) {
			this.channelType.click();
		}
		if (isReadOnly) {
			this.channelReadOnly.click();
		}
		browser.pause(200);
		this.saveChannelBtn.click();
		browser.waitForExist('[title="'+channelName+'"]', 1000);
		this.channelType.waitForVisible(500, true);
	}

	addPeopleToChannel(user) {
		this.membersTab.click();
		this.userSearchBar.waitForVisible();
		this.userSearchBar.setValue(user);
		browser.waitForVisible('.-autocomplete-item');
		browser.click('.-autocomplete-item');
	}

	removePeopleFromChannel(user) {
		this.membersTab.click();
		browser.waitForVisible('[title="'+user+'"]');
		browser.click('[title="'+user+'"]');
		this.removeUserBtn.click();
	}

	startDirectMessage(user) {
		this.newDirectMessageBtn.waitForVisible(3000);
		this.newDirectMessageBtn.click();
		this.directMessageTarget.waitForVisible(3000);
		this.directMessageTarget.setValue(user);
		browser.waitForVisible('.-autocomplete-item', 3000);
		browser.click('.-autocomplete-item');
		browser.pause(200);
		this.saveDirectMessageBtn.click();
		browser.waitForExist('[title="'+user+'"]');
	}
}

module.exports = new SideNav();
<commit_msg>try to fix private channel creation<commit_after>import Page from './Page';

class SideNav extends Page {
	get directMessageTarget() { return browser.element('.flex-nav input#who'); }
	get saveDirectMessageBtn() { return browser.element('.save-direct-message'); }

	get channelType() { return browser.element('label[for="channel-type"]'); }
	get channelReadOnly() { return browser.element('label[for="channel-ro"]'); }
	get channelName() { return browser.element('#channel-name'); }
	get saveChannelBtn() { return browser.element('.save-channel'); }

	get messageInput() { return browser.element('.input-message'); }

	get accountBoxUserName() { return browser.element('.account-box .data h4'); }
	get accountBoxUserAvatar() { return browser.element('.account-box .avatar-image'); }

	get newChannelBtn() { return browser.element('.rooms-list .add-room:nth-of-type(1)'); }
	get newChannelIcon() { return browser.element('.rooms-list .add-room:nth-of-type(1) .icon-plus'); }
	get moreChannels() { return browser.element('.rooms-list .more-channels'); }

	get newDirectMessageBtn() { return browser.element('.rooms-list .add-room:nth-of-type(2)'); }
	get newDirectMessageIcon() { return browser.element('.rooms-list .add-room:nth-of-type(2) .icon-plus'); }
	get moreDirectMessages() { return browser.element('.rooms-list .more-direct-messages'); }

	get general() { return browser.element('.rooms-list > .wrapper > ul [title="general"]'); }
	get channelHoverIcon() { return browser.element('.rooms-list > .wrapper > ul [title="general"] .icon-eye-off'); }

	get userOptions() { return browser.element('.options'); }
	get statusOnline() { return browser.element('.online'); }
	get statusAway() { return browser.element('.away'); }
	get statusBusy() { return browser.element('.busy'); }
	get statusOffline() { return browser.element('.offline'); }
	get account() { return browser.element('#account'); }
	get logout() { return browser.element('#logout'); }
	get sideNavBar() { return browser.element('.side-nav '); }
	get sideNavBtn() { return browser.element('.fixed-title .burger'); }

	get preferences() { return browser.element('.account-link:nth-of-type(1)'); }
	get profile() { return browser.element('.account-link:nth-of-type(2)'); }
	get avatar() { return browser.element('.account-link:nth-of-type(3)'); }
	get preferencesClose() { return browser.element('.side-nav .arrow.close'); }

	openChannel(channelName) {
		browser.click('.rooms-list > .wrapper > ul [title="'+channelName+'"]');
		this.messageInput.waitForExist(5000);
		browser.waitUntil(function() {
			return browser.getText('.room-title') === channelName;
		}, 5000);
	}

	getChannelFromList(channelName) {
		return browser.element('.rooms-list > .wrapper > ul [title="'+channelName+'"]');
	}

	createChannel(channelName, isPrivate, isReadOnly) {
		this.newChannelBtn.waitForVisible(10000);
		this.newChannelBtn.click();
		this.channelType.waitForVisible(10000);
		this.channelName.setValue(channelName);
		if (isPrivate) {
			this.channelType.click();
		}
		if (isReadOnly) {
			this.channelReadOnly.click();
		}
		browser.pause(200);
		this.saveChannelBtn.click();
		browser.pause(1000);
		browser.waitForExist('[title="'+channelName+'"]', 1000);
		this.channelType.waitForVisible(500, true);
	}

	addPeopleToChannel(user) {
		this.membersTab.click();
		this.userSearchBar.waitForVisible();
		this.userSearchBar.setValue(user);
		browser.waitForVisible('.-autocomplete-item');
		browser.click('.-autocomplete-item');
	}

	removePeopleFromChannel(user) {
		this.membersTab.click();
		browser.waitForVisible('[title="'+user+'"]');
		browser.click('[title="'+user+'"]');
		this.removeUserBtn.click();
	}

	startDirectMessage(user) {
		this.newDirectMessageBtn.waitForVisible(3000);
		this.newDirectMessageBtn.click();
		this.directMessageTarget.waitForVisible(3000);
		this.directMessageTarget.setValue(user);
		browser.waitForVisible('.-autocomplete-item', 3000);
		browser.click('.-autocomplete-item');
		browser.pause(200);
		this.saveDirectMessageBtn.click();
		browser.waitForExist('[title="'+user+'"]');
	}
}

module.exports = new SideNav();
<|endoftext|>


<commit_before>var http = require('flowhttp');
var Stream = require('stream');

exports.request = function (chain, options, onError) {

    // TODO transform object to string/buffer (JSON.stringify)

    /*
    var opts = {
        method: 'POST|GET|PUT|DELETE',
        path: '/' + instance._name + ':' + eventName.substr(1)
       headers: {},
        host: window.location.host,
        port: window.location.port
        responseType: 'response type to set on the underlying xhr object'
    };
    */

    var url = options.url || ('/flow/' + options.to + ':' + options.emit);
    var input = http[options.method || 'post'](url);
    chain.i.pipe(input).pipe(output);

    // check status code and emit error
    input.on('response', function (res) {
        var code = res.statusCode;
        if (code > 299) {

            // end output stream immediately
            chain.i.end();

            // collect error data
            var resData = '';
            res.on('data', function (chunk) {
                resData += chunk.toString();
            });

            // emit error on response end
            res.on('end', function () {
                var err = new Error(resData);
                err.statusCode = code;
                chain.o.emit('error', err);
            });
        }
    });
};

<commit_msg>simply request a URL, routing handles flow emits<commit_after>var http = require('flowhttp');
var Stream = require('stream');

exports.request = function (chain, options, onError) {

    // TODO transform object to string/buffer (JSON.stringify)

    /*
    var opts = {
        method: 'POST|GET|PUT|DELETE',
        path: '/' + instance._name + ':' + eventName.substr(1)
       headers: {},
        host: window.location.host,
        port: window.location.port
        responseType: 'response type to set on the underlying xhr object'
    };
    */

    if (typeof url !== string) {
        return chain.o.emit('error', new Error('Flow-http.request: Invalid url.', url))
    }

    var input = http[options.method || 'post'](options.url);
    chain.i.pipe(input).pipe(output);

    // check status code and emit error
    input.on('response', function (res) {
        var code = res.statusCode;
        if (code > 299) {

            // end output stream immediately
            chain.i.end();

            // collect error data
            var resData = '';
            res.on('data', function (chunk) {
                resData += chunk.toString();
            });

            // emit error on response end
            res.on('end', function () {
                var err = new Error(resData);
                err.statusCode = code;
                chain.o.emit('error', err);
            });
        }
    });
};

<|endoftext|>


<commit_before>( function ( $, mw ) {
	var oldContent = '';
	mw.hook( 'codeEditor.configure' ).add( function ( session ) {
		function refreshGraph() {
			try {
				var spec,
					el = $( '.mw-wiki-graph' ).get( 0 ),
					content = session.getValue();

				if ( oldContent === content ) {
					return;
				}
				oldContent = content;

				spec = $.parseJSON( content );
				if ( spec === null ) {
					return;
				}

				vg.parse.spec( spec, function ( chart ) {
					chart( { el: el } ).update();
				} );
			} finally {
				// FIXME: This should be done on data modification, not on timer
				setTimeout( refreshGraph, 300 );
			}
		}
		refreshGraph();
	} );
}( jQuery, mediaWiki ) );
<commit_msg>Fix undefined error in Graph editor<commit_after>( function ( $, mw ) {
	var oldContent = '';
	mw.hook( 'codeEditor.configure' ).add( function ( session ) {
		function refreshGraph() {
			try {
				var spec,
					el = $( '.mw-wiki-graph' ).get( 0 ),
					content = session.getValue();

				if ( typeof vg === 'undefined' || oldContent === content ) {
					return;
				}
				oldContent = content;

				spec = $.parseJSON( content );
				if ( spec === null ) {
					return;
				}

				vg.parse.spec( spec, function ( chart ) {
					chart( { el: el } ).update();
				} );
			} finally {
				// FIXME: This should be done on data modification, not on timer
				setTimeout( refreshGraph, 300 );
			}
		}
		refreshGraph();
	} );
}( jQuery, mediaWiki ) );
<|endoftext|>