<commit_before>/**
 * The main application component.
 *
 * @jsx React.DOM
 **/

/*jshint unused:false*/

var React = require('react');

var SimpleValue = require('./SimpleValue.js').SimpleValue;
var TraitValue = require('./TraitValue.js').TraitValue;

exports.TraitsApp = React.createClass({

	propTypes: {
		speech: React.PropTypes.arrayOf(React.PropTypes.string),
		hair: React.PropTypes.arrayOf(React.PropTypes.string),
		facialFeatures: React.PropTypes.arrayOf(React.PropTypes.string),
		bodyLocations: React.PropTypes.arrayOf(React.PropTypes.string),
		personality: React.PropTypes.arrayOf(React.PropTypes.string)
	},

	/**
	 * Just reset the props, let the random selection begin again.
	 */
	handleRegen: function () {
		this.replaceProps(this.props);
	},

	/**
	 * TODO Abstract to helper object?
	 */
	getRandomValue: function (data) {
		return data[Math.floor(Math.random() * data.length)];
	},

	render: function () {

		var characteristic = this.getRandomValue(this.props.characteristics);
		var charLoc = characteristic.hasLocation ? this.getRandomValue(this.props.bodyLocations) : null;

		/*jshint ignore:start*/
		return (

Character Traits NPC traits generator, for your roleplaying games.

						<SimpleValue title="Hair" text={this.getRandomValue(this.props.hair)}/>
						<SimpleValue title="Face" text={this.getRandomValue(this.props.facialFeatures)}/>

						<TraitValue title="Characteristic" text={characteristic.text} location={charLoc}/>

						<SimpleValue title="Personality" text={this.getRandomValue(this.props.personality)}/>
						<SimpleValue title="Speech" text={this.getRandomValue(this.props.speech)}/>

						<button type="button" className="btn btn-primary"
						onClick={this.handleRegen}>Generate new traits</button>

		);
		/*jshint ignore:end*/

	}

});<commit_msg>Renamed Face to Facial, more accurate.<commit_after>/**
 * The main application component.
 *
 * @jsx React.DOM
 **/

/*jshint unused:false*/

var React = require('react');

var SimpleValue = require('./SimpleValue.js').SimpleValue;
var TraitValue = require('./TraitValue.js').TraitValue;

exports.TraitsApp = React.createClass({

	propTypes: {
		speech: React.PropTypes.arrayOf(React.PropTypes.string),
		hair: React.PropTypes.arrayOf(React.PropTypes.string),
		facialFeatures: React.PropTypes.arrayOf(React.PropTypes.string),
		bodyLocations: React.PropTypes.arrayOf(React.PropTypes.string),
		personality: React.PropTypes.arrayOf(React.PropTypes.string)
	},

	/**
	 * Just reset the props, let the random selection begin again.
	 */
	handleRegen: function () {
		this.replaceProps(this.props);
	},

	/**
	 * TODO Abstract to helper object?
	 */
	getRandomValue: function (data) {
		return data[Math.floor(Math.random() * data.length)];
	},

	render: function () {

		var characteristic = this.getRandomValue(this.props.characteristics);
		var charLoc = characteristic.hasLocation ? this.getRandomValue(this.props.bodyLocations) : null;

		/*jshint ignore:start*/
		return (

Character Traits NPC traits generator, for your roleplaying games.

						<SimpleValue title="Hair" text={this.getRandomValue(this.props.hair)}/>
						<SimpleValue title="Facial" text={this.getRandomValue(this.props.facialFeatures)}/>

						<TraitValue title="Characteristic" text={characteristic.text} location={charLoc}/>

						<SimpleValue title="Personality" text={this.getRandomValue(this.props.personality)}/>
						<SimpleValue title="Speech" text={this.getRandomValue(this.props.speech)}/>

						<button type="button" className="btn btn-primary"
						onClick={this.handleRegen}>Generate new traits</button>

		);
		/*jshint ignore:end*/

	}

});<|endoftext|>


<commit_before>'use strict';

import Logger from '../../services/logger';
import Platform from '../../services/platform';
import ComponentLoader from '../../services/componentLoader';

const baseDependencies = {
  'cdk': ['virtualbox', 'cygwin'],
  'devstudio': ['jdk'],
  'jbosseap': ['jdk']
};

class ConfirmController {

  constructor($scope, $state, $timeout, installerDataSvc, electron) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.loader = new ComponentLoader(installerDataSvc);

    this.installedSearchNote = '';
    this.isDisabled = false;
    this.numberOfExistingInstallations = 0;

    this.installables = {};
    $scope.checkboxModel = {};
    $scope.platform = Platform.OS;
    $scope.detectionStyle = false;
    $scope.virtualization = true;

    for (let [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchInstallSelectionChange() {
        $scope.checkboxModel[key].validateVersion();
      });
    }

    $scope.isConfigurationValid = this.isConfigurationValid;

    let watchedComponents = {};
    for (let key in baseDependencies) {
      if ($scope.checkboxModel[key]) {
        watchedComponents[key] = [];
        let installAfter = this.installerDataSvc.getInstallable(key).getInstallAfter();
        let keyName;

        while (installAfter) {
          keyName = installAfter.keyName;
          if (baseDependencies[key].indexOf(keyName) > -1) {
            watchedComponents[key].push(keyName);
          }
          installAfter = installAfter.getInstallAfter();
        }
      }
    }

    for (let key in watchedComponents) {
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchComponent(nVal) {
        console.log($scope.checkboxModel.devstudio.selectedOption, $scope.checkboxModel.jbosseap.selectedOption);
        for (let keyName of watchedComponents[key]) {
          console.log(keyName);
          if ( keyName === 'jdk' ) {
            if ($scope.checkboxModel.devstudio.selectedOption === 'detected' && $scope.checkboxModel.jbosseap.selectedOption === 'detected' ) {
              $scope.checkboxModel[keyName].selectedOption = 'detected';
            } else {
              $scope.checkboxModel[keyName].selectedOption = 'install';
            }
          } else {
            if(nVal=='install') {
              if($scope.checkboxModel[keyName].selectedOption == 'detected'
                && !$scope.checkboxModel[keyName].hasOption('detected')) {
                $scope.checkboxModel[keyName].selectedOption = 'install';
              }
            } else if (nVal=='detected') {
              $scope.checkboxModel[keyName].selectedOption = 'detected';
            }
          }
        }
      });
    }

    $scope.$watch('$viewContentLoaded', ()=>{
      this.detectInstalledComponents();
    });

    this.electron.remote.getCurrentWindow().addListener('focus', ()=> {
      this.timeout( () => {
        this.detectInstalledComponents();
        this.sc.$apply();
      });
    });
  }

  detectInstalledComponents() {
    if(!this.isDisabled) {
      this.isDisabled = true;
      this.installedSearchNote = ' The system is checking if you have any installed components.';
      let detectors = [];
      for (var installer of this.installerDataSvc.allInstallables().values()) {
        detectors.push(installer.detectExistingInstall());
      }
      this.detection = Promise.all(detectors).then(()=> {
        this.setIsDisabled();
      }).catch(()=> {
        this.setIsDisabled();
      });
    }
    return this.detection;
  }

  download(url) {
    this.electron.shell.openExternal(url);
  }

  // Prep the install location path for each product, then go to the next page.
  install() {
    if (this.sc.checkboxModel.hyperv && this.sc.checkboxModel.hyperv.isConfigured()) {
      this.loader.removeComponent('virtualbox');
    } else {
      this.loader.removeComponent('hyperv');
    }

    let possibleComponents = ['virtualbox', 'jdk', 'devstudio', 'jbosseap', 'cygwin', 'cdk', 'kompose'];
    for (let i = 0; i < possibleComponents.length; i++) {
      let component = this.installerDataSvc.getInstallable(possibleComponents[i]);
      if (component) {
        possibleComponents[i] = component.getLocation();
      } else {
        possibleComponents[i] = undefined;
      }
    }

    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.installerDataSvc.setup(...possibleComponents);
    this.router.go('install');
  }

  setIsDisabled() {
    // Uncomment the timeout to see the initial disabled view.
    this.timeout( () => {
      // Switch this boolean flag when the app is done looking for existing installations.
      this.isDisabled = !this.isDisabled;
      this.numberOfExistingInstallations = 0;
      // Count the number of existing installations.
      for (var [, value] of this.installerDataSvc.allInstallables()) {
        if (value.hasOption('detected')) {
          ++this.numberOfExistingInstallations;
        }
      }

      // Set the message depending on if the view is disabled or not.
      if (this.isDisabled) {
        this.installedSearchNote = '  The system is checking if you have any installed components';
      } else {
        if (this.numberOfExistingInstallations == 1) {
          this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed component`;
        } else if (this.numberOfExistingInstallations > 1) {
          this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed components`;
        } else {
          this.installedSearchNote = '';
        }
      }

      // Call the digest cycle so that the view gets updated.
      this.sc.$apply();
    });
  }

  devstudioIsConfigured() {
    return this.sc.checkboxModel.jdk.isConfigured()
      && this.sc.checkboxModel.devstudio.isConfigured()
      || this.sc.checkboxModel.devstudio.isSkipped();
  }

  cdkIsConfigured() {
    return this.sc.checkboxModel.cdk.isConfigured()
      && this.virtualizationIsConfigured()
      && (!this.sc.checkboxModel.cygwin || this.sc.checkboxModel.cygwin.isConfigured())
      || this.sc.checkboxModel.cdk.isSkipped();
  }

  virtualizationIsConfigured() {
    return (this.sc.checkboxModel.virtualbox
      && this.sc.checkboxModel.virtualbox.isConfigured())
      || (this.sc.checkboxModel.hyperv
      && this.sc.checkboxModel.hyperv.isConfigured()
      || this.sc.checkboxModel.cdk.selectedOption !== 'install');
  }

  isConfigurationValid() {
    return this.devstudioIsConfigured()
      && this.cdkIsConfigured()
      && this.virtualizationIsConfigured()
      && this.isAtLeastOneSelected();
  }

  isAtLeastOneSelected() {
    for (var [, value] of this.installerDataSvc.allInstallables()) {
      if(!value.isSkipped()) {
        return true;
      }
    }
    return false;
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }

  back() {
    Logger.info('Going back a page');
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('location');
  }
}

ConfirmController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc', 'electron'];

export default ConfirmController;
<commit_msg>Remove console.log() calls from confirm/controller.js<commit_after>'use strict';

import Logger from '../../services/logger';
import Platform from '../../services/platform';
import ComponentLoader from '../../services/componentLoader';

const baseDependencies = {
  'cdk': ['virtualbox', 'cygwin'],
  'devstudio': ['jdk'],
  'jbosseap': ['jdk']
};

