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

/**
 * @toc {Data Storage} HTML5 Local Storage
 * @PB10+
 * @namespace This object provides functions to access a list of key/value pairs.
 *
Each Storage object provides access to a list of key/value pairs, which are sometimes called items.
 * Keys are strings. Any string (including the empty string) is a valid key.
 * Values can be any data type supported by the structured clone algorithm.
 *
 */

localStorage ={
		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description The number of key/value pairs currently present in the list associated with the object.
		 * @readOnly
		 * @type Number
		 */
		length :0,

		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description Returns the name of the nth key in the list. The order of keys is user-agent defined, but must be consistent within an object so long as the number of keys doesn't change.
		 * @param {Number} index The nth key in the list
		 * @returns {String} The name of the nth key in the list. Returns null if the index is greater than or equal to the number of key/value pairs in the object.
		 */
		key : function(index){},

		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description Returns a structured clone of the current value associated with the given key.
		 * @param {String} key The key for the key/value pair
		 * @returns {Object} The value associated with the given key. Returns null if the given key does not exist.
		 * @example
		 * var cityName=localStorage.getItem("cityName");
		 */
		getItem : function(key){},

		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description This method first creates a structured clone of the given value. The user agent checks if a key/value pair with the given key already exists in the list associated with the object.
		 * If it does not, then a new key/value pair must be added to the list, with the given key and with its value set to the newly obtained clone of value.
		 * If the given key does exist in the list, then it must have its value updated to the newly obtained clone of value.
		 * @param {String} key The key for the key/value pair
		 * @param {Object} value The value for the key/value pair
		 * @throws {Exception} If a structured clone of the given value cannot be created. The list associated with the object is left unchanged.
         * @throws {NOT_SUPPORTED_ERR} If the structured clone involving the construction of a new ImageData object cannot be created.
         * @throws {QUOTA_EXCEEDED_ERR} If the new value couldn't be set (for example, if the user disabled storage for the site, or if the quota has been exceeded).
		 * @example
		 * localStorage.setItem("cityName", "Toronto");
		 */
		setItem : function(key, value){},

		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description This method causes the key/value pair with the given key to be removed from the list associated with the object, if it exists. If no item with that key exists, the method does nothing.
		 * @param  {String} key The key for the key/value pair
		 * @example
		 * localStorage.removeItem("cityName");
		 */
		removeItem : function(key){},

		/**
		 * @PB10+
         * @BB70+
		 * @RIPPLE
		 * @description This method atomically causes the list associated with the object to be emptied of all key/value pairs, if there are any. If there are none, then the method does nothing.
		 */
		clear : function(){}
};<commit_msg>Included BB 6.0 support; added notice about 6.0 being mainly supported but not always in 6.0 dot revisions<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * @notice {Support for BlackBerry 6.0:}
 * This API supports BlackBerry 6.0; however, some BlackBerry 6.0 dot revisions may not be fully supported.
 * @toc {Data Storage} HTML5 Local Storage
 * @PB10+
 * @BB60+
 * @namespace This object provides functions to access a list of key/value pairs.
 *
Each Storage object provides access to a list of key/value pairs, which are sometimes called items.
 * Keys are strings. Any string (including the empty string) is a valid key.
 * Values can be any data type supported by the structured clone algorithm.

 *
 */

localStorage ={
		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description The number of key/value pairs currently present in the list associated with the object.
		 * @readOnly
		 * @type Number
		 */
		length :0,

		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description Returns the name of the nth key in the list. The order of keys is user-agent defined, but must be consistent within an object so long as the number of keys doesn't change.
		 * @param {Number} index The nth key in the list
		 * @returns {String} The name of the nth key in the list. Returns null if the index is greater than or equal to the number of key/value pairs in the object.
		 */
		key : function(index){},

		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description Returns a structured clone of the current value associated with the given key.
		 * @param {String} key The key for the key/value pair
		 * @returns {Object} The value associated with the given key. Returns null if the given key does not exist.
		 * @example
		 * var cityName=localStorage.getItem("cityName");
		 */
		getItem : function(key){},

		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description This method first creates a structured clone of the given value. The user agent checks if a key/value pair with the given key already exists in the list associated with the object.
		 * If it does not, then a new key/value pair must be added to the list, with the given key and with its value set to the newly obtained clone of value.
		 * If the given key does exist in the list, then it must have its value updated to the newly obtained clone of value.
		 * @param {String} key The key for the key/value pair
		 * @param {Object} value The value for the key/value pair
		 * @throws {Exception} If a structured clone of the given value cannot be created. The list associated with the object is left unchanged.
         * @throws {NOT_SUPPORTED_ERR} If the structured clone involving the construction of a new ImageData object cannot be created.
         * @throws {QUOTA_EXCEEDED_ERR} If the new value couldn't be set (for example, if the user disabled storage for the site, or if the quota has been exceeded).
		 * @example
		 * localStorage.setItem("cityName", "Toronto");
		 */
		setItem : function(key, value){},

		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description This method causes the key/value pair with the given key to be removed from the list associated with the object, if it exists. If no item with that key exists, the method does nothing.
		 * @param  {String} key The key for the key/value pair
		 * @example
		 * localStorage.removeItem("cityName");
		 */
		removeItem : function(key){},

		/**
		 * @PB10+
         * @BB60+
		 * @RIPPLE
		 * @description This method atomically causes the list associated with the object to be emptied of all key/value pairs, if there are any. If there are none, then the method does nothing.
		 */
		clear : function(){}
};<|endoftext|>


<commit_before>import React from 'react';
import { dispatch } from '../stores/user/UserDispatcher';
import UserStore from '../stores/user/UserStore';
import { Container } from 'flux/utils';
import { Link } from 'react-router';

import $ from 'jquery';

import Nav from 'react-bootstrap/lib/Nav';
import Navbar from 'react-bootstrap/lib/Navbar';
import Button from 'react-bootstrap/lib/Button';
import NavItem from 'react-bootstrap/lib/NavItem';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import NavDropdown from 'react-bootstrap/lib/NavDropdown';

class HeaderComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      open: false,
      labelText: 'Sign In',
      username: ''
    };

    this.goToSignIn = this.goToSignIn.bind(this);
    this.goToSignUp = this.goToSignUp.bind(this);
    this.goToProfile = this.goToProfile.bind(this);
    this.goToLanding = this.goToLanding.bind(this);
    this.signOut = this.signOut.bind(this);
    this.handleToggle = this.handleToggle.bind(this);
  }

  static getStores() {
    return [UserStore];
  }

  static calculateState(prevState) {
    let currentState = {
      user: UserStore.getState(),
      isLoggedIn: UserStore.isLoggedIn()
    };
    return currentState;
  }

  handleToggle() {
    this.setState({
      open: !this.state.open
    });
  }

  goToSignIn(e) {
    this.props.history.pushState(null, '/signin');
  }

  goToSignUp(e) {
    this.props.history.pushState(null, '/signup');
  }

  goToProfile(e) {
    this.props.history.pushState(null, '/about');
  }

  goToLanding(e) {
    this.props.history.pushState(null, '/');
  }

  signOut(e) {
    let self = this;
    $.post('/api/logout', this.state).done(function (data) {
      if (data.success) {
        dispatch({
          type: 'user/logout'
        });
        self.setState({
          username: ''
        });
        self.props.history.pushState(null, '/');
      }
    });
  }

  render() {
    const { username } = this.props;
    let userMenu;
    let signUpButton;
    if (username) {
      userMenu = (
        <NavDropdown eventKey={3} title={username} id='basic-nav-dropdown'>
          <MenuItem eventKey={3.1} onClick={this.goToProfile}>Profile</MenuItem>
          <MenuItem eventKey={3.2}>Help</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey={3.3} onClick={this.signOut}>Sign Out</MenuItem>
        </NavDropdown>
      );
    } else {
      signUpButton = (

          <NavItem onClick={this.goToSignUp}>Sign Up</NavItem>
          <NavItem primary onClick={this.goToSignIn}>Sign In</NavItem>

      );
    }
    return (
      <Navbar>
        <Navbar.Header>
          <Navbar.Brand>
            KTS
          </Navbar.Brand>
        </Navbar.Header>

          {userMenu}

        {signUpButton}
      </Navbar>
    );
  }
}

HeaderComponent.propTypes = {
  history: React.PropTypes.object.isRequired,
  username: React.PropTypes.string.isRequired
};

const container = Container.create(HeaderComponent);

export default HeaderComponent;
<commit_msg>fixed store population<commit_after>import React from 'react';
import { dispatch } from '../stores/user/UserDispatcher';
import UserStore from '../stores/user/UserStore';
import { Link } from 'react-router';

import $ from 'jquery';

import Nav from 'react-bootstrap/lib/Nav';
import Navbar from 'react-bootstrap/lib/Navbar';
import Button from 'react-bootstrap/lib/Button';
import NavItem from 'react-bootstrap/lib/NavItem';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import NavDropdown from 'react-bootstrap/lib/NavDropdown';

class HeaderComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      open: false,
      labelText: 'Sign In',
      username: ''
    };

    this.goToSignIn = this.goToSignIn.bind(this);
    this.goToSignUp = this.goToSignUp.bind(this);
    this.goToProfile = this.goToProfile.bind(this);
    this.goToLanding = this.goToLanding.bind(this);
    this.signOut = this.signOut.bind(this);
  }

  goToSignIn(e) {
    this.props.history.pushState(null, '/signin');
  }

  goToSignUp(e) {
    this.props.history.pushState(null, '/signup');
  }

  goToProfile(e) {
    this.props.history.pushState(null, '/profile');
  }

  goToLanding(e) {
    this.props.history.pushState(null, '/');
  }

  signOut(e) {
    let self = this;
    $.post('/api/logout', this.state).done(function (data) {
      if (data.success) {
        dispatch({
          type: 'user/logout'
        });
        self.setState({
          username: ''
        });
        self.props.history.pushState(null, '/');
      }
    });
  }

  render() {
    const { username } = this.props;
    let userMenu;
    let signUpButton;
    if (username) {
      userMenu = (
        <NavDropdown eventKey={3} title={username} id='basic-nav-dropdown'>
          <MenuItem eventKey={3.1} onClick={this.goToProfile}>Profile</MenuItem>
          <MenuItem eventKey={3.2}>Help</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey={3.3} onClick={this.signOut}>Sign Out</MenuItem>
        </NavDropdown>
      );
    } else {
      signUpButton = (

          <NavItem onClick={this.goToSignUp}>Sign Up</NavItem>
          <NavItem primary onClick={this.goToSignIn}>Sign In</NavItem>

      );
    }
    return (
      <Navbar>
        <Navbar.Header>
          <Navbar.Brand>
            KTS
          </Navbar.Brand>
        </Navbar.Header>

          {userMenu}

        {signUpButton}
      </Navbar>
    );
  }
}

HeaderComponent.propTypes = {
  history: React.PropTypes.object.isRequired,
  username: React.PropTypes.string.isRequired
};

export default HeaderComponent;
<|endoftext|>


<commit_before>'use strict';

exports.init = function(req, res){
  if (req.isAuthenticated()) {
    res.redirect(req.user.defaultReturnUrl());
  }
  else {
    res.render('login/forgot/index');
  }
};

exports.send = function(req, res, next){
  console.log('in send');
  //return 'test';

  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    console.log('in validate');
    if (!req.body.email) {
      workflow.outcome.errfor.email = 'required';
      return workflow.emit('response');
    }

    workflow.emit('generateToken');
  });

  workflow.on('generateToken', function() {
    console.log('in generateToken');
    var crypto = require('crypto');
    crypto.randomBytes(21, function(err, buf) {
      if (err) {
        return next(err);
      }

      var token = buf.toString('hex');
      console.log('before encryptPW');
      req.app.db.models.User.encryptPassword(token, function(err, hash) {
        if (err) {
          return next(err);
        }
        console.log('after encryptPW');
        workflow.emit('patchUser', token, hash);
      });
    });
  });

  workflow.on('patchUser', function(token, hash) {
    console.log('patchUser');
    var conditions = { email: req.body.email.toLowerCase() };
    var fieldsToSet = {
      resetPasswordToken: hash,
      resetPasswordExpires: Date.now() + 10000000
    };

     req.app.db.models.User.find({
          where: conditions
       })
      .error(function(err) {
        // error callback
        console.log('Couldnt find user: ' + err);
        return workflow.emit('exception', err);
      })
      .success(function(user) {
          console.log('User returned.');
          console.dir(user);

          if (!user) {
            return workflow.emit('exception', 'couldn\'t find user');
          }

          var userId = user.id;

          //create Resetpassword record
          var resetPW = req.app.db.models.ResetPassword.build({
            userId: userId,
            resetPasswordToken: fieldsToSet.resetPasswordToken,
            resetPasswordExpires: fieldsToSet.resetPasswordExpires,
            isUsed: 'N',
          });

          // persist an instance
          resetPW.save()
            .error(function(err) {
              // error callback
              console.log('Couldnt save resetPassword: ' + err);
              return workflow.emit('exception', err);
            })
            .success(function(newResetPW) {
              // success callback
              console.log('Saved new ResetPW: ' + newResetPW.resetPasswordToken);

              workflow.emit('sendEmail', token, user);

            });

      });

  });

  workflow.on('sendEmail', function(token, user) {
    console.log('reached sendEmail');
    req.app.utility.sendmail(req, res, {
      from: req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>',
      to: user.email,
      subject: 'Reset your '+ req.app.config.projectName +' password',
      textPath: 'login/forgot/email-text',
      htmlPath: 'login/forgot/email-html',
      locals: {
        username: user.username,
        resetLink: req.protocol +'://'+ req.headers.host +'?u=' + user.email + '&t=' + token, ///api/v1/login/reset/'+ user.email +'/'+ token +'/',
        projectName: req.app.config.projectName
      },
      success: function(message) {
        workflow.emit('response');
      },
      error: function(err) {
        workflow.outcome.errors.push('Error Sending: '+ err);
        workflow.emit('response');
      }
    });
  });

  workflow.emit('validate');

};

<commit_msg>testing<commit_after>'use strict';

exports.init = function(req, res){
  if (req.isAuthenticated()) {
    res.redirect(req.user.defaultReturnUrl());
  }
  else {
    res.render('login/forgot/index');
  }
};

exports.send = function(req, res, next){
  console.log('in send');
  return 'test';

  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    console.log('in validate');
    if (!req.body.email) {
      workflow.outcome.errfor.email = 'required';
      return workflow.emit('response');
    }

    workflow.emit('generateToken');
  });

  workflow.on('generateToken', function() {
    console.log('in generateToken');
    var crypto = require('crypto');
    crypto.randomBytes(21, function(err, buf) {
      if (err) {
        return next(err);
      }

      var token = buf.toString('hex');
      console.log('before encryptPW');
      req.app.db.models.User.encryptPassword(token, function(err, hash) {
        if (err) {
          return next(err);
        }
        console.log('after encryptPW');
        workflow.emit('patchUser', token, hash);
      });
    });
  });

  workflow.on('patchUser', function(token, hash) {
    console.log('patchUser');
    var conditions = { email: req.body.email.toLowerCase() };
    var fieldsToSet = {
      resetPasswordToken: hash,
      resetPasswordExpires: Date.now() + 10000000
    };

     req.app.db.models.User.find({
          where: conditions
       })
      .error(function(err) {
        // error callback
        console.log('Couldnt find user: ' + err);
        return workflow.emit('exception', err);
      })
      .success(function(user) {
          console.log('User returned.');
          console.dir(user);

          if (!user) {
            return workflow.emit('exception', 'couldn\'t find user');
          }

          var userId = user.id;

          //create Resetpassword record
          var resetPW = req.app.db.models.ResetPassword.build({
            userId: userId,
            resetPasswordToken: fieldsToSet.resetPasswordToken,
            resetPasswordExpires: fieldsToSet.resetPasswordExpires,
            isUsed: 'N',
          });

          // persist an instance
          resetPW.save()
            .error(function(err) {
              // error callback
              console.log('Couldnt save resetPassword: ' + err);
              return workflow.emit('exception', err);
            })
            .success(function(newResetPW) {
              // success callback
              console.log('Saved new ResetPW: ' + newResetPW.resetPasswordToken);

              workflow.emit('sendEmail', token, user);

            });

      });

  });

  workflow.on('sendEmail', function(token, user) {
    console.log('reached sendEmail: ');
    console.log(req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>');
    console.log(req.app.config.smtp.credentials.user + ', ' + req.app.config.smtp.credentials.host);
    req.app.utility.sendmail(req, res, {
      from: req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>',
      to: user.email,
      subject: 'Reset your '+ req.app.config.projectName +' password',
      textPath: 'login/forgot/email-text',
      htmlPath: 'login/forgot/email-html',
      locals: {
        username: user.username,
        resetLink: req.protocol +'://'+ req.headers.host +'?u=' + user.email + '&t=' + token, ///api/v1/login/reset/'+ user.email +'/'+ token +'/',
        projectName: req.app.config.projectName
      },
      success: function(message) {
        workflow.emit('response');
      },
      error: function(err) {
        workflow.outcome.errors.push('Error Sending: '+ err);
        workflow.emit('response');
      }
    });
  });

  workflow.emit('validate');

};

<|endoftext|>


<commit_before>var React = require('react'),
		Sticky = React.createClass({

  reset: function() {
    var html = document.documentElement,
        body = document.body,
        windowOffset = window.pageYOffset || (html.clientHeight ? html : body).scrollTop;

    this.elementOffset = this.getDOMNode().getBoundingClientRect().top + windowOffset;
  },

  handleResize: function() {
    // set style with callback to reset once style rendered succesfully
    this.setState({ style: {} }, this.reset);
  },

  handleScroll: function() {
    if (window.pageYOffset > this.elementOffset) this.setState({ style: this.props.stickyStyle });
    else this.setState({ style: {} });
  },

  getDefaultProps: function() {
    return {
      stickyStyle: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0
      }
    };
  },

  getInitialState: function() {
    return {
      style: {}
    };
  },

  componentDidMount: function() {
    this.reset();
    window.addEventListener('scroll', this.handleScroll);
    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('resize', this.handleResize);
  },

  render: function() {
    return React.DOM.div({
      style: this.state.style
    }, this.props.children);
  }
});

