<commit_before>const {autoUpdater} = require('electron');
const ms = require('ms');

const notify = require('./notify'); // eslint-disable-line no-unused-vars
const {version} = require('./package');

// accepted values: `osx`, `win32`
// https://nuts.gitbook.com/update-windows.html
const platform = process.platform === 'darwin' ?
  'osx' :
  process.platform;
const FEED_URL = `https://hyper-updates.now.sh/update/${platform}`;
let isInit = false;

function init() {
  autoUpdater.on('error', (err, msg) => {
    console.error('Error fetching updates', msg + ' (' + err.stack + ')');
  });

  autoUpdater.setFeedURL(`${FEED_URL}/${version}`);

  setTimeout(() => {
    autoUpdater.checkForUpdates();
  }, ms('10s'));

  setInterval(() => {
    autoUpdater.checkForUpdates();
  }, ms('5m'));

  isInit = true;
}

module.exports = function (win) {
  if (!isInit) {
    init();
  }

  const {rpc} = win;

  const onupdate = (ev, releaseNotes, releaseName) => {
    rpc.emit('update available', {releaseNotes, releaseName});
  };

  autoUpdater.on('update-downloaded', onupdate);

  rpc.once('quit and install', () => {
    autoUpdater.quitAndInstall();
  });

  win.on('close', () => {
    autoUpdater.removeListener('update-downloaded', onupdate);
  });
};
<commit_msg>increase timeout for update checks (#928)<commit_after>const {autoUpdater} = require('electron');
const ms = require('ms');

const notify = require('./notify'); // eslint-disable-line no-unused-vars
const {version} = require('./package');

// accepted values: `osx`, `win32`
// https://nuts.gitbook.com/update-windows.html
const platform = process.platform === 'darwin' ?
  'osx' :
  process.platform;
const FEED_URL = `https://hyper-updates.now.sh/update/${platform}`;
let isInit = false;

function init() {
  autoUpdater.on('error', (err, msg) => {
    console.error('Error fetching updates', msg + ' (' + err.stack + ')');
  });

  autoUpdater.setFeedURL(`${FEED_URL}/${version}`);

  setTimeout(() => {
    autoUpdater.checkForUpdates();
  }, ms('10s'));

  setInterval(() => {
    autoUpdater.checkForUpdates();
  }, ms('30m'));

  isInit = true;
}

module.exports = function (win) {
  if (!isInit) {
    init();
  }

  const {rpc} = win;

  const onupdate = (ev, releaseNotes, releaseName) => {
    rpc.emit('update available', {releaseNotes, releaseName});
  };

  autoUpdater.on('update-downloaded', onupdate);

  rpc.once('quit and install', () => {
    autoUpdater.quitAndInstall();
  });

  win.on('close', () => {
    autoUpdater.removeListener('update-downloaded', onupdate);
  });
};
<|endoftext|>


<commit_before>(function ()
{
	var root = this;

 	// Configure Requirement
	require.config({
		paths: {
			'backbone': '../lib/backbone.min',
			'bootstrap': '../lib/bootstrap/js/bootstrap.min',
			'jquery': '../lib/jquery-1.9.1.min',
			'marionette': '../lib/backbone.marionette.min',
			//'marionette.formview': '../lib/backbone.marionette.formview.min',
			'marionette.formview': '../lib/backbone.marionette.formview',
			'underscore': '../lib/underscore.min'
		},
		shim: {
			'backbone': {
				deps: ['underscore', 'jquery', 'bootstrap'],
				exports: 'Backbone'
			},
			'bootstrap': {
				deps: ['jquery'],
				exports: "bootstrap"
			},
			'jquery': {
				exports: '$'
			},
			'marionette': {
				deps: ['backbone'],
				exports: 'Backbone.Marionette'
			},
			'marionette.formview': {
				deps: ['marionette']
			},
			'underscore': {
				exports: '_'
			},
		}
	});

	//these are defined externally so they can be used in our view templates:
	//define('jquery', [], function () { return root.jQuery; });
	define('moment', [], function ()
	{
		return root.moment;
	});

 	// Run the application
	require(['app'], function (App)
	{
		App.start({
			url: '/sample-app/'
		});
	});

})();
<commit_msg>remove unused lib<commit_after>(function ()
{
	var root = this;

 	// Configure Requirement
	require.config({
		paths: {
			'backbone': '../lib/backbone.min',
			'bootstrap': '../lib/bootstrap/js/bootstrap.min',
			'jquery': '../lib/jquery-1.9.1.min',
			'marionette': '../lib/backbone.marionette.min',
			'marionette.formview': '../lib/backbone.marionette.formview',
			'underscore': '../lib/underscore.min'
		},
		shim: {
			'backbone': {
				deps: ['underscore', 'jquery', 'bootstrap'],
				exports: 'Backbone'
			},
			'bootstrap': {
				deps: ['jquery'],
				exports: "bootstrap"
			},
			'jquery': {
				exports: '$'
			},
			'marionette': {
				deps: ['backbone'],
				exports: 'Backbone.Marionette'
			},
			'marionette.formview': {
				deps: ['marionette']
			},
			'underscore': {
				exports: '_'
			},
		}
	});

	//these are defined externally so they can be used in our view templates:
	//define('jquery', [], function () { return root.jQuery; });
	define('moment', [], function ()
	{
		return root.moment;
	});

 	// Run the application
	require(['app'], function (App)
	{
		App.start({
			url: '/sample-app/'
		});
	});

})();
<|endoftext|>


<commit_before>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

//Actions
import * as authActions from './../actions/authActions';
import * as searchActions from './../actions/searchActions';
import * as dinerActions from './../actions/dinerActions';
import * as pollActions from './../actions/pollActions';

//Components
import Navigation from './../components/Navigation';
import Menu from './../components/Menu';
import RestaurantList from './../components/RestaurantList';
import Poll from './../components/Poll';

class Profile extends React.Component {
  constructor(){
    super();
  }

  componentWillMount(){
    const { authenticateUser } = this.props.authActions;

    authenticateUser(localStorage.token);
  }

  render(){
    const { username } = this.props;

    let displayProfile = this.props.showPoll && this.props.isSubmitting ? (
        <Poll {...this.props} />
      ) : (

Welcome {username}!

          <Menu {...this.props} />
          <RestaurantList {...this.props} />

      );

    return(

        <Navigation {...this.props} />

          {displayProfile}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    username: state.authReducer.username,
    isLoggedIn: state.authReducer.isLoggedIn,
    isFetching: state.authReducer.isFetching,
    authErrorMsg: state.authReducer.authErrorMsg,
    showPoll: state.authReducer.showPoll,
    restaurants: state.searchReducer.businesses,
    searchErrorMsg: state.searchReducer.searchErrorMsg,
    isSubmitting: state.pollReducer.isSubmitting,
    selected: state.pollReducer.selected,
    unselected: state.pollReducer.unselected,
    pollErrorMessage: state.pollReducer.pollErrorMessage,
    data: state.pollReducer.data
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    authActions: bindActionCreators(authActions, dispatch),
    searchActions: bindActionCreators(searchActions, dispatch),
    dinerActions: bindActionCreators(dinerActions, dispatch),
    pollActions: bindActionCreators(pollActions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Profile);
<commit_msg>[refactor] removes search from profile<commit_after>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

//Actions
import * as authActions from './../actions/authActions';
import * as searchActions from './../actions/searchActions';
import * as dinerActions from './../actions/dinerActions';
import * as pollActions from './../actions/pollActions';

//Components
import Navigation from './../components/Navigation';
import Menu from './../components/Menu';
import Poll from './../components/Poll';

class Profile extends React.Component {
  constructor(){
    super();
  }

  componentWillMount(){
    const { authenticateUser } = this.props.authActions;

    authenticateUser(localStorage.token);
  }

  render(){
    const { username } = this.props;

    let displayProfile = this.props.showPoll && this.props.isSubmitting ? (
        <Poll {...this.props} />
      ) : (

Welcome {username}!

          <Menu {...this.props} />

      );

    return(

        <Navigation {...this.props} />

          {displayProfile}

    )
  }
}

const mapStateToProps = (state) => {
  return {
    username: state.authReducer.username,
    isLoggedIn: state.authReducer.isLoggedIn,
    isFetching: state.authReducer.isFetching,
    authErrorMsg: state.authReducer.authErrorMsg,
    showPoll: state.authReducer.showPoll,
    restaurants: state.searchReducer.businesses,
    searchErrorMsg: state.searchReducer.searchErrorMsg,
    isSubmitting: state.pollReducer.isSubmitting,
    selected: state.pollReducer.selected,
    unselected: state.pollReducer.unselected,
    pollErrorMessage: state.pollReducer.pollErrorMessage,
    data: state.pollReducer.data
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    authActions: bindActionCreators(authActions, dispatch),
    searchActions: bindActionCreators(searchActions, dispatch),
    dinerActions: bindActionCreators(dinerActions, dispatch),
    pollActions: bindActionCreators(pollActions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Profile);
<|endoftext|>


<commit_before>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

exports.PTP_OC_Undefined              =  0x1000
exports.PTP_OC_GetDeviceInfo          =  0x1001
exports.PTP_OC_OpenSession            =  0x1002
exports.PTP_OC_CloseSession           =  0x1003
exports.PTP_OC_GetStorageIDs          =  0x1004
exports.PTP_OC_GetStorageInfo         =  0x1005
exports.PTP_OC_GetNumObjects          =  0x1006
exports.PTP_OC_GetObjectHandles       =  0x1007
exports.PTP_OC_GetObjectInfo          =  0x1008
exports.PTP_OC_GetObject              =  0x1009
exports.PTP_OC_GetThumb               =  0x100A
exports.PTP_OC_DeleteObject           =  0x100B
exports.PTP_OC_SendObjectInfo         =  0x100C
exports.PTP_OC_SendObject             =  0x100D
exports.PTP_OC_InitiateCapture        =  0x100E
exports.PTP_OC_FormatStore            =  0x100F
exports.PTP_OC_ResetDevice            =  0x1010
exports.PTP_OC_SelfTest               =  0x1011
exports.PTP_OC_SetObjectProtection    =  0x1012
exports.PTP_OC_PowerDown              =  0x1013
exports.PTP_OC_GetDevicePropDesc      =  0x1014
exports.PTP_OC_GetDevicePropValue     =  0x1015
exports.PTP_OC_SetDevicePropValue     =  0x1016
exports.PTP_OC_ResetDevicePropValue   =  0x1017
exports.PTP_OC_TerminateOpenCapture   =  0x1018
exports.PTP_OC_MoveObject             =  0x1019
exports.PTP_OC_CopyObject             =  0x101A
exports.PTP_OC_GetPartialObject       =  0x101B
exports.PTP_OC_InitiateOpenCapture    =  0x101C

exports.uint16buf = function(uint16) {
	var buf = Buffer.alloc(2);
	buf.writeUInt16LE(uint16);
	return buf;
}

exports.init = function(cam, callback) {
	exports.transaction(cam, exports.PTP_OC_OpenSession, [0x00000001], null, function(err, responseCode, data) {
		console.log("session open", err, exports.hex(responseCode), data);
		exports.transaction(cam, exports.PTP_OC_GetDeviceInfo, [], null, function(err, responseCode, data) {
			console.log("init complete", err, exports.hex(responseCode), data);
			var di = exports.parseDeviceInfo(data);
			console.log("device info:", di);
			//console.log("entering olympus pc mode...");
			callback && callback(err, di);
			//exports.transaction(cam, 0x1016, [0xD052], exports.uint16buf(1), function(err, responseCode, data) {
			//	console.log("olympus pc mode", err, responseCode);
			//	exports.transaction(cam, 0x9481, [0x3], null, function(err, responseCode, data)  {
			//		exports.transaction(cam, 0x9481, [0x6], null, function(err, responseCode, data) {
			//		});
			//	});
			//});
		});
	});
}

exports.setPropU16 = function(cam, prop, value, callback) {
	exports.transaction(cam, exports.PTP_OC_SetDevicePropValue, [prop], exports.uint16buf(value), function(err, responseCode, data) {
		callback && callback(err || responseCode == 0x2001 ? null : responseCode);
	});
}

exports.getPropU16 = function(cam, prop, value, callback) {
	exports.transaction(cam, exports.PTP_OC_GetDevicePropValue, [prop], null, function(err, responseCode, data) {
		callback && callback(err || responseCode == 0x2001 ? null : responseCode, data && data.readUInt16LE && data.readUInt16LE(0));
	});
}

exports.hex = function(val) {
	if(val == null) return "null";
	return "0x" + val.toString(16);
}

exports.transaction = function(cam, opcode, params, data, callback) {
	if(!params) params = [];
	cam.transactionId++
	var length = 12 + 4 * params.length;
	var type = 1; // command
	var maxPacket = cam.ep.in.descriptor.wMaxPacketSize;

	// uint32 length (4) 0
	// uint16 type (2) 4
	// uint16 opcode (2) 6
	// uint32 transactionId (4) 8
	// uint32[4] params (optional) or data 12

	var buf = Buffer.alloc(length);

	buf.writeUInt32LE(length, 0);
	buf.writeUInt16LE(type, 4);
	buf.writeUInt16LE(opcode, 6);
	buf.writeUInt32LE(cam.transactionId, 8);
	for(var i = 0; i < params.length; i++) {
		buf.writeUInt32LE(params[i], 12 + i * 4);
	}

	var send = function(buf, cb) {
		cam.ep.out.transfer(buf, function(err)  {
			console.log("sent", buf);
			if(data) {
				buf.writeUInt32LE(12 + data.length, 0); // overwrite length
				buf.writeUInt16LE(2, 4); // update type to 2 (data)
				var dbuf = Buffer.concat([buf.slice(0, 12), data]);
				data = null;
				send(dbuf, cb);
			} else {
				cb && cb(err);
			}
		});
	}

	var packetSize = function(ep, bytes) {
		return Math.ceil(bytes / maxPacket) * maxPacket;
	}

	var parseResponse = function(buf) {
		if(buf && buf.length == 12) {
			return buf.readUInt16LE(6);
		} else {
			return null;
		}
	}

	var receive = function(cb, rbuf) {
		console.log("reading 12 bytes...");
		cam.ep.in.transfer(packetSize(cam.ep.in, 12), function(err, data) {
			if(!err && data) {
				var rlen = data.readUInt32LE(0);
				var rtype = data.readUInt16LE(4);
				if(rtype == 3) {
					cb && cb(err, parseResponse(data), rbuf);
				} else {
					console.log("data received:", rlen);
					if(rlen > 12) {
						console.log("requesting mode data:", rlen - 12);
						cam.ep.in.transfer(packetSize(cam.ep.in, rlen - 12), function(err, data2) {
							receive(cb, Buffer.concat([data, data2]));
						});
					} else {
						receive(cb, data);
					}
				}
			} else {
				console.log("error reading:", err);
				cb && cb(err);
			}
		});
	}

	send(buf, function(err) {
		receive(callback);
	});

}

exports.parseUnicodeString = function(buf, offset) {
	var end = offset;
	for(var i = offset; i < buf.length; i += 2) {
		if(buf.readUInt16LE(i) == 0) {
			end = i;
			break;
		}
	}
	return buf.toString('utf16le', offset, end);
}

exports.parseDeviceInfo = function(buf) {
	var di = {};
	var offset = 12 + 8;
	di.vendorExtDesc = exports.parseUnicodeString(buf, offset);
	offset += di.vendorExtDesc.length * 2;
	offset += 3;
	di.operationsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.operations = [];
	for(var i = 0; i < di.operationsCount; i++) {
		di.operations.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.eventsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.events = [];
	for(var i = 0; i < di.eventsCount; i++) {
		di.events.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.propertiesCount = buf.readUInt32LE(offset);
	offset += 4;
	di.properties = [];
	for(var i = 0; i < di.propertiesCount; i++) {
		di.properties.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.captureFormatsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.captureFormats = [];
	for(var i = 0; i < di.captureFormatsCount; i++) {
		di.captureFormats.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.imageFormatsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.imageFormats = [];
	for(var i = 0; i < di.imageFormatsCount; i++) {
		di.imageFormats.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	offset += 1;
	di.manufacturer = exports.parseUnicodeString(buf, offset);
	offset += di.manufacturer.length * 2;
	offset += 3;
	di.model = exports.parseUnicodeString(buf, offset);
	offset += di.model.length * 2;
	offset += 3;
	di.version = exports.parseUnicodeString(buf, offset);
	offset += di.version.length * 2;
	offset += 3;

	return di;
}
<commit_msg>usb testing<commit_after>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

exports.PTP_OC_Undefined              =  0x1000
exports.PTP_OC_GetDeviceInfo          =  0x1001
exports.PTP_OC_OpenSession            =  0x1002
exports.PTP_OC_CloseSession           =  0x1003
exports.PTP_OC_GetStorageIDs          =  0x1004
exports.PTP_OC_GetStorageInfo         =  0x1005
exports.PTP_OC_GetNumObjects          =  0x1006
exports.PTP_OC_GetObjectHandles       =  0x1007
exports.PTP_OC_GetObjectInfo          =  0x1008
exports.PTP_OC_GetObject              =  0x1009
exports.PTP_OC_GetThumb               =  0x100A
exports.PTP_OC_DeleteObject           =  0x100B
exports.PTP_OC_SendObjectInfo         =  0x100C
exports.PTP_OC_SendObject             =  0x100D
exports.PTP_OC_InitiateCapture        =  0x100E
exports.PTP_OC_FormatStore            =  0x100F
exports.PTP_OC_ResetDevice            =  0x1010
exports.PTP_OC_SelfTest               =  0x1011
exports.PTP_OC_SetObjectProtection    =  0x1012
exports.PTP_OC_PowerDown              =  0x1013
exports.PTP_OC_GetDevicePropDesc      =  0x1014
exports.PTP_OC_GetDevicePropValue     =  0x1015
exports.PTP_OC_SetDevicePropValue     =  0x1016
exports.PTP_OC_ResetDevicePropValue   =  0x1017
exports.PTP_OC_TerminateOpenCapture   =  0x1018
exports.PTP_OC_MoveObject             =  0x1019
exports.PTP_OC_CopyObject             =  0x101A
exports.PTP_OC_GetPartialObject       =  0x101B
exports.PTP_OC_InitiateOpenCapture    =  0x101C

exports.uint16buf = function(uint16) {
	var buf = new Buffer(2);
	buf.writeUInt16LE(uint16);
	return buf;
}

exports.init = function(cam, callback) {
	exports.transaction(cam, exports.PTP_OC_OpenSession, [0x00000001], null, function(err, responseCode, data) {
		console.log("session open", err, exports.hex(responseCode), data);
		exports.transaction(cam, exports.PTP_OC_GetDeviceInfo, [], null, function(err, responseCode, data) {
			console.log("init complete", err, exports.hex(responseCode), data);
			var di = exports.parseDeviceInfo(data);
			console.log("device info:", di);
			//console.log("entering olympus pc mode...");
			callback && callback(err, di);
			//exports.transaction(cam, 0x1016, [0xD052], exports.uint16buf(1), function(err, responseCode, data) {
			//	console.log("olympus pc mode", err, responseCode);
			//	exports.transaction(cam, 0x9481, [0x3], null, function(err, responseCode, data)  {
			//		exports.transaction(cam, 0x9481, [0x6], null, function(err, responseCode, data) {
			//		});
			//	});
			//});
		});
	});
}

exports.setPropU16 = function(cam, prop, value, callback) {
	exports.transaction(cam, exports.PTP_OC_SetDevicePropValue, [prop], exports.uint16buf(value), function(err, responseCode, data) {
		callback && callback(err || responseCode == 0x2001 ? null : responseCode);
	});
}

exports.getPropU16 = function(cam, prop, value, callback) {
	exports.transaction(cam, exports.PTP_OC_GetDevicePropValue, [prop], null, function(err, responseCode, data) {
		callback && callback(err || responseCode == 0x2001 ? null : responseCode, data && data.readUInt16LE && data.readUInt16LE(0));
	});
}

exports.hex = function(val) {
	if(val == null) return "null";
	return "0x" + val.toString(16);
}

exports.transaction = function(cam, opcode, params, data, callback) {
	if(!params) params = [];
	cam.transactionId++
	var length = 12 + 4 * params.length;
	var type = 1; // command
	var maxPacket = cam.ep.in.descriptor.wMaxPacketSize;

	// uint32 length (4) 0
	// uint16 type (2) 4
	// uint16 opcode (2) 6
	// uint32 transactionId (4) 8
	// uint32[4] params (optional) or data 12

	var buf = new Buffer(length);

	buf.writeUInt32LE(length, 0);
	buf.writeUInt16LE(type, 4);
	buf.writeUInt16LE(opcode, 6);
	buf.writeUInt32LE(cam.transactionId, 8);
	for(var i = 0; i < params.length; i++) {
		buf.writeUInt32LE(params[i], 12 + i * 4);
	}

	var send = function(buf, cb) {
		cam.ep.out.transfer(buf, function(err)  {
			console.log("sent", buf);
			if(data) {
				buf.writeUInt32LE(12 + data.length, 0); // overwrite length
				buf.writeUInt16LE(2, 4); // update type to 2 (data)
				var dbuf = Buffer.concat([buf.slice(0, 12), data]);
				data = null;
				send(dbuf, cb);
			} else {
				cb && cb(err);
			}
		});
	}

	var packetSize = function(ep, bytes) {
		return Math.ceil(bytes / maxPacket) * maxPacket;
	}

	var parseResponse = function(buf) {
		if(buf && buf.length == 12) {
			return buf.readUInt16LE(6);
		} else {
			return null;
		}
	}

	var receive = function(cb, rbuf) {
		console.log("reading 12 bytes...");
		cam.ep.in.transfer(packetSize(cam.ep.in, 12), function(err, data) {
			if(!err && data) {
				var rlen = data.readUInt32LE(0);
				var rtype = data.readUInt16LE(4);
				if(rtype == 3) {
					cb && cb(err, parseResponse(data), rbuf);
				} else {
					console.log("data received:", rlen);
					if(rlen > 12) {
						console.log("requesting mode data:", rlen - 12);
						cam.ep.in.transfer(packetSize(cam.ep.in, rlen - 12), function(err, data2) {
							receive(cb, Buffer.concat([data, data2]));
						});
					} else {
						receive(cb, data);
					}
				}
			} else {
				console.log("error reading:", err);
				cb && cb(err);
			}
		});
	}

	send(buf, function(err) {
		receive(callback);
	});

}

exports.parseUnicodeString = function(buf, offset) {
	var end = offset;
	for(var i = offset; i < buf.length; i += 2) {
		if(buf.readUInt16LE(i) == 0) {
			end = i;
			break;
		}
	}
	return buf.toString('utf16le', offset, end);
}

exports.parseDeviceInfo = function(buf) {
	var di = {};
	var offset = 12 + 8;
	di.vendorExtDesc = exports.parseUnicodeString(buf, offset);
	offset += di.vendorExtDesc.length * 2;
	offset += 3;
	di.operationsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.operations = [];
	for(var i = 0; i < di.operationsCount; i++) {
		di.operations.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.eventsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.events = [];
	for(var i = 0; i < di.eventsCount; i++) {
		di.events.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.propertiesCount = buf.readUInt32LE(offset);
	offset += 4;
	di.properties = [];
	for(var i = 0; i < di.propertiesCount; i++) {
		di.properties.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.captureFormatsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.captureFormats = [];
	for(var i = 0; i < di.captureFormatsCount; i++) {
		di.captureFormats.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	di.imageFormatsCount = buf.readUInt32LE(offset);
	offset += 4;
	di.imageFormats = [];
	for(var i = 0; i < di.imageFormatsCount; i++) {
		di.imageFormats.push(buf.readUInt16LE(offset).toString(16));
		offset += 2;
	}
	offset += 1;
	di.manufacturer = exports.parseUnicodeString(buf, offset);
	offset += di.manufacturer.length * 2;
	offset += 3;
	di.model = exports.parseUnicodeString(buf, offset);
	offset += di.model.length * 2;
	offset += 3;
	di.version = exports.parseUnicodeString(buf, offset);
	offset += di.version.length * 2;
	offset += 3;

	return di;
}
<|endoftext|>


<commit_before>$(function() {
	$("#loginForm").submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find("[type=submit]");

		$submitButton.attr("disabled", true);
		$form.css({
			"transform": "perspective(512px) rotateX(-90deg)",
			"opacity": "0",
			"transition": "all ease-in 0.5s"
		});

		$.ajax({
			url: $form.attr("action"),
			type: $form.attr("method"),
			data: $form.serialize()
		}).done(function() {
			location.reload();
		}).fail(function() {
			$submitButton.attr("disabled", false);
			setTimeout(function() {
				$form.css({
					"transform": "perspective(512px) scale(1)",
					"opacity": "1",
					"transition": "all ease 0.7s"
				});
			}, 500);
		});
	});

	$('#new').click(function() {
		showRegisterForm();
	});

	initRegisterForm();

	$('#passwordRetype').keyup(function() {
		$("#passwordRetypeAvailable").remove();
		var password = $('#password').val();
		var passwordRetype = $('#passwordRetype').val();
		if (passwordRetype.length == 0) {
			return false;
		}
		if (passwordRetype != password) {
			$('#passwordRetype').before('
一致していませんっ
');
			return false;
		}
		$('#passwordRetype').before('
Okay!
');
	});

	$('#color').change(function() {
		$("#colorAvailable").remove();
		var color = $('#color').val();
		$('#color').before('
Good!
');
	});

	$('#form').submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find('[type=submit]');

		$submitButton.attr('disabled', true);
		$submitButton.val('少々お待ちください...');

		$.ajax('https://api.misskey.xyz/account/create', {
			type: 'post',
			data: $form.serialize(),
			dataType: 'json',
			xhrFields: { withCredentials: true }
		}).done(function(data) {
			location.href = 'https://misskey.xyz';
		}).fail(function(data) {
			$submitButton.attr('disabled', false);
			$submitButton.text('失敗しました :(');
		});
	});
});

function initRegisterForm() {
	var $progress = $('#registerForm progress');
	var userNameInputQuery = '#registerForm .user-name .user-name-input';
	var nicknameInputQuery = '#registerForm .nickname .nickname-input';
	var passwordInputQuery = '#registerForm .password .password-input';

	initUserNameSection();
	initNicknameSection();
	initPasswordSection();

	function initUserNameSection() {
		var $cancelButton = $('#registerForm .user-name button.cancel')
		var $nextButton = $('#registerForm .user-name button.next')

		$nextButton.click(function() {
			$progress.attr('value', 2);
			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(-45deg) translateZ(-100px)');
			$('#registerForm .user-name').animate({
				left: '-50%',
				opacity: 0.2
			}, 500, 'easeOutQuint');
			$('#registerForm .nickname').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .nickname .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(userNameInputQuery).keyup(function() {
			$nextButton.attr('disabled', true);
			hideMessage();
			var sn = $(userNameInputQuery).val();

			if (sn == '') {
				return false;
			}
			if (sn.length < 4) {
				showMessage('4文字以上でお願いしますっ', false)
				return false;
			}
			if (sn.match(/^[0-9]+$/)) {
				showMessage('すべてを数字にすることはできませんっ', false)
				return false;
			}
			if (!sn.match(/^[a-zA-Z0-9_]+$/)) {
				showMessage('半角英数記号(_)のみでお願いしますっ', false)
				return false;
			}
			if (sn.length > 20) {
				showMessage('20文字以内でお願いします', false)
				return false;
			}

			showMessage('確認中...', null);
			$.ajax('https://api.misskey.xyz/screenname-available', {
				type: 'get',
				data: { 'screen-name': sn },
				dataType: 'json',
				xhrFields: { withCredentials: true }
			}).done(function(result) {
				if (result) {
					showMessage('このIDは既に使用されていますっ', false)
				} else {
					showMessage('このIDは使用できますっ！', true)
					$nextButton.attr('disabled', false);
				}
			}).fail(function() {
			});
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(userNameInputQuery).position().top - 32 + ($(userNameInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .user-name').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#userNameAvailable').remove();
		}
	}

	function initNicknameSection() {
		var $backButton = $('#registerForm .nickname button.back')
		var $nextButton = $('#registerForm .nickname button.next')

		$backButton.click(function() {
			$progress.attr('value', 1);

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(-0) translateZ(0)');
			$('#registerForm .user-name').animate({
				left: 0,
				opacity: 1
			}, 500, 'easeOutQuint');

			$('#registerForm .nickname').animate({
				left: '100%',
				opacity: 0
			}, 1000, 'easeOutQuint');
			$('#registerForm .nickname .title').animate({
				left: '64px',
				opacity: 0
			}, 1000, 'easeOutQuint');
		});

		$nextButton.click(function() {
			$progress.attr('value', 3);

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(-45deg) translateZ(-100px)');
			$('#registerForm .nickname').animate({
				left: '-50%',
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').animate({
				left: '-100%'
			}, 500, 'easeOutQuint');

			$('#registerForm .password').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .password .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(nicknameInputQuery).keyup(function() {
			hideMessage();
			$nextButton.attr('disabled', true);
			var name = $(nicknameInputQuery).val();
			if (name.length == 0) {
				return false;
			}
			showMessage('Great!', true);
			$nextButton.attr('disabled', false);
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(nicknameInputQuery).position().top - 32 + ($(nicknameInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .nickname').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#nicknameAvailable').remove();
		}
	}

	function initPasswordSection() {
		var $backButton = $('#registerForm .password button.back')
		var $nextButton = $('#registerForm .password button.next')

		$backButton.click(function() {
			$progress.attr('value', 2);

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(-0) translateZ(0)');
			$('#registerForm .nickname').animate({
				left: 0,
				opacity: 1
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').animate({
				left: '-50%'
			}, 500, 'easeOutQuint');

			$('#registerForm .password').animate({
				left: '100%',
				opacity: 0
			}, 1000, 'easeOutQuint');
			$('#registerForm .password .title').animate({
				left: '64px',
				opacity: 0
			}, 1000, 'easeOutQuint');
		});

		$nextButton.click(function() {
			$progress.attr('value', 4);

			$('#registerForm .password').css('transform', 'perspective(512px) rotateY(-45deg) translateZ(-100px)');
			$('#registerForm .password').animate({
				left: '-50%',
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').animate({
				left: '-150%'
			}, 500, 'easeOutQuint');

			$('#registerForm .nickname').animate({
				left: '-100%'
			}, 500, 'easeOutQuint');

			$('#registerForm .password-retype').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .password-retype .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(passwordInputQuery).keyup(function() {
			hideMessage();
			$nextButton.attr('disabled', true);
			var password = $(passwordInputQuery).val();
			if (password.length == 0) {
				return false;
			}
			if (password.length < 8) {
				showMessage('8文字以上でお願いします', false);
				return false;
			}
			showMessage('Nice!', true);
			$nextButton.attr('disabled', false);
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(passwordInputQuery).position().top - 32 + ($(passwordInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .password').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#passwordAvailable').remove();
		}
	}
}

function showRegisterForm() {
	$('#registerForm').css({
		display: 'block'
	});
	$('#registerForm .user-name').animate({
		left: 0,
		opacity: 1
	}, 500, 'easeOutQuint');
	$('#registerForm .user-name .title').animate({
		left: 0,
		opacity: 1
	}, 1000, 'easeOutElastic');
	$('#registerForm progress').attr('value', 1);
}<commit_msg>Update design<commit_after>$(function() {
	$("#loginForm").submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find("[type=submit]");

		$submitButton.attr("disabled", true);
		$form.css({
			"transform": "perspective(512px) rotateX(-90deg)",
			"opacity": "0",
			"transition": "all ease-in 0.5s"
		});

		$.ajax({
			url: $form.attr("action"),
			type: $form.attr("method"),
			data: $form.serialize()
		}).done(function() {
			location.reload();
		}).fail(function() {
			$submitButton.attr("disabled", false);
			setTimeout(function() {
				$form.css({
					"transform": "perspective(512px) scale(1)",
					"opacity": "1",
					"transition": "all ease 0.7s"
				});
			}, 500);
		});
	});

	$('#new').click(function() {
		showRegisterForm();
	});

	initRegisterForm();

	$('#color').change(function() {
		$("#colorAvailable").remove();
		var color = $('#color').val();
		$('#color').before('
Good!
');
	});

	$('#form').submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find('[type=submit]');

		$submitButton.attr('disabled', true);
		$submitButton.val('少々お待ちください...');

		$.ajax('https://api.misskey.xyz/account/create', {
			type: 'post',
			data: $form.serialize(),
			dataType: 'json',
			xhrFields: { withCredentials: true }
		}).done(function(data) {
			location.href = 'https://misskey.xyz';
		}).fail(function(data) {
			$submitButton.attr('disabled', false);
			$submitButton.text('失敗しました :(');
		});
	});
});

function initRegisterForm() {
	var $progress = $('#registerForm progress');
	var userNameInputQuery = '#registerForm .user-name .user-name-input';
	var nicknameInputQuery = '#registerForm .nickname .nickname-input';
	var passwordInputQuery = '#registerForm .password .password-input';
	var passwordRetypeInputQuery = '#registerForm .password-retype .password-retype-input';

	initUserNameSection();
	initNicknameSection();
	initPasswordSection();
	initPasswordRetypeSection();

	function initUserNameSection() {
		var $cancelButton = $('#registerForm .user-name button.cancel')
		var $nextButton = $('#registerForm .user-name button.next')

		$nextButton.click(function() {
			$progress.attr('value', 2);

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-300px) translateZ(-100px)');
			$('#registerForm .user-name').animate({
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .nickname').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .nickname .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(userNameInputQuery).keyup(function() {
			$nextButton.attr('disabled', true);
			hideMessage();
			var sn = $(userNameInputQuery).val();

			if (sn == '') {
				return false;
			}
			if (sn.length < 4) {
				showMessage('4文字以上でお願いしますっ', false)
				return false;
			}
			if (sn.match(/^[0-9]+$/)) {
				showMessage('すべてを数字にすることはできませんっ', false)
				return false;
			}
			if (!sn.match(/^[a-zA-Z0-9_]+$/)) {
				showMessage('半角英数記号(_)のみでお願いしますっ', false)
				return false;
			}
			if (sn.length > 20) {
				showMessage('20文字以内でお願いします', false)
				return false;
			}

			showMessage('確認中...', null);
			$.ajax('https://api.misskey.xyz/screenname-available', {
				type: 'get',
				data: { 'screen-name': sn },
				dataType: 'json',
				xhrFields: { withCredentials: true }
			}).done(function(result) {
				if (result) {
					showMessage('このIDは既に使用されていますっ', false)
				} else {
					showMessage('このIDは使用できますっ！', true)
					$nextButton.attr('disabled', false);
				}
			}).fail(function() {
			});
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(userNameInputQuery).position().top - 32 + ($(userNameInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .user-name').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#userNameAvailable').remove();
		}
	}

	function initNicknameSection() {
		var $backButton = $('#registerForm .nickname button.back')
		var $nextButton = $('#registerForm .nickname button.next')

		$backButton.click(function() {
			$progress.attr('value', 1);

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(0) translateX(0) translateZ(0)');
			$('#registerForm .user-name').animate({
				opacity: 1
			}, 500, 'easeOutQuint');

			$('#registerForm .nickname').animate({
				left: '100%',
				opacity: 0
			}, 1000, 'easeOutQuint');
			$('#registerForm .nickname .title').animate({
				left: '64px',
				opacity: 0
			}, 1000, 'easeOutQuint');
		});

		$nextButton.click(function() {
			$progress.attr('value', 3);

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-300px) translateZ(-100px)');
			$('#registerForm .nickname').animate({
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-600px) translateZ(-100px)');

			$('#registerForm .password').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .password .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(nicknameInputQuery).keyup(function() {
			hideMessage();
			$nextButton.attr('disabled', true);
			var name = $(nicknameInputQuery).val();
			if (name.length == 0) {
				return false;
			}
			showMessage('Great!', true);
			$nextButton.attr('disabled', false);
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(nicknameInputQuery).position().top - 32 + ($(nicknameInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .nickname').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#nicknameAvailable').remove();
		}
	}

	function initPasswordSection() {
		var $backButton = $('#registerForm .password button.back')
		var $nextButton = $('#registerForm .password button.next')

		$backButton.click(function() {
			$progress.attr('value', 2);

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(0) translateX(0) translateZ(0)');
			$('#registerForm .nickname').animate({
				left: 0,
				opacity: 1
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(0) translateX(-300px) translateZ(0)');

			$('#registerForm .password').animate({
				left: '100%',
				opacity: 0
			}, 1000, 'easeOutQuint');
			$('#registerForm .password .title').animate({
				left: '64px',
				opacity: 0
			}, 1000, 'easeOutQuint');
		});

		$nextButton.click(function() {
			$progress.attr('value', 4);

			$('#registerForm .password').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-300px) translateZ(-100px)');
			$('#registerForm .password').animate({
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(0) translateX(-900px) translateZ(0)');

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(0) translateX(-600px) translateZ(0)');

			$('#registerForm .password-retype').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .password-retype .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(passwordInputQuery).keyup(function() {
			hideMessage();
			$nextButton.attr('disabled', true);
			var password = $(passwordInputQuery).val();
			if (password.length == 0) {
				return false;
			}
			if (password.length < 8) {
				showMessage('8文字以上でお願いします', false);
				return false;
			}
			showMessage('Nice!', true);
			$nextButton.attr('disabled', false);
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(passwordInputQuery).position().top - 32 + ($(passwordInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .password').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#passwordAvailable').remove();
		}
	}

	function initPasswordRetypeSection() {
		var $backButton = $('#registerForm .password-retype button.back')
		var $nextButton = $('#registerForm .password-retype button.next')

		$backButton.click(function() {
			$progress.attr('value', 3);

			$('#registerForm .password').css('transform', 'perspective(512px) rotateY(0) translateX(0) translateZ(0)');
			$('#registerForm .password').animate({
				left: 0,
				opacity: 1
			}, 500, 'easeOutQuint');

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(0) translateX(-300px) translateZ(0)');

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(0) translateX(-600px) translateZ(0)');

			$('#registerForm .password-retype').animate({
				left: '100%',
				opacity: 0
			}, 1000, 'easeOutQuint');
			$('#registerForm .password-retype .title').animate({
				left: '64px',
				opacity: 0
			}, 1000, 'easeOutQuint');
		});

		$nextButton.click(function() {
			$progress.attr('value', 5);

			$('#registerForm .password-retype').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-300px) translateZ(-100px)');
			$('#registerForm .password-retype').animate({
				opacity: 0.2
			}, 500, 'easeOutQuint');

			$('#registerForm .user-name').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-1200px) translateZ(-100px)');

			$('#registerForm .nickname').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-900px) translateZ(-100px)');

			$('#registerForm .password').css('transform', 'perspective(512px) rotateY(-45deg) translateX(-600px) translateZ(-100px)');

			$('#registerForm .user-color').animate({
				left: 0,
				opacity: 1
			}, 1000, 'easeOutElastic');
			$('#registerForm .user-color .title').animate({
				left: 0,
				opacity: 1
			}, 2000, 'easeOutElastic');
		});

		$(passwordInputQuery).keyup(function() {
			hideMessage();
			$nextButton.attr('disabled', true);
			var password = $(passwordInputQuery).val();
			var passwordRetype = $(passwordRetypeInputQuery).val();
			if (passwordRetype.length == 0) {
				return false;
			}
			if (passwordRetype != password) {
				showMessage('一致していませんっ！', false);
				return false;
			}
			showMessage('Okay!', true);
			$nextButton.attr('disabled', false);
		});

		function showMessage(message, success) {
			hideMessage();
			var klass = success == null ? '' : success ? 'done' : 'fail';
			var $message = $('
' + message + '
');
			$message.css('top', $(passwordRetypeInputQuery).position().top - 32 + ($(passwordRetypeInputQuery).outerHeight() / 2));
			$message.appendTo('#registerForm .password').animate({
				'margin-right': 0,
				opacity: 1
			}, 500, 'easeOutCubic');
		}

		function hideMessage() {
			$('#passwordAvailable').remove();
		}
	}
}

function showRegisterForm() {
	$('#registerForm').css({
		display: 'block'
	});
	$('#registerForm .user-name').animate({
		left: 0,
		opacity: 1
	}, 500, 'easeOutQuint');
	$('#registerForm .user-name .title').animate({
		left: 0,
		opacity: 1
	}, 1000, 'easeOutElastic');
	$('#registerForm progress').attr('value', 1);
}<|endoftext|>


<commit_before>/** This Javascript module alters the search box to have a graphical
    drop down akin to the Firefox drop down on server load

    Global variables: Flag to make sure that we only populate the drop down box once!!

    Public functions: remove_search_index(code); add_search_index(code,label);
**/

  var ENSEMBL_TRANSCRIPT_DROPDOWN = 0;

  function __init_transcript_dropdown() {
/** Initialize the search box... make it a "graphical" drop down and add
    entries for Ensembl, EBI and Sanger

    PRIVATE - should only be executed once on page load
**/

    if( ENSEMBL_TRANSCRIPT_DROPDOWN==1 ) return; // Only execute once
      ENSEMBL_TRANSCRIPT_DROPDOWN = 1;

    if($('transcripts')){                    // Only if search box exists...
      __debug( 'Initializing transcript_dropdown box' );
      $('transcripts_text').appendChild(
        Builder.node( 'div', { id: 'transcripts_link' }, 'select transcript' )
      );
      Event.observe($('transcripts_link'),'click',function(event){
        $('transcripts').toggle();
      });
      Event.observe($('transcripts'),'click',function(event){
        $('transcripts').toggle();
      });
      /*
      Event.observe($('transcripts_link'),'click',function(event){
        var box  = $('transcripts_link');
        var menu = $('transcripts');
        Position.clone(box,menu,{setWidth:false,offsetTop:box.getHeight()-4});
        menu.toggle();
      });
      */
// Create the search list!
    }
  }

  addLoadEvent( __init_transcript_dropdown );
<commit_msg><commit_after>/** This Javascript module alters the search box to have a graphical
    drop down akin to the Firefox drop down on server load

    Global variables: Flag to make sure that we only populate the drop down box once!!

    Public functions: remove_search_index(code); add_search_index(code,label);
**/

  var ENSEMBL_TRANSCRIPT_DROPDOWN = 0;

  function __init_transcript_dropdown() {
/** Initialize the search box... make it a "graphical" drop down and add
    entries for Ensembl, EBI and Sanger

    PRIVATE - should only be executed once on page load
**/

    if( ENSEMBL_TRANSCRIPT_DROPDOWN==1 ) return; // Only execute once
      ENSEMBL_TRANSCRIPT_DROPDOWN = 1;

    if($('transcripts')){                    // Only if search box exists...
      __debug( 'Initializing transcript_dropdown box' );
      $('transcripts_text').appendChild(
        Builder.node( 'div', { id: 'transcripts_link' }, 'choose a transcript' )
      );
      Event.observe($('transcripts_link'),'click',function(event){
        $('transcripts').toggle();
      });
      Event.observe($('transcripts'),'click',function(event){
        $('transcripts').toggle();
      });
      /*
      Event.observe($('transcripts_link'),'click',function(event){
        var box  = $('transcripts_link');
        var menu = $('transcripts');
        Position.clone(box,menu,{setWidth:false,offsetTop:box.getHeight()-4});
        menu.toggle();
      });
      */
// Create the search list!
    }
  }

  addLoadEvent( __init_transcript_dropdown );
<|endoftext|>


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

new Handsontable(grid, {
    data: [
        ['a', 'd'],
        ['b', 'c']
    ],
    copyPaste: false
});
<commit_msg>コピーできる列数の制限<commit_after>var grid = document.getElementById('grid');

new Handsontable(grid, {
    data: [
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5]
    ],
    copyColsLimit: 2
});
<|endoftext|>


<commit_before>(function(root, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('d3'));
    } else if (typeof define === 'function' && define.amd) {
        define(['d3'], factory);
    } else {
        root.d3 = factory(root.d3);
    }
}(this, function(d3) {

    d3.selection.prototype.translate = function(xy) {
        return this.attr('transform', function(d,i) {
            return 'translate('+[typeof xy == 'function' ? xy.call(this, d,i) : xy]+')';
        });
    };

    d3.transition.prototype.translate = function(xy) {
        return this.attr('transform', function(d,i) {
            return 'translate('+[typeof xy == 'function' ? xy.call(this, d,i) : xy]+')';
        });
    };

    d3.selection.prototype.tspans = function(lines, lh) {
        return this.selectAll('tspan')
            .data(lines)
            .enter()
            .append('tspan')
            .text(function(d) { return d; })
            .attr('x', 0)
            .attr('dy', function(d,i) { return i ? lh || 15 : 0; });
    };

    d3.selection.prototype.append = function(name) {
        var n = d3_parse_attributes(name), s;
        name = n.attr ? n.tag : name;
        name = d3_selection_creator(name);
        s = this.select(function() {
            return this.appendChild(name.apply(this, arguments));
        });
        //attrs not provided by default in v4
        for (var name in n.attr) { s.attr(name, n.attr[name]) }
        return s;
    };

    d3.selection.prototype.insert = function(name, before) {
        var n = d3_parse_attributes(name), s;
        name = n.attr ? n.tag : name;
        name = d3_selection_creator(name);
        before = d3_selection_selector(before);
        s = this.select(function() {
            return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
        });
        //attrs not provided by default in v4
        for (var name in n.attr) { s.attr(name, n.attr[name]) }
        return s;
    };

    //no selection.enter in v4
    if (d3.selection.enter){
        d3.selection.enter.prototype.append = d3.selection.prototype.append
        d3.selection.enter.prototype.insert = d3.selection.prototype.insert
    }

    var d3_parse_attributes_regex = /([\.#])/g;

    function d3_parse_attributes(name) {
        if (typeof name === "string") {
            var attr = {},
                parts = name.split(d3_parse_attributes_regex), p;
                name = parts.shift();
            while ((p = parts.shift())) {
                if (p == '.') attr['class'] = attr['class'] ? attr['class'] + ' ' + parts.shift() : parts.shift();
                else if (p == '#') attr.id = parts.shift();
            }
            return attr.id || attr['class'] ? { tag: name, attr: attr } : name;
        }
        return name;
    }

    function d3_selection_creator(name) {
        var qualify = d3.namespace || d3.ns.qualify //v4 API change
        return typeof name === "function" ? name : (name = qualify(name)).local ? function() {
            return this.ownerDocument.createElementNS(name.space, name.local);
        } : function() {
            return this.ownerDocument.createElementNS(this.namespaceURI, name);
        };
    }

    function d3_selection_selector(selector) {
        return typeof selector === "function" ? selector : function() {
            return this.querySelector(selector);
        };
    }

    d3.wordwrap = function(line, maxCharactersPerLine) {
        var w = line.split(' '),
            lines = [],
            words = [],
            maxChars = maxCharactersPerLine || 40,
            l = 0;
        w.forEach(function(d) {
            if (l+d.length > maxChars) {
                lines.push(words.join(' '));
                words.length = 0;
                l = 0;
            }
            l += d.length;
            words.push(d);
        });
        if (words.length) {
            lines.push(words.join(' '));
        }
        return lines;
    };

    d3.ascendingKey = function(key) {
        return typeof key == 'function' ? function (a, b) {
              return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : key(a) >= key(b) ? 0 : NaN;
        } : function (a, b) {
              return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : a[key] >= b[key] ? 0 : NaN;
        };
    };

    d3.descendingKey = function(key) {
        return typeof key == 'function' ? function (a, b) {
            return key(b) < key(a) ? -1 : key(b) > key(a) ? 1 : key(b) >= key(a) ? 0 : NaN;
        } : function (a, b) {
            return b[key] < a[key] ? -1 : b[key] > a[key] ? 1 : b[key] >= a[key] ? 0 : NaN;
        };
    };

    d3.f = function(){
        var functions = arguments;
        //convert all string arguments into field accessors
        var i = 0, l = functions.length;
        while (i < l) {
            if (functions[i] in d3.f._) {
                functions[i] = (function(f){ return function(d){ return f(d); }; })(d3.f._[functions[i]]);
            } else if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number'){
                functions[i] = (function(str){ return function(d){ return d[str]; }; })(functions[i]);
            } else if (typeof(functions[i]) === 'object'){
                functions[i] = (function(map){ return function(d){ return map[d]; }; })(functions[i]);
            }
            i++;
        }
         //return composition of functions
        return function(d) {
            var i=0, l = functions.length;
            while (i++ < l) d = functions[i-1].call(this, d);
            return d;
        };
    };

    // special operator functions
    d3.f._ = {
        'ƒ.call': function(d) { return d(); },
        'ƒ.not': function(d) { return !d; }
    };

    // store d3.f as convenient unicode character function (alt-f on macs)
    if (typeof window !== 'undefined' && !window.hasOwnProperty('ƒ')) window.ƒ = d3.f;

    // this tweak allows setting a listener for multiple events, jquery style
    var d3_selection_on = d3.selection.prototype.on;
    d3.selection.prototype.on = function(type, listener, capture) {
        if (typeof type == 'string' && type.indexOf(' ') > -1) {
            type = type.split(' ');
            for (var i = 0; i<type.length; i++) {
                d3_selection_on.apply(this, [type[i], listener, capture]);
            }
        } else {
            d3_selection_on.apply(this, [type, listener, capture]);
        }
        return this;
    };

    // for everyone's sake, let's add prop as alias for property
    d3.selection.prototype.prop = d3.selection.prototype.property;

    // combines data().enter().append()
    d3.selection.prototype.appendMany = function(data, name){
        return this.selectAll(name).data(data).enter().append(name);
    };

    return d3;

}));
<commit_msg>saved d3.round for future generations<commit_after>(function(root, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('d3'));
    } else if (typeof define === 'function' && define.amd) {
        define(['d3'], factory);
    } else {
        root.d3 = factory(root.d3);
    }
}(this, function(d3) {

    d3.selection.prototype.translate = function(xy) {
        return this.attr('transform', function(d,i) {
            return 'translate('+[typeof xy == 'function' ? xy.call(this, d,i) : xy]+')';
        });
    };

    d3.transition.prototype.translate = function(xy) {
        return this.attr('transform', function(d,i) {
            return 'translate('+[typeof xy == 'function' ? xy.call(this, d,i) : xy]+')';
        });
    };

    d3.selection.prototype.tspans = function(lines, lh) {
        return this.selectAll('tspan')
            .data(lines)
            .enter()
            .append('tspan')
            .text(function(d) { return d; })
            .attr('x', 0)
            .attr('dy', function(d,i) { return i ? lh || 15 : 0; });
    };

    d3.selection.prototype.append = function(name) {
        var n = d3_parse_attributes(name), s;
        name = n.attr ? n.tag : name;
        name = d3_selection_creator(name);
        s = this.select(function() {
            return this.appendChild(name.apply(this, arguments));
        });
        //attrs not provided by default in v4
        for (var name in n.attr) { s.attr(name, n.attr[name]) }
        return s;
    };

    d3.selection.prototype.insert = function(name, before) {
        var n = d3_parse_attributes(name), s;
        name = n.attr ? n.tag : name;
        name = d3_selection_creator(name);
        before = d3_selection_selector(before);
        s = this.select(function() {
            return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
        });
        //attrs not provided by default in v4
        for (var name in n.attr) { s.attr(name, n.attr[name]) }
        return s;
    };

    //no selection.enter in v4
    if (d3.selection.enter){
        d3.selection.enter.prototype.append = d3.selection.prototype.append
        d3.selection.enter.prototype.insert = d3.selection.prototype.insert
    }

    var d3_parse_attributes_regex = /([\.#])/g;

    function d3_parse_attributes(name) {
        if (typeof name === "string") {
            var attr = {},
                parts = name.split(d3_parse_attributes_regex), p;
                name = parts.shift();
            while ((p = parts.shift())) {
                if (p == '.') attr['class'] = attr['class'] ? attr['class'] + ' ' + parts.shift() : parts.shift();
                else if (p == '#') attr.id = parts.shift();
            }
            return attr.id || attr['class'] ? { tag: name, attr: attr } : name;
        }
        return name;
    }

    function d3_selection_creator(name) {
        var qualify = d3.namespace || d3.ns.qualify //v4 API change
        return typeof name === "function" ? name : (name = qualify(name)).local ? function() {
            return this.ownerDocument.createElementNS(name.space, name.local);
        } : function() {
            return this.ownerDocument.createElementNS(this.namespaceURI, name);
        };
    }

    function d3_selection_selector(selector) {
        return typeof selector === "function" ? selector : function() {
            return this.querySelector(selector);
        };
    }

    d3.wordwrap = function(line, maxCharactersPerLine) {
        var w = line.split(' '),
            lines = [],
            words = [],
            maxChars = maxCharactersPerLine || 40,
            l = 0;
        w.forEach(function(d) {
            if (l+d.length > maxChars) {
                lines.push(words.join(' '));
                words.length = 0;
                l = 0;
            }
            l += d.length;
            words.push(d);
        });
        if (words.length) {
            lines.push(words.join(' '));
        }
        return lines;
    };

    d3.ascendingKey = function(key) {
        return typeof key == 'function' ? function (a, b) {
              return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : key(a) >= key(b) ? 0 : NaN;
        } : function (a, b) {
              return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : a[key] >= b[key] ? 0 : NaN;
        };
    };

    d3.descendingKey = function(key) {
        return typeof key == 'function' ? function (a, b) {
            return key(b) < key(a) ? -1 : key(b) > key(a) ? 1 : key(b) >= key(a) ? 0 : NaN;
        } : function (a, b) {
            return b[key] < a[key] ? -1 : b[key] > a[key] ? 1 : b[key] >= a[key] ? 0 : NaN;
        };
    };

    d3.f = function(){
        var functions = arguments;
        //convert all string arguments into field accessors
        var i = 0, l = functions.length;
        while (i < l) {
            if (functions[i] in d3.f._) {
                functions[i] = (function(f){ return function(d){ return f(d); }; })(d3.f._[functions[i]]);
            } else if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number'){
                functions[i] = (function(str){ return function(d){ return d[str]; }; })(functions[i]);
            } else if (typeof(functions[i]) === 'object'){
                functions[i] = (function(map){ return function(d){ return map[d]; }; })(functions[i]);
            }
            i++;
        }
         //return composition of functions
        return function(d) {
            var i=0, l = functions.length;
            while (i++ < l) d = functions[i-1].call(this, d);
            return d;
        };
    };

    // special operator functions
    d3.f._ = {
        'ƒ.call': function(d) { return d(); },
        'ƒ.not': function(d) { return !d; }
    };

    // store d3.f as convenient unicode character function (alt-f on macs)
    if (typeof window !== 'undefined' && !window.hasOwnProperty('ƒ')) window.ƒ = d3.f;

    // this tweak allows setting a listener for multiple events, jquery style
    var d3_selection_on = d3.selection.prototype.on;
    d3.selection.prototype.on = function(type, listener, capture) {
        if (typeof type == 'string' && type.indexOf(' ') > -1) {
            type = type.split(' ');
            for (var i = 0; i<type.length; i++) {
                d3_selection_on.apply(this, [type[i], listener, capture]);
            }
        } else {
            d3_selection_on.apply(this, [type, listener, capture]);
        }
        return this;
    };

    // for everyone's sake, let's add prop as alias for property
    d3.selection.prototype.prop = d3.selection.prototype.property;

    // combines data().enter().append()
    d3.selection.prototype.appendMany = function(data, name){
        return this.selectAll(name).data(data).enter().append(name);
    };

    d3.round = d3.round || function(n, p) {
        d = Math.pow(10, p);
        return Math.round(n * d) / d;
    };

    return d3;

}));
<|endoftext|>


<commit_before>// Copyright 2012 WebDriver committers
// Copyright 2012 Software Freedom Conservancy
//
// 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.

/**
 * @fileoverview Synthetic events for fun and profit.
 */

goog.provide('webdriver.atoms.inputs');

goog.require('bot.Keyboard');
goog.require('bot.Mouse');
goog.require('bot.action');
goog.require('goog.array');

/**
 * Send keyboard input to a particular element.
 *
 * @param {!Element} element The element to send the keyboard input to.
 * @param {Array.<!bot.Keyboard.Key>=} opt_state The keyboard to use, or construct one.
 * @param {...(string|!Array.<string>)} var_args What to type.
 * @return {Array.<!bot.Keyboard.Key>} The keyboard state.
 */
webdriver.atoms.inputs.sendKeys = function(element, opt_state, var_args) {
  var keyboard = new bot.Keyboard(opt_state);
  var to_type = goog.array.slice(arguments, 2);
  var flattened = goog.array.flatten(to_type);

  if (!element) {
    element = bot.dom.getActiveElement(document);
  }
  bot.action.type(element, flattened, keyboard);

  return keyboard.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.sendKeys',
                  webdriver.atoms.inputs.sendKeys);

/**
* Click on an element.
*
* @param {!Element} element The element to click.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.click = function(element, opt_state) {
  var mouse = new bot.Mouse(opt_state);
  if (!element) {
    element = mouse.getElement();
  }
  bot.action.click(element, null, mouse);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.click',
                  webdriver.atoms.inputs.click);

/**
* Move the mouse to a specific element and/or coordinate location.
*
* @param {!Element} element The element to move the mouse to.
* @param {int} x_offset The x coordinate to use as an offset.
* @param {int} y_offset The y coordinate to use as an offset.
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseMove = function(element, x_offset, y_offset, opt_state) {
  var mouse = new bot.Mouse(opt_state);
  var target = element || mouse.getElement();

  x_offset = x_offset || 0;
  y_offset = y_offset || 0;

  // Right now, we're using the upper-left corner of the element.
  // I believe this is wrong, and we should be using the center,
  // if the offset is set to 0, 0.
  // if (element) {
  //   if (x_offset == 0 && y_offset == 0) {
  //     var source_element_size = bot.action.getInteractableSize_(element);
  //     x_offset = Math.round(source_element_size.width / 2);
  //     y_offset = Math.round(source_element_size.height / 2);
  //   }
  // } else {
  //   var target_element_size = bot.action.getInteractableSize_(target);
  //   x_offset += Math.round(target_element_size.width / 2);
  //   y_offset += Math.round(target_element_size.height / 2);
  // }

  var doc = goog.dom.getOwnerDocument(target);
  var win = goog.dom.getWindow(doc);
  var inViewAfterScroll = bot.action.scrollIntoView(
      target,
      new goog.math.Coordinate(x_offset, y_offset));

  var coords = new goog.math.Coordinate(x_offset, y_offset);
  mouse.move(target, coords);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseMove',
                  webdriver.atoms.inputs.mouseMove);

/**
* Presses the primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseButtonDown = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.LEFT);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseButtonDown',
                  webdriver.atoms.inputs.mouseButtonDown);

/**
* Releases the primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseButtonUp = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseButtonUp',
                  webdriver.atoms.inputs.mouseButtonUp);

/**
* Double-clicks primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.doubleClick = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.LEFT);
  mouse.releaseButton();
  mouse.pressButton(bot.Mouse.Button.LEFT);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.doubleClick',
                  webdriver.atoms.inputs.doubleClick);

/**
* Right-clicks mouse button at the current location.
*
* @param {Object)} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.rightClick = function (opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.RIGHT);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.rightClick',
                  webdriver.atoms.inputs.rightClick);
<commit_msg>JimEvans: Correcting synthetic mouse movement to use center of element if offset is not specified.<commit_after>// Copyright 2012 WebDriver committers
// Copyright 2012 Software Freedom Conservancy
//
// 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.

/**
 * @fileoverview Synthetic events for fun and profit.
 */

goog.provide('webdriver.atoms.inputs');

goog.require('bot.Keyboard');
goog.require('bot.Mouse');
goog.require('bot.action');
goog.require('goog.array');

/**
 * Send keyboard input to a particular element.
 *
 * @param {!Element} element The element to send the keyboard input to.
 * @param {Array.<!bot.Keyboard.Key>=} opt_state The keyboard to use, or construct one.
 * @param {...(string|!Array.<string>)} var_args What to type.
 * @return {Array.<!bot.Keyboard.Key>} The keyboard state.
 */
webdriver.atoms.inputs.sendKeys = function(element, opt_state, var_args) {
  var keyboard = new bot.Keyboard(opt_state);
  var to_type = goog.array.slice(arguments, 2);
  var flattened = goog.array.flatten(to_type);

  if (!element) {
    element = bot.dom.getActiveElement(document);
  }
  bot.action.type(element, flattened, keyboard);

  return keyboard.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.sendKeys',
                  webdriver.atoms.inputs.sendKeys);

/**
* Click on an element.
*
* @param {!Element} element The element to click.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.click = function(element, opt_state) {
  var mouse = new bot.Mouse(opt_state);
  if (!element) {
    element = mouse.getElement();
  }
  bot.action.click(element, null, mouse);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.click',
                  webdriver.atoms.inputs.click);

/**
* Move the mouse to a specific element and/or coordinate location.
*
* @param {!Element} element The element to move the mouse to.
* @param {int} x_offset The x coordinate to use as an offset.
* @param {int} y_offset The y coordinate to use as an offset.
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseMove = function(element, x_offset, y_offset, opt_state) {
  var mouse = new bot.Mouse(opt_state);
  var target = element || mouse.getElement();

  var offset_specified = (x_offset != null) && (y_offset != null);
  x_offset = x_offset || 0;
  y_offset = y_offset || 0;

  // If we have specified an element and no offset, we should
  // move the mouse to the center of the specified element.
  if (element) {
    if (!offset_specified) {
      var source_element_size = bot.action.getInteractableSize_(element);
      x_offset = Math.floor(source_element_size.width / 2);
      y_offset = Math.floor(source_element_size.height / 2);
    }
  } else {
    // Moving to an absolute offset from the current target element,
    // so we have to account for the existing offset of the current
    // mouse position to the element origin (upper-left corner).
    var pos = goog.style.getClientPosition(target);
    x_offset += (mouse.clientXY_.x - pos.x);
    y_offset += (mouse.clientXY_.y - pos.y);
  }

  var doc = goog.dom.getOwnerDocument(target);
  var win = goog.dom.getWindow(doc);
  var inViewAfterScroll = bot.action.scrollIntoView(
      target,
      new goog.math.Coordinate(x_offset, y_offset));

  var coords = new goog.math.Coordinate(x_offset, y_offset);
  mouse.move(target, coords);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseMove',
                  webdriver.atoms.inputs.mouseMove);

/**
* Presses the primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseButtonDown = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.LEFT);
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseButtonDown',
                  webdriver.atoms.inputs.mouseButtonDown);

/**
* Releases the primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.mouseButtonUp = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.mouseButtonUp',
                  webdriver.atoms.inputs.mouseButtonUp);

/**
* Double-clicks primary mouse button at the current location.
*
* @param {Object} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.doubleClick = function(opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.LEFT);
  mouse.releaseButton();
  mouse.pressButton(bot.Mouse.Button.LEFT);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.doubleClick',
                  webdriver.atoms.inputs.doubleClick);

/**
* Right-clicks mouse button at the current location.
*
* @param {Object)} opt_state The serialized state of the mouse.
* @return {Object} The mouse state.
*/
webdriver.atoms.inputs.rightClick = function (opt_state) {
  var mouse = new bot.Mouse(opt_state);
  mouse.pressButton(bot.Mouse.Button.RIGHT);
  mouse.releaseButton();
  return mouse.getState();
};
goog.exportSymbol('webdriver.atoms.inputs.rightClick',
                  webdriver.atoms.inputs.rightClick);
<|endoftext|>


<commit_before>/* global renderAreaURL:true, _, arealist, msglist, phiBar */

renderAreaURL = function(URL, parsedURL){
   if ( parsedURL.objectPath.length > 0 ){
      phiBar.reportErrorHTML([
         'Sorry, opening files embedded in echomail ',
         'is not (yet) supported in PhiDo.',
         '
The address ',
         _.escapeHTML(URL),
         ' could not be opened.',
         '
'
      ].join(''));
   } else if( parsedURL.echoNames.length < 1 ){
      arealist();
   } else if ( parsedURL.echoNames.length === 1 ){
      msglist( parsedURL.echoNames[0][0] );
   } else {
      phiBar.reportErrorHTML([
         'Sorry, opening multiple echomail areas at once ',
         'is not (yet) supported in PhiDo.',
         '
The address ',
         _.escapeHTML(URL),
         ' could not be opened.',
         '
'
      ].join(''));
   }
};<commit_msg>area:// processing: errors first,then the most simple case (arealist)<commit_after>/* global renderAreaURL:true, _, arealist, msglist, phiBar */

renderAreaURL = function(URL, parsedURL){
   if ( parsedURL.objectPath.length > 0 ){
      phiBar.reportErrorHTML([
         'Sorry, opening files embedded in echomail ',
         'is not (yet) supported in PhiDo.',
         '
The address ',
         _.escapeHTML(URL),
         ' could not be opened.',
         '
'
      ].join(''));
      return;
   }
   if( parsedURL.echoNames.length > 1 ){
      phiBar.reportErrorHTML([
         'Sorry, opening multiple echomail areas at once ',
         'is not (yet) supported in PhiDo.',
         '
The address ',
         _.escapeHTML(URL),
         ' could not be opened.',
         '
'
      ].join(''));
      return;
   }
   if( parsedURL.echoNames.length < 1 ){
      arealist();
      return;
   }
   // parsedURL.echoNames.length === 1
   msglist( parsedURL.echoNames[0][0] );
};<|endoftext|>


<commit_before>function ddg_spice_rhymes(response) {
    var query = decodeURIComponent(rq);
    query = query.replace(/^(what|rhymes( with| for)?)| |\?/gi, "")
    var words = new Array();
	for (var i = 0; i < response.length; i++) {
        word = response.splice(Math.random()*response.length, 1)[0];
        if (word.score == 300)
	        words.push(word.word);
        if (words.length == 30) break;
	}
    if (words.length == 0) return;

	var items = new Array();
	items[0] = new Array();
    items[0]['a'] = "Rhymes: " + words.join(', ') + ".";
	items[0]['h'] = query + " (Rhymes)";
	items[0]['s'] = 'RhymeBrain';
	items[0]['u'] = 'http://rhymebrain.com/';
    items[0]["force_big_header"] = true;

	nra(items);
}
<commit_msg>Changed ref to new RhymeBrain cannonical URL<commit_after>function ddg_spice_rhymes(response) {
    var query = decodeURIComponent(rq);
    query = query.replace(/^(what|rhymes( with| for)?)| |\?/gi, "")
    var words = new Array();
	for (var i = 0; i < response.length; i++) {
        word = response.splice(Math.random()*response.length, 1)[0];
        if (word.score == 300)
	        words.push(word.word);
        if (words.length == 30) break;
	}
    if (words.length == 0) return;

	var items = new Array();
	items[0] = new Array();
    items[0]['a'] = "Rhymes: " + words.join(', ') + ".";
	items[0]['h'] = query + " (Rhymes)";
	items[0]['s'] = 'RhymeBrain';
	items[0]['u'] = 'http://rhymebrain.com/en/What_rhymes_with_'
                  + encodeURI(query) + '.html';
    items[0]["force_big_header"] = true;

	nra(items);
}
<|endoftext|>


<commit_before>/**
 * KumbiaPHP web & app Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://wiki.kumbiaphp.com/Licencia
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@kumbiaphp.com so we can send you a copy immediately.
 *
 * Plugin para jQuery que incluye los callbacks basicos para los Helpers
 *
 * @copyright  Copyright (c) 2005-2009 Kumbia Team (http://www.kumbiaphp.com)
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
 */

(function($) {
    /**
     * Objeto KumbiaPHP
     *
     **/
    $.KumbiaPHP = {
        /**
         * Muestra mensaje de confirmacion
         *
         * @param Object event
         **/
        cConfirm: function(event) {
            if(!confirm(this.title)) {
                event.preventDefault();
            }
        },
        /**
         * Aplica un efecto a un elemento
         *
         * @param String fx
         **/
        cFx: function(fx) {
            return function(event) {
                event.preventDefault();
                (($(this.rel))[fx])();
            }
        },
        /**
         * Carga con AJAX
         *
         * @param Object event
         **/
        cRemote: function(event) {
            event.preventDefault();
            $(this.rel).load(this.href);
        },
        /**
         * Carga con AJAX y Confirmacion
         *
         * @param Object event
         **/
        cRemoteConfirm: function(event) {
            event.preventDefault();
            if(confirm(this.title)) {
                $(this.rel).load(this.href);
            }
        },
        /**
         * Metodo para utilizar con map de jQuery, el cual genera calendarios jsCalendar
         *
         **/
        calendar: function() {
            var tigger = $('#' + this.id + '_tigger').get(0);
            Calendar.setup({ inputField: this.id, ifFormat: tigger.alt, daFormat: tigger.alt, button: tigger.id});
        },

        /**
		 * Enviar formularios de manera asincronica, via POST
		 * Y los carga en un contenedor
		 **/
		cFRemote: function(e){
			e.preventDefault();
			self = $(this);
			var url = self.attr('action');
			var div = self.attr('rel');
			$.post(url, self.serialize(), function(data, status){
				$('#'+div).html(data);
			});
		},

        /**
         * Carga con AJAX al cambiar select
         *
         * @param Object event
         **/
        cUpdaterSelect: function(event) {
            $('#' + $.KumbiaPHP.metadata[this.id].update).load($.KumbiaPHP.metadata[this.id].action + this.value);
        },

        /**
         * Enlaza a las clases por defecto
         *
         **/
        bind : function() {
            $("a.js-confirm").live('click', this.cConfirm);
            $("a.js-remote").live('click', this.cRemote);
            $("a.js-remote-confirm").live('click', this.cRemoteConfirm);
            $("a.js-show").live('click', this.cFx('show'));
            $("a.js-hide").live('click', this.cFx('hide'));
            $("a.js-toggle").live('click', this.cFx('toggle'));
            $("a.js-fade-in").live('click', this.cFx('fadeIn'));
            $("a.js-fade-out").live('click', this.cFx('fadeOut'));

            $("div.js-remote").ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
                $.KumbiaPHP.bindNoLive(this);
            });

            // enlaza los que no funcionan con live
            this.bindNoLive(document);
        },
        /**
         * Aquellos que no se enlazan automaticamente con live
         *
         * @param DomObject parent
         **/
        bindNoLive : function(parent) {
            // lista desplegable que actualiza con ajax
            $("select.js-remote", parent).bind('change', this.cUpdaterSelect);

            // calendario
            $("input.js-calendar", parent).map(this.calendar);

            // formulario ajax
            $("form.js-remote", parent).bind('submit', this.cFRemote);
        }
    }

     // Enlaza a las clases por defecto
    $(function(){ $.KumbiaPHP.bind(); });
})(jQuery);<commit_msg>Agregada la autocarga de plugin en jquery<commit_after>/**
 * KumbiaPHP web & app Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://wiki.kumbiaphp.com/Licencia
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@kumbiaphp.com so we can send you a copy immediately.
 *
 * Plugin para jQuery que incluye los callbacks basicos para los Helpers
 *
 * @copyright  Copyright (c) 2005-2009 Kumbia Team (http://www.kumbiaphp.com)
 * @license	http://wiki.kumbiaphp.com/Licencia	 New BSD License
 */

(function($) {
	/**
	 * Objeto KumbiaPHP
	 *
	 **/
	$.KumbiaPHP = {
		plugin: [],
		/**
		 * Muestra mensaje de confirmacion
		 *
		 * @param Object event
		 **/
		cConfirm: function(event) {
			if(!confirm(this.title)) {
				event.preventDefault();
			}
		},
		/**
		 * Aplica un efecto a un elemento
		 *
		 * @param String fx
		 **/
		cFx: function(fx) {
			return function(event) {
				event.preventDefault();
				(($(this.rel))[fx])();
			}
		},
		/**
		 * Carga con AJAX
		 *
		 * @param Object event
		 **/
		cRemote: function(event) {
			event.preventDefault();
			$(this.rel).load(this.href);
		},
		/**
		 * Carga con AJAX y Confirmacion
		 *
		 * @param Object event
		 **/
		cRemoteConfirm: function(event) {
			event.preventDefault();
			if(confirm(this.title)) {
				$(this.rel).load(this.href);
			}
		},
		/**
		 * Metodo para utilizar con map de jQuery, el cual genera calendarios jsCalendar
		 *
		 **/
		calendar: function() {
			var tigger = $('#' + this.id + '_tigger').get(0);
			Calendar.setup({ inputField: this.id, ifFormat: tigger.alt, daFormat: tigger.alt, button: tigger.id});
		},

		/**
		 * Enviar formularios de manera asincronica, via POST
		 * Y los carga en un contenedor
		 **/
		cFRemote: function(e){
			e.preventDefault();
			self = $(this);
			var button = $('[type=submit]', self);
			button.attr('disabled', 'disabled');
			var url = self.attr('action');
			var div = self.attr('data-div');
			$.post(url, self.serialize(), function(data, status){
				var capa = $('#'+div);
				capa.html(data);
				capa.hide();
				capa.show('slow');
				button.attr('disabled', null);
			});
		},

		/**
		 * Carga con AJAX al cambiar select
		 *
		 * @param Object event
		 **/
		cUpdaterSelect: function(event) {
			$('#' + $.KumbiaPHP.metadata[this.id].update).load($.KumbiaPHP.metadata[this.id].action + this.value);
		},

		/**
		 * Enlaza a las clases por defecto
		 *
		 **/
		bind : function() {
			$("a.js-confirm").live('click', this.cConfirm);
			$("a.js-remote").live('click', this.cRemote);
			$("a.js-remote-confirm").live('click', this.cRemoteConfirm);
			$("a.js-show").live('click', this.cFx('show'));
			$("a.js-hide").live('click', this.cFx('hide'));
			$("a.js-toggle").live('click', this.cFx('toggle'));
			$("a.js-fade-in").live('click', this.cFx('fadeIn'));
			$("a.js-fade-out").live('click', this.cFx('fadeOut'));
			$("form.js-remote").live('submit', this.cFRemote);
			$("div.js-remote").ajaxComplete(function (event, XMLHttpRequest, ajaxOptions) {
				$.KumbiaPHP.bindNoLive(this);
			});
			// enlaza los que no funcionan con live
			this.bindNoLive(document);
		},
			/**
			* Aquellos que no se enlazan automaticamente con live
			*
			* @param DomObject parent
			**/
			bindNoLive : function(parent) {
				// lista desplegable que actualiza con ajax
				$("select.js-remote", parent).bind('change', this.cUpdaterSelect);
				// calendario
				$("input.js-calendar", parent).map(this.calendar);
				// formulario ajax
				$("form.js-remote", parent).bind('submit', this.cFRemote);
			},
			/* Implementa la autocarga de plugins, estos deben seguir
			 * una convención para que pueda funcionar correctamente
			 */
			autoload: function(){
				var elem = $("[class*='jp-']");
				$.each(elem, function(i, val){
					var self = $(this); //apunta al elemento con clase jp-*
					var classes = self.attr('class').split(' ');
					for (i in classes){
						if(classes[i].substr(0, 3) == 'jp-'){
							if(jQuery.inArray(classes[i].substr(3),$.KumbiaPHP.plugin) != -1)
								continue;
							$.KumbiaPHP.plugin.push(classes[i].substr(3))
						}
					}
				});
				var head = $('head');
				for(i in $.KumbiaPHP.plugin){
					jQuery.ajaxSetup({ cache: true});
					head.append('<link href="css/'+$.KumbiaPHP.plugin[i]+'.css" type="text/css" rel="stylesheet"/>');
					jQuery.getScript('javascript/jquery/jquery.'+$.KumbiaPHP.plugin[i]+'.js', function(data, text){

					});
			}
		}
	}
	// Enlaza a las clases por defecto
	$(function(){ $.KumbiaPHP.bind(); $.KumbiaPHP.autoload()});
})(jQuery);
<|endoftext|>


<commit_before>'use strict';
var db = require('./database'),
    config = require('./config.json'),
    cache = require('./cache'),
    async = require('async'),
    request = require('request');
var checkers = config.checks.map(function (url) {
        return createCheck(url);
    }),
    delay = config.pollDelay * 1000,
    timeout = Math.max(12 + 3, config.pollDelay * config.checks.length) * 1000;

function createCheck(url) {
    return function sitehome(next) {
        var now = Date.now();
        request({
            rejectUnauthorized: false,
            url: url,
            timeout: timeout
        }, function (err, resp) {
            var complete = Date.now() - now;
            console.log(err);
            if (err) {
                return db.addCheck(url, 599, 0, complete, function () {
                    next();
                });
            }
            var readonly = !!resp.headers['Discourse-Readonly'];
            db.addCheck(url, resp.statusCode, readonly,
                complete,
                function () {
                    next();
                });
        });
    };
}
exports.updated = false;

function getNotice(callback) {
    request(config.siteSettings, function (err, _, body) {
        if (err) {
            return callback();
        }
        try {
            var settings = JSON.parse(body);
            cache.global_notice = settings.global_notice;
        } catch (ignore) {} //eslint-disable-line no-empty
        callback();
    });
}

exports.start = function () {
    async.forever(function (next) {
        async.eachSeries(checkers, function (check, callback) {
                exports.updated = true;
                check(function () {
                    setTimeout(callback, delay);
                });
            },
            function () {
                getNotice(next);
            });
    });
};
<commit_msg>remove debugstatement<commit_after>'use strict';
var db = require('./database'),
    config = require('./config.json'),
    cache = require('./cache'),
    async = require('async'),
    request = require('request');
var checkers = config.checks.map(function (url) {
        return createCheck(url);
    }),
    delay = config.pollDelay * 1000,
    timeout = Math.max(12 + 3, config.pollDelay * config.checks.length) * 1000;

function createCheck(url) {
    return function sitehome(next) {
        var now = Date.now();
        request({
            rejectUnauthorized: false,
            url: url,
            timeout: timeout
        }, function (err, resp) {
            var complete = Date.now() - now;
            if (err) {
                return db.addCheck(url, 599, 0, complete, function () {
                    next();
                });
            }
            var readonly = !!resp.headers['Discourse-Readonly'];
            db.addCheck(url, resp.statusCode, readonly,
                complete,
                function () {
                    next();
                });
        });
    };
}
exports.updated = false;

function getNotice(callback) {
    request(config.siteSettings, function (err, _, body) {
        if (err) {
            return callback();
        }
        try {
            var settings = JSON.parse(body);
            cache.global_notice = settings.global_notice;
        } catch (ignore) {} //eslint-disable-line no-empty
        callback();
    });
}

exports.start = function () {
    async.forever(function (next) {
        async.eachSeries(checkers, function (check, callback) {
                exports.updated = true;
                check(function () {
                    setTimeout(callback, delay);
                });
            },
            function () {
                getNotice(next);
            });
    });
};
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { NumberLabelRow } from './NumberLabelRow';
import { DetailRow } from './DetailRow';
import { SimpleLabel } from './SimpleLabel';
import { TouchableNoFeedback } from './DataTable';

import { dispensingStrings } from '../localization';
import currency from '../localization/currency';

/**
 * Simple layout component for primary use within the PrescriptionSummary
 * component.
 *
 * Simply lays out a TransactionItem record showing details related to
 * the prescription it is related from.
 *
 * @param {Object} item A TransactionItem record to display details for.
 */
export const PrescriptionSummaryRow = ({ item }) => {
  const { itemName, itemCode, totalQuantity, note, totalPrice } = item;

  const details = [{ label: 'Code', text: itemCode }];

  return (
    <TouchableNoFeedback style={localStyles.mainContainer}>
      <NumberLabelRow text={itemName} number={totalQuantity} />
      <View style={localStyles.marginFive} />
      <DetailRow details={details} />
      <View style={localStyles.marginFive} />
      <SimpleLabel label={dispensingStrings.directions} text={note} />
      <View style={localStyles.marginFive} />
      <SimpleLabel label="Price" text={currency(totalPrice).format()} />
    </TouchableNoFeedback>
  );
};

const localStyles = StyleSheet.create({
  mainContainer: { justifyContent: 'space-evenly', flex: 1, flexDirection: 'column' },
  marginFive: { margin: 5 },
});

PrescriptionSummaryRow.propTypes = { item: PropTypes.object.isRequired };
<commit_msg>Add batch name to prescription summary row<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import { View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { NumberLabelRow } from './NumberLabelRow';
import { DetailRow } from './DetailRow';
import { SimpleLabel } from './SimpleLabel';
import { TouchableNoFeedback } from './DataTable';

import { generalStrings, dispensingStrings } from '../localization';
import currency from '../localization/currency';

/**
 * Simple layout component for primary use within the PrescriptionSummary
 * component.
 *
 * Simply lays out a TransactionItem record showing details related to
 * the prescription it is related from.
 *
 * @param {Object} item A TransactionItem record to display details for.
 */
export const PrescriptionSummaryRow = ({ item }) => {
  const { itemName, itemCode, totalQuantity, note, totalPrice, batch } = item;

  const details = [{ label: 'Code', text: itemCode }];

  return (
    <TouchableNoFeedback style={localStyles.mainContainer}>
      <NumberLabelRow text={itemName} number={totalQuantity} />
      <View style={localStyles.marginFive} />
      <SimpleLabel label={generalStrings.batch_name} text={batch} />
      <View style={localStyles.marginFive} />
      <DetailRow details={details} />
      <View style={localStyles.marginFive} />
      <SimpleLabel label={dispensingStrings.directions} text={note} />
      <View style={localStyles.marginFive} />
      <SimpleLabel label="Price" text={currency(totalPrice).format()} />
    </TouchableNoFeedback>
  );
};

const localStyles = StyleSheet.create({
  mainContainer: { justifyContent: 'space-evenly', flex: 1, flexDirection: 'column' },
  marginFive: { margin: 5 },
});

PrescriptionSummaryRow.propTypes = { item: PropTypes.object.isRequired };
<|endoftext|>


<commit_before>var _ = require('lodash');
var React = require('react');

var RequirementSet = require('./requirementSet');

var getRandomInt = require('../helpers/getRandomInt')

var areas = {
	major: {
		'Computer Science': require('../../mockups/csci'),
		'Asian Studies': require('../../mockups/asian studies')
	},
	degree: {
		'Bachelor of Arts': require('../../mockups/bachelor of music'),
		'Bachelor of Music': require('../../mockups/bachelor of arts')
	},
	concentration: {
		'Computer Science': require('../../mockups/csci'),
		'Asian Studies': require('../../mockups/asian studies')
	}
}

function findType(result, details) {
	if (_.isArray(details)) {
		return 'array'
	}
	else if (_.isUndefined(details) && _.isBoolean(result)) {
		return 'boolean'
	}
	else if (_.isPlainObject(details)) {
		if (_.every(details, _.isBoolean)) {
			return 'object/boolean'
		}
		else if (_.some(details, _.isNumber)) {
			return 'object/number'
		}
	}
	else {
		return null
	}
}

var AreaOfStudy = React.createClass({
	load: function() {
		var type = this.props.type
		var title = this.props.title

		var area = areas[type][title]

		if (typeof area === 'function') {
			area(this.props).bind(this)
				.then(function(results) {
					console.log('calculated ' + this.props.abbr + ' graduation possibility', results)
					this.setState({
						result: results
					})
				})
		} else {
			this.setState({
				result: {
					result: false,
					details: [{
						title: this.props.type + ' not found!',
						description: 'This ' + this.props.type + ' could not be found.',
						result: false
					}]
				}
			})
		}
	},
	getInitialState: function() {
		return {
			result: {
				result: false,
				details: []
			}
		}
	},
	componentWillReceiveProps: function() {
		this.load()
	},
	componentDidMount: function() {
		this.load()
	},
	render: function() {
		// console.log('area-of-study render')

		var requirementSets = _.map(this.state.result.details, function(reqset) {
			return RequirementSet({
				key: reqset.title,
				title: reqset.title,
				description: reqset.description,
				type: findType(reqset.result, reqset.details),
				result: reqset.result,
				details: reqset.details || null
			});
		}, this);

		var results = _.chain(this.state.result.details)
			.flatten()
			.toArray()
			.pluck('result')
			.value()

		// TODO: Use the number of requirements, instead of the number of sections.

		var currentProgress = _.size(_.compact(results))
		var maxProgress = _.size(results)

		return React.DOM.article({id: this.props.id, className: 'area-of-study'},
			React.DOM.details(null,
				React.DOM.summary(null,
					React.DOM.h1(null, this.props.title),
					React.DOM.progress({value: currentProgress, max: maxProgress})
				),
				requirementSets
			)
		);
	}
});

module.exports = AreaOfStudy
<commit_msg>Fix a reversed array<commit_after>var _ = require('lodash');
var React = require('react');

var RequirementSet = require('./requirementSet');

var getRandomInt = require('../helpers/getRandomInt')

var areas = {
	major: {
		'Computer Science': require('../../mockups/csci'),
		'Asian Studies': require('../../mockups/asian studies')
	},
	degree: {
		'Bachelor of Arts': require('../../mockups/bachelor of arts'),
		'Bachelor of Music': require('../../mockups/bachelor of music')
	},
	concentration: {
		'Computer Science': require('../../mockups/csci'),
		'Asian Studies': require('../../mockups/asian studies')
	}
}

function findType(result, details) {
	if (_.isArray(details)) {
		return 'array'
	}
	else if (_.isUndefined(details) && _.isBoolean(result)) {
		return 'boolean'
	}
	else if (_.isPlainObject(details)) {
		if (_.every(details, _.isBoolean)) {
			return 'object/boolean'
		}
		else if (_.some(details, _.isNumber)) {
			return 'object/number'
		}
	}
	else {
		return null
	}
}

var AreaOfStudy = React.createClass({
	load: function() {
		var type = this.props.type
		var title = this.props.title

		var area = areas[type][title]

		if (typeof area === 'function') {
			area(this.props).bind(this)
				.then(function(results) {
					console.log('calculated ' + this.props.abbr + ' graduation possibility', results)
					this.setState({
						result: results
					})
				})
		} else {
			this.setState({
				result: {
					result: false,
					details: [{
						title: this.props.type + ' not found!',
						description: 'This ' + this.props.type + ' could not be found.',
						result: false
					}]
				}
			})
		}
	},
	getInitialState: function() {
		return {
			result: {
				result: false,
				details: []
			}
		}
	},
	componentWillReceiveProps: function() {
		this.load()
	},
	componentDidMount: function() {
		this.load()
	},
	render: function() {
		// console.log('area-of-study render')

		var requirementSets = _.map(this.state.result.details, function(reqset) {
			return RequirementSet({
				key: reqset.title,
				title: reqset.title,
				description: reqset.description,
				type: findType(reqset.result, reqset.details),
				result: reqset.result,
				details: reqset.details || null
			});
		}, this);

		var results = _.chain(this.state.result.details)
			.flatten()
			.toArray()
			.pluck('result')
			.value()

		// TODO: Use the number of requirements, instead of the number of sections.

		var currentProgress = _.size(_.compact(results))
		var maxProgress = _.size(results)

		return React.DOM.article({id: this.props.id, className: 'area-of-study'},
			React.DOM.details(null,
				React.DOM.summary(null,
					React.DOM.h1(null, this.props.title),
					React.DOM.progress({value: currentProgress, max: maxProgress})
				),
				requirementSets
			)
		);
	}
});

module.exports = AreaOfStudy
<|endoftext|>