class ConfirmController {

  constructor($scope, $state, $timeout, installerDataSvc, electron) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.loader = new ComponentLoader(installerDataSvc);

    this.installedSearchNote = '';
    this.isDisabled = false;
    this.numberOfExistingInstallations = 0;

    this.installables = {};
    $scope.checkboxModel = {};
    $scope.platform = Platform.OS;
    $scope.detectionStyle = false;
    $scope.virtualization = true;

    for (let [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchInstallSelectionChange() {
        $scope.checkboxModel[key].validateVersion();
      });
    }

    $scope.isConfigurationValid = this.isConfigurationValid;

    let watchedComponents = {};
    for (let key in baseDependencies) {
      if ($scope.checkboxModel[key]) {
        watchedComponents[key] = [];
        let installAfter = this.installerDataSvc.getInstallable(key).getInstallAfter();
        let keyName;

        while (installAfter) {
          keyName = installAfter.keyName;
          if (baseDependencies[key].indexOf(keyName) > -1) {
            watchedComponents[key].push(keyName);
          }
          installAfter = installAfter.getInstallAfter();
        }
      }
    }

    for (let key in watchedComponents) {
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchComponent(nVal) {
        for (let keyName of watchedComponents[key]) {
          if ( keyName === 'jdk' ) {
            if ($scope.checkboxModel.devstudio.selectedOption === 'detected' && $scope.checkboxModel.jbosseap.selectedOption === 'detected' ) {
              $scope.checkboxModel[keyName].selectedOption = 'detected';
            } else {
              $scope.checkboxModel[keyName].selectedOption = 'install';
            }
          } else {
            if(nVal=='install') {
              if($scope.checkboxModel[keyName].selectedOption == 'detected'
                && !$scope.checkboxModel[keyName].hasOption('detected')) {
                $scope.checkboxModel[keyName].selectedOption = 'install';
              }
            } else if (nVal=='detected') {
              $scope.checkboxModel[keyName].selectedOption = 'detected';
            }
          }
        }
      });
    }

    $scope.$watch('$viewContentLoaded', ()=>{
      this.detectInstalledComponents();
    });

    this.electron.remote.getCurrentWindow().addListener('focus', ()=> {
      this.timeout( () => {
        this.detectInstalledComponents();
        this.sc.$apply();
      });
    });
  }

  detectInstalledComponents() {
    if(!this.isDisabled) {
      this.isDisabled = true;
      this.installedSearchNote = ' The system is checking if you have any installed components.';
      let detectors = [];
      for (var installer of this.installerDataSvc.allInstallables().values()) {
        detectors.push(installer.detectExistingInstall());
      }
      this.detection = Promise.all(detectors).then(()=> {
        this.setIsDisabled();
      }).catch(()=> {
        this.setIsDisabled();
      });
    }
    return this.detection;
  }

  download(url) {
    this.electron.shell.openExternal(url);
  }

  // Prep the install location path for each product, then go to the next page.
  install() {
    if (this.sc.checkboxModel.hyperv && this.sc.checkboxModel.hyperv.isConfigured()) {
      this.loader.removeComponent('virtualbox');
    } else {
      this.loader.removeComponent('hyperv');
    }

    let possibleComponents = ['virtualbox', 'jdk', 'devstudio', 'jbosseap', 'cygwin', 'cdk', 'kompose'];
    for (let i = 0; i < possibleComponents.length; i++) {
      let component = this.installerDataSvc.getInstallable(possibleComponents[i]);
      if (component) {
        possibleComponents[i] = component.getLocation();
      } else {
        possibleComponents[i] = undefined;
      }
    }

    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.installerDataSvc.setup(...possibleComponents);
    this.router.go('install');
  }

  setIsDisabled() {
    // Uncomment the timeout to see the initial disabled view.
    this.timeout( () => {
      // Switch this boolean flag when the app is done looking for existing installations.
      this.isDisabled = !this.isDisabled;
      this.numberOfExistingInstallations = 0;
      // Count the number of existing installations.
      for (var [, value] of this.installerDataSvc.allInstallables()) {
        if (value.hasOption('detected')) {
          ++this.numberOfExistingInstallations;
        }
      }

      // Set the message depending on if the view is disabled or not.
      if (this.isDisabled) {
        this.installedSearchNote = '  The system is checking if you have any installed components';
      } else {
        if (this.numberOfExistingInstallations == 1) {
          this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed component`;
        } else if (this.numberOfExistingInstallations > 1) {
          this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed components`;
        } else {
          this.installedSearchNote = '';
        }
      }

      // Call the digest cycle so that the view gets updated.
      this.sc.$apply();
    });
  }

  devstudioIsConfigured() {
    return this.sc.checkboxModel.jdk.isConfigured()
      && this.sc.checkboxModel.devstudio.isConfigured()
      || this.sc.checkboxModel.devstudio.isSkipped();
  }

  cdkIsConfigured() {
    return this.sc.checkboxModel.cdk.isConfigured()
      && this.virtualizationIsConfigured()
      && (!this.sc.checkboxModel.cygwin || this.sc.checkboxModel.cygwin.isConfigured())
      || this.sc.checkboxModel.cdk.isSkipped();
  }

  virtualizationIsConfigured() {
    return (this.sc.checkboxModel.virtualbox
      && this.sc.checkboxModel.virtualbox.isConfigured())
      || (this.sc.checkboxModel.hyperv
      && this.sc.checkboxModel.hyperv.isConfigured()
      || this.sc.checkboxModel.cdk.selectedOption !== 'install');
  }

  isConfigurationValid() {
    return this.devstudioIsConfigured()
      && this.cdkIsConfigured()
      && this.virtualizationIsConfigured()
      && this.isAtLeastOneSelected();
  }

  isAtLeastOneSelected() {
    for (var [, value] of this.installerDataSvc.allInstallables()) {
      if(!value.isSkipped()) {
        return true;
      }
    }
    return false;
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }

  back() {
    Logger.info('Going back a page');
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('location');
  }
}

ConfirmController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc', 'electron'];

export default ConfirmController;
<|endoftext|>


<commit_before>var models = require('../models');

var coursesCtrl = module.exports = {};

coursesCtrl.list = function (req, res) {
  models.Course.findAll()
    .then(function (allCourses) {
      res.send(allCourses);
    });
};

coursesCtrl.getCreate = function (req, res) {
  res.render('courses/create');
};

coursesCtrl.create = function (req, res) {
  var courseDetails = {
    name: req.body.name,
    description: req.body.desc,
  };
  models.Course.create(courseDetails)
    .then(function (course) {
      models.User.findOne({where: {id: req.user.id}})
        .then(function (user) {
          user.addCourse(course);
          res.redirect('/courses/' + course.id + '/edit');
        });
    });
};

coursesCtrl.getCourse = function (req, res) {
  models.Course.findOne({where: {id: req.params.courseId}})
    .then(function (course) {
      course.getSections({raw: true})
        .then(function (sections) {
          res.render('courses/single', {
            username: req.user.username,
            courseId: course.id,
            name: course.name,
            desc: course.description,
            sections: sections,
          });
        });
    });
};

coursesCtrl.getSection = function (req, res) {
  models.Section.findOne({
    where: {
      id: req.params.sectionId,
    },
    raw: true,
  })
    .then(function (section) {
      res.render('courses/section', {
        title: section.title,
        content: section.content,
      });
    });
};

coursesCtrl.edit = function (req, res) {
  console.log('req.params.courseId', req.params.courseId);
  models.Section.create(req.body)
    .then(function (section) {
      models.Course.findOne({where: {id: req.params.courseId}})
        .then(function (course) {
          course.addSection(section);
          // res.redirect(req.get('referer'));
          res.redirect('/' + req.user.username + '/' + req.params.courseId);
        });
    });
};
<commit_msg>fix new course redir<commit_after>var models = require('../models');

var coursesCtrl = module.exports = {};

coursesCtrl.list = function (req, res) {
  models.Course.findAll()
    .then(function (allCourses) {
      res.send(allCourses);
    });
};

coursesCtrl.getCreate = function (req, res) {
  res.render('courses/create');
};

coursesCtrl.create = function (req, res) {
  var courseDetails = {
    name: req.body.name,
    description: req.body.desc,
  };
  models.Course.create(courseDetails)
    .then(function (course) {
      models.User.findOne({where: {id: req.user.id}})
        .then(function (user) {
          user.addCourse(course);
          res.redirect('/courses/' + course.id);
        });
    });
};

coursesCtrl.getCourse = function (req, res) {
  models.Course.findOne({where: {id: req.params.courseId}})
    .then(function (course) {
      course.getSections({raw: true})
        .then(function (sections) {
          res.render('courses/single', {
            username: req.user.username,
            courseId: course.id,
            name: course.name,
            desc: course.description,
            sections: sections,
          });
        });
    });
};

coursesCtrl.getSection = function (req, res) {
  models.Section.findOne({
    where: {
      id: req.params.sectionId,
    },
    raw: true,
  })
    .then(function (section) {
      res.render('courses/section', {
        title: section.title,
        content: section.content,
      });
    });
};

coursesCtrl.edit = function (req, res) {
  console.log('req.params.courseId', req.params.courseId);
  models.Section.create(req.body)
    .then(function (section) {
      models.Course.findOne({where: {id: req.params.courseId}})
        .then(function (course) {
          course.addSection(section);
          // res.redirect(req.get('referer'));
          res.redirect('/' + req.user.username + '/' + req.params.courseId);
        });
    });
};
<|endoftext|>


<commit_before><commit_msg>fix incorrect texCoord argument<commit_after><|endoftext|>


<commit_before>//	This file is part of the "jQuery.Syntax" project, and is licensed under the GNU AGPLv3.
//	Copyright 2010 Samuel Williams. All rights reserved.
//	See <jquery.syntax.js> for licensing details.