module.exports = Sticky;
<commit_msg>trigger the onStickyStateChange callback function when resizing or scrolling<commit_after>var React = require('react'),
		Sticky = React.createClass({

  reset: function() {
    var html = document.documentElement,
        body = document.body,
        windowOffset = window.pageYOffset || (html.clientHeight ? html : body).scrollTop;

    this.elementOffset = this.getDOMNode().getBoundingClientRect().top + windowOffset;
  },

  handleResize: function() {
    this.props.onStickyStateChange( false );
    // set style with callback to reset once style rendered succesfully
    this.setState({ style: {} }, this.reset);
  },

  handleScroll: function() {
    if (window.pageYOffset > this.elementOffset){
      this.props.onStickyStateChange( true );
      this.setState({ style: this.props.stickyStyle });
    }
    else{
      this.props.onStickyStateChange( false );
      this.setState({ style: {} });
    }
  },

  getDefaultProps: function() {
    return {
      stickyStyle: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0
      },
      onStickyStateChange: function () {}
    };
  },

  getInitialState: function() {
    return {
      style: {}
    };
  },

  componentDidMount: function() {
    this.reset();
    window.addEventListener('scroll', this.handleScroll);
    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('resize', this.handleResize);
  },

  render: function() {
    return React.DOM.div({
      style: this.state.style
    }, this.props.children);
  }
});

module.exports = Sticky;
<|endoftext|>


<commit_before>'use strict';

/**
 * @param  {Object}  gulp    The gulp object
 * @param  {Object}  config  The configuration for gulp tasks. To get a property using `config.a.b.c` or `config.get('a.b.c')`
 * @param  {Object}  LL      Lazy required libraries and other data
 * @param  {Object}  args    The parsed arguments from comment line
 */
