<commit_before>define([
	"intern!tdd",
	"intern/assert",
	"dgrid/OnDemandList",
	"dgrid/OnDemandGrid",
	"dgrid/Keyboard",
	"dojo/_base/declare",
	"dojo/on",
	"dojo/query",
	"put-selector/put",
	"dgrid/test/data/base"
], function(test, assert, OnDemandList, OnDemandGrid, Keyboard, declare, on, query, put){
	var handles = [],
		columns = {
			col1: "Column 1",
			col3: "Column 3",
			col5: "Column 5"
		},
		grid;

	function destroyGrid(){
		grid.destroy();
	}

	function removeHandles(){
		for(var i = handles.length; i--;){
			handles[i].remove && handles[i].remove();
		}
		handles = [];
	}

	// Common test functions for grid w/ cellNavigation: false and list

	function testRowFocus(){
		var rowId;
		// listen for a dgrid-cellfocusin event
		handles.push(on(document.body, "dgrid-cellfocusin", function(e){
			assert.ok(e.row, "dgrid-cellfocusin event got a non-null row value");
			rowId = e.row.id;
		}));
		// trigger a focus with no argument, which should focus the first row
		grid.focus();
		// XXX: dgrid/List#row returns string ID when looking up DOM node
		assert.strictEqual(rowId, "0",
			"dgrid-cellfocusin event triggered on first row on focus() call");
	}

	function testRowFocusArgs(){
		var rowId;
		// listen for a dgrid-cellfocusin event
		handles.push(on(document.body, "dgrid-cellfocusin", function(e){
			assert.ok(e.row, "dgrid-cellfocusin event got a non-null row value");
			rowId = e.row.id;
		}));
		// trigger a body focus with the second row as the target
		grid.focus(query(".dgrid-row", grid.contentNode)[1]);
		// make sure we got the right row
		assert.strictEqual(rowId, "1",
			"dgrid-cellfocusin event triggered on expected row");
	}

	function testRowBlur(){
		var blurredRow,
			targets = query(".dgrid-row", grid.contentNode);

		// call one focus event, followed by a subsequent focus event,
		// thus triggering a dgrid-cellfocusout event
		grid.focus(targets[0]);

		// listen for a dgrid-cellfocusout event
		handles.push(on(document.body, "dgrid-cellfocusout", function(e){
			blurredRow = e.row;
			assert.ok(blurredRow, "dgrid-cellfocusout event got a non-null row value");
		}));

		grid.focus(targets[1]);
		// make sure our handler was called
		assert.strictEqual(blurredRow && blurredRow.id, "0",
			"dgrid-cellfocusout event triggered on expected row");
	}

	test.suite("Keyboard (Grid + cellNavigation:true)", function(){
		test.before(function(){
			grid = new (declare([OnDemandGrid, Keyboard]))({
				store: testStore,
				columns: columns
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		test.afterEach(removeHandles);
		test.after(destroyGrid);

		test.test("grid.focus + no args", function(){
			var colId;
			// listen for a dgrid-cellfocusin event
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				colId = e.cell.column.id;
			}));
			// trigger a focus with no argument, which should focus the first cell
			grid.focus();
			assert.strictEqual(colId, "col1",
				"dgrid-cellfocusin event triggered on first cell on focus() call");
		});

		test.test("grid.focusHeader + no args", function(){
			var colId;
			// listen for a dgrid-cellfocusin event (header triggers same event)
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				assert.ok(!e.row, "dgrid-cellfocusin event for header got a falsy row value");
				colId = e.cell.column.id;
			}));
			// trigger a header focus with no argument, which should focus the first cell
			grid.focusHeader();
			assert.strictEqual(colId, "col1",
				"dgrid-cellfocusin event triggered on first cell on focusHeader() call");
		});

		test.test("grid.focus + args", function(){
			var focusedCell;
			// listen for a dgrid-cellfocusin event
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				focusedCell = e.cell;
			}));
			// trigger a body focus with the second cell as the target
			grid.focus(query(".dgrid-cell", grid.contentNode)[1]);
			// make sure our handler was called appropriately
			assert.ok(focusedCell, "dgrid-cellfocusin event fired");
			assert.strictEqual(focusedCell.row.id, "0",
				"dgrid-cellfocusin event triggered on expected row");
			assert.strictEqual(focusedCell.column.id, "col3",
				"dgrid-cellfocusin event triggered on second cell on focus(...) call");
		});

		test.test("grid.focusHeader + args", function(){
			var colId;
			// listen for a dgrid-cellfocusin event (header triggers same event)
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				assert.ok(!e.row, "dgrid-cellfocusin event for header got a falsy row value");
				colId = e.cell.column.id;
			}));
			// trigger a focus on the first header cell
			grid.focus(query(".dgrid-cell", grid.headerNode)[1]);
			// make sure we got the right header cell
			assert.strictEqual(colId, "col3", "dgrid-cellfocusin event triggered on expected header cell");
		});

		test.test("dgrid-cellfocusout event", function(){
			var blurredCell,
				targets = query(".dgrid-cell", grid.contentNode);

			// call one focus event, followed by a subsequent focus event,
			// thus triggering a dgrid-cellfocusout event
			grid.focus(targets[0]);

			// listen for a dgrid-cellfocusout event
			handles.push(on(document.body, "dgrid-cellfocusout", function(e){
				blurredCell = e.cell;
				assert.ok(blurredCell, "dgrid-cellfocusout event got a non-null cell value");
			}));

			grid.focus(targets[1]);
			// make sure our handler was called appropriately
			assert.ok(blurredCell, "dgrid-cellfocusout event fired");
			assert.strictEqual(blurredCell.row.id, "0",
				"dgrid-cellfocusout event triggered on expected row");
			assert.strictEqual(blurredCell.column.id, "col1",
				"dgrid-cellfocusout event triggered on expected column");
		});
	});

	test.suite("Keyboard (Grid + cellNavigation:false)", function(){
		test.before(function(){
			grid = new (declare([OnDemandGrid, Keyboard]))({
				store: testStore,
				columns: columns,
				cellNavigation: false
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		test.afterEach(removeHandles);
		test.after(destroyGrid);

		test.test("grid.focus + no args", testRowFocus);
		test.test("grid.focus + args", testRowFocusArgs);
		test.test("dgrid-cellfocusout event", testRowBlur);
	});

	test.suite("Keyboard (List)", function(){
		test.before(function(){
			grid = new (declare([OnDemandList, Keyboard]))({
				store: testStore,
				renderRow: function(item){ return put("div", item.col5); }
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		test.afterEach(removeHandles);
		test.after(destroyGrid);

		test.test("list.focus + no args", testRowFocus);
		test.test("list.focus + args", testRowFocusArgs);
		test.test("dgrid-cellfocusout event", testRowBlur);
	});
});<commit_msg>Add Keyboard tests for focus after item updates<commit_after>define([
	"intern!tdd",
	"intern/assert",
	"dgrid/OnDemandList",
	"dgrid/OnDemandGrid",
	"dgrid/Keyboard",
	"dojo/_base/declare",
	"dojo/on",
	"dojo/query",
	"put-selector/put",
	"dgrid/test/data/base"
], function(test, assert, OnDemandList, OnDemandGrid, Keyboard, declare, on, query, put){
	var handles = [],
		columns = {
			col1: "Column 1",
			col3: "Column 3",
			col5: "Column 5"
		},
		item = testStore.get(1),
		grid;

	// Common functions run after each test and suite

	function afterEach(){
		for(var i = handles.length; i--;){
			handles[i].remove && handles[i].remove();
		}
		handles = [];
	}

	function after(){
		// Destroy list or grid
		grid.destroy();
		// Restore item that was removed for focus retention test
		testStore.put(item);
	}

	// Common test functions for grid w/ cellNavigation: false and list

	function testRowFocus(){
		var rowId;
		// listen for a dgrid-cellfocusin event
		handles.push(on(document.body, "dgrid-cellfocusin", function(e){
			assert.ok(e.row, "dgrid-cellfocusin event got a non-null row value");
			rowId = e.row.id;
		}));
		// trigger a focus with no argument, which should focus the first row
		grid.focus();
		// XXX: dgrid/List#row returns string ID when looking up DOM node
		assert.strictEqual(document.activeElement, query(".dgrid-row", grid.contentNode)[0],
			"focus() targeted the first row");
		assert.strictEqual(rowId, "0",
			"dgrid-cellfocusin event triggered on first row on focus() call");
	}

	function testRowFocusArgs(){
		var rowId, target;
		// listen for a dgrid-cellfocusin event
		handles.push(on(document.body, "dgrid-cellfocusin", function(e){
			assert.ok(e.row, "dgrid-cellfocusin event got a non-null row value");
			rowId = e.row.id;
		}));
		// trigger a body focus with the second row as the target
		target = query(".dgrid-row", grid.contentNode)[1];
		grid.focus(target);
		// make sure we got the right row
		assert.strictEqual(document.activeElement, target,
			"focus(...) targeted the expected row");
		assert.strictEqual(rowId, "1",
			"dgrid-cellfocusin event triggered on expected row");
	}

	function testRowBlur(){
		var blurredRow,
			targets = query(".dgrid-row", grid.contentNode);

		// call one focus event, followed by a subsequent focus event,
		// thus triggering a dgrid-cellfocusout event
		grid.focus(targets[0]);

		// listen for a dgrid-cellfocusout event
		handles.push(on(document.body, "dgrid-cellfocusout", function(e){
			blurredRow = e.row;
			assert.ok(blurredRow, "dgrid-cellfocusout event got a non-null row value");
		}));

		grid.focus(targets[1]);
		// make sure our handler was called
		assert.strictEqual(blurredRow && blurredRow.id, "0",
			"dgrid-cellfocusout event triggered on expected row");
	}

	function testRowUpdate(){
		var element, elementId;
		// Focus a row based on a store ID, then issue an update and make sure
		// the same id is still focused
		grid.focus(1);

		element = document.activeElement;
		assert.ok(element && element.className && element.className.indexOf("dgrid-row") > -1,
			"focus(id) call focused a row");

		elementId = element.id;
		grid.store.put(item);
		assert.notStrictEqual(element, document.activeElement,
			"A different DOM element is focused after updating the item");
		assert.strictEqual(elementId, document.activeElement.id,
			"The item's new row is focused after updating the item");
	}

	function testRowRemove(){
		var dfd = this.async(1000),
			element,
			nextElement;

		// Focus a row based on a store ID, then remove the item and
		// make sure the corresponding cell is eventually focused
		grid.focus(1);

		element = document.activeElement;
		assert.ok(element && element.className && element.className.indexOf("dgrid-row") > -1,
			"focus(id) call focused a row");

		nextElement = element.nextSibling;
		grid.store.remove(1);

		// The logic responsible for moving to the next row runs on next turn,
		// since it operates as a fallback that is run only if a replacement
		// is not immediately inserted.  Therefore we need to execute our
		// assertions on the next turn as well.
		setTimeout(dfd.callback(function(){
			assert.strictEqual(nextElement, document.activeElement,
				"The next row is focused after removing the item");
		}), 0);

		return dfd;
	}

	function registerRowTests(name) {
		test.afterEach(afterEach);
		test.after(after);

		test.test(name + ".focus + no args", testRowFocus);
		test.test(name + ".focus + args", testRowFocusArgs);
		test.test("dgrid-cellfocusout event", testRowBlur);
		test.test(name + ".focus + item update", testRowUpdate);
		test.test(name + ".focus + item removal", testRowRemove);
	}

	test.suite("Keyboard (Grid + cellNavigation:true)", function(){
		test.before(function(){
			grid = new (declare([OnDemandGrid, Keyboard]))({
				columns: columns,
				sort: "id",
				store: testStore
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		test.afterEach(afterEach);
		test.after(after);

		test.test("grid.focus + no args", function(){
			var colId;
			// listen for a dgrid-cellfocusin event
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				colId = e.cell.column.id;
			}));
			// trigger a focus with no argument, which should focus the first cell
			grid.focus();
			assert.strictEqual(document.activeElement, query(".dgrid-cell", grid.contentNode)[0],
				"focus() targeted the first cell");
			assert.strictEqual(colId, "col1",
				"dgrid-cellfocusin event triggered on first cell on focus() call");
		});

		test.test("grid.focusHeader + no args", function(){
			var colId;
			// listen for a dgrid-cellfocusin event (header triggers same event)
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				assert.ok(!e.row, "dgrid-cellfocusin event for header got a falsy row value");
				colId = e.cell.column.id;
			}));
			// trigger a header focus with no argument, which should focus the first cell
			grid.focusHeader();
			assert.strictEqual(document.activeElement, query(".dgrid-cell", grid.headerNode)[0],
				"focus() targeted the first header cell");
			assert.strictEqual(colId, "col1",
				"dgrid-cellfocusin event triggered on first cell on focusHeader() call");
		});

		test.test("grid.focus + args", function(){
			var focusedCell, target;
			// listen for a dgrid-cellfocusin event
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				focusedCell = e.cell;
			}));
			// trigger a body focus with the second cell as the target
			target = query(".dgrid-cell", grid.contentNode)[1];
			grid.focus(target);
			assert.strictEqual(document.activeElement, target,
				"focus(...) targeted the expected cell");
			assert.ok(focusedCell, "dgrid-cellfocusin event fired");
			assert.strictEqual(focusedCell.row.id, "0",
				"dgrid-cellfocusin event triggered on expected row");
			assert.strictEqual(focusedCell.column.id, "col3",
				"dgrid-cellfocusin event triggered on second cell on focus(...) call");
		});

		test.test("grid.focusHeader + args", function(){
			var colId, target;
			// listen for a dgrid-cellfocusin event (header triggers same event)
			handles.push(on(document.body, "dgrid-cellfocusin", function(e){
				assert.ok(e.cell, "dgrid-cellfocusin event got a non-null cell value");
				assert.ok(!e.row, "dgrid-cellfocusin event for header got a falsy row value");
				colId = e.cell.column.id;
			}));
			// trigger a focus on the first header cell
			target = query(".dgrid-cell", grid.headerNode)[1];
			grid.focus(target);
			assert.strictEqual(document.activeElement, target,
				"focusHeader(...) targeted the expected cell");
			assert.strictEqual(colId, "col3", "dgrid-cellfocusin event triggered on expected header cell");
		});

		test.test("dgrid-cellfocusout event", function(){
			var blurredCell,
				targets = query(".dgrid-cell", grid.contentNode);

			// call one focus event, followed by a subsequent focus event,
			// thus triggering a dgrid-cellfocusout event
			grid.focus(targets[0]);

			// listen for a dgrid-cellfocusout event
			handles.push(on(document.body, "dgrid-cellfocusout", function(e){
				blurredCell = e.cell;
				assert.ok(blurredCell, "dgrid-cellfocusout event got a non-null cell value");
			}));

			grid.focus(targets[1]);
			// make sure our handler was called appropriately
			assert.ok(blurredCell, "dgrid-cellfocusout event fired");
			assert.strictEqual(blurredCell.row.id, "0",
				"dgrid-cellfocusout event triggered on expected row");
			assert.strictEqual(blurredCell.column.id, "col1",
				"dgrid-cellfocusout event triggered on expected column");
		});

		test.test("grid.focus + item update", function(){
			var element, elementId;
			// Focus a row based on a store ID + column ID,
			// then issue an update and make sure the same id is still focused
			grid.focus(grid.cell(1, "col1"));

			element = document.activeElement;
			assert.ok(element && element.className && element.className.indexOf("dgrid-cell") > -1,
				"focus(id) call focused a cell");

			elementId = element.id;
			grid.store.put(item);
			assert.notStrictEqual(element, document.activeElement,
				"A different DOM element is focused after updating the item");
			assert.strictEqual(grid.cell(1, "col1").element, document.activeElement,
				"The item's new cell is focused after updating the item");
		});

		test.test("grid.focus + item removal", function(){
			var dfd = this.async(1000),
				element,
				nextElement;

			// Focus a cell based on a store ID, then remove the item and
			// make sure the corresponding cell is eventually focused
			grid.focus(grid.cell(1, "col1"));

			element = document.activeElement;
			assert.ok(element && element.className && element.className.indexOf("dgrid-cell") > -1,
				"focus(id) call focused a cell");

			nextElement = grid.cell(2, "col1").element;
			grid.store.remove(1);

			// The logic responsible for moving to the next row runs on next turn,
			// since it operates as a fallback that is run only if a replacement
			// is not immediately inserted.  Therefore we need to execute our
			// assertions on the next turn as well.
			setTimeout(dfd.callback(function(){
				assert.strictEqual(nextElement, document.activeElement,
					"The next row is focused after removing the item");
			}), 0);

			return dfd;
		});
	});

	test.suite("Keyboard (Grid + cellNavigation:false)", function(){
		test.before(function(){
			grid = new (declare([OnDemandGrid, Keyboard]))({
				cellNavigation: false,
				columns: columns,
				sort: "id",
				store: testStore
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		registerRowTests("grid");
	});

	test.suite("Keyboard (List)", function(){
		test.before(function(){
			grid = new (declare([OnDemandList, Keyboard]))({
				sort: "id",
				store: testStore,
				renderRow: function(item){ return put("div", item.col5); }
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
		});

		registerRowTests("list");
	});
});<|endoftext|>


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

function Input({
  type, value, onChangeValue, long, choices, ...rest
}) {
  const onChange = (event) => {
    const { target } = event;

    onChangeValue((typeof target.value !== 'undefined') ? target.value : target.checked);

    if (!!rest.onChange) {
      rest.onChange(event);
    }
  }

  if (type === 'boolean') {
    return (
      <input type={ type } checked={ value } { ...rest } onChange={ onChange } />
    );
  }
  else if (type === 'choice') {
    return (
      <select value={ value } { ...rest } onChange={ onChange }>
        { choices.map(choice =>
          <option key={ choice.id } value={ choice.id }>{ choice.title }</option>
        ) }
      </select>
    );
  }
  else {
    if (long) {
      return (
        <textarea value={ value } rows={ 6 } { ...rest } onChange={ onChange } />
      );
    } else {
      return (
        <input type={ type } value={ value } { ...rest } onChange={ onChange } />
      );
    }
  }
}

function Label({
  title, description, children, required = false, recommended = false, showAfterChildren = false
}) {
  if (required) {
		title += ' (required)'
	}
	else if (recommended) {
		title += ' (recommended)'
	}

  let elements = [];

	elements.push(

      { title }

	);

	if (description) {
    elements.push(

        { description }

		);
	}

  children = (showAfterChildren) ? (
    children.concat(elements)
  ) : (
    elements.concat(children)
  );

	return (
    { children }
	);
}

export default function Field({
  type,
  title,
  description,
  required,
  recommended,
  tabIndex,
  onChangeValue,
  ...rest
}) {
  return (

      <Input
        type={ type }
        { ...rest }
        onChangeValue={ onChangeValue }
      />

  );
};
<commit_msg>Fix type for DefaultField’s boolean<commit_after>import React, { PropTypes } from 'react';

function Input({
  type, value, onChangeValue, long, choices, ...rest
}) {
  const onChange = (event) => {
    const { target } = event;

    onChangeValue((typeof target.value !== 'undefined') ? target.value : target.checked);

    if (!!rest.onChange) {
      rest.onChange(event);
    }
  }

  if (type === 'boolean') {
    return (
      <input type='checkbox' checked={ value } { ...rest } onChange={ onChange } />
    );
  }
  else if (type === 'choice') {
    return (
      <select value={ value } { ...rest } onChange={ onChange }>
        { choices.map(choice =>
          <option key={ choice.id } value={ choice.id }>{ choice.title }</option>
        ) }
      </select>
    );
  }
  else {
    if (long) {
      return (
        <textarea value={ value } rows={ 6 } { ...rest } onChange={ onChange } />
      );
    } else {
      return (
        <input type={ type } value={ value } { ...rest } onChange={ onChange } />
      );
    }
  }
}

function Label({
  title, description, children, required = false, recommended = false, showAfterChildren = false
}) {
  if (required) {
		title += ' (required)'
	}
	else if (recommended) {
		title += ' (recommended)'
	}

  let elements = [];

	elements.push(

      { title }

	);

	if (description) {
    elements.push(

        { description }

		);
	}

  children = (showAfterChildren) ? (
    children.concat(elements)
  ) : (
    elements.concat(children)
  );

	return (
    { children }
	);
}

export default function Field({
  type,
  title,
  description,
  required,
  recommended,
  tabIndex,
  onChangeValue,
  ...rest
}) {
  return (

      <Input
        type={ type }
        { ...rest }
        onChangeValue={ onChangeValue }
      />

  );
};
<|endoftext|>


<commit_before>import React from 'react'
import ReactHighcharts from 'react-highcharts';

import './styles.css'

// drilldown WIP
const buildDrillDown = () => {
  return {
    series: []
  }
}

const chartConfig = (voteSummary) => {
    return {
    chart: {
        backgroundColor: 'transparent',
        type: 'pie'
    },
    title: {
      text: ''
    },
    subtitle: {
      text: ''
    },
    plotOptions: {
      series: {
        dataLabels: {
          enabled: false,
          format: '{point.name}: {point.y:.1f}%'
        }
      }
    },
    tooltip: {
      headerFormat: '{series.name}
',
      pointFormat: '{point.y:.2f}% {point.name} ({point.amount} atkvæði)
'
    },
    series: [{
      name: voteSummary.name,
      data: [{
        amount: parseInt(voteSummary.voteSummary.numberOfStandsTaken, 10),
        color: 'lightgreen',
        name: 'afstaða tekin',
        y: parseFloat(voteSummary.votePercentages.standsTaken)
      }, {
        amount: parseInt(voteSummary.voteSummary.numberOfIdleVotes, 10),
        color: 'lightgrey',
        name: 'hlutleysi',
        y: parseFloat(voteSummary.votePercentages.idle)
      }, {
        amount: parseInt(voteSummary.voteSummary.numberOfAway, 10),
        color: 'salmon',
        name: 'fjarverandi',
        y: parseFloat(voteSummary.votePercentages.away)
      }]
    }],
    drilldown: buildDrillDown()
  };
};

const Piechart = ({
  voteSummary
}) => {
  return (

{voteSummary.voteSummary.numberOfVotes} atkvæði

        <ReactHighcharts config={ chartConfig(voteSummary) }></ReactHighcharts>

◼ afstaða tekin

◼ hlutleysi

◼ fjarverandi

  )
}

Piechart.propTypes = {
  voteSummary: React.PropTypes.object
}

export default Piechart
<commit_msg>weird utf-8 bug - mobile safari f**ks up the 1st two squares<commit_after>import React from 'react'
import ReactHighcharts from 'react-highcharts';

import './styles.css'

// drilldown WIP
const buildDrillDown = () => {
  return {
    series: []
  }
}

const chartConfig = (voteSummary) => {
    return {
    chart: {
        backgroundColor: 'transparent',
        type: 'pie'
    },
    title: {
      text: ''
    },
    subtitle: {
      text: ''
    },
    plotOptions: {
      series: {
        dataLabels: {
          enabled: false,
          format: '{point.name}: {point.y:.1f}%'
        }
      }
    },
    tooltip: {
      headerFormat: '{series.name}
',
      pointFormat: '{point.y:.2f}% {point.name} ({point.amount} atkvæði)
'
    },
    series: [{
      name: voteSummary.name,
      data: [{
        amount: parseInt(voteSummary.voteSummary.numberOfStandsTaken, 10),
        color: 'lightgreen',
        name: 'afstaða tekin',
        y: parseFloat(voteSummary.votePercentages.standsTaken)
      }, {
        amount: parseInt(voteSummary.voteSummary.numberOfIdleVotes, 10),
        color: 'lightgrey',
        name: 'hlutleysi',
        y: parseFloat(voteSummary.votePercentages.idle)
      }, {
        amount: parseInt(voteSummary.voteSummary.numberOfAway, 10),
        color: 'salmon',
        name: 'fjarverandi',
        y: parseFloat(voteSummary.votePercentages.away)
      }]
    }],
    drilldown: buildDrillDown()
  };
};

const Piechart = ({
  voteSummary
}) => {
  return (

{voteSummary.voteSummary.numberOfVotes} atkvæði

        <ReactHighcharts config={ chartConfig(voteSummary) }></ReactHighcharts>

◼ afstaða tekin

◼ hlutleysi

◼ fjarverandi

  )
}

Piechart.propTypes = {
  voteSummary: React.PropTypes.object
}

export default Piechart
<|endoftext|>


<commit_before>var Reader = require('../lib/reader');
var moment = require('moment');
var Q = require('q');

var day_range = 2;  // 7 days
var parallel_count = 10;
var interval = 30 * 1000;
var system_count = 1000;

var calcSum = function (obj){
	var count = 0;
	for (var key in obj){
		count += obj[key].length;
	}

	return count;
}

var ReadOne = function (topic_name){
	return Q.Promise(function (resolve, reject){
		var reader = new Reader(topic_name);

		var start = Date.now();
		var query_start = moment()-moment.duration(day_range, "days")
		var query_end = moment().valueOf();

		reader.readRaw(query_start, query_end, function (err, data){
			var end = Date.now();
			if (err){
				console.log("Read %s error: %s.", topic_name, err);
				reject(err);
			}
			else {
				console.log("Read %s, %s records, cost:%s ms.", topic_name, calcSum(data), (end - start));
				resolve();
			}
		});
	});
}

var doRead = function (){
	var callbacks = [];
	for (var i=0; i<parallel_count; i++){
		var topic = "system_" + Math.floor(Math.random()*system_count);
		callbacks.push(ReadOne(topic));
	}

	Q.allSettled(callbacks).then(function (results){
		console.log(results[0].state)
		console.log("=====================================");
	});
}

var run = function (){
	doRead();
	setInterval(doRead, interval);
}

run();<commit_msg>read bench<commit_after>var Reader = require('../lib/reader');
var moment = require('moment');
var Q = require('q');

var day_range = 6;  // 7 days
var parallel_count = 10;
var interval = 30 * 1000;
var system_count = 1000;
var field_names = ["a_1", "d_1", "a_11", "d_11", "a_100", "d_100"]

var calcSum = function (obj){
	var count = 0;
	for (var key in obj){
		count += obj[key].length;
	}

	return count;
}

var ReadOne = function (topic_name){
	return Q.Promise(function (resolve, reject){
		var reader = new Reader(topic_name);

		var start = Date.now();
		var query_start = moment()-moment.duration(day_range, "days")
		var query_end = moment().valueOf();

		reader.readRaw(query_start, query_end, function (err, data){
			var end = Date.now();
			if (err){
				console.log("Read %s error: %s.", topic_name, err);
				reject(err);
			}
			else {
				console.log("Read %s, %s records, cost:%s ms.", topic_name, calcSum(data), (end - start));
				resolve();
			}
		});
	});
}

var doRead = function (){
	var callbacks = [];
	for (var i=0; i<parallel_count; i++){
		var topic = "system_" + Math.floor(Math.random()*system_count);
		callbacks.push(ReadOne(topic));
	}

	Q.allSettled(callbacks).then(function (results){
		console.log(results[0].state)
		console.log("=====================================");
	});
}

var run = function (){
	doRead();
	setInterval(doRead, interval);
}

run();<|endoftext|>


<commit_before>(function (window, Cryptoloji, undefined) {
  'use strict'

  Cryptoloji.states.loading = {
    enter: function () {
      $(".section_loading").addClass("section-show")
      Cryptoloji.stateman.emit('header:hide')

      $( ".section_loading_wrapper" ).load( "assets/svg/loading.svg", function() {
        svgTransition()
      })
      setTimeout(function(){
        Cryptoloji.stateman.go('home')
      }, 5800)
    },
    leave: function () {
      $(".section_loading").removeClass("section-show")
    }
  }

  function svgTransition(){

    var callbacks = $.Callbacks()

    function animate_async(item_class, element_time, delay, value) {
      $(item_class).each(function(i) {
        var j=($(item_class).length-1) - i
        TweenLite.to($(this), element_time, {delay: element_time * j + delay, opacity: value})
      })
    }

    callbacks.add(animate_async)
    callbacks.fire('.emoji_item', 0, 0, '0');
    callbacks.fire('.loading_text_black', 0, 0, '0')
    callbacks.fire('.loading_text_gray', 0, 0, '0')
    callbacks.fire('.loading_text_gray', .07, 0, '1')
    callbacks.fire('.loading_text_black', .07, .8, '1')
    callbacks.fire('.letter_t', 0, 2.5, '0')
    callbacks.fire('.emoji_t', 0, 2.55, '1')
    callbacks.fire('.letter_i', 0, 2, '0')
    callbacks.fire('.emoji_i', 0.05, 2, '1' )
    callbacks.fire('.letter_o', 0, 2.3, 0)
    callbacks.fire('.emoji_o', 0.05, 2.3, '1')
    callbacks.fire('.letter_s', 0, 2.7, '0')
    callbacks.fire('.emoji_s', 0.05, 2.7, '1')
    callbacks.fire('.letter_c', 0, 3.4, '0')
    callbacks.fire('.emoji_c', 0.05, 3.4, '1')
    callbacks.fire('.letter_r', 0, 3.3, '0')
    callbacks.fire('.emoji_r', 0.05, 3.3, '1')
    callbacks.fire('.letter_j', 0, 3.2, '0')
    callbacks.fire('.emoji_j', 0.05, 3.2, '1')
    callbacks.fire('.letter_p', 0, 3.1, '0')
    callbacks.fire('.emoji_p', 0.05, 3.1, '1')
    callbacks.fire('.letter_y', 0, 3.0, '0')
    callbacks.fire('.emoji_y', 0.05, 3.0, '1')
    callbacks.fire('.letter_h', 0, 2.9, '0')
    callbacks.fire('.emoji_h', 0.05, 2.9, '1')
    callbacks.fire('.letter_l', 0, 2.8, '0')
    callbacks.fire('.emoji_l', 0.05, 2.8, '1')
    callbacks.fire('.emoji_item', 0.1, 4, '0')
  }
})(window, window.Cryptoloji)

<commit_msg>jump to encrypt status after onboarding<commit_after>(function (window, Cryptoloji, undefined) {
  'use strict'

  Cryptoloji.states.loading = {
    enter: function () {
      $(".section_loading").addClass("section-show")
      Cryptoloji.stateman.emit('header:hide')

      $( ".section_loading_wrapper" ).load( "assets/svg/loading.svg", function() {
        svgTransition()
      })
      setTimeout(function(){
        Cryptoloji.stateman.go('encrypt')
      }, 5800)
    },
    leave: function () {
      $(".section_loading").removeClass("section-show")
    }
  }

  function svgTransition(){

    var callbacks = $.Callbacks()

    function animate_async(item_class, element_time, delay, value) {
      $(item_class).each(function(i) {
        var j=($(item_class).length-1) - i
        TweenLite.to($(this), element_time, {delay: element_time * j + delay, opacity: value})
      })
    }

    callbacks.add(animate_async)
    callbacks.fire('.emoji_item', 0, 0, '0');
    callbacks.fire('.loading_text_black', 0, 0, '0')
    callbacks.fire('.loading_text_gray', 0, 0, '0')
    callbacks.fire('.loading_text_gray', .07, 0, '1')
    callbacks.fire('.loading_text_black', .07, .8, '1')
    callbacks.fire('.letter_t', 0, 2.5, '0')
    callbacks.fire('.emoji_t', 0, 2.55, '1')
    callbacks.fire('.letter_i', 0, 2, '0')
    callbacks.fire('.emoji_i', 0.05, 2, '1' )
    callbacks.fire('.letter_o', 0, 2.3, 0)
    callbacks.fire('.emoji_o', 0.05, 2.3, '1')
    callbacks.fire('.letter_s', 0, 2.7, '0')
    callbacks.fire('.emoji_s', 0.05, 2.7, '1')
    callbacks.fire('.letter_c', 0, 3.4, '0')
    callbacks.fire('.emoji_c', 0.05, 3.4, '1')
    callbacks.fire('.letter_r', 0, 3.3, '0')
    callbacks.fire('.emoji_r', 0.05, 3.3, '1')
    callbacks.fire('.letter_j', 0, 3.2, '0')
    callbacks.fire('.emoji_j', 0.05, 3.2, '1')
    callbacks.fire('.letter_p', 0, 3.1, '0')
    callbacks.fire('.emoji_p', 0.05, 3.1, '1')
    callbacks.fire('.letter_y', 0, 3.0, '0')
    callbacks.fire('.emoji_y', 0.05, 3.0, '1')
    callbacks.fire('.letter_h', 0, 2.9, '0')
    callbacks.fire('.emoji_h', 0.05, 2.9, '1')
    callbacks.fire('.letter_l', 0, 2.8, '0')
    callbacks.fire('.emoji_l', 0.05, 2.8, '1')
    callbacks.fire('.emoji_item', 0.1, 4, '0')
  }
})(window, window.Cryptoloji)
<|endoftext|>


<commit_before>var reducer = require('../../src/reducers/syncState');

describe('syncState', () => {

  it('should return the initial state', () => {
    expect(
      reducer(undefined, {})
    ).to.deep.equal({code: 0})
  })

  it('should not change the passed state', (done) => {

    const state = Object.freeze({});
    reducer(state, {type: 'INVALID'});

    done();
  });
});
<commit_msg>Updtaes the specification for the sync state reducer<commit_after>var reducer = require('../../src/reducers/syncState');

describe('syncState', () => {

  it('should return the initial state', () => {
    expect(
      reducer(undefined, {})
    ).to.deep.equal({code: 900})
  })

  it('should not change the passed state', (done) => {

    const state = Object.freeze({});
    reducer(state, {type: 'INVALID'});

    done();
  });
});
<|endoftext|>


<commit_before>var cssnext = require("./")
var t = require("microtime")
var assign = require("object-assign")

var input = require("fs").readFileSync("./test/fixtures/cases/example.css")

// test each features
var keys = Object.keys(cssnext.features)
var allOff = {}

keys.forEach(function(k) {
  allOff[k] = false
})

keys.forEach(function(k) {
  var enable = assign({}, allOff)
  enable[k] = true
  var start = t.now()
  cssnext(input, {features: enable})
  var stop = t.now()

  console.log(k + " takes " + ((stop - start) / 100000) + "s") // , enable)
})
<commit_msg>Fix sec display in benchmarks<commit_after>var cssnext = require("./")
var t = require("microtime")
var assign = require("object-assign")

var input = require("fs").readFileSync("./test/fixtures/cases/example.css")

// test each features
var keys = Object.keys(cssnext.features)
var allOff = {}

keys.forEach(function(k) {
  allOff[k] = false
})

keys.forEach(function(k) {
  var enable = assign({}, allOff)
  enable[k] = true
  var start = t.now()
  cssnext(input, {features: enable})
  var stop = t.now()

  console.log(k + " takes " + ((stop - start) / 1000000) + "s") // , enable)
})
<|endoftext|>


<commit_before>#!/usr/bin/env node
var configFile = process.argv[2];
var port = parseInt(process.argv[3], 10);

if (!configFile || !port) {
    console.error('Usage: bouncy [routes.json] [port]');
    process.exit(1);
}

var fs = require('fs');
var config = JSON.parse(fs.readFileSync(configFile));

var bouncy = require('bouncy');
bouncy(function (req, bounce) {
    var host = (req.headers.host || '').replace(/:\d+$/, '');
    var route = config[host] || config[''];

    if (Array.isArray(route)) {
        // jump to a random route on arrays
        route = route[Math.floor(Math.random() * route.length)];
    }

    req.on('error', function(err) {
        req.destroy();
    });

    if (typeof route === 'string') {
        var s = route.split(':');
        if (s[1]) {
            bounce(s[0], s[1]);
        }
        else {
            bounce(s);
        }
    }
    else if (route) {
        bounce(route);
    }
    else {
        var res = bounce.respond();
        res.statusCode = 404;
        res.write('no such host');
        res.end();
    }
}).listen(port);
<commit_msg>listen for errors on bounces in the cli tool<commit_after>#!/usr/bin/env node
var configFile = process.argv[2];
var port = parseInt(process.argv[3], 10);

if (!configFile || !port) {
    console.error('Usage: bouncy [routes.json] [port]');
    process.exit(1);
}

var fs = require('fs');
var config = JSON.parse(fs.readFileSync(configFile));

var bouncy = require('bouncy');
bouncy(function (req, bounce) {
    var host = (req.headers.host || '').replace(/:\d+$/, '');
    var route = config[host] || config[''];

    if (Array.isArray(route)) {
        // jump to a random route on arrays
        route = route[Math.floor(Math.random() * route.length)];
    }

    req.on('error', onerror);
    function onerror (err) { req.destroy() }

    if (typeof route === 'string') {
        var s = route.split(':');
        if (s[1]) {
            bounce(s[0], s[1]).on('error', onerror);
        }
        else {
            bounce(s).on('error', onerror);
        }
    }
    else if (route) {
        bounce(route).on('error', onerror);
    }
    else {
        var res = bounce.respond();
        res.statusCode = 404;
        res.write('no such host');
        res.end();
    }
}).listen(port);
<|endoftext|>


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

const style = {
  list: {
    selected: { bg: 'blue', bold: true },
  },
  focus: {
    border: { fg: 'cyan' },
  },
  blur: {
    border: { fg: 'white' },
  },
};

export default class TableList extends Component {

  static propTypes = {
    items: PropTypes.array.isRequired,
    // events
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    // actions
    onExecute: PropTypes.func,
  };

  constructor (props) {
    super(props);

    this.state = { focused: false };
  }

  focus () {
    this.refs.list.focus();
  }

  handleFocus () {
    this.setState({ focused: true });
    if (this.props.onFocus) this.props.onFocus(this);
  }

  handleBlur () {
    this.setState({ focused: false });
    if (this.props.onBlur) this.props.onBlur(this);
  }

  handleKeypress (ch, key) {
    const { onExecute, items } = this.props;

    switch (key.full) {
    case 'enter': {
      if (onExecute && items && items.length) {
        onExecute(items[this.refs.list.selected]);
      }
      break;
    }
    default: return;
    }
  }

  render () {
    const { items } = this.props;
    return (
      <list
        ref="list"
        keys="true"
        mouse="true"
        border="line"
        label="Tables"
        scrollbar={{
          ch: 'x',
          track: { bg: 'cyan' },
          style: { inverse: true },
        }}
        style={{ ...style.list, ...(this.state.focused ? style.focus : style.blur)}}
        onFocus={::this.handleFocus}
        onBlur={::this.handleBlur}
        onKeypress={::this.handleKeypress}
        items={items}
      />
    );
  }

}
<commit_msg>Add support to Shortcuts smart component<commit_after>import React, { Component, PropTypes } from 'react';

const style = {
  list: {
    selected: { bg: 'blue', bold: true },
  },
  focus: {
    border: { fg: 'cyan' },
  },
  blur: {
    border: { fg: 'white' },
  },
};

export default class TableList extends Component {

  static propTypes = {
    items: PropTypes.array.isRequired,
    // events
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onKeypress: PropTypes.func,
  };

  constructor (props) {
    super(props);

    this.state = { focused: false };
  }

  selected () {
    if (this.refs.list) return this.refs.list.selected;
    return 0;
  }

  focus () {
    this.refs.list.focus();
  }

  handleFocus () {
    this.setState({ focused: true });
    if (this.props.onFocus) this.props.onFocus();
  }

  handleBlur () {
    this.setState({ focused: false });
    if (this.props.onBlur) this.props.onBlur();
  }

  handleKeypress (ch, key) {
    if (this.props.onKeypress) this.props.onKeypress(ch, key);
  }

  render () {
    const { items } = this.props;
    return (
      <list
        ref="list"
        keys="true"
        mouse="true"
        border="line"
        label="Tables"
        scrollbar={{
          ch: 'x',
          track: { bg: 'cyan' },
          style: { inverse: true },
        }}
        style={{ ...style.list, ...(this.state.focused ? style.focus : style.blur)}}
        onFocus={::this.handleFocus}
        onBlur={::this.handleBlur}
        onKeypress={::this.handleKeypress}
        items={items}
      />
    );
  }

}
<|endoftext|>


<commit_before>var isAttending = function(value) {
  if (value === 'on') return true;
  return false;
}

$(document).ready(function() {
  // Handle Guest RSVP Form Submission
  var db = firebase.database();

  // Elements
  var guestForm = $('#guest-rsvp-form');
  var loadingMessage = $('.message.loading');
  var errorMessage = $('.message.error');
  var successMessage = $('.message.success');

  var messageDelay = 2000;

  // Message handlers
  var clearMessages = function() {
    errorMessage.removeClass('active');
    successMessage.removeClass('active');
    loadingMessage.removeClass('active');
  }

  var showLoading = function(message) {
    if (!message) {
      message = 'Confirming Your RSVP...';
    }
    loadingMessage.text(message);

    errorMessage.removeClass('active');
    successMessage.removeClass('active');
    loadingMessage.addClass('active');
  }

  var showError = function(message, disableDelay) {
    if (!message) {
      message = 'There was an error confirming your RSVP.';
    }
    errorMessage.text(message);

    var delay = messageDelay;
    if (disableDelay) { delay = 0; }

    setTimeout(function() {
      successMessage.removeClass('active');
      loadingMessage.removeClass('active');
      errorMessage.addClass('active');
    }, delay);
  }

  var showSuccess = function(message, disableDelay) {
    if (!message) {
      message = 'RSVP Confirmed!';
    }
    successMessage.text(message);

    var delay = messageDelay;
    if (disableDelay) { delay = 0; }

    setTimeout(function() {
      loadingMessage.removeClass('active');
      errorMessage.removeClass('active');
      successMessage.addClass('active');
    }, delay);
  }

  guestForm.submit(function(e) {
    e.preventDefault();

    // Serialize form data
    var data = $(this).serializeObject();
    var firstName = data['first-name'];
    var lastName = data['last-name'];
    var attendingCeremony = data['attending-ceremony'];
    var attendingReception = data['attending-reception'];
    var message = data['message'];
    // console.log('guestForm', data);
    console.log('firstName', firstName);
    console.log('lastName', lastName);
    console.log('attendingCeremony', attendingCeremony);
    console.log('attendingReception', attendingReception);
    console.log('message', message);

    // Get the fullName for this user
    var fullName = firstName.toLowerCase() + '-' + lastName.toLowerCase();
    console.log('fullName', fullName);

    if (!firstName) return showError('Please provide a first name.', true);
    if (!lastName) return showError('Please provide a last name.', true);

    // Show a loading message
    showLoading();

    // Check for if the fullName exists in our invited collection
    db.ref('invited/' + fullName).once('value').then(function(snap) {
      if (snap.exists()) {
        console.log('User exists in invite list. Add RSVP info.');

        // Create the payload of data for the user's RSVP
        var payload = {
          'first-name': firstName,
          'last-name': lastName,
          'attending-ceremony': isAttending(attendingCeremony),
          'attending-reception': isAttending(attendingReception),
          message: message,
        };

        // Persist the RSVP to the server
        // Check for if ref already exists before confirming it.
        db.ref('rsvp/' + fullName).once('value').then(function(snap) {
          if (snap.exists()) {
            console.log('RSVP already confirmed, show success message');
            showSuccess();
          } else {
            console.log('RSVP not created yet, create it.');
            db.ref('rsvp/' + fullName).set(payload).then(function(result) {
              console.log('RSVP successful', result);
              showSuccess();
            }).catch(function(error) {
              console.log('RSVP error', error);
              showError();
            });
          }
        });
      } else {
        console.log('User not invited. Throw error.');
        showError();
      }
    });
  });

  guestForm.on('keyup', function(e) {
    // Clear any messages that are currently being displayed
    clearMessages();
  });
});
<commit_msg>Removed console logs<commit_after>var isAttending = function(value) {
  if (value === 'on') return true;
  return false;
}

$(document).ready(function() {
  // Handle Guest RSVP Form Submission
  var db = firebase.database();

  // Elements
  var guestForm = $('#guest-rsvp-form');
  var loadingMessage = $('.message.loading');
  var errorMessage = $('.message.error');
  var successMessage = $('.message.success');

  var messageDelay = 2000;

  // Message handlers
  var clearMessages = function() {
    errorMessage.removeClass('active');
    successMessage.removeClass('active');
    loadingMessage.removeClass('active');
  }

  var showLoading = function(message) {
    if (!message) {
      message = 'Confirming Your RSVP...';
    }
    loadingMessage.text(message);

    errorMessage.removeClass('active');
    successMessage.removeClass('active');
    loadingMessage.addClass('active');
  }

  var showError = function(message, disableDelay) {
    if (!message) {
      message = 'There was an error confirming your RSVP.';
    }
    errorMessage.text(message);

    var delay = messageDelay;
    if (disableDelay) { delay = 0; }

    setTimeout(function() {
      successMessage.removeClass('active');
      loadingMessage.removeClass('active');
      errorMessage.addClass('active');
    }, delay);
  }

  var showSuccess = function(message, disableDelay) {
    if (!message) {
      message = 'RSVP Confirmed!';
    }
    successMessage.text(message);

    var delay = messageDelay;
    if (disableDelay) { delay = 0; }

    setTimeout(function() {
      loadingMessage.removeClass('active');
      errorMessage.removeClass('active');
      successMessage.addClass('active');
    }, delay);
  }

  guestForm.submit(function(e) {
    e.preventDefault();

    // Serialize form data
    var data = $(this).serializeObject();
    var firstName = data['first-name'];
    var lastName = data['last-name'];
    var attendingCeremony = data['attending-ceremony'];
    var attendingReception = data['attending-reception'];
    var message = data['message'];

    /* console.log('firstName', firstName);
    console.log('lastName', lastName);
    console.log('attendingCeremony', attendingCeremony);
    console.log('attendingReception', attendingReception);
    console.log('message', message);*/

    // Get the fullName for this user
    var fullName = firstName.toLowerCase() + '-' + lastName.toLowerCase();
    // console.log('fullName', fullName);

    if (!firstName) return showError('Please provide a first name.', true);
    if (!lastName) return showError('Please provide a last name.', true);

    // Show a loading message
    showLoading();

    // Check for if the fullName exists in our invited collection
    db.ref('invited/' + fullName).once('value').then(function(snap) {
      if (snap.exists()) {
        // console.log('User exists in invite list. Add RSVP info.');

        // Create the payload of data for the user's RSVP
        var payload = {
          'first-name': firstName,
          'last-name': lastName,
          'attending-ceremony': isAttending(attendingCeremony),
          'attending-reception': isAttending(attendingReception),
          message: message,
        };

        // Persist the RSVP to the server
        // Check for if ref already exists before confirming it.
        db.ref('rsvp/' + fullName).once('value').then(function(snap) {
          if (snap.exists()) {
            // console.log('RSVP already confirmed, show success message');
            showSuccess();
          } else {
            // console.log('RSVP not created yet, create it.');
            db.ref('rsvp/' + fullName).set(payload).then(function(result) {
              // console.log('RSVP successful', result);
              showSuccess();
            }).catch(function(error) {
              // console.log('RSVP error', error);
              showError();
            });
          }
        });
      } else {
        // console.log('User not invited. Throw error.');
        showError();
      }
    });
  });

  guestForm.on('keyup', function(e) {
    // Clear any messages that are currently being displayed
    clearMessages();
  });
});
<|endoftext|>


<commit_before>// Client-side code
/* jshint browser: true, jquery: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, trailing: true */
/* global io: true, console: true */

var main = function() {
    "use strict";

    //var socket = io.connect();
    var socket = io("/guesswhat");

    var gw = {
        landpage: {
            section: {
                navbar: "",
                content: {
                    canvasDiv: "#divCanvas",
                    chatform: {
                        handle: "#gwChatForm",
                        field: {
                            sendButton: "#gwChatButton"
                        }
                    },
                    hintCard: {
                        handle: "#hintCard",
                        definition: "#modal-definition"
                    },
                    playCard: {
                        handle: "#playCard",
                        expand: "#toggleFit",
                        welcome: "#modal-welcome",
                        moretext: "#modal-description",
                        form: "#playForm",
                        btn1: "#btn-solo",
                        btn2: "#btn-teams",
                        status: "#playStatus",
                        submit: "#playSubmit",
                        username: "#nameInput",
                        groupdiv: ".groupname",
                        groupname: "#groupInput"
                    },
                    activeusersList: "#gwActiveUser",
                    colorPicker: "#gwColorPicker",
                    chatMessages: "#gwMessages",
                    word: "#gwPrompt"
                },
                footer: ""
            },
            action: {
                red: "#gwRed",
                black: "#gwBlack",
                green: "#gwGreen",
                blue: "#gwBlue",
                clearCanvas: "#gwClear"
            },
        },
        canvas: {
            handle: "#gw_Canvas"
        },
        mouse: {
            click: false,
            move: false,
            pos: {
                x: 0,
                y: 0
            },
            pos_prev: {
                x:0,
                y:0
            }
        },
        color: "#000000"
    };

    var context = $(gw.canvas.handle)[0].getContext("2d");
    var width = $(gw.landpage.section.content.canvasDiv).width();
    var height = $(gw.landpage.section.content.canvasDiv).height();

    //Function to handle Clear Canvas
    $(gw.landpage.action.clearCanvas).on("click", function() {
        context.clearRect(0, 0, width, height);
        socket.emit("clearcanvas", "hello");
    });
    //Function to handle Red Color
    $(gw.landpage.action.red).on("click", function() {
        gw.color = "#990000";
    });
    //Function to handle Black Color
    $(gw.landpage.action.black).on("click", function() {
        gw.color = "#000000";
    });
    //Function to handle Green Color
    $(gw.landpage.action.green).on("click", function() {
        gw.color = "#006600";
    });
    //Function to handle blue Color
    $(gw.landpage.action.blue).on("click", function() {
        gw.color = "#0000ff";
    });

    //Function to HandleSocket Emit on mouse movements
    function handleSocketEmit() {
        // check if the user is drawing
        if (gw.mouse.click && gw.mouse.move) {
            socket.emit("draw_line", {
                x: gw.mouse.pos.x,
                y: gw.mouse.pos.y,
                prevX: gw.mouse.pos_prev.x,
                prevY: gw.mouse.pos_prev.y,
                color: gw.color
            });
            gw.mouse.move = false;
        }

        setTimeout(handleSocketEmit, 5);
    }

    function drawCanvas(x, y, pX, pY, c) {

                context.beginPath();
                context.lineWidth = 5;
                context.lineJoin = context.lineCap = "round";
                context.strokeStyle = c;
                context.moveTo(pX, pY);
                context.lineTo(x, y);
                context.stroke();
        }

    // Function to track User mouse events on canvas
    function handleDrawEvent() {
        var touchcanvas = document.getElementById("gw_Canvas");
        $(gw.canvas.handle)[0].width = width;
        $(gw.canvas.handle)[0].height = height;

        touchcanvas.addEventListener("touchstart", function(e) {
            gw.mouse.click = true;
            if (e) {
                console.log("error", "onTouchstart", e);
            }
        }, false);

        touchcanvas.addEventListener("touchmove", function(e) {
            if (e) {
                console.log("error", "ontouchmove", e);
            }

            gw.mouse.pos_prev.x = gw.mouse.pos.x;
            gw.mouse.pos_prev.y = gw.mouse.pos.y;

            var offset = $(this).offset();
            gw.mouse.pos.x = e.pageX - offset.left;
            gw.mouse.pos.y = e.pageY - offset.top;
            gw.mouse.move = true;
        }, false);

        $(gw.canvas.handle)[0].onmousedown = function() {
            gw.mouse.click = true;
        };

        $(gw.canvas.handle)[0].onmouseup = function() {
            gw.mouse.click = false;
        };

        $(gw.canvas.handle)[0].onmousemove = function(e) {
            gw.mouse.pos_prev.x = gw.mouse.pos.x;
            gw.mouse.pos_prev.y = gw.mouse.pos.y;

            var offset = $(this).offset();
            gw.mouse.pos.x = e.pageX - offset.left;
            gw.mouse.pos.y = e.pageY - offset.top;
            gw.mouse.move = true;
        };

        socket.on("draw_line", function(data) {
            drawCanvas(data.x, data.y, data.prevX, data.prevY, data.color);
        });

        handleSocketEmit();
    }

    function autoScroll() {
        // get height of chat box
        var h = 0;
        $(".gwMsg").each(function() {
            h += parseInt($(this).height()) + 20;
        });
        h = h.toString();

        // scroll to bottom of chat
        $(".chatPanel").animate({scrollTop: h});
    }

    // login success
    function formSuccess(mode, user, group) {
        $(gw.landpage.section.content.playCard.status).removeClass("toggleshow");
        $(gw.landpage.section.content.playCard.status).removeClass("alert-danger").addClass("alert-success");
        $(gw.landpage.section.content.playCard.status).html("Success! Joining a game");
        $(gw.landpage.section.content.playCard.status).show().fadeOut(500, function() {
            console.log("connect socket #" + mode);
            socket.emit("adduser", mode, user, group);
        });

        $(gw.landpage.section.content.playCard.handle).modal("hide");

        // Confirm leaving webapp
        window.onbeforeunload = function() {
            return "";
        };
    }

    // login error
    function formFailure(error) {
        $(gw.landpage.section.content.playCard.status).removeClass("toggleshow");
        $(gw.landpage.section.content.playCard.status).removeClass("alert-success").addClass("alert-danger");
        $(gw.landpage.section.content.playCard.status).html("Error! " + error).show().fadeOut(2000);
    }

    // handle expand button toggle
    $(gw.landpage.section.content.playCard.expand).on("click", function() {
        if ($(this).hasClass("glyphicon-chevron-down")) {
            $(gw.landpage.section.content.playCard.welcome).removeClass("fitonmodal");
            $(gw.landpage.section.content.playCard.moretext).removeClass("fitonmodal");
            $(this).removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-right");
        }
        else {
            $(gw.landpage.section.content.playCard.welcome).addClass("fitonmodal");
            $(gw.landpage.section.content.playCard.moretext).addClass("fitonmodal");
            $(this).removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-down");
        }
    });

    // handle mode button toggle
    $(gw.landpage.section.content.playCard.btn1).on("click", function() {
        $(this).addClass("active");
        $(gw.landpage.section.content.playCard.btn2).removeClass("active");
        $(gw.landpage.section.content.playCard.groupdiv).addClass("toggleshow");
    });

    $(gw.landpage.section.content.playCard.btn2).on("click", function() {
        $(this).addClass("active");
        $(gw.landpage.section.content.playCard.btn1).removeClass("active");
        $(gw.landpage.section.content.playCard.groupdiv).removeClass("toggleshow");
    });

    // logout
    $("#logoutLink").on("click", function() {
        console.log("logging out");
        socket.emit("logout", function() {
            socket.disconnect();
        });
        $(gw.landpage.section.content.playCard.handle).modal("show");
    });

    // show definition
    $(gw.landpage.section.content.word).on("click", function() {
        $(gw.landpage.section.content.hintCard.handle).modal("show");
    });

    // handle chat message input
    $(gw.landpage.section.content.chatform.handle).submit(function() {
        socket.emit("sendchat", $(gw.landpage.section.content.chatform.field.sendButton).val());
        $(gw.landpage.section.content.chatform.field.sendButton).val("");
        return false;
    });

    // call the server-side function "adduser" and send two parameters (mode, name)
    socket.on("connect", function() {
        $(gw.landpage.section.content.playCard.handle).modal({backdrop: "static",keyboard: false});
        $(gw.landpage.section.content.playCard.handle).modal("show");

        // handle username input
        $(gw.landpage.section.content.playCard.form).submit(function(event) {
            var newuser = $(gw.landpage.section.content.playCard.username).val();
            var grpname = $(gw.landpage.section.content.playCard.groupname).val();

            if ($(gw.landpage.section.content.playCard.btn1).hasClass("active")) {
                if (newuser.length > 2) {
                    formSuccess(1, newuser, "");
                    return false;
                }
                else {
                    formFailure("Invalid username");
                    $(gw.landpage.section.content.playCard.username).val("");
                    event.preventDefault();
                }
            }
            else if ($(gw.landpage.section.content.playCard.btn2).hasClass("active")) {
                if (grpname.length > 2 && newuser.length > 2) {
                    formSuccess(2, newuser, grpname);
                    return false;
                }
                else if (newuser.length > 2) {
                    formFailure("Invalid group name");
                    $(gw.landpage.section.content.playCard.groupname).val("");
                    event.preventDefault();
                }
                else {
                    formFailure("Invalid username");
                    $(gw.landpage.section.content.playCard.username).val("");
                    event.preventDefault();
                }
            }
            else {
                formFailure("Unable to join game");
                $(gw.landpage.section.content.playCard.username).val("");
                event.preventDefault();
            }
        });
    });

    // listener, whenever the server emits "updatechat", this updates the chat body
    socket.on("updatechat", function(username, data) {
        $(gw.landpage.section.content.chatMessages).append("
" + username + ": " + data + "
");
        autoScroll();
    });

    // listener, whenever the server emits "updateword", this updates the game round
    socket.on("displayword", function(word, definition) {
        console.log("displayword");
        $(gw.landpage.section.content.word).text(word);
        $(gw.landpage.section.content.hintCard.definition).text(definition);
    });

    // listener, whenever the server emits "updateword", this updates the game round
    socket.on("updateword", function(data) {
        $(gw.landpage.section.content.chatMessages).append("
" + "SERVER: " + data + "
");
        context.clearRect(0, 0, width, height);
        autoScroll();
    });

    socket.on("updateusers", function(data) {
        $(gw.landpage.section.content.activeusersList).empty();
        data.forEach(function(key){
            $(gw.landpage.section.content.activeusersList).append("" + key +"
");
        });
    });

    socket.on("clearcanvas", function() {
        context.clearRect(0, 0, width, height);
    });

    handleDrawEvent();
};

$(document).ready(main);
<commit_msg>Called disconnect on click of logout but there is still an issue #13<commit_after>// Client-side code
/* jshint browser: true, jquery: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, trailing: true */
/* global io: true, console: true */

var main = function() {
    "use strict";

    //var socket = io.connect();
    var socket = io("/guesswhat");

    var gw = {
        landpage: {
            section: {
                navbar: "",
                content: {
                    canvasDiv: "#divCanvas",
                    chatform: {
                        handle: "#gwChatForm",
                        field: {
                            sendButton: "#gwChatButton"
                        }
                    },
                    hintCard: {
                        handle: "#hintCard",
                        definition: "#modal-definition"
                    },
                    playCard: {
                        handle: "#playCard",
                        expand: "#toggleFit",
                        welcome: "#modal-welcome",
                        moretext: "#modal-description",
                        form: "#playForm",
                        btn1: "#btn-solo",
                        btn2: "#btn-teams",
                        status: "#playStatus",
                        submit: "#playSubmit",
                        username: "#nameInput",
                        groupdiv: ".groupname",
                        groupname: "#groupInput"
                    },
                    activeusersList: "#gwActiveUser",
                    colorPicker: "#gwColorPicker",
                    chatMessages: "#gwMessages",
                    word: "#gwPrompt"
                },
                footer: ""
            },
            action: {
                red: "#gwRed",
                black: "#gwBlack",
                green: "#gwGreen",
                blue: "#gwBlue",
                clearCanvas: "#gwClear"
            },
        },
        canvas: {
            handle: "#gw_Canvas"
        },
        mouse: {
            click: false,
            move: false,
            pos: {
                x: 0,
                y: 0
            },
            pos_prev: {
                x:0,
                y:0
            }
        },
        color: "#000000"
    };

    var context = $(gw.canvas.handle)[0].getContext("2d");
    var width = $(gw.landpage.section.content.canvasDiv).width();
    var height = $(gw.landpage.section.content.canvasDiv).height();

    //Function to handle Clear Canvas
    $(gw.landpage.action.clearCanvas).on("click", function() {
        context.clearRect(0, 0, width, height);
        socket.emit("clearcanvas", "hello");
    });
    //Function to handle Red Color
    $(gw.landpage.action.red).on("click", function() {
        gw.color = "#990000";
    });
    //Function to handle Black Color
    $(gw.landpage.action.black).on("click", function() {
        gw.color = "#000000";
    });
    //Function to handle Green Color
    $(gw.landpage.action.green).on("click", function() {
        gw.color = "#006600";
    });
    //Function to handle blue Color
    $(gw.landpage.action.blue).on("click", function() {
        gw.color = "#0000ff";
    });

    //Function to HandleSocket Emit on mouse movements
    function handleSocketEmit() {
        // check if the user is drawing
        if (gw.mouse.click && gw.mouse.move) {
            socket.emit("draw_line", {
                x: gw.mouse.pos.x,
                y: gw.mouse.pos.y,
                prevX: gw.mouse.pos_prev.x,
                prevY: gw.mouse.pos_prev.y,
                color: gw.color
            });
            gw.mouse.move = false;
        }

        setTimeout(handleSocketEmit, 5);
    }

    function drawCanvas(x, y, pX, pY, c) {

                context.beginPath();
                context.lineWidth = 5;
                context.lineJoin = context.lineCap = "round";
                context.strokeStyle = c;
                context.moveTo(pX, pY);
                context.lineTo(x, y);
                context.stroke();
        }

    // Function to track User mouse events on canvas
    function handleDrawEvent() {
        var touchcanvas = document.getElementById("gw_Canvas");
        $(gw.canvas.handle)[0].width = width;
        $(gw.canvas.handle)[0].height = height;

        touchcanvas.addEventListener("touchstart", function(e) {
            gw.mouse.click = true;
            if (e) {
                console.log("error", "onTouchstart", e);
            }
        }, false);

        touchcanvas.addEventListener("touchmove", function(e) {
            if (e) {
                console.log("error", "ontouchmove", e);
            }

            gw.mouse.pos_prev.x = gw.mouse.pos.x;
            gw.mouse.pos_prev.y = gw.mouse.pos.y;

            var offset = $(this).offset();
            gw.mouse.pos.x = e.pageX - offset.left;
            gw.mouse.pos.y = e.pageY - offset.top;
            gw.mouse.move = true;
        }, false);

        $(gw.canvas.handle)[0].onmousedown = function() {
            gw.mouse.click = true;
        };

        $(gw.canvas.handle)[0].onmouseup = function() {
            gw.mouse.click = false;
        };

        $(gw.canvas.handle)[0].onmousemove = function(e) {
            gw.mouse.pos_prev.x = gw.mouse.pos.x;
            gw.mouse.pos_prev.y = gw.mouse.pos.y;

            var offset = $(this).offset();
            gw.mouse.pos.x = e.pageX - offset.left;
            gw.mouse.pos.y = e.pageY - offset.top;
            gw.mouse.move = true;
        };

        socket.on("draw_line", function(data) {
            drawCanvas(data.x, data.y, data.prevX, data.prevY, data.color);
        });

        handleSocketEmit();
    }

    function autoScroll() {
        // get height of chat box
        var h = 0;
        $(".gwMsg").each(function() {
            h += parseInt($(this).height()) + 20;
        });
        h = h.toString();

        // scroll to bottom of chat
        $(".chatPanel").animate({scrollTop: h});
    }

    // login success
    function formSuccess(mode, user, group) {
        $(gw.landpage.section.content.playCard.status).removeClass("toggleshow");
        $(gw.landpage.section.content.playCard.status).removeClass("alert-danger").addClass("alert-success");
        $(gw.landpage.section.content.playCard.status).html("Success! Joining a game");
        $(gw.landpage.section.content.playCard.status).show().fadeOut(500, function() {
            console.log("connect socket #" + mode);
            socket.emit("adduser", mode, user, group);
        });

        $(gw.landpage.section.content.playCard.handle).modal("hide");

        // Confirm leaving webapp
        window.onbeforeunload = function() {
            return "";
        };
    }

    // login error
    function formFailure(error) {
        $(gw.landpage.section.content.playCard.status).removeClass("toggleshow");
        $(gw.landpage.section.content.playCard.status).removeClass("alert-success").addClass("alert-danger");
        $(gw.landpage.section.content.playCard.status).html("Error! " + error).show().fadeOut(2000);
    }

    // handle expand button toggle
    $(gw.landpage.section.content.playCard.expand).on("click", function() {
        if ($(this).hasClass("glyphicon-chevron-down")) {
            $(gw.landpage.section.content.playCard.welcome).removeClass("fitonmodal");
            $(gw.landpage.section.content.playCard.moretext).removeClass("fitonmodal");
            $(this).removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-right");
        }
        else {
            $(gw.landpage.section.content.playCard.welcome).addClass("fitonmodal");
            $(gw.landpage.section.content.playCard.moretext).addClass("fitonmodal");
            $(this).removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-down");
        }
    });

    // handle mode button toggle
    $(gw.landpage.section.content.playCard.btn1).on("click", function() {
        $(this).addClass("active");
        $(gw.landpage.section.content.playCard.btn2).removeClass("active");
        $(gw.landpage.section.content.playCard.groupdiv).addClass("toggleshow");
    });

    $(gw.landpage.section.content.playCard.btn2).on("click", function() {
        $(this).addClass("active");
        $(gw.landpage.section.content.playCard.btn1).removeClass("active");
        $(gw.landpage.section.content.playCard.groupdiv).removeClass("toggleshow");
    });

    // logout
    $("#logoutLink").on("click", function() {
        console.log("logging out");
        $(gw.landpage.section.content.activeusersList).empty();
        socket.emit("disconnect", function() {
            socket.disconnect();
        });
        $(gw.landpage.section.content.playCard.handle).modal("show");
    });

    // show definition
    $(gw.landpage.section.content.word).on("click", function() {
        $(gw.landpage.section.content.hintCard.handle).modal("show");
    });

    // handle chat message input
    $(gw.landpage.section.content.chatform.handle).submit(function() {
        socket.emit("sendchat", $(gw.landpage.section.content.chatform.field.sendButton).val());
        $(gw.landpage.section.content.chatform.field.sendButton).val("");
        return false;
    });

    // call the server-side function "adduser" and send two parameters (mode, name)
    socket.on("connect", function() {
        $(gw.landpage.section.content.playCard.handle).modal({backdrop: "static",keyboard: false});
        $(gw.landpage.section.content.playCard.handle).modal("show");

        // handle username input
        $(gw.landpage.section.content.playCard.form).submit(function(event) {
            var newuser = $(gw.landpage.section.content.playCard.username).val();
            var grpname = $(gw.landpage.section.content.playCard.groupname).val();

            if ($(gw.landpage.section.content.playCard.btn1).hasClass("active")) {
                if (newuser.length > 2) {
                    formSuccess(1, newuser, "");
                    return false;
                }
                else {
                    formFailure("Invalid username");
                    $(gw.landpage.section.content.playCard.username).val("");
                    event.preventDefault();
                }
            }
            else if ($(gw.landpage.section.content.playCard.btn2).hasClass("active")) {
                if (grpname.length > 2 && newuser.length > 2) {
                    formSuccess(2, newuser, grpname);
                    return false;
                }
                else if (newuser.length > 2) {
                    formFailure("Invalid group name");
                    $(gw.landpage.section.content.playCard.groupname).val("");
                    event.preventDefault();
                }
                else {
                    formFailure("Invalid username");
                    $(gw.landpage.section.content.playCard.username).val("");
                    event.preventDefault();
                }
            }
            else {
                formFailure("Unable to join game");
                $(gw.landpage.section.content.playCard.username).val("");
                event.preventDefault();
            }
        });
    });

    // listener, whenever the server emits "updatechat", this updates the chat body
    socket.on("updatechat", function(username, data) {
        $(gw.landpage.section.content.chatMessages).append("
" + username + ": " + data + "
");
        autoScroll();
    });

    // listener, whenever the server emits "updateword", this updates the game round
    socket.on("displayword", function(word, definition) {
        console.log("displayword");
        $(gw.landpage.section.content.word).text(word);
        $(gw.landpage.section.content.hintCard.definition).text(definition);
    });

    // listener, whenever the server emits "updateword", this updates the game round
    socket.on("updateword", function(data) {
        $(gw.landpage.section.content.chatMessages).append("
" + "SERVER: " + data + "
");
        context.clearRect(0, 0, width, height);
        autoScroll();
    });

    socket.on("updateusers", function(data) {
        $(gw.landpage.section.content.activeusersList).empty();
        data.forEach(function(key){
            $(gw.landpage.section.content.activeusersList).append("" + key +"
");
        });
    });

    socket.on("clearcanvas", function() {
        context.clearRect(0, 0, width, height);
    });

    handleDrawEvent();
};

$(document).ready(main);
<|endoftext|>


<commit_before>module.exports = {
  // db
  ['db/path']: 'mongodb://localhost/test',
  // server
  ['server/port']: 3000,
  // local server
  ['localServer/port']: 3001,
  // zigbee
  ['zigbee/bridgeEp']: 8,
  ['zigbee/appMsgCluster']: 0xff00,
  ['zigbee/appType/lamp']: 0x0000,
  ['zigbee/appType/gray-lamp']: 0x0001,
  ['zigbee/appType/switch']: 0x0100,
  ['zigbee/appType/gray-switch']: 0x0101,
  ['zigbee/appType/pulse']: 0x0102,
  ['zigbee/appType/illuminance-sensor']: 0x0300,
  ['zigbee/appType/temperature-sensor']: 0x0301,
  ['zigbee/appType/asr-sensor']: 0x0302,
  ['zigbee/appType/occupy-sensor']: 0x0303,
  // app
  ['app/illuminance-sensor/range']: [0, 65535],
  ['app/temperature-sensor/range']: [-50, 100],
  // serial
  ['serial/path']: 'COM5',
  ['serial/rate']: 38400,
  // log
  ['log/path']: 'logs/app.log',
  ['log/maxLogSize']: 10485760,
  ['log/numBackups']: 3,
  ['log/level']: 'TRACE',
};
<commit_msg>clean<commit_after><|endoftext|>


<commit_before>coord = function(x, y) {
    return "" + x + "," + y;
}

function Boundary(axes, fill, vertices) {
    this.vertices = vertices;
    var points_str = "";
    for(var i = 0; i < this.vertices.length; i++) {
        points_str += coord(this.vertices[i][0], this.vertices[i][1])
            + " ";
    }
    points_str += coord(this.vertices[0][0], this.vertices[0][1]);
    axes.append("polyline")
        .attr("points", points_str)
        .attr("stroke", "brown")
        .attr("stroke-width", "3.0")
        .attr("fill", fill);
}

function HouseBoat() { }

HouseBoat.prototype.initialize = function(axes) {
    // Initialize boat geometry.
    this.deg2rad = Math.PI / 180;
    this.length = 100;
    this.width = 60;
    // Initialize boat state.
    this.x = 0.0;
    this.y = 0.0;
    this.theta = 45.0;
    this.vx = 0.0;
    this.vy = 0.0;
    this.omega = 0.0;
    this.throttle = 0.0;
    this.steering = 0.0;
    this.phi = 0.0;
    this.damage = [0.1, 0.1, 0.1, 0.1];
    // Initialize an array of corner locations.
    this.corners = [[0.,0.], [0.,0.], [0.,0.], [0.,0.]];
    this.update_corners();
    // Create boat's visual representation.
    this.boat = axes.append("g");
    this.boat.append("rect")
        .attr("width", "" + this.length)
        .attr("height", "" + this.width)
        .attr("transform", "translate(-50, -30)")
        .attr("fill", "gray")
        .attr("stroke", "black");
    var wake_group = this.boat.append("g")
        .attr("transform", "translate(-50, 0)");
    this.wake = wake_group.append("polyline")
        .attr("points", "-50,-15 0,0 -50,15")
        .attr("transform", "rotate(0) scale(-0.5)")
        .attr("stroke", "red")
        .attr("fill", "none");
    this.corner_circles = [];
    var L = 0.5 * this.length, W = 0.5 * this.width;
    var xy = [[-L, -W], [-L, +W], [+L, +W], [+L, -W]];
    for(var i = 0; i < 4; i++) {
        var circle = this.boat.append("circle")
            .attr("stroke", "none")
            .attr("fill", "red")
            .attr("cx", xy[i][0])
            .attr("cy", xy[i][1])
            .attr("r", 8);
        this.corner_circles.push(circle);
    }
    this.draw();
    // Initialize model constants.
    this.max_thrust = 10.0;
    this.drag_p = 0.1;
    this.drag_t = 2.0;
    this.drag_r = 0.2;
    this.current_x = 0.0;
    this.current_y = 0.0;
    this.leverarm = 1.0;
}

HouseBoat.prototype.update = function(throttle, steering) {
    dt = 0.1;
    this.throttle = throttle;
    this.steering = steering;
    this.phi = 90.0 * steering;
    // Initialize a unit vector aligned with the pontoons.
    var theta = this.theta * this.deg2rad;
    var nx = Math.cos(theta), ny = Math.sin(theta);
    // Split the velocity (vx,vy) into components parallel
    // and perpendicular to the pontoons.
    var dotprod = this.vx * nx + this.vy * ny;
    var vpx = dotprod * nx;
    var vpy = dotprod * ny;
    var vtx = this.vx - vpx;
    var vty = this.vy - vpy;
    // Calculate the combined drag force.
    var drag_x = -this.drag_p * vpx - this.drag_t * vtx;
    var drag_y = -this.drag_p * vpy - this.drag_t * vty;
    // Calculate the thrust force on the COM.
    var phi = this.phi * this.deg2rad;
    var angle = theta + phi;
    var thrust_mag = this.max_thrust * this.throttle;
    var thrust_x = thrust_mag * Math.cos(angle);
    var thrust_y = thrust_mag * Math.sin(angle);
    // Calculate the net force on the COM
    var Fx = thrust_x + drag_x + this.current_x;
    var Fy = thrust_y + drag_y + this.current_y;
    // Update the position and bearing using the present motion.
    this.x += this.vx * dt;
    this.y += this.vy * dt;
    this.theta += this.omega * dt;
    //Update the COM velocity (assuming mass=1).
    this.vx += Fx * dt;
    this.vy += Fy * dt;
    // Calculate the torque about the COM due to the thrust.
    var tprop = -thrust_mag * this.leverarm * Math.sin(phi);
    // Calculate the torque about the COM due to rotational drag.
    var tdrag = -this.omega * this.drag_r;
    // Calculate the net torque about the COM.
    var tnet = tprop + tdrag;
    // Update the angular velocity about the COM (assuming I=1).
    this.omega += tnet * dt;
    // Update corner coordinates.
    this.update_corners();
}

HouseBoat.prototype.update_corners = function() {
    var theta = this.theta * this.deg2rad;
    var nx = Math.cos(theta), ny = -Math.sin(theta);
    var L = 0.5 * this.length, W = 0.5 * this.width;
    this.corners[0][0] = this.x - nx * L - ny * W;
    this.corners[0][1] = this.y + ny * L - nx * W;
    this.corners[1][0] = this.x - nx * L + ny * W;
    this.corners[1][1] = this.y + ny * L + nx * W;
    this.corners[2][0] = this.x + nx * L + ny * W;
    this.corners[2][1] = this.y - ny * L + nx * W;
    this.corners[3][0] = this.x + nx * L - ny * W;
    this.corners[3][1] = this.y - ny * L - nx * W;
}

HouseBoat.prototype.draw = function() {
    this.boat
        .attr("transform",
            "translate(" + coord(this.x,this.y) + ") rotate(" +
            this.theta + ",0,0)");
    if(Math.abs(this.throttle) < 0.1) {
        wake_scale = 0.1;
    }
    else {
        wake_scale = this.throttle;
    }
    this.wake
        .attr("transform", "rotate(" + this.phi + ") scale(" +
            wake_scale + ")");
    for(var i = 0; i < 4; i++) {
        this.corner_circles[i].attr("fill-opacity", "" + this.damage[i]);
    }
}

function Simulator() {
}

Simulator.prototype.initialize = function() {
    this.svg = d3.select("svg");
    this.window_width = +this.svg.attr("width");
    this.window_height = +this.svg.attr("height");
    var wby2 = 0.5 * this.window_width, hby2 = 0.5 * this.window_height;
    // Set coordinate system with origin at center of the window,
    // x increasing to the right, and y increasing upwards.
    this.axes = this.svg.append("g")
        .attr("transform", "translate(" + coord(wby2, hby2) +
            ") scale(1, -1)");
    // Initialize throttle and steering controls.
    var radius = 16.0;
    this.throttle_display = this.svg.append("circle")
        .attr("cx", this.window_width - radius)
        .attr("cy", hby2)
        .attr("r", radius)
        .attr("stroke", "black")
        .attr("fill-opacity", "0.5")
        .attr("fill", "green");
    this.steering_display = this.svg.append("circle")
        .attr("cx", wby2)
        .attr("cy", this.window_height - radius)
        .attr("r", radius)
        .attr("stroke", "black")
        .attr("fill-opacity", "0.5")
        .attr("fill", "green");
    // Draw center marks for each control.
    var w = 0.2 * radius, h = 0.6 * radius;
    this.svg.append("polygon")
        .attr("points",
            coord(wby2 - w, this.window_height) + " " +
            coord(wby2, this.window_height - h) + " " +
            coord(wby2 + w, this.window_height))
        .attr("stroke", "black")
        .attr("fill", "blue");
    this.svg.append("polygon")
        .attr("points",
            coord(this.window_width, hby2 - w) + " " +
            coord(this.window_width - h, hby2) + " " +
            coord(this.window_width, hby2 + w))
        .attr("stroke", "black")
        .attr("fill", "blue");
    this.throttle_max = this.window_height - 2 * radius;
    this.steering_max = this.window_width - 2 * radius;

    // Capture arrow keypress events.
    this.right = false;
    this.left = false;
    this.up = false;
    this.down = false;
    var self = this;
    d3.select("body")
        .on("keydown", function() {
            var code = d3.event.keyCode;
            if(code == 39) {
                self.right = true;
            }
            else if(code == 37) {
                self.left = true;
            }
            else if(code == 38) {
                self.up = true;
            }
            else if(code == 40) {
                self.down = true;
            }
            if(self.right || self.left) {
                self.steering_display.attr("fill-opacity", "1.0");
            }
            if(self.up || self.down) {
                self.throttle_display.attr("fill-opacity", "1.0");
            }
        })
        .on("keyup", function() {
            var code = d3.event.keyCode;
            if(code == 39) {
                self.right = false;
            }
            else if(code == 37) {
                self.left = false;
            }
            else if(code == 38) {
                self.up = false;
            }
            else if(code == 40) {
                self.down = false;
            }
            if(!self.right && !self.left) {
                self.steering_display.attr("fill-opacity", "0.5");
            }
            if(!self.up && !self.down) {
                self.throttle_display.attr("fill-opacity", "0.5");
            }
        });

    limits = new Boundary(this.axes, "lightblue",
        [[-wby2, -hby2], [-wby2, hby2], [wby2, hby2], [wby2, -hby2]]);
    this.boundaries = [ limits ];

    this.houseboat = new HouseBoat();
    this.houseboat.initialize(this.axes);
}

Simulator.prototype.run = function() {
    var ival = 50; // milliseconds
    // Start the interval timer.
    var self = this;
    d3.interval(function(elapsed) {
        // Adjust the throttle.
        var throttle = self.houseboat.throttle;
        var throttle_adjust = +1. * self.up - 1. * self.down;
        throttle += 0.01 * throttle_adjust;
        if(throttle > 1.0) { throttle = 1.0; }
        else if(throttle < -1.0) { throttle = -1.0; }
        // Adjust the steering.
        var steering = self.houseboat.steering;
        var steering_adjust = +1. * self.right - 1. * self.left;
        steering += 0.01 * steering_adjust;
        if(steering > 1.0) { steering = 1.0; }
        else if(steering < -1.0) { steering = -1.0; }
        self.throttle_display
            .attr("cy",
            0.5 * (self.window_height - self.throttle_max * throttle));
        self.steering_display
            .attr("cx",
            0.5 * (self.window_width + self.steering_max * steering));
        // Test for any boat-boundary collisions.
        var corners = self.houseboat.corners;
        for(var i = 0; i < self.boundaries.length; i++) {
            var boundary = self.boundaries[i];
            // Loop over corners of the boat.
            for(var j = 0; j < corners.length; j++) {
                if(!d3.polygonContains(boundary.vertices, corners[j])) {
                    self.houseboat.damage[j] += 0.02;
                }
            }
        }
        self.houseboat.update(throttle, steering);
        self.houseboat.draw();
    }, ival);
}

var sim = new Simulator();

$(function() {
    // DOM is ready.
    sim.initialize();
    sim.run();
});
<commit_msg>Implement COM collisions (no torque yet)<commit_after>coord = function(x, y) {
    return "" + x + "," + y;
}

function Boundary(axes, fill, spring_constant, vertices) {
    this.vertices = vertices;
    this.spring_constant = spring_constant;
    var points_str = "";
    for(var i = 0; i < this.vertices.length; i++) {
        points_str += coord(this.vertices[i][0], this.vertices[i][1])
            + " ";
    }
    points_str += coord(this.vertices[0][0], this.vertices[0][1]);
    axes.append("polyline")
        .attr("points", points_str)
        .attr("stroke", "brown")
        .attr("stroke-width", "3.0")
        .attr("fill", fill);
}

Boundary.prototype.restoring_force = function(point) {
    // Find which edge was breached.
    var x0 = point[0], y0 = point[1], x1, x2, y1, y2, s;
    for(var i1 = 0; i1 < this.vertices.length; i1++) {
        i2 = (i1 + 1) % this.vertices.length;
        x1 = this.vertices[i1][0];
        x2 = this.vertices[i2][0];
        y1 = this.vertices[i1][1];
        y2 = this.vertices[i2][1];
        s = ((x0 - x1) * (x2 - x1) + (y0 - y1) * (y2 - y1)) /
            ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
        if((s < 0) || (s >= 1)) continue;
        fx = this.spring_constant * ((1 - s) * x1 + s * x2 - x0);
        fy = this.spring_constant * ((1 - s) * y1 + s * y2 - y0);
        // Limit the maximum restoring force.
        var fnorm2 = fx * fx + fy * fy;
        var fnorm2max = 10000.0;
        if(fnorm2 > fnorm2max) {
            var scale = Math.sqrt(fnorm2max / fnorm2);
            fx *= scale;
            fy *= scale;
        }
        return [fx, fy];
    }
    console.log('No breach found');
    return [0., 0.];
}

function HouseBoat() { }

HouseBoat.prototype.initialize = function(axes) {
    // Initialize boat geometry.
    this.deg2rad = Math.PI / 180;
    this.length = 100;
    this.width = 60;
    // Initialize boat state.
    this.x = 0.0;
    this.y = 0.0;
    this.theta = 45.0;
    this.vx = 0.0;
    this.vy = 0.0;
    this.omega = 0.0;
    this.throttle = 0.0;
    this.steering = 0.0;
    this.phi = 0.0;
    this.damage = [0.0, 0.0, 0.0, 0.0];
    // Initialize an array of corner locations.
    this.corners = [[0.,0.], [0.,0.], [0.,0.], [0.,0.]];
    this.update_corners();
    // Create boat's visual representation.
    this.boat = axes.append("g");
    this.boat.append("rect")
        .attr("width", "" + this.length)
        .attr("height", "" + this.width)
        .attr("transform", "translate(-50, -30)")
        .attr("fill", "gray")
        .attr("stroke", "black");
    var wake_group = this.boat.append("g")
        .attr("transform", "translate(-50, 0)");
    this.wake = wake_group.append("polyline")
        .attr("points", "-50,-15 0,0 -50,15")
        .attr("transform", "rotate(0) scale(-0.5)")
        .attr("stroke", "red")
        .attr("fill", "none");
    this.corner_circles = [];
    var L = 0.5 * this.length, W = 0.5 * this.width;
    var xy = [[-L, -W], [-L, +W], [+L, +W], [+L, -W]];
    for(var i = 0; i < 4; i++) {
        var circle = this.boat.append("circle")
            .attr("stroke", "none")
            .attr("fill", "red")
            .attr("cx", xy[i][0])
            .attr("cy", xy[i][1])
            .attr("r", 8);
        this.corner_circles.push(circle);
    }
    this.draw();
    // Initialize model constants.
    this.max_thrust = 10.0;
    this.drag_p = 0.1;
    this.drag_t = 2.0;
    this.drag_r = 0.2;
    this.current_x = 0.0;
    this.current_y = 0.0;
    this.leverarm = 1.0;
}

HouseBoat.prototype.update = function(
    throttle, steering, external_force) {
    dt = 0.1;
    this.throttle = throttle;
    this.steering = steering;
    this.phi = 90.0 * steering;
    // Initialize a unit vector aligned with the pontoons.
    var theta = this.theta * this.deg2rad;
    var nx = Math.cos(theta), ny = Math.sin(theta);
    // Split the velocity (vx,vy) into components parallel
    // and perpendicular to the pontoons.
    var dotprod = this.vx * nx + this.vy * ny;
    var vpx = dotprod * nx;
    var vpy = dotprod * ny;
    var vtx = this.vx - vpx;
    var vty = this.vy - vpy;
    // Calculate the combined drag force.
    var drag_x = -this.drag_p * vpx - this.drag_t * vtx;
    var drag_y = -this.drag_p * vpy - this.drag_t * vty;
    // Calculate the thrust force on the COM.
    var phi = this.phi * this.deg2rad;
    var angle = theta + phi;
    var thrust_mag = this.max_thrust * this.throttle;
    var thrust_x = thrust_mag * Math.cos(angle);
    var thrust_y = thrust_mag * Math.sin(angle);
    // Calculate the net force on the COM
    var Fx = thrust_x + drag_x + this.current_x + external_force[0];
    var Fy = thrust_y + drag_y + this.current_y + external_force[1];
    // Update the position and bearing using the present motion.
    this.x += this.vx * dt;
    this.y += this.vy * dt;
    this.theta += this.omega * dt;
    //Update the COM velocity (assuming mass=1).
    this.vx += Fx * dt;
    this.vy += Fy * dt;
    // Calculate the torque about the COM due to the thrust.
    var tprop = -thrust_mag * this.leverarm * Math.sin(phi);
    // Calculate the torque about the COM due to rotational drag.
    var tdrag = -this.omega * this.drag_r;
    // Calculate the net torque about the COM.
    var tnet = tprop + tdrag;
    // Update the angular velocity about the COM (assuming I=1).
    this.omega += tnet * dt;
    // Update corner coordinates.
    this.update_corners();
}

HouseBoat.prototype.update_corners = function() {
    var theta = this.theta * this.deg2rad;
    var nx = Math.cos(theta), ny = -Math.sin(theta);
    var L = 0.5 * this.length, W = 0.5 * this.width;
    this.corners[0][0] = this.x - nx * L - ny * W;
    this.corners[0][1] = this.y + ny * L - nx * W;
    this.corners[1][0] = this.x - nx * L + ny * W;
    this.corners[1][1] = this.y + ny * L + nx * W;
    this.corners[2][0] = this.x + nx * L + ny * W;
    this.corners[2][1] = this.y - ny * L + nx * W;
    this.corners[3][0] = this.x + nx * L - ny * W;
    this.corners[3][1] = this.y - ny * L - nx * W;
}

HouseBoat.prototype.draw = function() {
    this.boat
        .attr("transform",
            "translate(" + coord(this.x,this.y) + ") rotate(" +
            this.theta + ",0,0)");
    if(Math.abs(this.throttle) < 0.1) {
        wake_scale = 0.1;
    }
    else {
        wake_scale = this.throttle;
    }
    this.wake
        .attr("transform", "rotate(" + this.phi + ") scale(" +
            wake_scale + ")");
    for(var i = 0; i < 4; i++) {
        this.corner_circles[i].attr("fill-opacity", "" + this.damage[i]);
    }
}

function Simulator() {
}

Simulator.prototype.initialize = function() {
    this.svg = d3.select("svg");
    this.window_width = +this.svg.attr("width");
    this.window_height = +this.svg.attr("height");
    var wby2 = 0.5 * this.window_width, hby2 = 0.5 * this.window_height;
    // Set coordinate system with origin at center of the window,
    // x increasing to the right, and y increasing upwards.
    this.axes = this.svg.append("g")
        .attr("transform", "translate(" + coord(wby2, hby2) +
            ") scale(1, -1)");
    // Initialize throttle and steering controls.
    var radius = 16.0;
    this.throttle_display = this.svg.append("circle")
        .attr("cx", this.window_width - radius)
        .attr("cy", hby2)
        .attr("r", radius)
        .attr("stroke", "black")
        .attr("fill-opacity", "0.5")
        .attr("fill", "green");
    this.steering_display = this.svg.append("circle")
        .attr("cx", wby2)
        .attr("cy", this.window_height - radius)
        .attr("r", radius)
        .attr("stroke", "black")
        .attr("fill-opacity", "0.5")
        .attr("fill", "green");
    // Draw center marks for each control.
    var w = 0.2 * radius, h = 0.6 * radius;
    this.svg.append("polygon")
        .attr("points",
            coord(wby2 - w, this.window_height) + " " +
            coord(wby2, this.window_height - h) + " " +
            coord(wby2 + w, this.window_height))
        .attr("stroke", "black")
        .attr("fill", "blue");
    this.svg.append("polygon")
        .attr("points",
            coord(this.window_width, hby2 - w) + " " +
            coord(this.window_width - h, hby2) + " " +
            coord(this.window_width, hby2 + w))
        .attr("stroke", "black")
        .attr("fill", "blue");
    this.throttle_max = this.window_height - 2 * radius;
    this.steering_max = this.window_width - 2 * radius;

    // Capture arrow keypress events.
    this.right = false;
    this.left = false;
    this.up = false;
    this.down = false;
    var self = this;
    d3.select("body")
        .on("keydown", function() {
            var code = d3.event.keyCode;
            if(code == 39) {
                self.right = true;
            }
            else if(code == 37) {
                self.left = true;
            }
            else if(code == 38) {
                self.up = true;
            }
            else if(code == 40) {
                self.down = true;
            }
            if(self.right || self.left) {
                self.steering_display.attr("fill-opacity", "1.0");
            }
            if(self.up || self.down) {
                self.throttle_display.attr("fill-opacity", "1.0");
            }
        })
        .on("keyup", function() {
            var code = d3.event.keyCode;
            if(code == 39) {
                self.right = false;
            }
            else if(code == 37) {
                self.left = false;
            }
            else if(code == 38) {
                self.up = false;
            }
            else if(code == 40) {
                self.down = false;
            }
            if(!self.right && !self.left) {
                self.steering_display.attr("fill-opacity", "0.5");
            }
            if(!self.up && !self.down) {
                self.throttle_display.attr("fill-opacity", "0.5");
            }
        });

    limits = new Boundary(this.axes, "lightblue", 1000.0,
        [[-wby2, -hby2], [-wby2, hby2], [wby2, hby2], [wby2, -hby2]]);
    this.boundaries = [ limits ];

    this.houseboat = new HouseBoat();
    this.houseboat.initialize(this.axes);
}

Simulator.prototype.run = function() {
    var ival = 50; // milliseconds
    // Start the interval timer.
    var self = this;
    d3.interval(function(elapsed) {
        // Adjust the throttle.
        var throttle = self.houseboat.throttle;
        var throttle_adjust = +1. * self.up - 1. * self.down;
        throttle += 0.01 * throttle_adjust;
        if(throttle > 1.0) { throttle = 1.0; }
        else if(throttle < -1.0) { throttle = -1.0; }
        // Adjust the steering.
        var steering = self.houseboat.steering;
        var steering_adjust = +1. * self.right - 1. * self.left;
        steering += 0.01 * steering_adjust;
        if(steering > 1.0) { steering = 1.0; }
        else if(steering < -1.0) { steering = -1.0; }
        self.throttle_display
            .attr("cy",
            0.5 * (self.window_height - self.throttle_max * throttle));
        self.steering_display
            .attr("cx",
            0.5 * (self.window_width + self.steering_max * steering));
        // Test for any boat-boundary collisions.
        var corners = self.houseboat.corners;
        var external_torque = 0.0, external_force = [0., 0.];
        for(var i = 0; i < self.boundaries.length; i++) {
            var boundary = self.boundaries[i];
            // Loop over corners of the boat.
            for(var j = 0; j < corners.length; j++) {
                if(!d3.polygonContains(boundary.vertices, corners[j])) {
                    force = boundary.restoring_force(corners[j]);
                    external_force[0] += force[0];
                    external_force[1] += force[1];
                    damage = 0.0002 * Math.sqrt(
                        force[0] * force[0] + force[1] * force[1]);
                    self.houseboat.damage[j] += damage;
                    if(self.houseboat.damage[j] > 1.0) {
                        self.houseboat.damage[j] = 1.0;
                    }
                }
            }
        }
        self.houseboat.update(throttle, steering, external_force);
        self.houseboat.draw();
    }, ival);
}

var sim = new Simulator();

$(function() {
    // DOM is ready.
    sim.initialize();
    sim.run();
});
<|endoftext|>


<commit_before>var config = {};

config.port = process.env.PORT || '3000';
config.host = process.env.HOST || 'localhost';
config.sessionSecret = process.env.SESSION_SECRET || 'e70a1e1ee4b8f662f78'
config.mailgun_key = process.env.MAILGUN_KEY

config.cookieduration = 1000 * 60 * 60 * 24; //one hour

module.exports = config;
<commit_msg>add savesearch config var<commit_after>var config = {};

config.port = process.env.PORT || '3000';
config.host = process.env.HOST || 'localhost';
config.sessionSecret = process.env.SESSION_SECRET || 'e70a1e1ee4b8f662f78'
config.mailgun_key = process.env.MAILGUN_KEY

config.save_search = false;

config.cookieduration = 1000 * 60 * 60 * 24; //one hour

module.exports = config;
<|endoftext|>