Syntax.layouts.list = function(options, code, container) {
	var list = jQuery('

'), line = 1, space = /^\s*$/;

	// Source code
	code.children().each(function() {
		var li = document.createElement('li');
		li.className = "line ln" + line

		if (line % 2) {
			li.className += " alt";
		}

		if (line == 1) {
			li.className += " first"
		}

		var div = document.createElement('div');
		div.className = "source "  + this.className;

		if (!this.innerHTML.match(space)) {
			div.innerHTML = this.innerHTML;
		} else {
			div.innerHTML = " ";
		}

		li.appendChild(div);
		list[0].appendChild(li);

		line = line + 1;
	});

	return list;
};
<commit_msg>Minor improvement in output whitespace.<commit_after>//	This file is part of the "jQuery.Syntax" project, and is licensed under the GNU AGPLv3.
//	Copyright 2010 Samuel Williams. All rights reserved.
//	See <jquery.syntax.js> for licensing details.

Syntax.layouts.list = function(options, code, container) {
	var list = jQuery('

'), line = 1, space = /^\s*$/;

	// Source code
	code.children().each(function() {
		var li = document.createElement('li');
		li.className = "line ln" + line

		if (line % 2) {
			li.className += " alt";
		}

		if (line == 1) {
			li.className += " first"
		}

		var div = document.createElement('div');
		div.className = "source "  + this.className;

		if (!this.innerHTML.match(space)) {
			div.innerHTML = this.innerHTML.replace(/ /g, "\u00a0\u200b").replace(/\n/g, "
");
		} else {
			div.innerHTML = " ";
		}

		li.appendChild(div);
		list[0].appendChild(li);

		line = line + 1;
	});

	return list;
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { NativeModules, requireNativeComponent } from 'react-native';
import { toJSONString, cloneReactChildrenWithProps } from '../utils';

const MapboxGL = NativeModules.MGLModule;

export const NATIVE_MODULE_NAME = 'RCTMGLShapeSource';

const RCTMGLShapeSource = requireNativeComponent(NATIVE_MODULE_NAME, ShapeSource);

/**
 * ShapeSource is a map content source that supplies vector shapes to be shown on the map.
 * The shape may be a url or a GeoJSON object
 */
class ShapeSource extends React.Component {
  static propTypes = {
    /**
     * A string that uniquely identifies the source.
     */
    id: PropTypes.string,

    /**
     * An HTTP(S) URL, absolute file URL, or local file URL relative to the current application’s resource bundle.
     */
    url: PropTypes.string,

    /**
     * The contents of the source. A shape can represent a GeoJSON geometry, a feature, or a feature colllection.
     */
    shape: PropTypes.object,

    /**
     * Enables clustering on the source for point shapes.
     */
    cluster: PropTypes.bool,

    /**
     * Specifies the radius of each cluster if clustering is enabled.
     * A value of 512 produces a radius equal to the width of a tile.
     * The default value is 50.
     */
    clusterRadius: PropTypes.number,

    /**
     * Specifies the maximum zoom level at which to cluster points if clustering is enabled.
     * Defaults to one zoom level less than the value of maxZoomLevel so that, at the maximum zoom level,
     * the shapes are not clustered.
     */
    clusterMaxZoomLevel: PropTypes.number,

    /**
     * Specifies the maximum zoom level at which to create vector tiles.
     * A greater value produces greater detail at high zoom levels.
     * The default value is 18.
     */
    maxZoomLevel: PropTypes.number,

    /**
     * Specifies the size of the tile buffer on each side.
     * A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself.
     * Larger values produce fewer rendering artifacts near tile edges and slower performance.
     * The default value is 128.
     */
    buffer: PropTypes.number,

    /**
     * Specifies the Douglas-Peucker simplification tolerance.
     * A greater value produces simpler geometries and improves performance.
     * The default value is 0.375.
     */
    tolerance: PropTypes.number,
  };

  static defaultProps = {
    id: MapboxGL.StyleSource.DefaultSourceID,
  };

  _getShape () {
    if (!this.props.shape) {
      return;
    }
    // TODO: Add turf validation and throw exeception
    return toJSONString(this.props.shape);
  }

  render () {
    const props = {
      id: this.props.id,
      url: this.props.url,
      shape: this._getShape(),
      cluster: this.props.cluster ? 1 : 0,
      clusterRadius: this.props.clusterRadius,
      clusterMaxZoomLevel: this.props.clusterMaxZoomLevel,
      maxZoomLevel: this.props.maxZoomLevel,
      buffer: this.props.buffer,
      tolerance: this.props.tolerance,
    };
    return (
      <RCTMGLShapeSource {...props}>
        {cloneReactChildrenWithProps(this.props.children, { sourceID: this.props.id })}
      </RCTMGLShapeSource>
    );
  }
}

export default ShapeSource;
<commit_msg>Update ShapeSouce JS component to include images<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { NativeModules, requireNativeComponent } from 'react-native';
import { toJSONString, cloneReactChildrenWithProps } from '../utils';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const MapboxGL = NativeModules.MGLModule;

export const NATIVE_MODULE_NAME = 'RCTMGLShapeSource';

const RCTMGLShapeSource = requireNativeComponent(NATIVE_MODULE_NAME, ShapeSource);

/**
 * ShapeSource is a map content source that supplies vector shapes to be shown on the map.
 * The shape may be a url or a GeoJSON object
 */
class ShapeSource extends React.Component {
  static propTypes = {
    /**
     * A string that uniquely identifies the source.
     */
    id: PropTypes.string,

    /**
     * An HTTP(S) URL, absolute file URL, or local file URL relative to the current application’s resource bundle.
     */
    url: PropTypes.string,

    /**
     * The contents of the source. A shape can represent a GeoJSON geometry, a feature, or a feature colllection.
     */
    shape: PropTypes.object,

    /**
     * Enables clustering on the source for point shapes.
     */
    cluster: PropTypes.bool,

    /**
     * Specifies the radius of each cluster if clustering is enabled.
     * A value of 512 produces a radius equal to the width of a tile.
     * The default value is 50.
     */
    clusterRadius: PropTypes.number,

    /**
     * Specifies the maximum zoom level at which to cluster points if clustering is enabled.
     * Defaults to one zoom level less than the value of maxZoomLevel so that, at the maximum zoom level,
     * the shapes are not clustered.
     */
    clusterMaxZoomLevel: PropTypes.number,

    /**
     * Specifies the maximum zoom level at which to create vector tiles.
     * A greater value produces greater detail at high zoom levels.
     * The default value is 18.
     */
    maxZoomLevel: PropTypes.number,

    /**
     * Specifies the size of the tile buffer on each side.
     * A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself.
     * Larger values produce fewer rendering artifacts near tile edges and slower performance.
     * The default value is 128.
     */
    buffer: PropTypes.number,

    /**
     * Specifies the Douglas-Peucker simplification tolerance.
     * A greater value produces simpler geometries and improves performance.
     * The default value is 0.375.
     */
    tolerance: PropTypes.number,

    /**
     * Specifies the external images in key-value pairs required for the shape source.
     */
    images: PropTypes.object,
  };

  static defaultProps = {
    id: MapboxGL.StyleSource.DefaultSourceID,
  };

  _getShape () {
    if (!this.props.shape) {
      return;
    }
    // TODO: Add turf validation and throw exeception
    return toJSONString(this.props.shape);
  }

  _getImages () {
    if (!this.props.images) {
      return;
    }

    let images = {};

    const imageNames = Object.keys(this.props.images);
    for (let imageName of imageNames) {
      const res = resolveAssetSource(this.props.images[imageName]);

      if (res && res.uri) {
        images[imageName] = res.uri;
      }
    }

    return images;
  }

  render () {
    const props = {
      id: this.props.id,
      url: this.props.url,
      shape: this._getShape(),
      cluster: this.props.cluster ? 1 : 0,
      clusterRadius: this.props.clusterRadius,
      clusterMaxZoomLevel: this.props.clusterMaxZoomLevel,
      maxZoomLevel: this.props.maxZoomLevel,
      buffer: this.props.buffer,
      tolerance: this.props.tolerance,
      images: this._getImages(),
    };
    return (
      <RCTMGLShapeSource {...props}>
        {cloneReactChildrenWithProps(this.props.children, { sourceID: this.props.id })}
      </RCTMGLShapeSource>
    );
  }
}

export default ShapeSource;
<|endoftext|>


<commit_before>module.exports = function oilsRenderTable(pluginConf, web, next) {
	web.renderTable = renderTable;
	web.utils.getTableFromModel = getTableFromModel;

	pluginConf = web.utils.extend(pluginConf, require('./conf.js'));
	var async = require('async');

	function getTableFromModel(ModelObj, opts, callback) {
		var tableObj = new Object();
		tableObj.tableId = opts.tableId;
		tableObj.rowsPerPage = opts.rowsPerPage;
		if (!tableObj.rowsPerPage) {
			tableObj.rowsPerPage = pluginConf.defaultRowsPerPage;
		}

		var pageNo = opts.pageNo || 1;
		var sort = opts.sort;

		ModelObj.count(opts.query).exec(function(err, count) {
			var maxPage = Math.ceil(count/tableObj.rowsPerPage);
			if (pageNo > maxPage) {
				pageNo = maxPage;
			}
			if (pageNo < 1) {
				pageNo = 1;
			}

			ModelObj.find(opts.query)
			    .select(opts.columns.join(' '))
			    .limit(tableObj.rowsPerPage)
			    .skip(tableObj.rowsPerPage * (pageNo-1))
			    .sort(sort)
			    .exec(function(err, records) {

		        	tableObj.columns = opts.columns;
		        	tableObj.labels = opts.labels || opts.columns;
					tableObj.count = count;
					tableObj.noRecordsFoundLabel = "No records found.";

					assignAllHandlers(opts.handlers, records, opts.columns, function(err, records) {
						tableObj.records = records;
						var pagination = null;

						if (count > tableObj.rowsPerPage) {
							pagination = new Object();
							pagination.pageNo = pageNo;
							pagination.totalPage = maxPage;
							//console.log('!!!' + pagination.totalPage);
							pagination.startPage = pageNo < 5 ? 1 : pageNo - 4;
							pagination.endPage = 8 + pagination.startPage;
							pagination.endPage = pagination.totalPage < pagination.endPage ? pagination.totalPage : pagination.endPage;
							pagination.diff = pagination.startPage - pagination.endPage + 8;
							pagination.startPage -= ((pagination.startPage - pagination.diff) > 0) ? pagination.diff : 0;
							pagination.pages = [];
							for (var i = pagination.startPage; i<=pagination.endPage; i++) {
								pagination.pages.push(i);
							}

						}

						tableObj.pagination = pagination;
						callback(null, tableObj);
					})
		        })
		    })
	}

	function renderTable(req, ModelObj, opts, callback) {
		opts.tableId = opts.tableId || getPrefix(ModelObj);
		opts.pageNo = req.query[opts.tableId + '_p'] || 1;

		web.utils.getTableFromModel(ModelObj, opts, function(err, tableObj) {
			web.templateEngine.render(pluginConf.pluginPath + '/templates/table.html', {table: tableObj}, function(err, resultStr) {
			            	callback(err, resultStr);
			            })
		})
	}

	function getPrefix(ModelObj) {
		return ModelObj.modelName.toLowerCase();
	}

	function assignAllHandlers(handlers, records, columns, assignAllHandlersCallback) {
		handlers = handlers || new Object();

		async.each(records, function(record, callback) {

			async.each(columns, function(column, columnsCallback) {

				if (!handlers[column]) {
					handlers[column] = defaultHandler;
				}

				assignHandler(column, handlers[column], record, columnsCallback);

			}, function(err) {
				callback();
			})

		}, function(err) {
			assignAllHandlersCallback(err, records);
		})

	}

	function assignHandler(key, handler, record, callback) {
		var escapedVal = web.templateEngine.filters.escape(record[key]);
		handler(record, key, escapedVal, function(err, value) {
			record[key] = value;
			callback();
		})
	}

	function defaultHandler(record, column, escapedVal, callback) {
		callback(null, escapedVal);
	}

	next();
}<commit_msg>removed select<commit_after>module.exports = function oilsRenderTable(pluginConf, web, next) {
	web.renderTable = renderTable;
	web.utils.getTableFromModel = getTableFromModel;

	pluginConf = web.utils.extend(pluginConf, require('./conf.js'));
	var async = require('async');

	function getTableFromModel(ModelObj, opts, callback) {
		var tableObj = new Object();
		tableObj.tableId = opts.tableId;
		tableObj.rowsPerPage = opts.rowsPerPage;
		if (!tableObj.rowsPerPage) {
			tableObj.rowsPerPage = pluginConf.defaultRowsPerPage;
		}

		var pageNo = opts.pageNo || 1;
		var sort = opts.sort;

		ModelObj.count(opts.query).exec(function(err, count) {
			var maxPage = Math.ceil(count/tableObj.rowsPerPage);
			if (pageNo > maxPage) {
				pageNo = maxPage;
			}
			if (pageNo < 1) {
				pageNo = 1;
			}

			ModelObj.find(opts.query)
			    .limit(tableObj.rowsPerPage)
			    .skip(tableObj.rowsPerPage * (pageNo-1))
			    .sort(sort)
			    .exec(function(err, records) {

		        	tableObj.columns = opts.columns;
		        	tableObj.labels = opts.labels || opts.columns;
					tableObj.count = count;
					tableObj.noRecordsFoundLabel = "No records found.";

					assignAllHandlers(opts.handlers, records, opts.columns, function(err, records) {
						tableObj.records = records;
						var pagination = null;

						if (count > tableObj.rowsPerPage) {
							pagination = new Object();
							pagination.pageNo = pageNo;
							pagination.totalPage = maxPage;
							//console.log('!!!' + pagination.totalPage);
							pagination.startPage = pageNo < 5 ? 1 : pageNo - 4;
							pagination.endPage = 8 + pagination.startPage;
							pagination.endPage = pagination.totalPage < pagination.endPage ? pagination.totalPage : pagination.endPage;
							pagination.diff = pagination.startPage - pagination.endPage + 8;
							pagination.startPage -= ((pagination.startPage - pagination.diff) > 0) ? pagination.diff : 0;
							pagination.pages = [];
							for (var i = pagination.startPage; i<=pagination.endPage; i++) {
								pagination.pages.push(i);
							}

						}

						tableObj.pagination = pagination;
						callback(null, tableObj);
					})
		        })
		    })
	}

	function renderTable(req, ModelObj, opts, callback) {
		opts.tableId = opts.tableId || getPrefix(ModelObj);
		opts.pageNo = req.query[opts.tableId + '_p'] || 1;

		web.utils.getTableFromModel(ModelObj, opts, function(err, tableObj) {
			web.templateEngine.render(pluginConf.pluginPath + '/templates/table.html', {table: tableObj}, function(err, resultStr) {
			            	callback(err, resultStr);
			            })
		})
	}

	function getPrefix(ModelObj) {
		return ModelObj.modelName.toLowerCase();
	}

	function assignAllHandlers(handlers, records, columns, assignAllHandlersCallback) {
		handlers = handlers || new Object();

		async.each(records, function(record, callback) {

			async.each(columns, function(column, columnsCallback) {

				if (!handlers[column]) {
					handlers[column] = defaultHandler;
				}

				assignHandler(column, handlers[column], record, columnsCallback);

			}, function(err) {
				callback();
			})

		}, function(err) {
			assignAllHandlersCallback(err, records);
		})

	}

	function assignHandler(key, handler, record, callback) {
		var escapedVal = web.templateEngine.filters.escape(record[key]);
		handler(record, key, escapedVal, function(err, value) {
			record[key] = value;
			callback();
		})
	}

	function defaultHandler(record, column, escapedVal, callback) {
		callback(null, escapedVal);
	}

	next();
}<|endoftext|>


<commit_before>var grid = document.getElementById('grid');

var table = new Handsontable(grid);

// 独自イベントの追加
Handsontable.hooks.register('onButtonClick');

// イベントハンドラの登録
Handsontable.hooks.add('onButtonClick', function () {
    console.log('click!!');
});

document.getElementById('button').addEventListener('click', function() {
    // 独自イベントを発火
    Handsontable.hooks.run(table, 'onButtonClick');
});
<commit_msg>Hooks run arguments<commit_after>var grid = document.getElementById('grid');

var table = new Handsontable(grid);

Handsontable.hooks.register('onButtonClick');

Handsontable.hooks.add('onButtonClick', function () {
    console.log(arguments);
});

document.getElementById('button').addEventListener('click', function() {
    Handsontable.hooks.run(table, 'onButtonClick', 1, 2, 3, 4, 5, 6, 7);
});
<|endoftext|>


<commit_before><commit_msg>fix(www): Cannot read property 'resolve' of undefined (#21022)<commit_after><|endoftext|>


<commit_before>var grid = document.getElementById('grid');

var flag = true;

var table = new Handsontable(grid, {
    contextMenu: {
        items: [
            {
                name: 'item1',
                disabled: true
            },
            {
                name: 'item2',
                disabled: function() {
                    flag = !flag;
                    return flag;
                }
            }
        ]
    }
});
<commit_msg>colToProp<commit_after>var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    data: [
        {name: 'Sato', age: 14, sex: 'male'},
        {name: 'Suzuki', age: 16, sex: 'female'},
        {name: 'Tanaka', age: 18, sex: 'male'}
    ]
});

console.log('2 = ' + table.colToProp(2));<|endoftext|>


<commit_before>//阅读理解javascript中策略模式练习
//文章链接如下http://www.360doc.com/content/15/0819/11/15077656_493376894.shtml
//奖金demo

var calcuateSalary = function(salary, level){
	if(level === 'A'){
		return salary * 4;
	}else if(level === 'B'){
		return salary * 3;
	}else if(level === 'C'){
		return salary * 2;
	}
};

//存在缺点：存在很多if else判断   函数缺乏弹性，如果再来个D,需要在函数内添加判断， 算法不能复用

//使用组合函数重构代码
<commit_msg>add demo<commit_after>//阅读理解javascript中策略模式练习
//文章链接如下http://www.360doc.com/content/15/0819/11/15077656_493376894.shtml
//奖金demo

var calcuateSalary = function(salary, level){
	if(level === 'A'){
		return salary * 4;
	}else if(level === 'B'){
		return salary * 3;
	}else if(level === 'C'){
		return salary * 2;
	}
};

//存在缺点：存在很多if else判断   函数缺乏弹性，如果再来个D,需要在函数内添加判断， 算法不能复用

//面向对象的方式来实现奖金的计算
var stragtegy = {
    'A' : function(salary) {
        return salary * 4;
    },
    'B' : function(salary) {
        return salary * 3;
    },
    'C' : function(salary) {
        return salary * 2;
    }
};

var bonus = function(salary) {
    this.salary = null;
    this.levelObj = null;
};

bonus.prototype.setSalary = function(salary) {
    this.salary = salary;
};

bonus.prototype.setLevel= function(levelObj){
    this.levelObj = levelObj;
};
bonus.prototype.getBonus = function(){
    return this.levelObj(this.salary);
};

var a = new bonus();
a.setSalary(1000);
a.setLevel(stragtegy['A']);
console.log(a.getBonus());

var b = new bonus();
b.setSalary(2000);
b.setLevel(stragtegy['B']);
console.log(b.getBonus());

var c = new bonus();
c.setSalary(1000);
c.setLevel(stragtegy['C']);
console.log(c.getBonus());

<|endoftext|>


<commit_before>var grid = document.getElementById('grid');

new Handsontable(grid, {
    columns: [
        {title: 'foo'},
        {}
    ]
});<commit_msg>plugin の基礎<commit_after>var grid = document.getElementById('grid');

var table = new Handsontable(grid, {
    comments: true
});

var comments = table.getPlugin('comments');

comments.setRange({
    from: {row: 1, col: 1}
});
comments.editor.setValue('Commnets Plugin');
comments.saveComment();
<|endoftext|>


<commit_before>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     * ComboBox for choosing allowed values for the field of a model
     *
     *     @example
     *     Ext.create('Ext.Container', {
     *         items: [{
     *             xtype: 'rallyattributecombobox',
     *             model: 'UserStory',
     *             field: 'ScheduleState'
     *         }],
     *         renderTo: Ext.getBody().dom
     *     });
     */
    Ext.define('Rally.ui.AttributeMultiComboBox', {
        requires: ['Ext.Array'],
        extend: 'Ext.ux.form.field.BoxSelect',
        alias: 'widget.rallyattributemulticombobox',

        config: {
            /**
             * @cfg {Ext.data.Model/String} model (required) The model containing the specified field used to populate the store.
             * Not required if field is an instance of Ext.data.Field.
             */
            model: undefined,

            /**
             * @cfg {Ext.data.Field/String} field (required) The model's field, whose allowed values will be used to populate the store.
             */
            field: undefined,

            /**
             * @cfg {Object} context An object specifying the scoping settings for retrieving the specified model
             * If not specified the values provided by {Rally.env.Environment#getContext} will be used.
             */
            context: undefined,

            /**
             * @cfg {Object} storeConfig A configuration object which will be passed to the underlying data store
             */
            storeConfig: undefined,

            queryMode: 'local',
            editable: false,
            valueField: 'value',
            displayField: 'name'
        },

        /**
         * @constructor
         */
        constructor: function(config) {

            this.mergeConfig(config);

            this.store = Ext.create('Ext.data.Store', {
                fields: [this.valueField, this.displayField],
                data: []
            });

            return this.callParent(arguments);
        },

        initComponent: function() {

            this.callParent(arguments);

            if(this.storeConfig && this.storeConfig.listeners) {
                this.store.on(this.storeConfig.listeners);
            }
            this.on('afterrender', this._onAfterRender, this);

            if (Ext.isString(this.model)) {
                this._fetchModel();
            } else {
                if (Ext.isString(this.field)) {
                    this.field = this.model.getField(this.field);
                }
                this._populateStore();
            }
        },

        _fetchModel: function() {
            Rally.data.ModelFactory.getModel({
                context: this.context,
                type: this.model,
                success: this._onModelRetrieved,
                scope: this
            });
        },

        _onModelRetrieved: function(model) {
            this.model = model;
            this.field = this.model.getField(this.field);
            this._populateStore();
        },

        _populateStore: function() {
            if (!this.field) {
                Ext.Error.raise('field config must be specified when creating a Rally.ui.AttributeComboBox');
            }
            var allowedValueObjects = this.field.allowedValues;
            var allowedValues = [];
            if (this.field.required === false) {
                var name = "-- No Entry --";
                var value = "";
                if (this.field.attributeDefinition.AttributeType.toLowerCase() === 'rating') {
                    name = "None";
                    value = "None";
                }
                var allowedValue = {};
                allowedValue[this.valueField] = value;
                allowedValue[this.displayField] = name;
                allowedValues.push(allowedValue);
            }
            Ext.each(allowedValueObjects, function(allowedValueObject) {
                if (allowedValueObject.StringValue != "") {
                    var allowedValue = {};
                    allowedValue[this.valueField] = allowedValueObject.StringValue;
                    allowedValue[this.displayField] = allowedValueObject.StringValue;
                    allowedValues.push(allowedValue);
                }
            }, this);
            this.store.loadRawData(allowedValues);
        },

        _onAfterRender: function() {
            this._afterRender = true;
            if(this._storeLoaded) {
                this.fireEvent('ready', this);
            }
        },

        onReady: function() {
            this._storeLoaded = true;
            if(this._afterRender) {
                this.fireEvent('ready', this);
            }
        }
    });
})();<commit_msg>fixed default states<commit_after>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     * ComboBox for choosing allowed values for the field of a model
     *
     *     @example
     *     Ext.create('Ext.Container', {
     *         items: [{
     *             xtype: 'rallyattributecombobox',
     *             model: 'UserStory',
     *             field: 'ScheduleState'
     *         }],
     *         renderTo: Ext.getBody().dom
     *     });
     */
    Ext.define('Rally.ui.AttributeMultiComboBox', {
        requires: ['Ext.Array'],
        extend: 'Ext.ux.form.field.BoxSelect',
        alias: 'widget.rallyattributemulticombobox',

        config: {
            /**
             * @cfg {Ext.data.Model/String} model (required) The model containing the specified field used to populate the store.
             * Not required if field is an instance of Ext.data.Field.
             */
            model: undefined,

            /**
             * @cfg {Ext.data.Field/String} field (required) The model's field, whose allowed values will be used to populate the store.
             */
            field: undefined,

            /**
             * @cfg {Object} context An object specifying the scoping settings for retrieving the specified model
             * If not specified the values provided by {Rally.env.Environment#getContext} will be used.
             */
            context: undefined,

            /**
             * @cfg {Object} storeConfig A configuration object which will be passed to the underlying data store
             */
            storeConfig: undefined,

            queryMode: 'local',
            editable: false,
            valueField: 'value',
            displayField: 'name'
        },

        /**
         * @constructor
         */
        constructor: function(config) {

            this.mergeConfig(config);

            this.store = Ext.create('Ext.data.Store', {
                fields: [this.valueField, this.displayField],
                data: []
            });

            return this.callParent(arguments);
        },

        initComponent: function() {

            this.callParent(arguments);

            if(this.storeConfig && this.storeConfig.listeners) {
                this.store.on(this.storeConfig.listeners);
            }
            this.on('afterrender', this._onAfterRender, this);

            if (Ext.isString(this.model)) {
                this._fetchModel();
            } else {
                if (Ext.isString(this.field)) {
                    this.field = this.model.getField(this.field);
                }
                this._populateStore();
            }
        },

        _fetchModel: function() {
            Rally.data.ModelFactory.getModel({
                context: this.context,
                type: this.model,
                success: this._onModelRetrieved,
                scope: this
            });
        },

        _onModelRetrieved: function(model) {
            this.model = model;
            this.field = this.model.getField(this.field);
            this._populateStore();
        },

        _populateStore: function() {
            if (!this.field) {
                Ext.Error.raise('field config must be specified when creating a Rally.ui.AttributeComboBox');
            }
            var allowedValueObjects = this.field.allowedValues;
            var allowedValues = [];
            if (this.field.required === false) {
                var name = "-- No Entry --";
                var value = "";
                if (this.field.attributeDefinition.AttributeType.toLowerCase() === 'rating') {
                    name = "None";
                    value = "None";
                }
                var allowedValue = {};
                allowedValue[this.valueField] = value;
                allowedValue[this.displayField] = name;
                allowedValues.push(allowedValue);
            }
            Ext.each(allowedValueObjects, function(allowedValueObject) {
                if (allowedValueObject.StringValue != "") {
                    var allowedValue = {};
                    allowedValue[this.valueField] = allowedValueObject.StringValue;
                    allowedValue[this.displayField] = allowedValueObject.StringValue;
                    allowedValues.push(allowedValue);
                }
            }, this);
            this.store.loadRawData(allowedValues);
			this.fireEvent('ready', this);
        },

        _onAfterRender: function() {
            this._afterRender = true;
            if(this._storeLoaded) {
                this.fireEvent('ready', this);
            }
        },

        onReady: function() {
            this._storeLoaded = true;
            if(this._afterRender) {
                this.fireEvent('ready', this);
            }
        }
    });
})();<|endoftext|>