module.exports = function(gulp, config, LL, args) {  // eslint-disable-line no-unused-vars
    gulp.task('release:license', ['clean:release'], function() {
        var conf = config.get('tasks.release.license');
        var license = LL.license;
        var filter = LL.filter;

        var matches = conf.get('matches');
        var author = conf.get('author');
        var defaultLicense = conf.get('license');

        var stream = gulp.src(conf.get('src'), conf.get('srcOpts'));

        matches.forEach(function(matchObj) {
            var f = filter(matchObj.glob, {restore: true});
            stream = stream.pipe(f)
                .pipe(license(matchObj.license || defaultLicense, {
                    organization: matchObj.author || author,
                }))
                .pipe(f.restore);
        });

        return stream.pipe(gulp.dest(conf.get('dest')));
    });

    gulp.task('release:npm-pack', ['clean:npm-package'], function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var src = Path.resolve(conf.get('src'));
        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
        var packageName = src.split('/').pop();

        var command = util.format('tar -czf %s -C %s %s', destFile, Path.resolve(src, '..'), packageName);

        CP.exec(command, done);
    });

    gulp.task('release:npm-publish', function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);

        var command = util.format('npm publish --access public %s', destFile);

        CP.exec(command, done);
    });

    gulp.task('release:pre', function(done) {
        var CP = LL.CP;

        var command = '\
            git add . && \
            git stash save "stash for release" && \
            git fetch --prune && \
            git rebase origin/develop release \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:changelog', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var changelog = LL.changelog;
        var conf = config.get('tasks.release.changelog');
        var name = conf.get('name');

        gulp.src(name, {
            buffer: false,
        })
            .pipe(changelog({
                preset: 'angular',
            }))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var command = util.format('git add %s', name);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    /**
     * gulp release:bump [options]
     *
     * options:
     *     -t --type [major, minor, patch]  Semver 2.0. default to patch
     *     -v --version VERSION  Bump to a specific version
     */
    gulp.task('release:bump', function(done) {
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;

        var bumpOpts = {
            key: 'version',
            indent: 2,
        };

        var version = args.v || args.version;
        var type = args.t || args.type || 'patch';

        if (version) {
            bumpOpts.version = version;
        } else {
            bumpOpts.type = type;
        }

        gulp.src(Path.resolve('./package.json'))
            .pipe(LL.bump(bumpOpts))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var packageJSON = LL.reload('packageJSON');
                var tag = packageJSON.version;

                var command = util.format('\
                    git add package.json && \
                    git commit -m "update version to %s" --no-edit \
                ', tag);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    gulp.task('release:branch', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var command = util.format('\
            git fetch --prune && \
            git rebase origin/develop develop && \
            git merge --no-ff --no-edit release && \
            git rebase origin/master master && \
            git merge --no-ff --no-edit release \
        ');
        CP.exec(command, done);
    });

    gulp.task('release:tag', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.reload('packageJSON');
        var tag = packageJSON.version;
        var conf = config.get('tasks.release.git-tag');
        var commitHash = conf.get('dest');

        var command = util.format('git tag -a v%s %s -m "release version %s"', tag, commitHash, tag);
        CP.exec(command, done);
    });

    gulp.task('release:push', function(done) {
        var CP = LL.CP;
        var command = '\
            git push origin develop && \
            git push origin master && \
            git push --tags \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:code', function(done) {
        LL.runSequence(
            'lint',
            'test',
            'release:pre',
            'release:changelog',
            'release:bump',
            'release:branch',
            'release:tag',
            'release:push',
            done
        );
    });

    gulp.task('release', function(done) {
        LL.runSequence(
            'release:code',
            'release:license',
            'release:npm-pack',
            'release:npm-publish',
            done
        );
    });
};
<commit_msg>update gulp release:changelog<commit_after>'use strict';

/**
 * @param  {Object}  gulp    The gulp object
 * @param  {Object}  config  The configuration for gulp tasks. To get a property using `config.a.b.c` or `config.get('a.b.c')`
 * @param  {Object}  LL      Lazy required libraries and other data
 * @param  {Object}  args    The parsed arguments from comment line
 */
module.exports = function(gulp, config, LL, args) {  // eslint-disable-line no-unused-vars
    gulp.task('release:license', ['clean:release'], function() {
        var conf = config.get('tasks.release.license');
        var license = LL.license;
        var filter = LL.filter;

        var matches = conf.get('matches');
        var author = conf.get('author');
        var defaultLicense = conf.get('license');

        var stream = gulp.src(conf.get('src'), conf.get('srcOpts'));

        matches.forEach(function(matchObj) {
            var f = filter(matchObj.glob, {restore: true});
            stream = stream.pipe(f)
                .pipe(license(matchObj.license || defaultLicense, {
                    organization: matchObj.author || author,
                }))
                .pipe(f.restore);
        });

        return stream.pipe(gulp.dest(conf.get('dest')));
    });

    gulp.task('release:npm-pack', ['clean:npm-package'], function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var src = Path.resolve(conf.get('src'));
        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
        var packageName = src.split('/').pop();

        var command = util.format('tar -czf %s -C %s %s', destFile, Path.resolve(src, '..'), packageName);

        CP.exec(command, done);
    });

    gulp.task('release:npm-publish', function(done) {
        var conf = config.get('tasks.release.npm');
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.packageJSON;

        var dest = Path.resolve(conf.get('dest'));
        var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);

        var command = util.format('npm publish --access public %s', destFile);

        CP.exec(command, done);
    });

    gulp.task('release:pre', function(done) {
        var CP = LL.CP;

        var command = '\
            git add . && \
            git stash save "stash for release" && \
            git fetch --prune && \
            git rebase origin/develop release \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:changelog:touch', function(done) {
        var name = config.get('tasks.release.changelog.name');
        LL.CP.exec('touch ' + name, done);
    });

    gulp.task('release:changelog', ['release:changelog:touch'], function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var changelog = LL.changelog;
        var conf = config.get('tasks.release.changelog');
        var name = conf.get('name');

        gulp.src(name, {
            buffer: false,
        })
            .pipe(changelog({
                preset: 'angular',
            }))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var command = util.format('git add %s', name);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    /**
     * gulp release:bump [options]
     *
     * options:
     *     -t --type [major, minor, patch]  Semver 2.0. default to patch
     *     -v --version VERSION  Bump to a specific version
     */
    gulp.task('release:bump', function(done) {
        var Path = LL.Path;
        var CP = LL.CP;
        var util = LL.nodeUtil;

        var bumpOpts = {
            key: 'version',
            indent: 2,
        };

        var version = args.v || args.version;
        var type = args.t || args.type || 'patch';

        if (version) {
            bumpOpts.version = version;
        } else {
            bumpOpts.type = type;
        }

        gulp.src(Path.resolve('./package.json'))
            .pipe(LL.bump(bumpOpts))
            .pipe(gulp.dest('./'))
            .on('end', function() {
                var packageJSON = LL.reload('packageJSON');
                var tag = packageJSON.version;

                var command = util.format('\
                    git add package.json && \
                    git commit -m "update version to %s" --no-edit \
                ', tag);
                CP.exec(command, done);
            })
            .on('error', done);
    });

    gulp.task('release:branch', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var command = util.format('\
            git fetch --prune && \
            git rebase origin/develop develop && \
            git merge --no-ff --no-edit release && \
            git rebase origin/master master && \
            git merge --no-ff --no-edit release \
        ');
        CP.exec(command, done);
    });

    gulp.task('release:tag', function(done) {
        var CP = LL.CP;
        var util = LL.nodeUtil;
        var packageJSON = LL.reload('packageJSON');
        var tag = packageJSON.version;
        var conf = config.get('tasks.release.git-tag');
        var commitHash = conf.get('dest');

        var command = util.format('git tag -a v%s %s -m "release version %s"', tag, commitHash, tag);
        CP.exec(command, done);
    });

    gulp.task('release:push', function(done) {
        var CP = LL.CP;
        var command = '\
            git push origin develop && \
            git push origin master && \
            git push --tags \
        ';
        CP.exec(command, done);
    });

    gulp.task('release:code', function(done) {
        LL.runSequence(
            'lint',
            'test',
            'release:pre',
            'release:changelog',
            'release:bump',
            'release:branch',
            'release:tag',
            'release:push',
            done
        );
    });

    gulp.task('release', function(done) {
        LL.runSequence(
            'release:code',
            'release:license',
            'release:npm-pack',
            'release:npm-publish',
            done
        );
    });
};
<|endoftext|>


<commit_before>$(function() {
    "use strict";
    var percentage, percentage_box_width, bg_color,
        $items = $('.content li'),
        $visited_items = $items.filter('.v'),
        $next_items = $items.filter('.n'),
        $message_box = $('#message'),
        $percentage_box = $('#percentage'),
        $btn_filter_visited = $('#filter_v'),
        $btn_filter_next = $('#filter_n'),
        is_smartphone = !$('.sidebar footer').is(':visible');

    // message
    $visited_items.hover(function() {
        var $t = $(this);

        $message_box.find('p').html($t.data('msg')).end()
                    .find('.date span').html($t.data('date')).end()
                    .show();
    },
    function() {
        $message_box.hide();
    });

    // percentage
    percentage = Math.floor($visited_items.length/$items.length * 100);
    percentage_box_width = $percentage_box.width() + 17; // 余白があるので大きめの画像を取得
    bg_color = $.fmtColor($('body').css("background-color")).replace('#','');

    $percentage_box.html('' + $visited_items.length + '/' + $items.length)
                       .css('background-image', 'url("http://chart.apis.google.com/chart?cht=p&chd=t:' + percentage + ',' + (100 - percentage) + '&chs=' + percentage_box_width + 'x' + percentage_box_width + '&chco=' + bg_color + '")');

    // filter_visited
    $btn_filter_visited.on('click', function() {
        var $t = $(this),
            $li = $t.closest('li');

        if ($li.hasClass('on')) {
            $items.show();
            $li.removeClass('on')
               .find('i').attr('class', 'icon-check-empty');

        } else {
            $items.not($visited_items).hide();
            $li.addClass('on')
               .find('i').attr('class', 'icon-check');
            $('body').scrollTop(0);
        }
    })
    .on('mouseover', function() {
        var $t = $(this);

        if ($t.closest('li').hasClass('on')) {
            $t.find('i').attr('class', 'icon-check-empty');
        } else {
            $t.find('i').attr('class', 'icon-check');
        }
    })
    .on('mouseout', function() {
        var $t = $(this);

        if ($t.closest('li').hasClass('on')) {
            $t.find('i').attr('class', 'icon-check');
        } else {
            $t.find('i').attr('class', 'icon-check-empty');
        }
    });

    // smartphone
    if (is_smartphone) {
        $items.not($visited_items).hide();
        $('.sidebar footer').clone()
                            .addClass('pure-hidden-tablet')
                            .addClass('pure-hidden-desktop')
                            .appendTo($('.content'));
    }
});
<commit_msg>fail test<commit_after>$(function() {
    "use strict";
    var percentage, percentage_box_width, bg_color,
        $items = $('.content li'),
        $visited_items = $items.filter('.v'),
        $next_items = $items.filter('.n'),
        $message_box = $('#message'),
        $percentage_box = $('#percentage'),
        $btn_filter_visited = $('#filter_v'),
        $btn_filter_next = $('#filter_n'),
        is_smartphone = !$('.sidebar footer').is(':visible');

    // message
    $visited_items.hover(function() {
        var $t = $(this);

        $message_box.find('p').html($t.data('msg')).end()
                    .find('.date span').html($t.data('date')).end()
                    .show();
    },
    function() {
        $message_box.hide();
    });

    // percentage
    percentage = Math.floor($visited_items.length/$items.length * 100);
    percentage_box_width = $percentage_box.width() + 17; // 余白があるので大きめの画像を取得
    bg_color = $.fmtColor($('body').css("background-color")).replace('#','');

    $percentage_box.html('' + $visited_items.length + '/' + $items.length)
                       .css('background-image', 'url("http://chart.apis.google.com/chart?cht=p&chd=t:' + percentage + ',' + (100 - percentage) + '&chs=' + percentage_box_width + 'x' + percentage_box_width + '&chco=' + bg_color + '")');

    // filter_visited
    $btn_filter_visited.on('click', function() {
        var $t = $(this),
            $li = $t.closest('li');

        if($li.hasClass('on')) {
            $items.show();
            $li.removeClass('on')
               .find('i').attr('class', 'icon-check-empty');

        } else {
            $items.not($visited_items).hide();
            $li.addClass('on')
               .find('i').attr('class', 'icon-check');
            $('body').scrollTop(0);
        }
    })
    .on('mouseover', function() {
        var $t = $(this);

        if ($t.closest('li').hasClass('on')) {
            $t.find('i').attr('class', 'icon-check-empty');
        } else {
            $t.find('i').attr('class', 'icon-check');
        }
    })
    .on('mouseout', function() {
        var $t = $(this);

        if ($t.closest('li').hasClass('on')) {
            $t.find('i').attr('class', 'icon-check');
        } else {
            $t.find('i').attr('class', 'icon-check-empty');
        }
    });

    // smartphone
    if (is_smartphone) {
        $items.not($visited_items).hide();
        $('.sidebar footer').clone()
                            .addClass('pure-hidden-tablet')
                            .addClass('pure-hidden-desktop')
                            .appendTo($('.content'));
    }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const ValueObject = require('../ValueObject.js').ValueObject;
const Site = require('../site/Site.js').Site;

/**
 * Describes a simple site specific data store
 *
 * @memberOf model.data
 */
class Data extends ValueObject
{
    /**
     * @constant {string}
     * @static
     */
    static get SITE()
    {
        return 'site';
    }

    /**
     * @constant {array}
     * @static
     */
    static get ANY()
    {
        return ['site'];
    }

    /**
     * @inheritDoc
     */
    get fields()
    {
        const fields = super.fields;
        fields.data = {};
        fields.site = false;
        return fields;
    }

    /**
     * @inheritDoc
     */
    shouldDehydrate(item)
    {
        if (item instanceof Site)
        {
            return false;
        }
        return true;
    }

    /**
     * @inheritDoc
     */
    initialize()
    {
        super.initialize();
        this._site = false;
        this._data = {};
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'model.data/Data';
    }

    /**
     * @inheritDoc
     */
    get uniqueId()
    {
        return (this.site)
            ? this.site.name
            : '__default__';
    }

    /**
     * @let {model.site.Site}
     */
    get site()
    {
        return this._site;
    }

    set site(value)
    {
        this._site = value;
    }

    /**
     * @let {String}
     */
    get data()
    {
        return this._data;
    }

    set data(value)
    {
        this._data = value;
    }

    /**
     * @param {*} values
     * @returns {void}
     */
    dehydrate(values)
    {
        super.dehydrate(values);
        this._site = values.site || false;
    }

    /**
     * @inheritDoc
     */
    toString()
    {
        return `[${this.className} ${this.site}]`;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.Data = Data;
<commit_msg>fix(model.data.Data): add check if values is defined<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const ValueObject = require('../ValueObject.js').ValueObject;
const Site = require('../site/Site.js').Site;

/**
 * Describes a simple site specific data store
 *
 * @memberOf model.data
 */
class Data extends ValueObject
{
    /**
     * @constant {string}
     * @static
     */
    static get SITE()
    {
        return 'site';
    }

    /**
     * @constant {array}
     * @static
     */
    static get ANY()
    {
        return ['site'];
    }

    /**
     * @inheritDoc
     */
    get fields()
    {
        const fields = super.fields;
        fields.data = {};
        fields.site = false;
        return fields;
    }

    /**
     * @inheritDoc
     */
    shouldDehydrate(item)
    {
        if (item instanceof Site)
        {
            return false;
        }
        return true;
    }

    /**
     * @inheritDoc
     */
    initialize()
    {
        super.initialize();
        this._site = false;
        this._data = {};
    }

    /**
     * @inheritDoc
     */
    static get className()
    {
        return 'model.data/Data';
    }

    /**
     * @inheritDoc
     */
    get uniqueId()
    {
        return (this.site)
            ? this.site.name
            : '__default__';
    }

    /**
     * @let {model.site.Site}
     */
    get site()
    {
        return this._site;
    }

    set site(value)
    {
        this._site = value;
    }

    /**
     * @let {String}
     */
    get data()
    {
        return this._data;
    }

    set data(value)
    {
        this._data = value;
    }

    /**
     * @param {*} values
     * @returns {void}
     */
    dehydrate(values)
    {
        super.dehydrate(values);
        this._site = values
            ? values.site || false
            : false;
    }

    /**
     * @inheritDoc
     */
    toString()
    {
        return `[${this.className} ${this.site}]`;
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.Data = Data;
<|endoftext|>


<commit_before>var React = require('react');
var LocationStore = require('../../../stores/LocationStore');

var Locations = React.createClass({
  getInitialState() {
    return LocationStore.getState();
  },

  componentDidMount() {
    LocationStore.listen(this.onChange);
  },

  componentWillUnmount() {
    LocationStore.unlisten(this.onChange);
  },

  onChange(state) {
    this.setState(state);
  },

  render() {
    return (

        {this.state.locations.map((location) => {
          return (

{location.name}

          );
        })}

    );
  }
});

module.exports = Locations;
<commit_msg>Update locations.js<commit_after>var React = require('react');
var AltContainer = require('../libraries/alt/AltContainer');
var LocationStore = require('../stores/LocationStore');
var FavoritesStore = require('../stores/FavoritesStore');
var LocationActions = require('../actions/LocationActions');

var Favorites = React.createClass({
  render() {
    return (

        {this.props.locations.map((location, i) => {
          return (

{location.name}

          );
        })}

    );
  }
});

var AllLocations = React.createClass({
  addFave(ev) {
    var location = LocationStore.getLocation(
      Number(ev.target.getAttribute('data-id'))
    );
    LocationActions.favoriteLocation(location);
  },

  render() {
    if (this.props.errorMessage) {
      return (

{this.props.errorMessage}

      );
    }

    if (LocationStore.isLoading()) {
      return (

      )
    }

    return (

        {this.props.locations.map((location, i) => {
          var faveButton = (
            <button onClick={this.addFave} data-id={location.id}>
              Favorite
            </button>
          );

          return (

              {location.name} {location.has_favorite ? '<3' : faveButton}

          );
        })}

    );
  }
});

var Locations = React.createClass({
  componentDidMount() {
    LocationStore.fetchLocations();
  },

  render() {
    return (

Locations

        <AltContainer store={LocationStore}>
          <AllLocations />
        </AltContainer>

Favorites

        <AltContainer store={FavoritesStore}>
          <Favorites />
        </AltContainer>

    );
  }
});

module.exports = Locations;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Icon from '../components/Icon'

import 'whatwg-fetch'

const defaultState = {
  form: {
    name: '',
    email: '',
    subject: '',
    question: '',
    errors: {}
  }
}

export default class ContactForm extends Component {

  constructor (props) {
    super(props)

    this.state = { ...defaultState }
  }

  handleChange = (event) => {
    this.setState({
      form: {
        ...this.state.form,
        [event.target.name]: event.target.value
      }
    })
  }

  handleSubmit = (event) => {
    event.preventDefault()

    const formData = new FormData()

    formData.append("form-data", "contact")
    formData.append("name", this.state.form.name)
    formData.append("email", this.state.form.email)
    formData.append("subject", this.state.form.subject)
    formData.append("question", this.state.form.question)

    fetch('/contact', {
      method: 'POST',
      body: formData
    }, (res) => {
      console.log(res);
    })
  }

  render() {
    return (
      <form ref="contactForm" name="contact" action="contact" data-netlify>

              From

                  <input className="input" name="name" type="text" placeholder="Name" value={this.state.form.name} onChange={this.handleChange} />
                  <Icon name="user" className="is-small is-left" />

                  <input className="input" type="email" placeholder="Email" name="email" value={this.state.form.email} onChange={this.handleChange} />
                  <Icon name="envelope" className="is-small is-left" />

              Subject

                  <input className="input" type="text" placeholder="e.g. Renovation Inquiry" name="subject" value={this.state.form.subject} onChange={this.handleChange} />

              Question

                  <textarea className="textarea" placeholder="Explain how we can help you" name="question" value={this.state.form.question} onChange={this.handleChange} ></textarea>

                  <button type="submit" className="button is-primary" onClick={this.handleSubmit}>
                    Contact Us
                  </button>

          <input type="hidden" name="contact" />
      </form>
    );
  }
}<commit_msg>Bug with form<commit_after>import React, { Component } from 'react'
import Icon from '../components/Icon'

import 'whatwg-fetch'

const defaultState = {
  form: {
    name: '',
    email: '',
    subject: '',
    question: '',
    errors: {}
  }
}

export default class ContactForm extends Component {

  constructor (props) {
    super(props)

    this.state = { ...defaultState }
  }

  handleChange = (event) => {
    this.setState({
      form: {
        ...this.state.form,
        [event.target.name]: event.target.value
      }
    })
  }

  handleSubmit = (event) => {
    event.preventDefault()

    const formData = new FormData()

    formData.append("form-name", "contact")
    formData.append("name", this.state.form.name)
    formData.append("email", this.state.form.email)
    formData.append("subject", this.state.form.subject)
    formData.append("question", this.state.form.question)

    fetch('/contact', {
      method: 'POST',
      body: formData
    }, (res) => {
      console.log(res);
    })
  }

  render() {
    return (
      <form ref="contactForm" name="contact" action="contact" data-netlify>

              From

                  <input className="input" name="name" type="text" placeholder="Name" value={this.state.form.name} onChange={this.handleChange} />
                  <Icon name="user" className="is-small is-left" />

                  <input className="input" type="email" placeholder="Email" name="email" value={this.state.form.email} onChange={this.handleChange} />
                  <Icon name="envelope" className="is-small is-left" />

              Subject

                  <input className="input" type="text" placeholder="e.g. Renovation Inquiry" name="subject" value={this.state.form.subject} onChange={this.handleChange} />

              Question

                  <textarea className="textarea" placeholder="Explain how we can help you" name="question" value={this.state.form.question} onChange={this.handleChange} ></textarea>

                  <button type="submit" className="button is-primary" onClick={this.handleSubmit}>
                    Contact Us
                  </button>

          <input type="hidden" name="contact" />
      </form>
    );
  }
}<|endoftext|>


<commit_before>
if ("undefined" == typeof(GanymedeOrg)) {

  var GanymedeOrg = {};

  var file = null;
  var oStream = null;
};

GanymedeOrg.BrowserOverlay = {

  startRecording : function(anEvent) {

    if (file == null) {

      file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("TmpD", Components.interfaces.nsIFile);
      file.append("test.txt");

      oStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
      oStream.init(file, 0x04 | 0x08 | 0x10, 0644, 0);

      var msg = "\nStart of recoding: " + Date() + " *******\n\n";

      oStream.write(msg, msg.length);

      gBrowser.addEventListener("load", this.findClassLabels, true);

      window.alert("starting...");

    } else {
      window.alert("already started.");
    }
  },

  stopRecording : function(anEvent) {

    var msg = "\nStopped recoding: " + Date() + " *******\n\n";

    oStream.write(msg, msg.length);

    oStream.close();

    oStream = null;

    file = null;

    gBrowser.removeEventListener("load", this.findClassLabels, true);

    window.alert("stopping...");
  },

  logg : function(str) {
    oStream.write(str, str.legnth);
  },

  findClassLabels : function(anEvent) {

    var doc = window.document;

    // Make sure the doc is not in a frame, is top doc.
    //     Not sure if this is necessary, and it did not make any difference.
    //
    /*
    if (doc instanceof HTMLDocument) {
      if (doc.defaultView.frameElement) {
        while (doc.defaultView.frameElement) {
          doc = doc.defaultView.frameElement.ownerDocument;
        }
      }
    }
    */

    var text = "// At " + Date() + ", Page = " + doc.title + "\n";

    oStream.write(text, text.length);

    var tags = doc.getElementsByTagName("*");

    for (var idx = 0; idx < tags.length; idx++) {

        var tag = tags[idx];

        var str = "tag: '" + tag.tagName + "' -> class: '" + tag.className + "'\n";

        oStream.write(str, str.length);
    }

    oStream.write("\nDONE\n\n", 7);
  }
};
<commit_msg>O M G. Finally works. Much thanks to http://stackoverflow.com/users/1828637/noitidart<commit_after>
if ("undefined" == typeof(GanymedeOrg)) {

  var GanymedeOrg = {};

  var file = null;
  var oStream = null;
};

GanymedeOrg.BrowserOverlay = {

  startRecording : function(anEvent) {

    if (file == null) {

      file = Components.classes["@mozilla.org/file/directory_service;1"].
                 getService(Components.interfaces.nsIProperties).
                 get("TmpD", Components.interfaces.nsIFile);
      file.append("test.txt");

      oStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
                 createInstance(Components.interfaces.nsIFileOutputStream);
      oStream.init(file, 0x04 | 0x08 | 0x10, 0644, 0);

      var msg = "\nStart of recoding: " + Date() + " *******\n\n";

      oStream.write(msg, msg.length);

      gBrowser.addEventListener("load", this.findClassLabels, true);

      window.alert("starting...");

    } else {
      window.alert("already started.");
    }
  },

  stopRecording : function(anEvent) {

    var msg = "\nStopped recoding: " + Date() + " *******\n\n";

    oStream.write(msg, msg.length);

    oStream.close();

    oStream = null;

    file = null;

    gBrowser.removeEventListener("load", this.findClassLabels, true);

    window.alert("stopping...");
  },

  logg : function(str) {
    oStream.write(str, str.legnth);
  },

  findClassLabels : function(anEvent) {

    var doc = window.gBrowser.contentWindow.document;

    // Make sure the doc is not in a frame, is top doc.
    //     Not sure if this is necessary, and it did not make any difference.
    //
    /*
    if (doc instanceof HTMLDocument) {
      if (doc.defaultView.frameElement) {
        while (doc.defaultView.frameElement) {
          doc = doc.defaultView.frameElement.ownerDocument;
        }
      }
    }
    */

    var text = "// At " + Date() + ", Page = " + doc.title + "\n";

    oStream.write(text, text.length);

    var tags = doc.getElementsByTagName("*");

    for (var idx = 0; idx < tags.length; idx++) {

        var tag = tags[idx];

        var str = "tag: '" + tag.tagName + "' -> class: '" + tag.className + "'\n";

        oStream.write(str, str.length);
    }

    oStream.write("\nDONE\n\n", 7);
  }
};
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import {Card} from '../components/card'
import {Button} from '../components/button'
import {Markdown} from '../components/markdown'
import {openUrl} from '../components/open-url'
import {sendEmail} from '../components/send-email'
import {callPhone} from '../components/call-phone'
import type {
	ToolOptions,
	CallPhoneButtonParams,
	SendEmailButtonParams,
	OpenUrlButtonParams,
} from './types'

function handleCallPhone(params: CallPhoneButtonParams) {
	callPhone(params.number)
}

function handleSendEmail(params: SendEmailButtonParams) {
	let {to, cc = [], bcc = [], subject, body} = params
	to = Array.isArray(to) ? to : [to]
	cc = Array.isArray(cc) ? cc : [cc]
	bcc = Array.isArray(bcc) ? bcc : [bcc]
	sendEmail({to, cc, bcc, subject, body})
}

function handleOpenUrl(params: OpenUrlButtonParams) {
	return openUrl(params.url)
}

function handleButtonPress(btn) {
	switch (btn.action) {
		case 'open-url':
			return handleOpenUrl(btn.params)
		case 'send-email':
			return handleSendEmail(btn.params)
		case 'call-phone':
			return handleCallPhone(btn.params)
		case 'custom':
			return
		default:
			;(btn.action: empty)
	}
}

type Props = {
	config: ToolOptions,
}

export class ToolView extends React.Component<Props> {
	render() {
		const toolEnabled = this.props.config.enabled

		return (
			<Card
				footer={
					!toolEnabled
						? this.props.config.message || 'This tool is disabled.'
						: false
				}
				header={this.props.config.title}
				style={styles.card}
			>
				<Markdown source={this.props.config.body} />

				{this.props.config.buttons.map(btn => {
					const {title, enabled = true} = btn
					return (
						<Button
							key={title}
							disabled={!toolEnabled || !enabled}
							onPress={() => handleButtonPress(btn)}
							title={title}
						/>
					)
				})}
			</Card>
		)
	}
}

export const styles = StyleSheet.create({
	card: {
		paddingHorizontal: 20,
		paddingVertical: 15,
		marginHorizontal: 0,
		marginBottom: 10,
	},
})
<commit_msg>Add margin back to help cards<commit_after>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import {Card} from '../components/card'
import {Button} from '../components/button'
import {Markdown} from '../components/markdown'
import {openUrl} from '../components/open-url'
import {sendEmail} from '../components/send-email'
import {callPhone} from '../components/call-phone'
import type {
	ToolOptions,
	CallPhoneButtonParams,
	SendEmailButtonParams,
	OpenUrlButtonParams,
} from './types'

function handleCallPhone(params: CallPhoneButtonParams) {
	callPhone(params.number)
}

function handleSendEmail(params: SendEmailButtonParams) {
	let {to, cc = [], bcc = [], subject, body} = params
	to = Array.isArray(to) ? to : [to]
	cc = Array.isArray(cc) ? cc : [cc]
	bcc = Array.isArray(bcc) ? bcc : [bcc]
	sendEmail({to, cc, bcc, subject, body})
}

function handleOpenUrl(params: OpenUrlButtonParams) {
	return openUrl(params.url)
}

function handleButtonPress(btn) {
	switch (btn.action) {
		case 'open-url':
			return handleOpenUrl(btn.params)
		case 'send-email':
			return handleSendEmail(btn.params)
		case 'call-phone':
			return handleCallPhone(btn.params)
		case 'custom':
			return
		default:
			;(btn.action: empty)
	}
}

type Props = {
	config: ToolOptions,
}

export class ToolView extends React.Component<Props> {
	render() {
		const toolEnabled = this.props.config.enabled

		return (
			<Card
				footer={
					!toolEnabled
						? this.props.config.message || 'This tool is disabled.'
						: false
				}
				header={this.props.config.title}
				style={styles.card}
			>
				<Markdown source={this.props.config.body} />

				{this.props.config.buttons.map(btn => {
					const {title, enabled = true} = btn
					return (
						<Button
							key={title}
							disabled={!toolEnabled || !enabled}
							onPress={() => handleButtonPress(btn)}
							title={title}
						/>
					)
				})}
			</Card>
		)
	}
}

export const styles = StyleSheet.create({
	card: {
		paddingHorizontal: 20,
		paddingVertical: 15,
		marginHorizontal: 10,
		marginBottom: 10,
	},
})
<|endoftext|>


<commit_before>/*jshint node:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, trailing:true, white:true */
/*global XT:true, XV:true, enyo:true, _:true, Globalize:true */

(function () {

  enyo.kind({
    name: "XV.Date",
    kind: "XV.Input",

    /**
      Sets the value programatically.

      @param value Can be Date or String, but if it's a string that doesn't
        look like a date then it will be set to null.
      @param {Object} options
     */
    setValue: function (value, options) {
      if (value) {
        value = new Date(value.valueOf()); // clone. Also converts string to date.
        if (isNaN(value.getTime())) {
          value = null;
        }
      } else {
        value = null;
      }
      XV.Input.prototype.setValue.call(this, value, options);
    },
    textToDate: function (value) {
      var date = null,
        daysInMilliseconds = 1000 * 60 * 60 * 24;

      // Try to parse out a date given the various allowable shortcuts
      if (value === '0' ||
        value.indexOf('+') === 0 ||
        value.indexOf('-') === 0) {
        // 0 means today, +1 means tomorrow, -2 means 2 days ago, etc.
        date = new Date(new Date().getTime() + value * daysInMilliseconds);
      } else if (value.indexOf('#') === 0) {
        // #40 means the fortieth day of this year, so set the month to 0
        // and set the date accordingly. JS appropriately pushes the date
        // into subsequent months as necessary
        date = new Date();
        date.setMonth(0);
        date.setDate(value.substring(1));
      } else if (value.length && !isNaN(value)) {
        // A positive integer by itself means that day of this month
        date = new Date();
        date.setDate(value);
      } else if (value) {
        // Dates in the format of dates as we're used to them.
        // we're counting on JS to parse the date correctly
        date = new Date(value);
      }

      // Validate
      if (date) {
        if (isNaN(date.getTime())) {
          date = false;
        } else {
          date.setHours(0, 0, 0, 0);
        }
      }
      return date;
    },
    validate: function (value) {
      value = this.textToDate(value);
      return (_.isDate(value) || _.isEmpty(value)) ? value : false;
    },
    valueChanged: function (value) {
      if (value) {
        value = new Date(value.valueOf());
        value.setMinutes(value.getTimezoneOffset());
        value = Globalize.format(value, "d");
      } else {
        value = "";
      }
      return XV.Input.prototype.valueChanged.call(this, value);
    }
  });

  enyo.kind({
    name: "XV.DateWidget",
    kind: "XV.Date",
    classes: "xv-inputwidget xv-datewidget",
    published: {
      label: "",
      showLabel: true
    },
    components: [
      {kind: "FittableColumns", components: [
        {name: "label", content: "", classes: "xv-decorated-label"},
        {kind: "onyx.InputDecorator", name: "decorator",
          classes: "xv-input-decorator", components: [
          {name: "input", kind: "onyx.Input", onchange: "inputChanged",
            classes: "xv-subinput"},
          {name: "icon", kind: "onyx.IconButton", ontap: "iconTapped", name: "iconButton",
            src: "assets/date-icon.png"},
          {name: "datePickPopup", kind: "onyx.Popup", modal: true, floating: true, components: [
            {kind: "GTS.DatePicker", name: "datePick", style: "", onChange: "datePicked"}
          ]}
        ]}
      ]}
    ],
    create: function () {
      this.inherited(arguments);
      this.labelChanged();
      this.showLabelChanged();
    },
    datePicked: function (inSender, inEvent) {
      this.setValue(inEvent);
      this.$.datePickPopup.hide();
    },
    getAbsoluteBounds: function (control) {
        var element = control.hasNode();
        var coord = {left: 0, top: 0, width: element.offsetWidth, height: element.offsetHeight};
        do {
                coord.left += element.offsetLeft;
                coord.top  += element.offsetTop;
        } while ( element = element.offsetParent );
        return coord;
    },
    iconTapped: function (inSender, inEvent) {
      var element = inSender,
        coord = {left: 0, top: 0, width: element.getBounds().width, height: element.getBounds().height};

      this.$.datePickPopup.show();
      /*
      do {
        console.log(element.name + " bounds are " + element.getBounds().top + ", " + element.getBounds().left);
        coord.left += element.getBounds && element.getBounds().left ? element.getBounds().left : 0;
        coord.top  += element.getBounds && element.getBounds().top ? element.getBounds().top : 0;
        this.$.datePickPopup.setBounds({ top: coord.top, left: (coord.left + coord.width) });
      } while ((element = element.parent));
      */
      var bounds = this.getAbsoluteBounds(inSender);
      this.$.datePickPopup.setBounds({ top: bounds.top, left: bounds.left + bounds.width});
    },
    labelChanged: function () {
      var label = (this.getLabel() || ("_" + this.attr || "").loc()) + ":";
      this.$.label.setContent(label);
    },
    showLabelChanged: function () {
      if (this.getShowLabel()) {
        this.$.label.show();
      } else {
        this.$.label.hide();
      }
    },
    valueChanged: function (value) {
      var dateValue = value;
      value = XV.Date.prototype.valueChanged.call(this, value);
      this.$.datePick.setValue(value ? dateValue : new Date());
      this.$.datePick.render();
    }
  });

}());
<commit_msg>datepicker popup actually looks good<commit_after>/*jshint node:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, trailing:true, white:true */
/*global XT:true, XV:true, enyo:true, _:true, Globalize:true */

(function () {

  enyo.kind({
    name: "XV.Date",
    kind: "XV.Input",

    /**
      Sets the value programatically.

      @param value Can be Date or String, but if it's a string that doesn't
        look like a date then it will be set to null.
      @param {Object} options
     */
    setValue: function (value, options) {
      if (value) {
        value = new Date(value.valueOf()); // clone. Also converts string to date.
        if (isNaN(value.getTime())) {
          value = null;
        }
      } else {
        value = null;
      }
      XV.Input.prototype.setValue.call(this, value, options);
    },
    textToDate: function (value) {
      var date = null,
        daysInMilliseconds = 1000 * 60 * 60 * 24;

      // Try to parse out a date given the various allowable shortcuts
      if (value === '0' ||
        value.indexOf('+') === 0 ||
        value.indexOf('-') === 0) {
        // 0 means today, +1 means tomorrow, -2 means 2 days ago, etc.
        date = new Date(new Date().getTime() + value * daysInMilliseconds);
      } else if (value.indexOf('#') === 0) {
        // #40 means the fortieth day of this year, so set the month to 0
        // and set the date accordingly. JS appropriately pushes the date
        // into subsequent months as necessary
        date = new Date();
        date.setMonth(0);
        date.setDate(value.substring(1));
      } else if (value.length && !isNaN(value)) {
        // A positive integer by itself means that day of this month
        date = new Date();
        date.setDate(value);
      } else if (value) {
        // Dates in the format of dates as we're used to them.
        // we're counting on JS to parse the date correctly
        date = new Date(value);
      }

      // Validate
      if (date) {
        if (isNaN(date.getTime())) {
          date = false;
        } else {
          date.setHours(0, 0, 0, 0);
        }
      }
      return date;
    },
    validate: function (value) {
      value = this.textToDate(value);
      return (_.isDate(value) || _.isEmpty(value)) ? value : false;
    },
    valueChanged: function (value) {
      if (value) {
        value = new Date(value.valueOf());
        value.setMinutes(value.getTimezoneOffset());
        value = Globalize.format(value, "d");
      } else {
        value = "";
      }
      return XV.Input.prototype.valueChanged.call(this, value);
    }
  });

  enyo.kind({
    name: "XV.DateWidget",
    kind: "XV.Date",
    classes: "xv-inputwidget xv-datewidget",
    published: {
      label: "",
      showLabel: true
    },
    components: [
      {kind: "FittableColumns", components: [
        {name: "label", content: "", classes: "xv-decorated-label"},
        {kind: "onyx.InputDecorator", name: "decorator",
          classes: "xv-input-decorator", components: [
          {name: "input", kind: "onyx.Input", onchange: "inputChanged",
            classes: "xv-subinput"},
          {kind: "onyx.MenuDecorator", components: [
            {name: "icon", kind: "onyx.IconButton", ontap: "iconTapped",
              src: "assets/date-icon.png"},
            {name: "datePickPopup", kind: "onyx.Menu", maxHeight: 400, modal: true, floating: true,
                style: "min-width:400px;",
                components: [
              {kind: "GTS.DatePicker", name: "datePick", onChange: "datePicked"}
            ]}
          ]}
        ]}
      ]}
    ],
    create: function () {
      this.inherited(arguments);
      this.labelChanged();
      this.showLabelChanged();
    },
    datePicked: function (inSender, inEvent) {
      this.setValue(inEvent);
      this.$.datePickPopup.hide();
    },
    iconTapped: function (inSender, inEvent) {
      this.$.datePick.render();
    },
    labelChanged: function () {
      var label = (this.getLabel() || ("_" + this.attr || "").loc()) + ":";
      this.$.label.setContent(label);
    },
    showLabelChanged: function () {
      if (this.getShowLabel()) {
        this.$.label.show();
      } else {
        this.$.label.hide();
      }
    },
    valueChanged: function (value) {
      var dateValue = value;
      value = XV.Date.prototype.valueChanged.call(this, value);
      this.$.datePick.setValue(value ? dateValue : new Date());
      this.$.datePick.render();
    }
  });

}());
<|endoftext|>


<commit_before>define( [
    'osg/Camera',
    'osg/Node',
    'osg/FrameStamp',
    'osg/Material',
    'osg/Depth',
    'osg/BlendFunc',
    'osg/CullFace',
    'osg/Viewport',
    'osg/Matrix',
    'osg/Light',
    'osg/WebGLCaps',
    'osg/Texture',
    'osgUtil/IntersectionVisitor',
    'osgUtil/LineSegmentIntersector'
], function ( Camera, Node, FrameStamp, Material, Depth, BlendFunc, CullFace, Viewport, Matrix, Light, WebGLCaps, Texture, IntersectionVisitor, LineSegmentIntersector ) {

    'use strict';

    var View = function () {
        this._graphicContext = undefined;
        this._camera = new Camera();
        this._scene = new Node();
        this._sceneData = undefined;
        this._frameStamp = new FrameStamp();
        this._lightingMode = undefined;
        this._manipulator = undefined;
        this._webGLCaps = undefined;

        this.setLightingMode( View.LightingMode.HEADLIGHT );

        this._scene.getOrCreateStateSet().setAttributeAndMode( new Material() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new Depth() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new BlendFunc() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new CullFace() );
    };

    View.LightingMode = {
        NO_LIGHT: 0,
        HEADLIGHT: 1,
        SKY_LIGHT: 2
    };

    View.prototype = {
        setGraphicContext: function ( gc ) {
            this._graphicContext = gc;
        },
        getGraphicContext: function () {
            return this._graphicContext;
        },
        getWebGLCaps: function () {
            return this._webGLCaps;
        },
        initWebGLCaps: function ( gl ) {
            this._webGLCaps = new WebGLCaps( gl );
            this._webGLCaps.init();
        },

        computeCanvasSize: ( function () {
            return function ( canvas ) {
                var canvasWidth = 0;
                var canvasHeight = 0;
                var clientWidth, clientHeight;
                clientWidth = canvas.clientWidth;
                clientHeight = canvas.clientHeight;

                if ( clientWidth < 1 ) clientWidth = 1;
                if ( clientHeight < 1 ) clientHeight = 1;

                var devicePixelRatio = 1;
                if ( this._options.getBoolean( 'useDevicePixelRatio' ) ) {
                    devicePixelRatio = window.devicePixelRatio || 1;
                }

                var widthPixel = clientWidth * devicePixelRatio;
                var heightPixel = clientHeight * devicePixelRatio;

                if ( canvasWidth !== widthPixel ) {
                    canvas.width = widthPixel;
                    canvasWidth = widthPixel;
                }

                if ( canvasHeight !== heightPixel ) {
                    canvas.height = heightPixel;
                    canvasHeight = heightPixel;
                }

            };
        } )(),

        setUpView: function ( canvas ) {
            this.computeCanvasSize( canvas );

            var ratio = canvas.clientWidth / canvas.clientHeight;

            var width = canvas.width;
            var height = canvas.height;

            this._camera.setViewport( new Viewport( 0, 0, width, height ) );

            this._camera.setGraphicContext( this._graphicContext );
            Matrix.makeLookAt( [ 0, 0, -10 ], [ 0, 0, 0 ], [ 0, 1, 0 ], this._camera.getViewMatrix() );
            Matrix.makePerspective( 55, ratio, 1.0, 1000.0, this._camera.getProjectionMatrix() );
        },

        /**
         * X = 0 at the left
         * Y = 0 at the BOTTOM
         */
        computeIntersections: function ( x, y, traversalMask ) {
            /*jshint bitwise: false */
            if ( traversalMask === undefined ) {
                traversalMask = ~0;
            }
            /*jshint bitwise: true */
            var lsi = new LineSegmentIntersector();
            lsi.set( [ x, y, 0.0 ], [ x, y, 1.0 ] );
            var iv = new IntersectionVisitor();
            iv.setTraversalMask( traversalMask );
            iv.setIntersector( lsi );
            this._camera.accept( iv );
            return lsi.getIntersections();
        },

        setFrameStamp: function ( frameStamp ) {
            this._frameStamp = frameStamp;
        },
        getFrameStamp: function () {
            return this._frameStamp;
        },
        setCamera: function ( camera ) {
            this._camera = camera;
        },
        getCamera: function () {
            return this._camera;
        },

        setSceneData: function ( node ) {
            this._scene.removeChildren();
            this._scene.addChild( node );
            this._sceneData = node;
            this._camera.addChild( this._sceneData );
        },
        getSceneData: function () {
            return this._sceneData;
        },
        getScene: function () {
            return this._scene;
        },

        getManipulator: function () {
            return this._manipulator;
        },
        setManipulator: function ( manipulator ) {
            this._manipulator = manipulator;
        },

        getLight: function () {
            return this._light;
        },
        setLight: function ( light ) {
            this._light = light;
            if ( this._lightingMode !== View.LightingMode.NO_LIGHT ) {
                this._scene.getOrCreateStateSet().setAttributeAndMode( this._light );
            }
        },
        getLightingMode: function () {
            return this._lightingMode;
        },
        setLightingMode: function ( lightingMode ) {
            if ( this._lightingMode !== lightingMode ) {
                this._lightingMode = lightingMode;
                if ( this._lightingMode !== View.LightingMode.NO_LIGHT ) {
                    if ( !this._light ) {
                        this._light = new Light();
                        //this._light.setColor( [ 0.8, 0.8, 0.8, 1.0 ] );
                    }
                } else {
                    this._light = undefined;
                }
            }
        },
        flushDeletedGLObjects: function ( /*currentTime,*/ availableTime )
        {
            // Flush all deleted OpenGL objects within the specified availableTime
            Texture.textureManager.flushDeletedTextureObjects( this.getGraphicContext(), availableTime );
            // More GL Objects....
        }

    };

    return View;
} );
<commit_msg>Added canvasWith and canvasHeight as View member variables<commit_after>define( [
    'osg/Camera',
    'osg/Node',
    'osg/FrameStamp',
    'osg/Material',
    'osg/Depth',
    'osg/BlendFunc',
    'osg/CullFace',
    'osg/Viewport',
    'osg/Matrix',
    'osg/Light',
    'osg/WebGLCaps',
    'osg/Texture',
    'osgUtil/IntersectionVisitor',
    'osgUtil/LineSegmentIntersector'
], function ( Camera, Node, FrameStamp, Material, Depth, BlendFunc, CullFace, Viewport, Matrix, Light, WebGLCaps, Texture, IntersectionVisitor, LineSegmentIntersector ) {

    'use strict';

    var View = function () {
        this._graphicContext = undefined;
        this._camera = new Camera();
        this._scene = new Node();
        this._sceneData = undefined;
        this._frameStamp = new FrameStamp();
        this._lightingMode = undefined;
        this._manipulator = undefined;
        this._webGLCaps = undefined;
        this._canvasWidth = 0;
        this._canvasHeight = 0;

        this.setLightingMode( View.LightingMode.HEADLIGHT );

        this._scene.getOrCreateStateSet().setAttributeAndMode( new Material() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new Depth() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new BlendFunc() );
        this._scene.getOrCreateStateSet().setAttributeAndMode( new CullFace() );
    };

    View.LightingMode = {
        NO_LIGHT: 0,
        HEADLIGHT: 1,
        SKY_LIGHT: 2
    };

    View.prototype = {
        setGraphicContext: function ( gc ) {
            this._graphicContext = gc;
        },
        getGraphicContext: function () {
            return this._graphicContext;
        },
        getWebGLCaps: function () {
            return this._webGLCaps;
        },
        initWebGLCaps: function ( gl ) {
            this._webGLCaps = new WebGLCaps( gl );
            this._webGLCaps.init();
        },

        computeCanvasSize: ( function () {
            return function ( canvas ) {

                var clientWidth, clientHeight;
                clientWidth = canvas.clientWidth;
                clientHeight = canvas.clientHeight;

                if ( clientWidth < 1 ) clientWidth = 1;
                if ( clientHeight < 1 ) clientHeight = 1;

                var devicePixelRatio = 1;
                if ( this._options.getBoolean( 'useDevicePixelRatio' ) ) {
                    devicePixelRatio = window.devicePixelRatio || 1;
                }

                var widthPixel = clientWidth * devicePixelRatio;
                var heightPixel = clientHeight * devicePixelRatio;

                if ( this._canvasWidth !== widthPixel ) {
                    canvas.width = widthPixel;
                    this._canvasWidth = widthPixel;
                }

                if ( this._canvasHeight !== heightPixel ) {
                    canvas.height = heightPixel;
                    this._canvasHeight = heightPixel;
                }

            };
        } )(),

        setUpView: function ( canvas ) {
            this.computeCanvasSize( canvas );

            var ratio = canvas.clientWidth / canvas.clientHeight;

            var width = canvas.width;
            var height = canvas.height;

            this._camera.setViewport( new Viewport( 0, 0, width, height ) );

            this._camera.setGraphicContext( this._graphicContext );
            Matrix.makeLookAt( [ 0, 0, -10 ], [ 0, 0, 0 ], [ 0, 1, 0 ], this._camera.getViewMatrix() );
            Matrix.makePerspective( 55, ratio, 1.0, 1000.0, this._camera.getProjectionMatrix() );
        },

        /**
         * X = 0 at the left
         * Y = 0 at the BOTTOM
         */
        computeIntersections: function ( x, y, traversalMask ) {
            /*jshint bitwise: false */
            if ( traversalMask === undefined ) {
                traversalMask = ~0;
            }
            /*jshint bitwise: true */
            var lsi = new LineSegmentIntersector();
            lsi.set( [ x, y, 0.0 ], [ x, y, 1.0 ] );
            var iv = new IntersectionVisitor();
            iv.setTraversalMask( traversalMask );
            iv.setIntersector( lsi );
            this._camera.accept( iv );
            return lsi.getIntersections();
        },

        setFrameStamp: function ( frameStamp ) {
            this._frameStamp = frameStamp;
        },
        getFrameStamp: function () {
            return this._frameStamp;
        },
        setCamera: function ( camera ) {
            this._camera = camera;
        },
        getCamera: function () {
            return this._camera;
        },

        setSceneData: function ( node ) {
            this._scene.removeChildren();
            this._scene.addChild( node );
            this._sceneData = node;
            this._camera.addChild( this._sceneData );
        },
        getSceneData: function () {
            return this._sceneData;
        },
        getScene: function () {
            return this._scene;
        },

        getManipulator: function () {
            return this._manipulator;
        },
        setManipulator: function ( manipulator ) {
            this._manipulator = manipulator;
        },

        getLight: function () {
            return this._light;
        },
        setLight: function ( light ) {
            this._light = light;
            if ( this._lightingMode !== View.LightingMode.NO_LIGHT ) {
                this._scene.getOrCreateStateSet().setAttributeAndMode( this._light );
            }
        },
        getLightingMode: function () {
            return this._lightingMode;
        },
        setLightingMode: function ( lightingMode ) {
            if ( this._lightingMode !== lightingMode ) {
                this._lightingMode = lightingMode;
                if ( this._lightingMode !== View.LightingMode.NO_LIGHT ) {
                    if ( !this._light ) {
                        this._light = new Light();
                        //this._light.setColor( [ 0.8, 0.8, 0.8, 1.0 ] );
                    }
                } else {
                    this._light = undefined;
                }
            }
        },
        flushDeletedGLObjects: function ( /*currentTime,*/ availableTime )
        {
            // Flush all deleted OpenGL objects within the specified availableTime
            Texture.textureManager.flushDeletedTextureObjects( this.getGraphicContext(), availableTime );
            // More GL Objects....
        }

    };

    return View;
} );
<|endoftext|>