<commit_before>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Button for selecting a game level.
 * Also depicts the progress made on each level.
 * See specification in https://github.com/phetsims/vegas/issues/59.
 *
 * @author John Blanco
 * @author Chris Malley
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var Dimension2 = require( 'DOT/Dimension2' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var ScoreDisplayDiscreteStars = require( 'VEGAS/ScoreDisplayDiscreteStars' );
  var ScoreDisplayNumberAndStar = require( 'VEGAS/ScoreDisplayNumberAndStar' );
  var ScoreDisplayTextAndNumber = require( 'VEGAS/ScoreDisplayTextAndNumber' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Text = require( 'SCENERY/nodes/Text' );
  var vegas = require( 'VEGAS/vegas' );

  // constants
  var SCALING_TOLERANCE = 1E-4; // Empirically chosen as something the human eye is unlikely to notice.

  /**
   * @param {Node} icon Scenery node that appears on the button above the score display, scaled to fit
   * @param {Node} scoreDisplay - displays the score
   * @param {Object} [options]
   * @constructor
   */
  function LevelSelectionItemNode( icon, scoreDisplay, options ) {

    assert && assert( icon instanceof Node );

    options = _.extend( {

      // score display type
      numStars: 1,

      listener: null, // {function}

      // button size and appearance
      buttonWidth: 150,
      buttonHeight: 150,
      cornerRadius: 10,
      baseColor: 'rgb( 242, 255, 204 )',
      buttonXMargin: 10,
      buttonYMargin: 10,

      // scoreDisplay  (stars)
      scoreDisplayProportion: 0.2, // percentage of the button height occupied by the score display, (0,0.5]
      scoreDisplayMinXMargin: 10,
      scoreDisplayMinYMargin: 5,
      iconToScoreDisplayYSpace: 10,

      // best time (optional)
      bestTimeProperty: null, // null if no best time || {Property.<number>} best time in seconds
      bestTimeVisibleProperty: null, // null || Property.<boolean>} controls visibility of best time
      bestTimeFill: 'black',
      bestTimeFont: new PhetFont( 24 ),
      bestTimeYSpacing: 10,  // vertical space between drop shadow and best time

      // Tandem
      tandem: Tandem.required
    }, options );

    Node.call( this );

    assert && assert(
    options.scoreDisplayProportion > 0 && options.scoreDisplayProportion <= 0.5,
      'scoreDisplayProportion value out of range'
    );

    var maxContentWidth = options.buttonWidth - 2 * options.buttonXMargin;

    // score display (stars), scaled to fit
    var scoreDisplayBackground = new Rectangle( 0, 0, maxContentWidth,
      options.buttonHeight * options.scoreDisplayProportion, options.cornerRadius, options.cornerRadius, {
        fill: 'white',
        stroke: 'black',
        lineWidth: 1,
        pickable: false
      } );

    // Icon, scaled and padded to fit and to make the button size correct.
    var iconSize = new Dimension2( maxContentWidth, options.buttonHeight - scoreDisplayBackground.height -
                                                    2 * options.buttonYMargin - options.iconToScoreDisplayYSpace );
    var adjustedIcon = LevelSelectionItemNode.createSizedImageNode( icon, iconSize );
    adjustedIcon.pickable = false; // TODO: is this needed?

    // Assemble the content.
    var contentNode = new Node();
    if ( scoreDisplayBackground.width > adjustedIcon.width ) {
      adjustedIcon.centerX = scoreDisplayBackground.centerX;
    }
    else {
      scoreDisplayBackground.centerX = adjustedIcon.centerX;
    }
    scoreDisplayBackground.top = adjustedIcon.bottom + options.iconToScoreDisplayYSpace;
    contentNode.addChild( adjustedIcon );
    contentNode.addChild( scoreDisplayBackground );
    contentNode.addChild( scoreDisplay );

    // Keep the score display centered when its bounds change
    var scoreDisplayUpdateLayout = function() {
      scoreDisplay.center = scoreDisplayBackground.center;
    };
    scoreDisplay.on( 'bounds', scoreDisplayUpdateLayout );
    scoreDisplayUpdateLayout();

    // Create the button
    var buttonOptions = {
      content: contentNode,
      xMargin: options.buttonXMargin,
      yMargin: options.buttonYMargin,
      baseColor: options.baseColor,
      cornerRadius: options.cornerRadius,
      listener: options.listener,

      // TODO: if LevelSelectionItemNode changes to inheritance, this will have to change,
      // see https://github.com/phetsims/vegas/issues/56
      tandem: options.tandem.createTandem( 'button' )
    };

    var button = new RectangularPushButton( buttonOptions );
    this.addChild( button );

    // Best time (optional), centered below the button, does not move when button is pressed
    if ( options.bestTimeProperty ) {
      var bestTimeNode = new Text( '', { font: options.bestTimeFont, fill: options.bestTimeFill } );
      this.addChild( bestTimeNode );
      options.bestTimeProperty.link( function( bestTime ) {
        bestTimeNode.text = ( bestTime ? GameTimer.formatTime( bestTime ) : '' );
        bestTimeNode.centerX = button.centerX;
        bestTimeNode.top = button.bottom + options.bestTimeYSpacing;
      } );
      if ( options.bestTimeVisibleProperty ) {
        options.bestTimeVisibleProperty.linkAttribute( bestTimeNode, 'visible' );
      }
    }

    // Pass options to parent class
    this.mutate( options );

    // @private
    this.disposeLevelSelectionItemNode = function() {
      if ( scoreDisplay.hasListener( 'bounds', scoreDisplayUpdateLayout ) ) {
        scoreDisplay.off( 'bounds', scoreDisplayUpdateLayout );
      }
    };
  }

  vegas.register( 'LevelSelectionItemNode', LevelSelectionItemNode );

  return inherit( Node, LevelSelectionItemNode, {

    // @public
    dispose: function() {
      this.disposeLevelSelectionItemNode();
      Node.prototype.dispose.call( this );
    }
  }, {
    /**
     * Creates a new the same dimensions as size with the specified icon. The icon will be scaled to fit, and a
     * background with the specified size may be added to ensure the bounds of the returned node are correct.
     * @public
     *
     * @param {Node} icon
     * @param {Dimension2} size
     * @returns {Node}
     */
    createSizedImageNode: function( icon, size ) {
      icon.scale( Math.min( size.width / icon.bounds.width, size.height / icon.bounds.height ) );
      if ( Math.abs( icon.bounds.width - size.width ) < SCALING_TOLERANCE &&
           Math.abs( icon.bounds.height - size.height ) < SCALING_TOLERANCE ) {
        // The aspect ratio of the icon matched that of the specified size, so no padding is necessary.
        return icon;
      }
      // else padding is needed in either the horizontal or vertical direction.
      var background = Rectangle.dimension( size, { fill: null } );
      icon.center = background.center;
      background.addChild( icon );
      return background;
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayDiscreteStars.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayDiscreteStars
     * @public
     * @static
     */
    createWithScoreDisplayDiscreteStars: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayDiscreteStars options
      }, options );

      var scoreDisplay = new ScoreDisplayDiscreteStars( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayNumberAndStar.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayNumberAndStar
     * @public
     * @static
     */
    createWithScoreDisplayNumberAndStar: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayNumberAndStar options
      }, options );

      var scoreDisplay = new ScoreDisplayNumberAndStar( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayTextAndNumber.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayTextAndNumber
     * @public
     * @static
     */
    createWithScoreDisplayTextAndNumber: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayTextAndNumber options
      }, options );

      var scoreDisplay = new ScoreDisplayTextAndNumber( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    }
  } );
} );<commit_msg>fix doc for createSizedImageNode<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Button for selecting a game level.
 * Also depicts the progress made on each level.
 * See specification in https://github.com/phetsims/vegas/issues/59.
 *
 * @author John Blanco
 * @author Chris Malley
 * @author Andrea Lin
 */
define( function( require ) {
  'use strict';

  // modules
  var Dimension2 = require( 'DOT/Dimension2' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var ScoreDisplayDiscreteStars = require( 'VEGAS/ScoreDisplayDiscreteStars' );
  var ScoreDisplayNumberAndStar = require( 'VEGAS/ScoreDisplayNumberAndStar' );
  var ScoreDisplayTextAndNumber = require( 'VEGAS/ScoreDisplayTextAndNumber' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Text = require( 'SCENERY/nodes/Text' );
  var vegas = require( 'VEGAS/vegas' );

  // constants
  var SCALING_TOLERANCE = 1E-4; // Empirically chosen as something the human eye is unlikely to notice.

  /**
   * @param {Node} icon Scenery node that appears on the button above the score display, scaled to fit
   * @param {Node} scoreDisplay - displays the score
   * @param {Object} [options]
   * @constructor
   */
  function LevelSelectionItemNode( icon, scoreDisplay, options ) {

    assert && assert( icon instanceof Node );

    options = _.extend( {

      // score display type
      numStars: 1,

      listener: null, // {function}

      // button size and appearance
      buttonWidth: 150,
      buttonHeight: 150,
      cornerRadius: 10,
      baseColor: 'rgb( 242, 255, 204 )',
      buttonXMargin: 10,
      buttonYMargin: 10,

      // scoreDisplay  (stars)
      scoreDisplayProportion: 0.2, // percentage of the button height occupied by the score display, (0,0.5]
      scoreDisplayMinXMargin: 10,
      scoreDisplayMinYMargin: 5,
      iconToScoreDisplayYSpace: 10,

      // best time (optional)
      bestTimeProperty: null, // null if no best time || {Property.<number>} best time in seconds
      bestTimeVisibleProperty: null, // null || Property.<boolean>} controls visibility of best time
      bestTimeFill: 'black',
      bestTimeFont: new PhetFont( 24 ),
      bestTimeYSpacing: 10,  // vertical space between drop shadow and best time

      // Tandem
      tandem: Tandem.required
    }, options );

    Node.call( this );

    assert && assert(
    options.scoreDisplayProportion > 0 && options.scoreDisplayProportion <= 0.5,
      'scoreDisplayProportion value out of range'
    );

    var maxContentWidth = options.buttonWidth - 2 * options.buttonXMargin;

    // score display (stars), scaled to fit
    var scoreDisplayBackground = new Rectangle( 0, 0, maxContentWidth,
      options.buttonHeight * options.scoreDisplayProportion, options.cornerRadius, options.cornerRadius, {
        fill: 'white',
        stroke: 'black',
        lineWidth: 1,
        pickable: false
      } );

    // Icon, scaled and padded to fit and to make the button size correct.
    var iconSize = new Dimension2( maxContentWidth, options.buttonHeight - scoreDisplayBackground.height -
                                                    2 * options.buttonYMargin - options.iconToScoreDisplayYSpace );
    var adjustedIcon = LevelSelectionItemNode.createSizedImageNode( icon, iconSize );
    adjustedIcon.pickable = false; // TODO: is this needed?

    // Assemble the content.
    var contentNode = new Node();
    if ( scoreDisplayBackground.width > adjustedIcon.width ) {
      adjustedIcon.centerX = scoreDisplayBackground.centerX;
    }
    else {
      scoreDisplayBackground.centerX = adjustedIcon.centerX;
    }
    scoreDisplayBackground.top = adjustedIcon.bottom + options.iconToScoreDisplayYSpace;
    contentNode.addChild( adjustedIcon );
    contentNode.addChild( scoreDisplayBackground );
    contentNode.addChild( scoreDisplay );

    // Keep the score display centered when its bounds change
    var scoreDisplayUpdateLayout = function() {
      scoreDisplay.center = scoreDisplayBackground.center;
    };
    scoreDisplay.on( 'bounds', scoreDisplayUpdateLayout );
    scoreDisplayUpdateLayout();

    // Create the button
    var buttonOptions = {
      content: contentNode,
      xMargin: options.buttonXMargin,
      yMargin: options.buttonYMargin,
      baseColor: options.baseColor,
      cornerRadius: options.cornerRadius,
      listener: options.listener,

      // TODO: if LevelSelectionItemNode changes to inheritance, this will have to change,
      // see https://github.com/phetsims/vegas/issues/56
      tandem: options.tandem.createTandem( 'button' )
    };

    var button = new RectangularPushButton( buttonOptions );
    this.addChild( button );

    // Best time (optional), centered below the button, does not move when button is pressed
    if ( options.bestTimeProperty ) {
      var bestTimeNode = new Text( '', { font: options.bestTimeFont, fill: options.bestTimeFill } );
      this.addChild( bestTimeNode );
      options.bestTimeProperty.link( function( bestTime ) {
        bestTimeNode.text = ( bestTime ? GameTimer.formatTime( bestTime ) : '' );
        bestTimeNode.centerX = button.centerX;
        bestTimeNode.top = button.bottom + options.bestTimeYSpacing;
      } );
      if ( options.bestTimeVisibleProperty ) {
        options.bestTimeVisibleProperty.linkAttribute( bestTimeNode, 'visible' );
      }
    }

    // Pass options to parent class
    this.mutate( options );

    // @private
    this.disposeLevelSelectionItemNode = function() {
      if ( scoreDisplay.hasListener( 'bounds', scoreDisplayUpdateLayout ) ) {
        scoreDisplay.off( 'bounds', scoreDisplayUpdateLayout );
      }
    };
  }

  vegas.register( 'LevelSelectionItemNode', LevelSelectionItemNode );

  return inherit( Node, LevelSelectionItemNode, {

    // @public
    dispose: function() {
      this.disposeLevelSelectionItemNode();
      Node.prototype.dispose.call( this );
    }
  }, {
    /**
     * Creates a new icon with the same dimensions as size with the specified icon. The new icon will be scaled to fit,
     * and a background with the specified size may be added to ensure that the bounds of the returned node are correct.
     * @public
     *
     * @param {Node} icon
     * @param {Dimension2} size
     * @returns {Node}
     */
    createSizedImageNode: function( icon, size ) {
      icon.scale( Math.min( size.width / icon.bounds.width, size.height / icon.bounds.height ) );
      if ( Math.abs( icon.bounds.width - size.width ) < SCALING_TOLERANCE &&
           Math.abs( icon.bounds.height - size.height ) < SCALING_TOLERANCE ) {
        // The aspect ratio of the icon matched that of the specified size, so no padding is necessary.
        return icon;
      }
      // else padding is needed in either the horizontal or vertical direction.
      var background = Rectangle.dimension( size, { fill: null } );
      icon.center = background.center;
      background.addChild( icon );
      return background;
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayDiscreteStars.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayDiscreteStars
     * @public
     * @static
     */
    createWithScoreDisplayDiscreteStars: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayDiscreteStars options
      }, options );

      var scoreDisplay = new ScoreDisplayDiscreteStars( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayNumberAndStar.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayNumberAndStar
     * @public
     * @static
     */
    createWithScoreDisplayNumberAndStar: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayNumberAndStar options
      }, options );

      var scoreDisplay = new ScoreDisplayNumberAndStar( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    },

    /**
     * Convenience function to create a LevelSelectionItemNode with a ScoreDisplayTextAndNumber.
     * @param {Node} icon
     * @param {Property.<number>} scoreProperty
     * @param {Object} [options] - see LevelSelectionItemNode and ScoreDisplayTextAndNumber
     * @public
     * @static
     */
    createWithScoreDisplayTextAndNumber: function( icon, scoreProperty, options ) {

      options = _.extend( {
        listener: null, // {function|null} called when the button is pressed
        scoreDisplayOptions: null // see ScoreDisplayTextAndNumber options
      }, options );

      var scoreDisplay = new ScoreDisplayTextAndNumber( scoreProperty, options.scoreDisplayOptions );

      return new LevelSelectionItemNode( icon, scoreDisplay, _.omit( options, [ 'scoreDisplayOptions' ] ) );
    }
  } );
} );<|endoftext|>


<commit_before>/* global MO5 */
MO5("MO5.script.Tokenizer", "MO5.script.Parser", "MO5.script.Context",
    "MO5.script.GlobalScope", "MO5.script.SpecialFormsContainer").
define("MO5.script.Interpreter",
function (Tokenizer, Parser, Context, GlobalScope, FormsContainer) {

    function Interpreter () {
        this.reset();
    }

    Interpreter.TypeError = function (message, line, column) {
        this.name = "TypeError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.TypeError.prototype = new Error();

    Interpreter.ReferenceError = function (message, line, column) {
        this.name = "ReferenceError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.ReferenceError.prototype = new Error();

    Interpreter.ScriptError = function (message, line, column) {
        this.name = "ScriptError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.ScriptError.prototype = new Error();

    Interpreter.prototype.reset = function () {
        this.parser = new Parser();
        this.forms = new FormsContainer();
        this.context = new Context(new GlobalScope());
        this.lastLine = 0;
        this.lastColumn = 0;
    };

    Interpreter.prototype.execute = function (input, context) {

        var ast, value, self = this;

        context = context || this.context;

        ast = this.parser.parse(input);

        ast.forEach(function (leaf) {
            value = executeInContext(self, leaf, context);
        });

        return value;
    };

    Interpreter.prototype.scriptValueToString = function (value) {

        var text = "";

        function makeString (val) {
            if (!val || !Array.isArray(val)) {

                if (val && typeof val === "object") {
                    val = val.value;
                }

                if (typeof val === "number" && val < 0) {
                    text += "(- " + Math.abs(val) + ")";
                }
                else {
                    text += "" + val;
                }

                return;
            }

            text += "(";

            val.forEach(function (item, i) {
                if (i === 0) {
                    makeString(item);
                }
                else {
                    text += " ";
                    makeString(item);
                }
            });

            text += ")";
        }

        makeString(value);

        return text;
    };

    return Interpreter;

    function executeInContext (interpreter, input, context) {

        var value;

        if (Array.isArray(input)) {

            if (input.firstLine) {
                interpreter.lastLine = input.firstLine;
                interpreter.lastColumn = input.firstColumn;
            }

            return executeListInContext(interpreter, input, context);
        }

        if (typeof input === "undefined") {
            return null;
        }

        if (input.type) {
            interpreter.lastLine = input.line;
            interpreter.lastColumn = input.column;
        }

        if (input.type === Tokenizer.SYMBOL) {

            if (input.value in interpreter.forms) {
                return interpreter.forms[input.value];
            }

            if (!context.has(input.value)) {
                throw new Interpreter.ReferenceError("Unbound symbol '" + input.value +
                    "'", input.line, input.column);
            }

            value = executeInContext(interpreter, context.find(input.value), context);

            return value;
        }

        if (input.type === Tokenizer.STRING || input.type === Tokenizer.NUMBER) {
            return input.value;
        }

        if (typeof input === "function") {
            return input;
        }

        return typeof input.value === "undefined" ? input : input.value;
    }

    function executeListInContext (interpreter, list, context) {

        var executedList, firstIsToken = false;

        if (list.length < 1) {
            throw new Interpreter.TypeError("Unquoted empty list",
                list.lastLine || interpreter.lastLine, list.lastColumn || interpreter.lastColumn);
        }

        if (!list[0]) {
            throw new Interpreter.TypeError("Head of list is not a function",
                list.lastLine || interpreter.lastLine, list.lastColumn || interpreter.lastColumn);
        }

        firstIsToken = typeof list[0].type === "undefined" ? false : true;

        if (firstIsToken) {
            interpreter.lastLine = list[0].line;
            interpreter.lastColumn = list[0].column;
        }

        if (firstIsToken && list[0].value in interpreter.forms) {
            //console.log("Executing special form: ", list[0]);
            return interpreter.forms[list[0].value](execute, list, context);
        }

        if (firstIsToken && context.hasMacro(list[0].value)) {
            //console.log("Executing special form: ", list[0]);
            return context.findMacro(list[0].value)(list.slice(1));
        }

        if (firstIsToken && list[0].type && list[0].type !== Tokenizer.SYMBOL) {
            throw new Interpreter.TypeError("Head " + list[0].value + " of list " +
                "is not a function", list[0].line, list[0].column);
        }
        else if (firstIsToken && list[0].type && !context.has(list[0].value)) {
            throw new Interpreter.ReferenceError("Unbound symbol '" + list[0].value + "'",
                list[0].line, list[0].column);
        }

        executedList = list.map(function (item) {
            return executeInContext(interpreter, item, context);
        });

        if (typeof executedList[0] === "function") {
            return executedList[0].apply(undefined, executedList.slice(1));
        }

        return execute(executedList, context);

        function execute (list, context) {
            return executeInContext(interpreter, list, context);
        }
    }

});<commit_msg>MO5.script.Interpreter now adds line and column to errors thrown while executing procedures.<commit_after>/* global MO5 */
MO5("MO5.script.Tokenizer", "MO5.script.Parser", "MO5.script.Context",
    "MO5.script.GlobalScope", "MO5.script.SpecialFormsContainer").
define("MO5.script.Interpreter",
function (Tokenizer, Parser, Context, GlobalScope, FormsContainer) {

    function Interpreter () {
        this.reset();
    }

    Interpreter.TypeError = function (message, line, column) {
        this.name = "TypeError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.TypeError.prototype = new Error();

    Interpreter.ReferenceError = function (message, line, column) {
        this.name = "ReferenceError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.ReferenceError.prototype = new Error();

    Interpreter.ScriptError = function (message, line, column) {
        this.name = "ScriptError";
        this.message = message || "";
        this.scriptLine = line;
        this.scriptColumn = column;
    };

    Interpreter.ScriptError.prototype = new Error();

    Interpreter.prototype.reset = function () {
        this.parser = new Parser();
        this.forms = new FormsContainer();
        this.context = new Context(new GlobalScope());
        this.lastLine = 0;
        this.lastColumn = 0;
    };

    Interpreter.prototype.execute = function (input, context) {

        var ast, value, self = this;

        context = context || this.context;

        ast = this.parser.parse(input);

        ast.forEach(function (leaf) {
            value = executeInContext(self, leaf, context);
        });

        return value;
    };

    Interpreter.prototype.scriptValueToString = function (value) {

        var text = "";

        function makeString (val) {
            if (!val || !Array.isArray(val)) {

                if (val && typeof val === "object") {
                    val = val.value;
                }

                if (typeof val === "number" && val < 0) {
                    text += "(- " + Math.abs(val) + ")";
                }
                else if (typeof val === "undefined") {
                    text += "nil";
                }
                else {
                    text += "" + val;
                }

                return;
            }

            text += "(";

            val.forEach(function (item, i) {
                if (i === 0) {
                    makeString(item);
                }
                else {
                    text += " ";
                    makeString(item);
                }
            });

            text += ")";
        }

        makeString(value);

        return text;
    };

    return Interpreter;

    function executeInContext (interpreter, input, context) {

        var value;

        if (Array.isArray(input)) {

            if (input.firstLine) {
                interpreter.lastLine = input.firstLine;
                interpreter.lastColumn = input.firstColumn;
            }

            return executeListInContext(interpreter, input, context);
        }

        if (typeof input === "undefined") {
            return null;
        }

        if (input.type) {
            interpreter.lastLine = input.line;
            interpreter.lastColumn = input.column;
        }

        if (input.type === Tokenizer.SYMBOL) {

            if (input.value in interpreter.forms) {
                return interpreter.forms[input.value];
            }

            if (!context.has(input.value)) {
                throw new Interpreter.ReferenceError("Unbound symbol '" + input.value +
                    "'", input.line, input.column);
            }

            value = executeInContext(interpreter, context.find(input.value), context);

            return value;
        }

        if (input.type === Tokenizer.STRING || input.type === Tokenizer.NUMBER) {
            return input.value;
        }

        if (typeof input === "function") {
            return input;
        }

        return typeof input.value === "undefined" ? input : input.value;
    }

    function executeListInContext (interpreter, list, context) {

        var executedList, firstIsToken = false;

        if (list.length < 1) {
            throw new Interpreter.TypeError("Unquoted empty list",
                list.lastLine || interpreter.lastLine, list.lastColumn || interpreter.lastColumn);
        }

        if (!list[0]) {
            throw new Interpreter.TypeError("Head of list is not a function",
                list.lastLine || interpreter.lastLine, list.lastColumn || interpreter.lastColumn);
        }

        firstIsToken = typeof list[0].type === "undefined" ? false : true;

        if (firstIsToken) {
            interpreter.lastLine = list[0].line;
            interpreter.lastColumn = list[0].column;
        }

        if (firstIsToken && list[0].value in interpreter.forms) {
            //console.log("Executing special form: ", list[0]);
            return interpreter.forms[list[0].value](execute, list, context);
        }

        if (firstIsToken && context.hasMacro(list[0].value)) {
            //console.log("Executing special form: ", list[0]);
            return context.findMacro(list[0].value)(list.slice(1));
        }

        if (firstIsToken && list[0].type && list[0].type !== Tokenizer.SYMBOL) {
            throw new Interpreter.TypeError("Head " + list[0].value + " of list " +
                "is not a function", list[0].line, list[0].column);
        }
        else if (firstIsToken && list[0].type && !context.has(list[0].value)) {
            throw new Interpreter.ReferenceError("Unbound symbol '" + list[0].value + "'",
                list[0].line, list[0].column);
        }

        executedList = list.map(function (item) {
            return executeInContext(interpreter, item, context);
        });

        if (typeof executedList[0] === "function") {
            return (function () {

                var val;

                try {
                    val = executedList[0].apply(undefined, executedList.slice(1));
                }
                catch (e) {
                    if (!e.scriptLine) {
                        e.scriptLine = interpreter.lastLine;
                        e.scriptColumn = interpreter.lastColumn;
                    }

                    throw e;
                }

                return val;
            }());
        }

        return execute(executedList, context);

        function execute (list, context) {
            return executeInContext(interpreter, list, context);
        }
    }

});<|endoftext|>


<commit_before>'use strict';

var scene = [];
var sceneLoader = [];
var onSceneOpen = [];
var onSceneClose = [];

var lastScene = null;
var currentScene = null;
var animDelay = 33;
var sceneAnimationTime = 350;
var elapsedTime = 0;
var sceneFadeInterval;

// No animation at all
function setScene(newScene) {
  lastScene = currentScene;
  currentScene = newScene;
  scene[currentScene].playSceneMusic();
  UpdateScreen();
}

// With animation
function changeScene(newScene) {
  elapsedTime = 0;

  // Changing to new scene
  lastScene = currentScene;
  currentScene = newScene;

  // Interval when both scenes appear at the same time
  scene[lastScene].disableSceneInteractiveness();
  scene[currentScene].disableSceneInteractiveness();
  scene[currentScene].saveAlphaValues();
  scene[currentScene].setFade(0);

  // Play new music
  scene[currentScene].playSceneMusic();

  // Running method for scene opened
  /*if (onSceneOpen[currentScene] != null) {
    onSceneOpen[currentScene]();
  }
  // Running method for scene closed
  if (onSceneClose[lastScene] != null) {
    onSceneClose[lastScene]();
  }*/

  sceneFade();
  sceneFadeInterval = setInterval(sceneFade, animDelay);
}

function sceneFade() {
  elapsedTime += animDelay;
  // Not finished animation
  if (elapsedTime < sceneAnimationTime) {
    // Draw the older scene
    scene[lastScene].showScene();
    // Change the newer scene fade
    scene[currentScene].setFade(elapsedTime/sceneAnimationTime);
  }
  // Finished animation
  else {
    scene[currentScene].setFade(1);
    scene[lastScene].enableSceneInteractiveness();
    scene[currentScene].enableSceneInteractiveness();
    clearInterval(sceneFadeInterval); // Stop calling itself
  }
  UpdateScreen();
}

function UpdateScreen() {
  if (scene[currentScene] != null) { // Validate scene
    scene[currentScene].showScene();
    ScreenUpdateRequest();
  }
  else {
    console.warn("Cannot draw on nonexistent scene. Scene number: " + currentScene);
  }
}
<commit_msg>improved UpdateScreen method<commit_after>'use strict';

var scene = [];
var sceneLoader = [];
var onSceneOpen = [];
var onSceneClose = [];

var lastScene = null;
var currentScene = null;
var animDelay = 33;
var sceneAnimationTime = 350;
var elapsedTime = 0;
var sceneFadeInterval;

// No animation at all
function setScene(newScene) {
  lastScene = currentScene;
  currentScene = newScene;
  scene[currentScene].playSceneMusic();
  UpdateScreen();
}

// With animation
function changeScene(newScene) {
  elapsedTime = 0;

  // Changing to new scene
  lastScene = currentScene;
  currentScene = newScene;

  // Interval when both scenes appear at the same time
  scene[lastScene].disableSceneInteractiveness();
  scene[currentScene].disableSceneInteractiveness();
  scene[currentScene].saveAlphaValues();
  scene[currentScene].setFade(0);

  // Play new music
  scene[currentScene].playSceneMusic();

  // Running method for scene opened
  /*if (onSceneOpen[currentScene] != null) {
    onSceneOpen[currentScene]();
  }
  // Running method for scene closed
  if (onSceneClose[lastScene] != null) {
    onSceneClose[lastScene]();
  }*/

  sceneFade();
  sceneFadeInterval = setInterval(sceneFade, animDelay);
}

function sceneFade() {
  elapsedTime += animDelay;
  // Not finished animation
  if (elapsedTime < sceneAnimationTime) {
    // Draw the older scene
    scene[lastScene].showScene();
    // Change the newer scene fade
    scene[currentScene].setFade(elapsedTime/sceneAnimationTime);
  }
  // Finished animation
  else {
    scene[currentScene].setFade(1);
    scene[lastScene].enableSceneInteractiveness();
    scene[currentScene].enableSceneInteractiveness();
    clearInterval(sceneFadeInterval); // Stop calling itself
  }
  UpdateScreen();
}

function UpdateScreen() {
  if (currentScene != null) { // Only update when a scene is set
    if (scene[currentScene] == null) { // Invalid scene
      console.warn("Cannot draw on nonexistent scene. Scene number: " + currentScene);
    }
    scene[currentScene].showScene();
    ScreenUpdateRequest();
  }
}
<|endoftext|>


<commit_before>imports.gi.versions.WebKit2 = '4.0';

const Endless = imports.gi.Endless;
const Gdk = imports.gi.Gdk;
const Gio = imports.gi.Gio;
const GObject = imports.gi.GObject;

const Actions = imports.app.actions;
const ControllerLoader = imports.app.controllerLoader;
const Dispatcher = imports.app.dispatcher;
const Knowledge = imports.app.knowledge;
const MoltresEngine = imports.search.moltresEngine;
const Utils = imports.app.utils;

/**
 * Class: MoltresApplication
 *
 * A trimmed down application class for running test app.json files
 */
const MoltresApplication = new Knowledge.Class({
    Name: 'MoltresApplication',
    Extends: Endless.Application,

    Properties: {
        /**
         * Property: app-json-path
         * Path to applications app.json file.
         */
        'app-json-path': GObject.ParamSpec.string('app-json-path',
            'App JSON Path', 'App JSON Path',
            GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''),
    },

    _init: function (props={}) {
        this.parent(props);
        this._controller = null;
    },

    vfunc_activate: function () {
        this.parent();
        if (this._controller === null) {
            let app_json = Utils.parse_object_from_file(Gio.File.new_for_path(this.app_json_path));

            MoltresEngine.override_engine();
            let css_file = Gio.File.new_for_path('data/css/default.css');
            let [success, data] = css_file.load_contents(null);
            let css = data.toString();
            this._controller = ControllerLoader.create_controller_with_app_json(this, app_json, {
                css: css,
            });
            this._controller.make_ready();
        }
        Dispatcher.get_default().dispatch({
            action_type: Actions.LAUNCHED_FROM_DESKTOP,
            timestamp: Gdk.CURRENT_TIME,
        });
    },
});
<commit_msg>Don't add default css overrides for moltres<commit_after>imports.gi.versions.WebKit2 = '4.0';

const Endless = imports.gi.Endless;
const Gdk = imports.gi.Gdk;
const Gio = imports.gi.Gio;
const GObject = imports.gi.GObject;

const Actions = imports.app.actions;
const ControllerLoader = imports.app.controllerLoader;
const Dispatcher = imports.app.dispatcher;
const Knowledge = imports.app.knowledge;
const MoltresEngine = imports.search.moltresEngine;
const Utils = imports.app.utils;

/**
 * Class: MoltresApplication
 *
 * A trimmed down application class for running test app.json files
 */
const MoltresApplication = new Knowledge.Class({
    Name: 'MoltresApplication',
    Extends: Endless.Application,

    Properties: {
        /**
         * Property: app-json-path
         * Path to applications app.json file.
         */
        'app-json-path': GObject.ParamSpec.string('app-json-path',
            'App JSON Path', 'App JSON Path',
            GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''),
    },

    _init: function (props={}) {
        this.parent(props);
        this._controller = null;
    },

    vfunc_activate: function () {
        this.parent();
        if (this._controller === null) {
            let app_json = Utils.parse_object_from_file(Gio.File.new_for_path(this.app_json_path));

            MoltresEngine.override_engine();
            this._controller = ControllerLoader.create_controller_with_app_json(this, app_json);
            this._controller.make_ready();
        }
        Dispatcher.get_default().dispatch({
            action_type: Actions.LAUNCHED_FROM_DESKTOP,
            timestamp: Gdk.CURRENT_TIME,
        });
    },
});
<|endoftext|>


<commit_before>module.exports = {
	'mongoUrl' : 'mongodb://192.168.33.101:27017/test'
}<commit_msg>Generic config file<commit_after>module.exports = {
	'mongoUrl' : 'mongodb://127.0.0.1:27017/test'
}
<|endoftext|>


<commit_before>// Description:
//   Build RPMs guy
//
// Commands:
//   hubot buildrpms <snappier-branch>,<snwebapi-branch>

var querystring = require('querystring');
var unirest = require('unirest');
var _ = require('lodash');

module.exports = function(robot) {
	robot.respond(/buildrpms (.*)/i, function(res) {
		var branches = res.match[1].trim().split(',');
		var snappierBranch = branches[0].trim();
		var webapiBranch = branches[0].trim();

    	if (snappierBranch === undefined || webapiBranch === undefined) {
    		res.reply('You did not provide both branches.');
    	} else {
			var endpoint;

			endpoint = process.env.JENKINS_URL;

			var webapi = 'view/WebAPI/job/WebAPI_Builder_v2/buildWithParameters?WebApiBranch=' + webapiBranch;
			var snappier1 = '/view/WebAPI/job/SNAppier_Builder_v2/buildWithParameters?Build_Target_Env=qa&SNAppierBranch=' + snappierBranch;
			var snappier2 = '/view/WebAPI/job/SNAppier_Builder_v2/buildWithParameters?Build_Target_Env=rc-sn&SNAppierBranch=' + snappierBranch;

			unirest.post(endpoint + webapi)
					.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
					.send(data)
					.end(function(response) {
						unirest.post(endpoint + snappier1)
								.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
								.send(data)
								.end(function(response) {
									unirest.post(endpoint + snappier2)
											.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
											.send(data)
											.end(function(response) {
												res.reply('done');
											});
								});
					});
    	}
	});
};<commit_msg>Missing forward slash<commit_after>// Description:
//   Build RPMs guy
//
// Commands:
//   hubot buildrpms <snappier-branch>,<snwebapi-branch>

var querystring = require('querystring');
var unirest = require('unirest');
var _ = require('lodash');

module.exports = function(robot) {
	robot.respond(/buildrpms (.*)/i, function(res) {
		var branches = res.match[1].trim().split(',');
		var snappierBranch = branches[0].trim();
		var webapiBranch = branches[0].trim();

    	if (snappierBranch === undefined || webapiBranch === undefined) {
    		res.reply('You did not provide both branches.');
    	} else {
			var endpoint;

			endpoint = process.env.JENKINS_URL;

			var webapi = '/view/WebAPI/job/WebAPI_Builder_v2/buildWithParameters?WebApiBranch=' + webapiBranch;
			var snappier1 = '/view/WebAPI/job/SNAppier_Builder_v2/buildWithParameters?Build_Target_Env=qa&SNAppierBranch=' + snappierBranch;
			var snappier2 = '/view/WebAPI/job/SNAppier_Builder_v2/buildWithParameters?Build_Target_Env=rc-sn&SNAppierBranch=' + snappierBranch;

			unirest.post(endpoint + webapi)
					.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
					.send(data)
					.end(function(response) {
						unirest.post(endpoint + snappier1)
								.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
								.send(data)
								.end(function(response) {
									unirest.post(endpoint + snappier2)
											.header('Authorization', 'Basic ' + process.env.JENKINS_API_KEY)
											.send(data)
											.end(function(response) {
												res.reply('done');
											});
								});
					});
    	}
	});
};<|endoftext|>