<commit_before>(function() {
	'use strict';

	var Waypoint = L.Class.extend({
			initialize: function(latLng, name) {
				this.latLng = latLng;
				this.name = name;
			}
		}),
	    GeocoderResults = L.Class.extend({
			initialize: function(results) {
				this._results = results;
			},

			addTo: function(elem) {
				var container = L.DomUtil.create('table', 'leaflet-routing-geocoder-result'),
					sibling = elem.nextSibling,
				    i,
				    tr,
				    td;

				this._elem = elem;

				for (i = 0; i < this._results.length; i++) {
					tr = L.DomUtil.create('tr', '', container);
					tr.setAttribute('data-result-index', i);
					td = L.DomUtil.create('td', '', tr);
					td.textContent = this._results[i].name;
					L.DomEvent.addListener(td, 'click', this._listener(this._results[i]), this);
				}

				L.DomEvent.addListener(elem, 'keydown', this._keyPressed, this);

				container.style.left = elem.offsetLeft;
				container.style.top = elem.offsetTop + elem.offsetHeight;
				container.style.width = elem.offsetWidth;

				if (sibling) {
					elem.parentElement.insertBefore(container, sibling);
				} else {
					elem.parentElement.appendChild(container);
				}

				this._container = container;

				return this;
			},

			onResultSelected: function() {},

			_listener: function(r) {
				return function() {
					this.onResultSelected(r);
				};
			},

			_keyPressed: function(e) {
				var _this = this,
					select = function select(dir) {
						if (_this._selection) {
							L.DomUtil.removeClass(_this._selection.firstChild, 'leaflet-routing-geocoder-selected');
							_this._selection = _this._selection[dir > 0 ? 'nextSibling' : 'previousSibling'];
						}
						if (!_this._selection) {
							_this._selection = _this._container[dir > 0 ? 'firstChild' : 'lastChild'];
						}

						if (_this._selection) {
							L.DomUtil.addClass(_this._selection.firstChild, 'leaflet-routing-geocoder-selected');
						}
					},
					index;

				switch (e.keyCode) {
				// Up
				case 38:
					select(-1);
					L.DomEvent.preventDefault(e);
					break;
				// Up
				case 40:
					select(1);
					L.DomEvent.preventDefault(e);
					break;
				// Enter
				case 13:
					if (this._selection) {
						index = parseInt(this._selection.getAttribute('data-result-index'), 10);
						this.onResultSelected(this._results[index]);
						L.DomEvent.preventDefault(e);
					}
				}
				return true;
			},

			remove: function() {
				if (this._container) {
					L.DomEvent.removeListener(this._elem, 'keydown', this._keyPressed);
					this._container.parentElement.removeChild(this._container);
					delete this._container;
					delete this._elem;
				}
			}
		});

	L.Routing = L.Routing || {};

	L.Routing.Plan = L.Class.extend({
		includes: L.Mixin.Events,

		options: {
			styles: [
				{color: 'black', opacity: 0.15, weight: 7},
				{color: 'white', opacity: 0.8, weight: 4},
				{color: 'orange', opacity: 1, weight: 2}
			],
			draggableWaypoints: true,
			addWaypoints: true
		},

		initialize: function(waypoints, options) {
			L.Util.setOptions(this, options);
			this._waypoints = [];
			this.setWaypoints(waypoints);
		},

		isReady: function() {
			var i;
			for (i = 0; i < this._waypoints.length; i++) {
				if (!this._waypoints[i].latLng) {
					return false;
				}
			}

			return true;
		},

		getWaypoints: function() {
			var i,
				wps = [];

			for (i = 0; i < this._waypoints.length; i++) {
				wps.push(this._waypoints[i].latLng);
			}

			return wps;
		},

		setWaypoints: function(waypoints) {
			this.spliceWaypoints(0, this._waypoints.length, waypoints);
		},

		spliceWaypoints: function() {
			var i,
				args = [arguments[0], arguments[1]];

			for (i = 0; arguments[2] && i < arguments[2].length; i++) {
				args.push(new Waypoint(arguments[2][i]));
			}

			[].splice.apply(this._waypoints, args);

			while (this._waypoints.length < 2) {
				this._waypoints.push(new Waypoint());
			}

			this._updateMarkers();
			this._fireChanged.apply(this, arguments);
		},

		onAdd: function(map) {
			this._map = map;
			this._updateMarkers();
		},

		onRemove: function() {
			this._removeMarkers();

			if (this._newWp) {
				this._map.removeLayer(this._newWp.line);
			}

			delete this._map;
		},

		createGeocoders: function() {
			var container = L.DomUtil.create('div', 'leaflet-routing-geocoders'),
				waypoints = this._waypoints,
			    i,
			    geocoderElem,
			    addWpBtn;

			this._geocoderContainer = container;
			this._geocoderElems = [];

			for (i = 0; i < waypoints.length; i++) {
				geocoderElem = this._createGeocoder(i);
				container.appendChild(geocoderElem);
				this._geocoderElems.push(geocoderElem);
			}

			addWpBtn = L.DomUtil.create('button', '', container);
			addWpBtn.type = 'button';
			addWpBtn.innerHTML = '+';
			L.DomEvent.addListener(addWpBtn, 'click', function() {
				this.spliceWaypoints(waypoints.length, 0, null);
			}, this);

			this.on('waypointsspliced', this._updateGeocoders);

			return container;
		},

		_createGeocoder: function(i) {
			var placeholder = (i === 0) ?
			        'Start' : (i >= this._waypoints.length - 1) ?
			        'End' : 'Via',
			    geocoderElem;

			geocoderElem = L.DomUtil.create('input', '');
			geocoderElem.placeholder = placeholder;

			L.DomEvent.addListener(geocoderElem, 'keydown', function(e) {
				var i,
					siblings = geocoderElem.parentElement.children,
					thisIndex = null;

				if (e.keyCode === 13) {
					for (i = 0; i < siblings.length && thisIndex === null; i++) {
						if (siblings[i] === geocoderElem) {
							thisIndex = i;
						}
					}

					this.options.geocoder.geocode(e.target.value, function(results) {
						var gr,
							_this = this;
						if (results.length === 1) {
							geocoderElem.value = results[0].name;
							this._waypoints[thisIndex].name = results[0].name;
							this._waypoints[thisIndex].latLng = results[0].center;
							this._updateMarkers();
							this._fireChanged();
						} else {
							gr = new GeocoderResults(results).addTo(geocoderElem);
							L.DomEvent.addListener(geocoderElem, 'blur', function() {
								// Don't remove before onResultSelected has got a chance to fire
								// TODO: this looks like a hack
								setTimeout(function() {gr.remove();}, 50);
							});
							gr.onResultSelected = function(r) {
								gr.remove();
								geocoderElem.value = r.name;
								_this._waypoints[thisIndex].name = r.name;
								_this._waypoints[thisIndex].latLng = r.center;
								_this._updateMarkers();
								_this._fireChanged();
							};
						}
					}, this);
				}
			}, this);

			return geocoderElem;
		},

		_updateGeocoders: function(e) {
			var newElems = [e.index, 0],
			    i,
			    geocoderElem;
			for (i = 0; i < e.added.length; i++) {
				geocoderElem = this._createGeocoder(e.index + i);
				this._geocoderContainer.insertBefore(geocoderElem, this._geocoderElems[e.index - 1].nextSibling);
				newElems.push(geocoderElem);
			}

			for (i = e.index; i < e.index + e.nRemoved; i++) {
				this._geocoderContainer.removeChild(this._geocoderElems[i]);
			}

			this._geocoderElems.splice(e.index, e.nRemoved);

			[].splice.apply(this._geocoderElems, newElems);
		},

		_setGeocoderValue: function(i, v) {
			this._geocoderElems[i].value = this._geocoderElems[i].value || v;
		},

		_removeMarkers: function() {
			var i;
			if (this._markers) {
				for (i = 0; i < this._markers.length; i++) {
					if (this._markers[i]) {
						this._map.removeLayer(this._markers[i]);
					}
				}
			}
			this._markers = [];
		},

		_updateMarkers: function() {
			var i,
			    m;

		    if (!this._map) {
		    	return;
		    }

			this._removeMarkers();

			for (i = 0; i < this._waypoints.length; i++) {
				if (this._waypoints[i].latLng) {
					m = L.marker(this._waypoints[i].latLng, { draggable: true }).addTo(this._map);
					if (this.options.draggableWaypoints) {
						this._hookWaypointEvents(m, i);
					}
				} else {
					m = null;
				}
				this._markers.push(m);
			}
		},

		_fireChanged: function() {
			if (this.isReady()) {
				this.fire('waypointschanged', {waypoints: this.getWaypoints()});
			}

			if (arguments.length >= 2) {
				this.fire('waypointsspliced', {
					index: Array.prototype.shift.call(arguments),
					nRemoved: Array.prototype.shift.call(arguments),
					added: arguments
				});
			}
		},

		_hookWaypointEvents: function(m, i) {
			m.on('dragstart', function(e) {
				this.fire('waypointdragstart', this._createWaypointEvent(i, e));
			}, this);
			m.on('drag', function(e) {
				this.fire('waypointdrag', this._createWaypointEvent(i, e));
			}, this);
			m.on('dragend', function(e) {
				this.fire('waypointdragend', this._createWaypointEvent(i, e));
				this._waypoints[i].latLng = e.target.getLatLng();
				this._waypoints[i].name = '';
				if (this._geocoderElems) {
					this._geocoderElems[i].value = '';
				}
				this._fireChanged();
			}, this);
		},

		_createWaypointEvent: function(i, e) {
			return {index: i, latlng: e.target.getLatLng()};
		},

		dragNewWaypoint: function(e) {
			this._newWp = {
				afterIndex: e.afterIndex,
				marker: L.marker(e.latlng).addTo(this._map),
				line: L.polyline([
					this._waypoints[e.afterIndex].latLng,
					e.latlng,
					this._waypoints[e.afterIndex + 1].latLng
				], this.options.dragStyle).addTo(this._map)
			};
			this._markers.splice(e.afterIndex + 1, 0, this._newWp.marker);
			this._map.on('mousemove', this._onDragNewWp, this);
			this._map.on('mouseup', this._onWpRelease, this);
		},

		_onDragNewWp: function(e) {
			this._newWp.marker.setLatLng(e.latlng);
			this._newWp.line.spliceLatLngs(1, 1, e.latlng);
		},

		_onWpRelease: function(e) {
			this._map.off('mouseup', this._onWpRelease, this);
			this._map.off('mousemove', this._onDragNewWp, this);
			this._map.removeLayer(this._newWp.line);
			this.spliceWaypoints(this._newWp.afterIndex + 1, 0, e.latlng);
			delete this._newWp;
		}
	});

	L.Routing.plan = function(waypoints, options) {
		return new L.Routing.Plan(waypoints, options);
	};
})();
<commit_msg>Fixed splicing *again*. Everything sort of works<commit_after>(function() {
	'use strict';

	var Waypoint = L.Class.extend({
			initialize: function(latLng, name) {
				this.latLng = latLng;
				this.name = name;
			}
		}),
	    GeocoderResults = L.Class.extend({
			initialize: function(results) {
				this._results = results;
			},

			addTo: function(elem) {
				var container = L.DomUtil.create('table', 'leaflet-routing-geocoder-result'),
					sibling = elem.nextSibling,
				    i,
				    tr,
				    td;

				this._elem = elem;

				for (i = 0; i < this._results.length; i++) {
					tr = L.DomUtil.create('tr', '', container);
					tr.setAttribute('data-result-index', i);
					td = L.DomUtil.create('td', '', tr);
					td.textContent = this._results[i].name;
					L.DomEvent.addListener(td, 'click', this._listener(this._results[i]), this);
				}

				L.DomEvent.addListener(elem, 'keydown', this._keyPressed, this);

				container.style.left = elem.offsetLeft;
				container.style.top = elem.offsetTop + elem.offsetHeight;
				container.style.width = elem.offsetWidth;

				if (sibling) {
					elem.parentElement.insertBefore(container, sibling);
				} else {
					elem.parentElement.appendChild(container);
				}

				this._container = container;

				return this;
			},

			onResultSelected: function() {},

			_listener: function(r) {
				return function() {
					this.onResultSelected(r);
				};
			},

			_keyPressed: function(e) {
				var _this = this,
					select = function select(dir) {
						if (_this._selection) {
							L.DomUtil.removeClass(_this._selection.firstChild, 'leaflet-routing-geocoder-selected');
							_this._selection = _this._selection[dir > 0 ? 'nextSibling' : 'previousSibling'];
						}
						if (!_this._selection) {
							_this._selection = _this._container[dir > 0 ? 'firstChild' : 'lastChild'];
						}

						if (_this._selection) {
							L.DomUtil.addClass(_this._selection.firstChild, 'leaflet-routing-geocoder-selected');
						}
					},
					index;

				switch (e.keyCode) {
				// Up
				case 38:
					select(-1);
					L.DomEvent.preventDefault(e);
					break;
				// Up
				case 40:
					select(1);
					L.DomEvent.preventDefault(e);
					break;
				// Enter
				case 13:
					if (this._selection) {
						index = parseInt(this._selection.getAttribute('data-result-index'), 10);
						this.onResultSelected(this._results[index]);
						L.DomEvent.preventDefault(e);
					}
				}
				return true;
			},

			remove: function() {
				if (this._container) {
					L.DomEvent.removeListener(this._elem, 'keydown', this._keyPressed);
					this._container.parentElement.removeChild(this._container);
					delete this._container;
					delete this._elem;
				}
			}
		});

	L.Routing = L.Routing || {};

	L.Routing.Plan = L.Class.extend({
		includes: L.Mixin.Events,

		options: {
			styles: [
				{color: 'black', opacity: 0.15, weight: 7},
				{color: 'white', opacity: 0.8, weight: 4},
				{color: 'orange', opacity: 1, weight: 2}
			],
			draggableWaypoints: true,
			addWaypoints: true
		},

		initialize: function(waypoints, options) {
			L.Util.setOptions(this, options);
			this._waypoints = [];
			this.setWaypoints(waypoints);
		},

		isReady: function() {
			var i;
			for (i = 0; i < this._waypoints.length; i++) {
				if (!this._waypoints[i].latLng) {
					return false;
				}
			}

			return true;
		},

		getWaypoints: function() {
			var i,
				wps = [];

			for (i = 0; i < this._waypoints.length; i++) {
				wps.push(this._waypoints[i].latLng);
			}

			return wps;
		},

		setWaypoints: function(waypoints) {
			var args = [0, this._waypoints.length].concat(waypoints);
			this.spliceWaypoints.apply(this, args);
		},

		spliceWaypoints: function() {
			var i,
				args = [arguments[0], arguments[1]];

			for (i = 2; i < arguments.length; i++) {
				args.push(new Waypoint(arguments[i]));
			}

			[].splice.apply(this._waypoints, args);

			while (this._waypoints.length < 2) {
				this._waypoints.push(new Waypoint());
			}

			this._updateMarkers();
			this._fireChanged.apply(this, arguments);
		},

		onAdd: function(map) {
			this._map = map;
			this._updateMarkers();
		},

		onRemove: function() {
			this._removeMarkers();

			if (this._newWp) {
				this._map.removeLayer(this._newWp.line);
			}

			delete this._map;
		},

		createGeocoders: function() {
			var container = L.DomUtil.create('div', 'leaflet-routing-geocoders'),
				waypoints = this._waypoints,
			    i,
			    geocoderElem,
			    addWpBtn;

			this._geocoderContainer = container;
			this._geocoderElems = [];

			for (i = 0; i < waypoints.length; i++) {
				geocoderElem = this._createGeocoder(i);
				container.appendChild(geocoderElem);
				this._geocoderElems.push(geocoderElem);
			}

			addWpBtn = L.DomUtil.create('button', '', container);
			addWpBtn.type = 'button';
			addWpBtn.innerHTML = '+';
			L.DomEvent.addListener(addWpBtn, 'click', function() {
				this.spliceWaypoints(waypoints.length, 0, null);
			}, this);

			this.on('waypointsspliced', this._updateGeocoders);

			return container;
		},

		_createGeocoder: function(i) {
			var placeholder = (i === 0) ?
			        'Start' : (i >= this._waypoints.length - 1) ?
			        'End' : 'Via',
			    geocoderElem;

			geocoderElem = L.DomUtil.create('input', '');
			geocoderElem.placeholder = placeholder;

			L.DomEvent.addListener(geocoderElem, 'keydown', function(e) {
				var i,
					siblings = geocoderElem.parentElement.children,
					thisIndex = null;

				if (e.keyCode === 13) {
					for (i = 0; i < siblings.length && thisIndex === null; i++) {
						if (siblings[i] === geocoderElem) {
							thisIndex = i;
						}
					}

					this.options.geocoder.geocode(e.target.value, function(results) {
						var gr,
							_this = this;
						if (results.length === 1) {
							geocoderElem.value = results[0].name;
							this._waypoints[thisIndex].name = results[0].name;
							this._waypoints[thisIndex].latLng = results[0].center;
							this._updateMarkers();
							this._fireChanged();
						} else {
							gr = new GeocoderResults(results).addTo(geocoderElem);
							L.DomEvent.addListener(geocoderElem, 'blur', function() {
								// Don't remove before onResultSelected has got a chance to fire
								// TODO: this looks like a hack
								setTimeout(function() {gr.remove();}, 50);
							});
							gr.onResultSelected = function(r) {
								gr.remove();
								geocoderElem.value = r.name;
								_this._waypoints[thisIndex].name = r.name;
								_this._waypoints[thisIndex].latLng = r.center;
								_this._updateMarkers();
								_this._fireChanged();
							};
						}
					}, this);
				}
			}, this);

			return geocoderElem;
		},

		_updateGeocoders: function(e) {
			var newElems = [e.index, 0],
			    i,
			    geocoderElem;
			for (i = 0; i < e.added.length; i++) {
				geocoderElem = this._createGeocoder(e.index + i);
				this._geocoderContainer.insertBefore(geocoderElem, this._geocoderElems[e.index - 1].nextSibling);
				newElems.push(geocoderElem);
			}

			for (i = e.index; i < e.index + e.nRemoved; i++) {
				this._geocoderContainer.removeChild(this._geocoderElems[i]);
			}

			this._geocoderElems.splice(e.index, e.nRemoved);

			[].splice.apply(this._geocoderElems, newElems);
		},

		_setGeocoderValue: function(i, v) {
			this._geocoderElems[i].value = this._geocoderElems[i].value || v;
		},

		_removeMarkers: function() {
			var i;
			if (this._markers) {
				for (i = 0; i < this._markers.length; i++) {
					if (this._markers[i]) {
						this._map.removeLayer(this._markers[i]);
					}
				}
			}
			this._markers = [];
		},

		_updateMarkers: function() {
			var i,
			    m;

		    if (!this._map) {
		    	return;
		    }

			this._removeMarkers();

			for (i = 0; i < this._waypoints.length; i++) {
				if (this._waypoints[i].latLng) {
					m = L.marker(this._waypoints[i].latLng, { draggable: true }).addTo(this._map);
					if (this.options.draggableWaypoints) {
						this._hookWaypointEvents(m, i);
					}
				} else {
					m = null;
				}
				this._markers.push(m);
			}
		},

		_fireChanged: function() {
			if (this.isReady()) {
				this.fire('waypointschanged', {waypoints: this.getWaypoints()});
			}

			if (arguments.length >= 2) {
				this.fire('waypointsspliced', {
					index: Array.prototype.shift.call(arguments),
					nRemoved: Array.prototype.shift.call(arguments),
					added: arguments
				});
			}
		},

		_hookWaypointEvents: function(m, i) {
			m.on('dragstart', function(e) {
				this.fire('waypointdragstart', this._createWaypointEvent(i, e));
			}, this);
			m.on('drag', function(e) {
				this.fire('waypointdrag', this._createWaypointEvent(i, e));
			}, this);
			m.on('dragend', function(e) {
				this.fire('waypointdragend', this._createWaypointEvent(i, e));
				this._waypoints[i].latLng = e.target.getLatLng();
				this._waypoints[i].name = '';
				if (this._geocoderElems) {
					this._geocoderElems[i].value = '';
				}
				this._fireChanged();
			}, this);
		},

		_createWaypointEvent: function(i, e) {
			return {index: i, latlng: e.target.getLatLng()};
		},

		dragNewWaypoint: function(e) {
			this._newWp = {
				afterIndex: e.afterIndex,
				marker: L.marker(e.latlng).addTo(this._map),
				line: L.polyline([
					this._waypoints[e.afterIndex].latLng,
					e.latlng,
					this._waypoints[e.afterIndex + 1].latLng
				], this.options.dragStyle).addTo(this._map)
			};
			this._markers.splice(e.afterIndex + 1, 0, this._newWp.marker);
			this._map.on('mousemove', this._onDragNewWp, this);
			this._map.on('mouseup', this._onWpRelease, this);
		},

		_onDragNewWp: function(e) {
			this._newWp.marker.setLatLng(e.latlng);
			this._newWp.line.spliceLatLngs(1, 1, e.latlng);
		},

		_onWpRelease: function(e) {
			this._map.off('mouseup', this._onWpRelease, this);
			this._map.off('mousemove', this._onDragNewWp, this);
			this._map.removeLayer(this._newWp.line);
			this.spliceWaypoints(this._newWp.afterIndex + 1, 0, e.latlng);
			delete this._newWp;
		}
	});

	L.Routing.plan = function(waypoints, options) {
		return new L.Routing.Plan(waypoints, options);
	};
})();
<|endoftext|>


<commit_before>import React                from 'react';
import { FileUploadEntry }  from '../../../../../panels/ItemEditor';

export default React.createClass({

  displayName: 'Simulation/New/PyFrExec',

  propTypes: {
    owner: React.PropTypes.func,
  },

  render() {
    return (

        <FileUploadEntry name="mesh" label="Mesh file (.msh)" accept=".msh" owner={ this.props.owner } />
        <FileUploadEntry name="ini" label="Ini file (.ini)" accept=".ini" owner={ this.props.owner } />

);
  },
});
<commit_msg>fix(PyFr): Allow PyFr mesh to either be .msh or .pyfrm<commit_after>import React                from 'react';
import { FileUploadEntry }  from '../../../../../panels/ItemEditor';

export default React.createClass({

  displayName: 'Simulation/New/PyFrExec',

  propTypes: {
    owner: React.PropTypes.func,
  },

  render() {
    return (

        <FileUploadEntry name="mesh" label="Mesh (msh, pyfrm)" accept=".msh,.pyfrm" owner={ this.props.owner } />
        <FileUploadEntry name="ini" label="Ini file" accept=".ini" owner={ this.props.owner } />

);
  },
});
<|endoftext|>


<commit_before>import React, { useEffect } from "react";
import classes from "./CompetitionCard.module.css";

const CompetitionCard = (props) => {
  return (

cdsaard

  );
};

export default CompetitionCard;
<commit_msg>Implement basic elements of competition card<commit_after>import React, { useEffect } from "react";
import classes from "./CompetitionCard.module.css";
import LinkButton from "../UI/LinkButton/LinkButton";

const CompetitionCard = (props) => {
  return (

Title

Organised by

Competition Details

Start date

End date

Ranking

Initial worth

Current worth

Currently available

        <LinkButton inverted>View Competition</LinkButton>

  );
};

export default CompetitionCard;
<|endoftext|>


<commit_before>var EE = require('events').EventEmitter;
var h = require('hyperscript');
var inherits = require('inherits');
var debounce = require('../lib/debounce');

function Input() {
    if (!this instanceof Input) {
        return new Input();
    }
    this.element = h('input', {
        type: 'text',
        onkeydown: this.onKeyDown.bind(this),
        onkeypress: this.onKeyPress.bind(this),
        onchange: this.finish.bind(this),
        onblur: this.finish.bind(this)
    });
    this.update = debounce(200, this.update);
    this.updateNow = this.update.immedCaller;
}

inherits(Input, EE);

Input.prototype.reset = function(expected) {
    this.element.value = '';
    this.element.size = expected.length + 2;
    this.element.focus();
};

Input.prototype.update = function() {
    this.emit('data', this.element.value, false);
};

Input.prototype.finish = function() {
    this.emit('data', this.element.value, true);
};

Input.prototype.onKeyDown = function(event) {
    if (event.keyCode  <  0x20 &&
        event.keyCode !== 0x0a &&
        event.keyCode !== 0x0d) {
        event.preventDefault();
        event.stopPropagation();
        this.emit('stop', event);
    }
};

Input.prototype.onKeyPress = function(event) {
    if (event.keyCode === 0x0a ||
        event.keyCode === 0x0d) {
        this.finish();
    } else {
        this.update();
    }
};

module.exports = Input;
<commit_msg>Input: add done state so that finish can only happen once<commit_after>var EE = require('events').EventEmitter;
var h = require('hyperscript');
var inherits = require('inherits');
var debounce = require('../lib/debounce');

function Input() {
    if (!this instanceof Input) {
        return new Input();
    }
    this.element = h('input', {
        type: 'text',
        onkeydown: this.onKeyDown.bind(this),
        onkeypress: this.onKeyPress.bind(this),
        onchange: this.finish.bind(this),
        onblur: this.finish.bind(this)
    });
    this.update = debounce(200, this.update);
    this.updateNow = this.update.immedCaller;
    this.done = false;
}

inherits(Input, EE);

Input.prototype.reset = function(expected) {
    this.done = false;
    this.element.value = '';
    this.element.size = expected.length + 2;
    this.element.focus();
};

Input.prototype.update = function() {
    if (this.done) return;
    this.emit('data', this.element.value, false);
};

Input.prototype.finish = function() {
    if (this.done) return;
    this.done = true;
    this.emit('data', this.element.value, true);
};

Input.prototype.onKeyDown = function(event) {
    if (event.keyCode  <  0x20 &&
        event.keyCode !== 0x0a &&
        event.keyCode !== 0x0d) {
        event.preventDefault();
        event.stopPropagation();
        this.emit('stop', event);
    }
};

Input.prototype.onKeyPress = function(event) {
    if (event.keyCode === 0x0a ||
        event.keyCode === 0x0d) {
        this.finish();
    } else {
        this.update();
    }
};

module.exports = Input;
<|endoftext|>


<commit_before>var RouterPlugin = require('./plugins/router.js'),
  RequestPlugin = require('./plugins/request'),
  Fluxible = require('fluxible');

var app = new Fluxible({
  appComponent: require('./components/Routes.jsx')
});

app.plug(RouterPlugin({
  location: require('react-router').HistoryLocation
}));

app.plug(RequestPlugin({
  request: require('superagent')
}));

app.registerStore(require('./stores/ApplicationStore.js'));
app.registerStore(require('./stores/BikeshedListStore.js'));
app.registerStore(require('./stores/LayoutStore.js'));
app.registerStore(require('./stores/RequestStore.js'));

module.exports = app;
<commit_msg>fix client request library<commit_after>var RouterPlugin = require('./plugins/router.js'),
  RequestPlugin = require('./plugins/request'),
  Fluxible = require('fluxible');

var app = new Fluxible({
  appComponent: require('./components/Routes.jsx')
});

app.plug(RouterPlugin({
  location: require('react-router').HistoryLocation
}));

app.plug(RequestPlugin({
  request: require('./utils/request.client.js'),
}));

app.registerStore(require('./stores/ApplicationStore.js'));
app.registerStore(require('./stores/BikeshedListStore.js'));
app.registerStore(require('./stores/LayoutStore.js'));
app.registerStore(require('./stores/RequestStore.js'));

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

define([], function() {

  /**
   * Displays the search box modal.
   */
  return Backbone.View.extend({
    csvFields: ['tags'],
    datetimePickerFormat: 'MM/DD/YYYY HH:mm:ss',

    initialize: function(options) {
      this.options = _.defaults(options, {
        acceptAnyTime: true,
        acceptSortOptions: true
      });
      this.render();
    },

    render: function() {
      var view = this,
          modal = this.$('.modal-body'),
          parser = this.$('.parser'),
          coreArgSelectors = ['.parser'];

      this.$('.modal-header > h4').text(this.options.title);

      if (this.options.acceptAnyTime) {
        $('#time-gte,#time-lte').each(function() {
          var input = $(this);
          // Invalidate the preset time range after a custom one is selected.
          input.change(function() { view.$('.time-interval').val(''); });
          // Activate date/time widgets when inputs gain focus.
          input.datetimepicker({});
        });

        coreArgSelectors.push('#time-gte', '#time-lte');
      } else {
        $('.any-time').remove();
      }

      if (this.options.acceptSortOptions) {
        coreArgSelectors.push('#sort-attr', '#sort-dir');
      } else {
        $('.sort-option').remove();
      }

      // Populate drop-downs.
      mainevent.helpers.Widget.fillParserSelect(parser);
      mainevent.helpers.Widget.fillPresetTimeSelect(
        this.$('.time-interval'),
        this.options.acceptAnyTime
      );

      // Apply core attributes (e.g. 'parser') that are already represented
      // by drop-downs or other widgets. Remove them from view.options.searchArgs
      // so they are not redundantly represented as 'x = y' conditions below.
      _.each(coreArgSelectors, function(selector) {
        var name = selector.substr(1);
        if (_.has(view.options.searchArgs, name)) {
          var value = view.options.searchArgs[name];
          if (('time-gte' == name || 'time-lte' == name)) {
            value = moment(parseInt(value, 10)).format(view.datetimePickerFormat);
          }
          view.$(selector).val(value);
          delete view.options.searchArgs[name];
        }
      });

      // Add text boxes for each 'x = y' condition.
      var condCount = 0;
      var condPairModel = this.$('.condition-pair');
      _.each(this.options.searchArgs, function(value, key) {
        if ('skip' == key || 'limit' == key) {
          return;
        }

        // Previously submitted array values.
        value = _.isArray(value) ? value.join(',') : value;

        // Reuse markup for the 1st pair.
        var condPair = condCount++ ? condPairModel.clone() : condPairModel;
        $('input:nth-child(1)', condPair).val(key);
        $('input:nth-child(3)', condPair).val(value);
        modal.append(condPair);
      });
      if (condCount) { // And an extra to hint at expansion behavior.
        view.addConditionRow();
      }

      this.$el.modal('show');
      parser.focus().select();
    },

    events: {
      'submit': 'submit',
      'change .time-interval': 'applyPresetTime',
      'click #time-interval-clear': 'onTimeIntervalClear',
      'click .condition-pair .btn-danger': 'onConditionRowRemove',
      'focus .condition-pair:last-child': 'onLastConditionPairFocus',
      'change .condition-pair input:nth-child(1)': 'onConditionNameChange'
    },

    /**
     * Submit search modal filters.
     *
     * @param event {Object} jQuery event object.
     */
    submit: function(event) {
      mainevent.helpers.Widget.closeModal(event);
      mainevent.helpers.Event.trigger('TimelineSearchSubmit', this.getSearchArgs());
    },

    /**
     * Update time range inputs with a preset relative range.
     *
     * @param event {Object} jQuery event object.
     */
    applyPresetTime: function(event) {
      $('#time-gte').val(moment().subtract('milliseconds', this.$('.time-interval').val()).format(this.datetimePickerFormat));
      $('#time-lte').val(moment().format(this.datetimePickerFormat));

      // Ex. search modal may be a sub-view of the dashboard, which also
      // has a time interval drop-down that reuses the same class.
      event.stopImmediatePropagation();
    },

    onTimeIntervalClear: function(event) {
      event.preventDefault();
      $('#time-interval,#time-gte,#time-lte').val('');
    },

    onConditionRowRemove: function(event) {
      event.preventDefault();
      if (this.$('.condition-pair').length > 1) {
        $(event.currentTarget).parent().remove();
      } else {
        $(event.currentTarget).parent().find('input,select').val('');
      }
    },

    onLastConditionPairFocus: function(event) {
      // Auto-expand the 'x = y' <input> rows.
      if (!$(event.target).hasClass('btn-danger')) {
        this.addConditionRow();
      }
    },

    onConditionNameChange: function(event) {
      var currentTarget = $(event.currentTarget),
          nameVal = currentTarget.val(),
          valueEl = currentTarget.parent().find('input:nth-child(3)');

      if (-1 != this.csvFields.indexOf(nameVal)) {
        // Don't recreate if flagged -- re-enable.
        if (valueEl.data('tooltipSet')) {
          valueEl.tooltip('enable');
        } else {
          valueEl.tooltip({
            placement: 'bottom',
            title: 'Accepts comma-separated values.',
            trigger: 'focus'
          });
          valueEl.data('tooltipSet', true);
        }
      } else {
        valueEl.tooltip('disable');
      }
    },

    /**
     * Append a pair of text boxes for defining 'x = y' conditions.
     */
    addConditionRow: function() {
      var modal = this.$('.modal-body');
      var condPair = modal.find('.condition-pair:last-child').clone();
      $('input:nth-child(1)', condPair).val('');
      $('input:nth-child(3)', condPair).val('');
      modal.append(condPair);
    },

    /**
     * Collect all search arguments.
     *
     * @return {Object}
     */
    getSearchArgs: function() {
      var args = {}, view = this;

      args['parser'] = this.$('.parser').val();
      args['interval'] = this.$('.time-interval').val();

      if (this.options.acceptAnyTime) {
        args['time-gte'] = (new Date($('#time-gte').val())).getTime();
        args['time-lte'] = (new Date($('#time-lte').val())).getTime();
      } else {
        args['time-lte'] = (new Date()).getTime();
        args['time-gte'] = args['time-lte'] - args['interval'];
      }

      // Collect 'x = y', 'x >= y', etc. condition pairs.
      var condPairs = this.$('.condition-pair').each(function(index, pair) {
        var input = $('input', pair),
            key = $(input[0]).val();

        if (!key.length) {
          return;
        }

        var conditional = $('select', pair).val();  // Ex. 'gte'
        if (conditional) {
          // Ex. args['code-gte'] = 302
          args[key + '-' + conditional] = $(input[1]).val();
        } else {
          // Ex. args['code'] = 302
          args[key] = $(input[1]).val();

          if (-1 != view.csvFields.indexOf(key)) {
            args[key] = args[key].split(',');
          }
        }
      });

      if (this.options.acceptSortOptions) {
        args['sort-attr'] = $('#sort-attr').val();
        if (args['sort-attr']) {
          args['sort-dir'] = $('#sort-dir').val();
        }
      }

      return args;
    }
  });
});
<commit_msg>Trim whitespace from CSV.<commit_after>'use strict';

define([], function() {

  /**
   * Displays the search box modal.
   */
  return Backbone.View.extend({
    csvFields: ['tags'],
    datetimePickerFormat: 'MM/DD/YYYY HH:mm:ss',

    initialize: function(options) {
      this.options = _.defaults(options, {
        acceptAnyTime: true,
        acceptSortOptions: true
      });
      this.render();
    },

    render: function() {
      var view = this,
          modal = this.$('.modal-body'),
          parser = this.$('.parser'),
          coreArgSelectors = ['.parser'];

      this.$('.modal-header > h4').text(this.options.title);

      if (this.options.acceptAnyTime) {
        $('#time-gte,#time-lte').each(function() {
          var input = $(this);
          // Invalidate the preset time range after a custom one is selected.
          input.change(function() { view.$('.time-interval').val(''); });
          // Activate date/time widgets when inputs gain focus.
          input.datetimepicker({});
        });

        coreArgSelectors.push('#time-gte', '#time-lte');
      } else {
        $('.any-time').remove();
      }

      if (this.options.acceptSortOptions) {
        coreArgSelectors.push('#sort-attr', '#sort-dir');
      } else {
        $('.sort-option').remove();
      }

      // Populate drop-downs.
      mainevent.helpers.Widget.fillParserSelect(parser);
      mainevent.helpers.Widget.fillPresetTimeSelect(
        this.$('.time-interval'),
        this.options.acceptAnyTime
      );

      // Apply core attributes (e.g. 'parser') that are already represented
      // by drop-downs or other widgets. Remove them from view.options.searchArgs
      // so they are not redundantly represented as 'x = y' conditions below.
      _.each(coreArgSelectors, function(selector) {
        var name = selector.substr(1);
        if (_.has(view.options.searchArgs, name)) {
          var value = view.options.searchArgs[name];
          if (('time-gte' == name || 'time-lte' == name)) {
            value = moment(parseInt(value, 10)).format(view.datetimePickerFormat);
          }
          view.$(selector).val(value);
          delete view.options.searchArgs[name];
        }
      });

      // Add text boxes for each 'x = y' condition.
      var condCount = 0;
      var condPairModel = this.$('.condition-pair');
      _.each(this.options.searchArgs, function(value, key) {
        if ('skip' == key || 'limit' == key) {
          return;
        }

        // Previously submitted array values.
        value = _.isArray(value) ? value.join(',') : value;

        // Reuse markup for the 1st pair.
        var condPair = condCount++ ? condPairModel.clone() : condPairModel;
        $('input:nth-child(1)', condPair).val(key);
        $('input:nth-child(3)', condPair).val(value);
        modal.append(condPair);
      });
      if (condCount) { // And an extra to hint at expansion behavior.
        view.addConditionRow();
      }

      this.$el.modal('show');
      parser.focus().select();
    },

    events: {
      'submit': 'submit',
      'change .time-interval': 'applyPresetTime',
      'click #time-interval-clear': 'onTimeIntervalClear',
      'click .condition-pair .btn-danger': 'onConditionRowRemove',
      'focus .condition-pair:last-child': 'onLastConditionPairFocus',
      'change .condition-pair input:nth-child(1)': 'onConditionNameChange'
    },

    /**
     * Submit search modal filters.
     *
     * @param event {Object} jQuery event object.
     */
    submit: function(event) {
      mainevent.helpers.Widget.closeModal(event);
      mainevent.helpers.Event.trigger('TimelineSearchSubmit', this.getSearchArgs());
    },

    /**
     * Update time range inputs with a preset relative range.
     *
     * @param event {Object} jQuery event object.
     */
    applyPresetTime: function(event) {
      $('#time-gte').val(moment().subtract('milliseconds', this.$('.time-interval').val()).format(this.datetimePickerFormat));
      $('#time-lte').val(moment().format(this.datetimePickerFormat));

      // Ex. search modal may be a sub-view of the dashboard, which also
      // has a time interval drop-down that reuses the same class.
      event.stopImmediatePropagation();
    },

    onTimeIntervalClear: function(event) {
      event.preventDefault();
      $('#time-interval,#time-gte,#time-lte').val('');
    },

    onConditionRowRemove: function(event) {
      event.preventDefault();
      if (this.$('.condition-pair').length > 1) {
        $(event.currentTarget).parent().remove();
      } else {
        $(event.currentTarget).parent().find('input,select').val('');
      }
    },

    onLastConditionPairFocus: function(event) {
      // Auto-expand the 'x = y' <input> rows.
      if (!$(event.target).hasClass('btn-danger')) {
        this.addConditionRow();
      }
    },

    onConditionNameChange: function(event) {
      var currentTarget = $(event.currentTarget),
          nameVal = currentTarget.val(),
          valueEl = currentTarget.parent().find('input:nth-child(3)');

      if (-1 != this.csvFields.indexOf(nameVal)) {
        // Don't recreate if flagged -- re-enable.
        if (valueEl.data('tooltipSet')) {
          valueEl.tooltip('enable');
        } else {
          valueEl.tooltip({
            placement: 'bottom',
            title: 'Accepts comma-separated values.',
            trigger: 'focus'
          });
          valueEl.data('tooltipSet', true);
        }
      } else {
        valueEl.tooltip('disable');
      }
    },

    /**
     * Append a pair of text boxes for defining 'x = y' conditions.
     */
    addConditionRow: function() {
      var modal = this.$('.modal-body');
      var condPair = modal.find('.condition-pair:last-child').clone();
      $('input:nth-child(1)', condPair).val('');
      $('input:nth-child(3)', condPair).val('');
      modal.append(condPair);
    },

    /**
     * Collect all search arguments.
     *
     * @return {Object}
     */
    getSearchArgs: function() {
      var args = {}, view = this;

      args['parser'] = this.$('.parser').val();
      args['interval'] = this.$('.time-interval').val();

      if (this.options.acceptAnyTime) {
        args['time-gte'] = (new Date($('#time-gte').val())).getTime();
        args['time-lte'] = (new Date($('#time-lte').val())).getTime();
      } else {
        args['time-lte'] = (new Date()).getTime();
        args['time-gte'] = args['time-lte'] - args['interval'];
      }

      // Collect 'x = y', 'x >= y', etc. condition pairs.
      var condPairs = this.$('.condition-pair').each(function(index, pair) {
        var input = $('input', pair),
            key = $(input[0]).val();

        if (!key.length) {
          return;
        }

        var conditional = $('select', pair).val();  // Ex. 'gte'
        if (conditional) {
          // Ex. args['code-gte'] = 302
          args[key + '-' + conditional] = $(input[1]).val();
        } else {
          // Ex. args['code'] = 302
          args[key] = $(input[1]).val();

          if (-1 != view.csvFields.indexOf(key)) {
            args[key] = _.map(args[key].split(','), function(s) { return s.trim(); });
          }
        }
      });

      if (this.options.acceptSortOptions) {
        args['sort-attr'] = $('#sort-attr').val();
        if (args['sort-attr']) {
          args['sort-dir'] = $('#sort-dir').val();
        }
      }

      return args;
    }
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
 */

import ActorSDK from '../src/sdk/actor-sdk';
import ActorSDKDelegate from '../src/sdk/actor-sdk-delegate';

const components = {};
const actions = {};
const l18n = {};

const options = {
  endpoints: [
    'wss://front1-ws-mtproto-api-rev2.actor.im',
    'wss://front2-ws-mtproto-api-rev2.actor.im'
  ],
  delegate: new ActorSDKDelegate(components, actions, l18n),
  isExperimental: true
};

const app = new ActorSDK(options);

app.startApp();
<commit_msg>wip(web): Switched to local installation<commit_after>/*
 * Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
 */

import ActorSDK from '../src/sdk/actor-sdk';
import ActorSDKDelegate from '../src/sdk/actor-sdk-delegate';

const components = {};
const actions = {};
const l18n = {};

const options = {
  endpoints: [
    'ws://192.168.1.189:9080'
  ],
  delegate: new ActorSDKDelegate(components, actions, l18n),
  isExperimental: true
};

const app = new ActorSDK(options);

app.startApp();
<|endoftext|>


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

import ViewModeButton from './view-mode-button';
import MetricSelector from './metric-selector';
import { setGraphView, setTableView, setResourceView } from '../actions/app-actions';
import { availableMetricsSelector } from '../selectors/node-metric';
import {
  isResourceViewModeSelector,
  resourceViewAvailableSelector,
} from '../selectors/topology';
import {
  GRAPH_VIEW_MODE,
  TABLE_VIEW_MODE,
  RESOURCE_VIEW_MODE,
} from '../constants/naming';

class ViewModeSelector extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.isResourceViewMode && !nextProps.hasResourceView) {
      nextProps.setGraphView();
    }
  }

  render() {
    return (

          <ViewModeButton
            label="Graph"
            icons="fa fa-share-alt"
            viewMode={GRAPH_VIEW_MODE}
            onClick={this.props.setGraphView}
          />
          <ViewModeButton
            label="Table"
            icons="fa fa-table"
            viewMode={TABLE_VIEW_MODE}
            onClick={this.props.setTableView}
          />
          <ViewModeButton
            label="Resources"
            icons="fa fa-bar-chart"
            viewMode={RESOURCE_VIEW_MODE}
            onClick={this.props.setResourceView}
            disabled={!this.props.hasResourceView}
          />

        <MetricSelector />

    );
  }
}

function mapStateToProps(state) {
  return {
    isResourceViewMode: isResourceViewModeSelector(state),
    hasResourceView: resourceViewAvailableSelector(state),
    showingMetricsSelector: availableMetricsSelector(state).count() > 0,
    topologyViewMode: state.get('topologyViewMode'),
    currentTopology: state.get('currentTopology'),
  };
}

export default connect(
  mapStateToProps,
  { setGraphView, setTableView, setResourceView }
)(ViewModeSelector);
<commit_msg>scripts: replace share icon with sitemap (graph)<commit_after>import React from 'react';
import { connect } from 'react-redux';

import ViewModeButton from './view-mode-button';
import MetricSelector from './metric-selector';
import { setGraphView, setTableView, setResourceView } from '../actions/app-actions';
import { availableMetricsSelector } from '../selectors/node-metric';
import {
  isResourceViewModeSelector,
  resourceViewAvailableSelector,
} from '../selectors/topology';
import {
  GRAPH_VIEW_MODE,
  TABLE_VIEW_MODE,
  RESOURCE_VIEW_MODE,
} from '../constants/naming';

class ViewModeSelector extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.isResourceViewMode && !nextProps.hasResourceView) {
      nextProps.setGraphView();
    }
  }

  render() {
    return (

          <ViewModeButton
            label="Graph"
            icons="fa fa-sitemap"
            viewMode={GRAPH_VIEW_MODE}
            onClick={this.props.setGraphView}
          />
          <ViewModeButton
            label="Table"
            icons="fa fa-table"
            viewMode={TABLE_VIEW_MODE}
            onClick={this.props.setTableView}
          />
          <ViewModeButton
            label="Resources"
            icons="fa fa-bar-chart"
            viewMode={RESOURCE_VIEW_MODE}
            onClick={this.props.setResourceView}
            disabled={!this.props.hasResourceView}
          />

        <MetricSelector />

    );
  }
}

function mapStateToProps(state) {
  return {
    isResourceViewMode: isResourceViewModeSelector(state),
    hasResourceView: resourceViewAvailableSelector(state),
    showingMetricsSelector: availableMetricsSelector(state).count() > 0,
    topologyViewMode: state.get('topologyViewMode'),
    currentTopology: state.get('currentTopology'),
  };
}

export default connect(
  mapStateToProps,
  { setGraphView, setTableView, setResourceView }
)(ViewModeSelector);
<|endoftext|>


<commit_before>class Example extends React.Component {

  getContent = (focused) => (
    <FlexView
      grow
      height={50}
      style={{ border: focused ? '1px solid blue' : undefined, backgroundColor: 'lightgray' }}
    />
  );

  render = () => (
    <FocusableView component={FlexView} style={{ outline: 'none' }}>
      {this.getContent}
    </FocusableView>
  );

}
<commit_msg>FocusableView example style<commit_after>class Example extends React.Component {

  getContent = (focused) => (
    <FlexView
      grow
      height={50}
      style={{
        cursor: 'pointer',
        border: focused ? '1px solid #1a91eb' : '1px solid #ced0da',
        backgroundColor: '#f0f3f8'
      }}
    />
  );

  render = () => (
    <FocusableView component={FlexView} style={{ outline: 'none' }}>
      {this.getContent}
    </FocusableView>
  );

}
<|endoftext|>


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

var BeakerPageObject = require('../../beaker.po.js');
var beakerPO;

describe('Large Integers in Tables and Autotranslation', function (done) {

    beforeAll(function(done){
        beakerPO = new BeakerPageObject();
        browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2FbigIntegerTables.bkr&readOnly=true").then(done);
        beakerPO.waitUntilLoadingFinished();
    });

    afterAll(function(done){
        beakerPO.createScreenshot('bigIntegerTablesTutorial');
        done();
    });

    var valueLong = "";
    it('Should display 64-bit Longs', function () {
        var idCell = "codeaOmhaj";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 1).getText().then(function(value){
            valueLong = value;
            expect(value.length).toBe(19);
            for(var i = 0; i < value.length; i++){
                expect(isFinite(value.substring(i, i+1))).toBe(true);
            }
        });
    });

    var valueBigNum = "";
    it('Should display BigNums', function () {
        var idCell = "codeoVvVNi";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 1).getText().then(function(value){
            valueBigNum = value;
            expect(value.length).toBe(19);
            for(var i = 0; i < value.length; i++){
                expect(isFinite(value.substring(i, i+1))).toBe(true);
            }
        });
    });

    it('Autotranslation of 64-bit Longs', function () {
        var idCell = "codelBVsT5";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 3).getText().then(function(value){
            expect(value).toBe(valueLong);
        });
    });

    it('Autotranslation of BigNums', function () {
        var idCell = "codeWmOT3I";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 3).getText().then(function(value){
            expect(value).toBe(valueBigNum);
        });
    });

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

var BeakerPageObject = require('../../beaker.po.js');
var beakerPO;

describe('Large Integers in Tables and Autotranslation', function (done) {

    beforeAll(function(done){
        beakerPO = new BeakerPageObject();
        browser.get(beakerPO.baseURL + "beaker/#/open?uri=file:config%2Ftutorials%2FbigIntegerTables.bkr&readOnly=true").then(done);
        beakerPO.waitUntilLoadingFinished();
    });

    afterAll(function(done){
        beakerPO.createScreenshot('bigIntegerTablesTutorial');
        done();
    });

    var valueLong = "";
    it('Should display 64-bit Longs', function () {
        var idCell = "codeaOmhaj";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 1).getText().then(function(value){
            valueLong = value;
            expect(value.length).toBe(19);
            for(var i = 0; i < value.length; i++){
                expect(isFinite(value.substring(i, i+1))).toBe(true);
            }
        });
    });

    var valueBigNum = "";
    it('Should display BigNums', function () {
        var idCell = "codeoVvVNi";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 1).getText().then(function(value){
            valueBigNum = value;
            expect(value.length).toBe(19);
            for(var i = 0; i < value.length; i++){
                expect(isFinite(value.substring(i, i+1))).toBe(true);
            }
        });
    });

    it('Autotranslation of 64-bit Longs', function () {
        var idCell = "codelBVsT5";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 3).getText().then(function(value){
            expect(value).toBe(valueLong);
        });
    });

    it('Autotranslation of BigNums', function () {
        var idCell = "codeWmOT3I";
        beakerPO.scrollToBkCellByIdCell(idCell);
        beakerPO.clickCodeCellInputButtonByIdCell(idCell, 'Table');
        beakerPO.getDataTablesColumnByIdCell(idCell, 3).getText().then(function(value){
            expect(value).toBe(valueBigNum);
        });
    });

});<|endoftext|>


<commit_before>function missing_avatar(element) {
  element.src = '/images/missing_thumb.png';
}

jQuery(function() {

  // Search button
  var $oldSearch = jQuery('#query');
  var $newSearch = jQuery('<input type="search">');
  $newSearch.attr({
     name     : 'query',
     id       : 'query',
     value    : $oldSearch.val(),
     results  : '5'
  });
  $oldSearch.replaceWith($newSearch);
  jQuery('#search-tasks input[type=submit]').hide();

  // Task actions
  jQuery('.task-actions').hide();
  jQuery('.task .bubble').hover(
    function() {
      jQuery(this).find('.task-actions').show();
    },
    function() {
      jQuery(this).find('.task-actions').hide();
    }
  );

  // Add comment
  // var $addComment = jQuery('
Add a comment
');
  //   var $newCommentForm = jQuery('#new_comment');
  //   $newCommentForm.before($addComment).hide();
  //   $addComment.click(function() {
  //     $newCommentForm.show();
  //     jQuery(this).hide();
  //     return false;
  //   });

  // Textarea counter
  if (jQuery('textarea').length > 0) {
    var maxChars = (jQuery('#comment_message').length > 0) ? 1000 : 255;
    var oldMsg = jQuery(this).attr('value');
    var countChars = function(val) {
      var cur = 0;
      if(val) {
        cur = val.length;
      }
      var charsLeft = maxChars - cur;
      jQuery('div.counter').text(charsLeft.toString())
    }
    var limitChars = function() {
      oldMsg = jQuery(this).attr('value');
      return (oldMsg.length < maxChars);
    }

    jQuery('textarea').after('

').each(function() {
      countChars(jQuery(this).attr('value'));
      jQuery(this)
        .bind('keypress', limitChars)
        .bind('paste', limitChars)
        .bind('keyup', function() {
          if (jQuery(this).attr('value').length > maxChars) {
            jQuery(this).attr('value', oldMsg);
          }
          countChars(jQuery(this).attr('value'));
        });
    });
  }

  // Refactor following

  jQuery.fn.appendAttachment = function() {
    var parent = jQuery(this).parent()
    var ts = new Date().getTime()
    var input = parent.html().replace(/attributes]\[\d+]/, 'attributes][' + ts + ']').replace(/attributes_\d+_/, 'attributes_' + ts + '_')
    var wrapper = jQuery('
').html(input)
    parent.after(wrapper)
    wrapper.children().change(function() {
      jQuery(this).appendAttachment()
    });
    return this
  }

  // Attach multiple files
  jQuery("input[type=file]").change(function() {
    jQuery(this).appendAttachment()
  });

  var viewportWidth = jQuery(window).width();
  if(viewportWidth < 800) {
    jQuery('#aside').remove()
    jQuery('#header').find('select').remove()
  } else {

    // Dress up search form
    jQuery('form#search').find('input[type=submit]').remove();
    jQuery('form#search').find('#query').map(function() {
      if(jQuery(this).val() == '' || jQuery(this).val() == 'Type your query') {
        jQuery(this).val('Type your query').addClass('labeled').focus(function() {
          jQuery(this).val('').removeClass('labeled')
        });
      }
    });

    // Rework nav select
    jQuery('#header select').change(function() {
      if(jQuery(this).val() != '') {
        window.location = jQuery(this).val()
      }
    })
  }
})<commit_msg>Dont restrict char count on comments and project descriptions<commit_after>function missing_avatar(element) {
  element.src = '/images/missing_thumb.png';
}

jQuery(function() {

  // Search button
  var $oldSearch = jQuery('#query');
  var $newSearch = jQuery('<input type="search">');
  $newSearch.attr({
     name     : 'query',
     id       : 'query',
     value    : $oldSearch.val(),
     results  : '5'
  });
  $oldSearch.replaceWith($newSearch);
  jQuery('#search-tasks input[type=submit]').hide();

  // Task actions
  jQuery('.task-actions').hide();
  jQuery('.task .bubble').hover(
    function() {
      jQuery(this).find('.task-actions').show();
    },
    function() {
      jQuery(this).find('.task-actions').hide();
    }
  );

  // Add comment
  // var $addComment = jQuery('
Add a comment
');
  //   var $newCommentForm = jQuery('#new_comment');
  //   $newCommentForm.before($addComment).hide();
  //   $addComment.click(function() {
  //     $newCommentForm.show();
  //     jQuery(this).hide();
  //     return false;
  //   });

  // Textarea counter
  if (jQuery('#task_message').length > 0) {
    var maxChars = 255;
    var oldMsg = jQuery(this).attr('value');
    var countChars = function(val) {
      var cur = 0;
      if(val) {
        cur = val.length;
      }
      var charsLeft = maxChars - cur;
      jQuery('div.counter').text(charsLeft.toString())
    }
    var limitChars = function() {
      oldMsg = jQuery(this).attr('value');
      return (oldMsg.length < maxChars);
    }

    jQuery('#task_message').after('

').each(function() {
      countChars(jQuery(this).attr('value'));
      jQuery(this)
        .bind('keypress', limitChars)
        .bind('paste', limitChars)
        .bind('keyup', function() {
          if (jQuery(this).attr('value').length > maxChars) {
            jQuery(this).attr('value', oldMsg);
          }
          countChars(jQuery(this).attr('value'));
        });
    });
  }

  // Refactor following

  jQuery.fn.appendAttachment = function() {
    var parent = jQuery(this).parent()
    var ts = new Date().getTime()
    var input = parent.html().replace(/attributes]\[\d+]/, 'attributes][' + ts + ']').replace(/attributes_\d+_/, 'attributes_' + ts + '_')
    var wrapper = jQuery('
').html(input)
    parent.after(wrapper)
    wrapper.children().change(function() {
      jQuery(this).appendAttachment()
    });
    return this
  }

  // Attach multiple files
  jQuery("input[type=file]").change(function() {
    jQuery(this).appendAttachment()
  });

  var viewportWidth = jQuery(window).width();
  if(viewportWidth < 800) {
    jQuery('#aside').remove()
    jQuery('#header').find('select').remove()
  } else {

    // Dress up search form
    jQuery('form#search').find('input[type=submit]').remove();
    jQuery('form#search').find('#query').map(function() {
      if(jQuery(this).val() == '' || jQuery(this).val() == 'Type your query') {
        jQuery(this).val('Type your query').addClass('labeled').focus(function() {
          jQuery(this).val('').removeClass('labeled')
        });
      }
    });

    // Rework nav select
    jQuery('#header select').change(function() {
      if(jQuery(this).val() != '') {
        window.location = jQuery(this).val()
      }
    })
  }
})<|endoftext|>


<commit_before>const request = require('request');
var _ = require( "underscore" );

var results = []
var survey_result = {}

if (!process.env.page_token) {
    console.log('Error: Specify page_token in environment');
    process.exit(1);
}

if (!process.env.verify_token) {
    console.log('Error: Specify verify_token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.facebookbot({
    debug: false,
    access_token: process.env.page_token,
    verify_token: process.env.verify_token,
});

var bot = controller.spawn({
});

controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
    controller.createWebhookEndpoints(webserver, bot, function() {
        console.log('ONLINE!');
    });
});

controller.hears(['hi','Hi'], 'message_received', function(bot, message) {
    getProfile(message.user, (err, profile) => {
        var found_result = _.findWhere(results, {id: message.user});
        if (found_result == undefined){
            bot.reply(message, `Hello ${profile.first_name}`);
            askSurvey(bot, message);
        } else {
            bot.reply(message, `Hello ${profile.first_name}, you have already done the survey`);
            redoSurvey(bot, message)
        }
    });

});
// POSTBACK HANLDER
controller.on('facebook_postback', function(bot, message) {
    if (message.payload == 'yes(start)') {
        bot.reply(message, `Excellent! Lets get started.`);
        getProfile(message.user, (err, profile) => {
            survey_result.id = message.user
            survey_result.user = `${profile.first_name} ${profile.last_name}`
            survey_result.gender = `${profile.gender}`
            survey_result.locale = `${profile.locale}`
            survey_result.timezone = `${profile.timezone}`
        });
        askRelationship(bot, message)
    } else if (message.payload == 'I love it' || message.payload == 'I hate it' || message.payload == 'Guilty pleasure') {

            if (survey_result.relationship == null) {
                survey_result.relationship = message.payload
                askDetail(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'I make it myself' || message.payload == 'KFC is my go to' || message.payload == 'Any way is good' || message.payload == 'Fried food is gross' || message.payload == `I don't eat animals` || message.payload == `It's a secret` || message.payload == `reward` ||message.payload == `cures hangover`) {

            if (survey_result.detail == null) {
                survey_result.detail = message.payload
                askMood(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == '(•‿•)' || message.payload == '(•︵•)' || message.payload == '(•_•)') {

            if (survey_result.mood == null) {
                survey_result.mood = message.payload
                askPreference(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'Chicken Parmesan' || message.payload == 'Double Down' || message.payload == 'Fried Drumsticks' || message.payload == 'Chicken Nuggets' || message.payload == 'Veggies') {

            if (survey_result.preference == null) {
                survey_result.preference = message.payload
                askHungry(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'yes' || message.payload == 'no' ) {

            if (survey_result.hungry == null) {
                survey_result.hungry = message.payload
                saveResults(bot, message)
            } else if (survey_result == {}){
            bot.reply(message, `You've already answered that question.`);
            }
    } else if (message.payload == 'no(survey)') {
        sayThanks(bot, message)
    } else if (message.payload == 'View results') {
        viewResults(bot, message)
    } else if (message.payload == 'Re-do survey') {
        bot.reply(message, `Excellent! Lets get started.`);
        survey_result = {}
        getProfile(message.user, (err, profile) => {
            survey_result.id = message.user
            survey_result.user = `${profile.first_name} ${profile.last_name}`
        });
        askRelationship(bot, message)
    }
});
// QUESTIONS
viewResults = function(bot, message) {
    var found_result = _.findWhere(results, {id: message.user});
    var text = JSON.stringify(found_result)
    bot.reply(message, `${text}`);

}

askSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Do you have a moment to answer some questions about fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':`Yes`,
                'payload':`yes(start)`
                },
                {
                'type':'postback',
                'title':`No`,
                'payload':`no(survey)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askRelationship = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text':  'What would you say your relationship is with fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':'I love it',
                'payload':'I love it'
                },
                {
                'type':'postback',
                'title':'I hate it',
                'payload':'I hate it'
                },
                {
                'type':'postback',
                'title':'Guilty pleasure',
                'payload':'Guilty pleasure'
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askDetail = function(bot, message) {
    if (message.payload == 'I love it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'What is your favourite way to eat fried chicken ?',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'I make it myself',
                    'payload':'I make it myself'
                    },
                    {
                    'type':'postback',
                    'title':'KFC is my go to',
                    'payload':'KFC is my go to'
                    },
                    {
                    'type':'postback',
                    'title':'Any way is good',
                    'payload':'Any way is good'
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'I hate it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'Not a fan ? tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'Fried food is gross',
                    'payload':'Fried food is gross'
                    },
                    {
                    'type':'postback',
                    'title':`I don't eat animals`,
                    'payload':`I don't eat animals`
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'Guilty pleasure') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text':  'Guilty pleasure you say, tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'When Hungover',
                    'payload':'cures hangover'
                    },
                    {
                    'type':'postback',
                    'title':'Reward for myself',
                    'payload':'reward'
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else  {
        bot.reply(message, 'oops')
    }

}

askMood = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'What is your current mood ?',
            'buttons':[
                {
                'type':'postback',
                'title':`(•‿•)`,
                'payload':`(•‿•)`
                },
                {
                'type':'postback',
                'title':`(•︵•)`,
                'payload':`(•︵•)`
                },
                {
                'type':'postback',
                'title':`(•_•)`,
                'payload':`(•_•)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

askPreference = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload': {
                'template_type': 'generic',
                'elements': [
                    {
                        'title': 'Chicken Parmesan',
                        'image_url': 'http://fiber-international.com/wp-content/uploads/2015/04/800x600-chicken.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Parmesan'
                            }
                        ]
                    },
                    {
                        'title': 'Double Down',
                        'image_url': 'http://assets.bwbx.io/images/ieMg5BCeWkWU/v1/-1x-1.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Double Down'
                            }
                        ]
                    },
                    {
                        'title': 'Fried Drumsticks',
                        'image_url': 'https://i.ytimg.com/vi/G8hbFO-r2nQ/maxresdefault.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Fried Drumsticks'
                            }
                        ]
                    },
                    {
                        'title': 'Chicken Nuggets',
                        'image_url': 'http://www.urbanmommies.com/wp-content/uploads/McDonalds-Chicken-Nuggets.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Nuggets'
                            }
                        ]
                    },
                    {
                        'title': 'Veggies',
                        'image_url': 'http://www.stevensonfitness.com/wp-content/uploads/2014/10/veggies.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Veggies'
                            }
                        ]
                    }
                ]
            }
    };

    bot.reply(message, {
        attachment: attachment,
    });

    bot.reply(message, 'Which of these meals your you like to be eating right now ?');
}

askHungry = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Have I made you hungry ?',
            'buttons':[
                {
                'type':'postback',
                'title':`yes`,
                'payload':`yes`
                },
                {
                'type':'postback',
                'title':`no`,
                'payload':`no`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// OTHER RESPONSES
sayThanks = function(bot, message) {
  bot.reply(message, 'OK! thanks for your time');
}

saveResults = function(bot, message) {
    results.push(survey_result)
    console.log(results)
    redoSurvey(bot, message)
}

redoSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'OK! thanks for your time',
            'buttons':[
                {
                'type':'postback',
                'title':`view results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`re-do survey`,
                'payload':`Re-do survey`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// GET USER INFO !!!()
getProfile = function (id, cb) {
    if (!cb) cb = Function.prototype

    request({
      method: 'GET',
      uri: `https://graph.facebook.com/v2.6/${id}`,
      qs: {
        fields: 'first_name,last_name,profile_pic,gender,locale,timezone',
        access_token: process.env.page_token
      },
      json: true
    }, (err, res, body) => {
      if (err) return cb(err)
      if (body.error) return cb(body.error)

      cb(null, body)
    })
}
<commit_msg>removed =><commit_after>const request = require('request');
var _ = require( "underscore" );

var results = []
var survey_result = {}

if (!process.env.page_token) {
    console.log('Error: Specify page_token in environment');
    process.exit(1);
}

if (!process.env.verify_token) {
    console.log('Error: Specify verify_token in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.facebookbot({
    debug: false,
    access_token: process.env.page_token,
    verify_token: process.env.verify_token,
});

var bot = controller.spawn({
});

controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
    controller.createWebhookEndpoints(webserver, bot, function() {
        console.log('ONLINE!');
    });
});

controller.hears(['hi','Hi'], 'message_received', function(bot, message) {
    getProfile(message.user, function(err, profile) {
        var found_result = _.findWhere(results, {id: message.user});
        if (found_result == undefined){
            bot.reply(message, `Hello ${profile.first_name}`);
            askSurvey(bot, message);
        } else {
            bot.reply(message, `Hello ${profile.first_name}, you have already done the survey`);
            redoSurvey(bot, message)
        }
    });

});
// POSTBACK HANLDER
controller.on('facebook_postback', function(bot, message) {
    if (message.payload == 'yes(start)') {
        bot.reply(message, `Excellent! Lets get started.`);
        getProfile(message.user, function(err, profile) {
            survey_result.id = message.user
            survey_result.user = `${profile.first_name} ${profile.last_name}`
            survey_result.gender = `${profile.gender}`
            survey_result.locale = `${profile.locale}`
            survey_result.timezone = `${profile.timezone}`
        });
        askRelationship(bot, message)
    } else if (message.payload == 'I love it' || message.payload == 'I hate it' || message.payload == 'Guilty pleasure') {

            if (survey_result.relationship == null) {
                survey_result.relationship = message.payload
                askDetail(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'I make it myself' || message.payload == 'KFC is my go to' || message.payload == 'Any way is good' || message.payload == 'Fried food is gross' || message.payload == `I don't eat animals` || message.payload == `It's a secret` || message.payload == `reward` ||message.payload == `cures hangover`) {

            if (survey_result.detail == null) {
                survey_result.detail = message.payload
                askMood(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == '(•‿•)' || message.payload == '(•︵•)' || message.payload == '(•_•)') {

            if (survey_result.mood == null) {
                survey_result.mood = message.payload
                askPreference(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'Chicken Parmesan' || message.payload == 'Double Down' || message.payload == 'Fried Drumsticks' || message.payload == 'Chicken Nuggets' || message.payload == 'Veggies') {

            if (survey_result.preference == null) {
                survey_result.preference = message.payload
                askHungry(bot, message)
            } else {
                bot.reply(message, `You've already answered that question.`);
            }

    } else if (message.payload == 'yes' || message.payload == 'no' ) {

            if (survey_result.hungry == null) {
                survey_result.hungry = message.payload
                saveResults(bot, message)
            } else if (survey_result == {}){
            bot.reply(message, `You've already answered that question.`);
            }
    } else if (message.payload == 'no(survey)') {
        sayThanks(bot, message)
    } else if (message.payload == 'View results') {
        viewResults(bot, message)
    } else if (message.payload == 'Re-do survey') {
        bot.reply(message, `Excellent! Lets get started.`);
        survey_result = {}
        getProfile(message.user, function(err, profile) {
            survey_result.id = message.user
            survey_result.user = `${profile.first_name} ${profile.last_name}`
        });
        askRelationship(bot, message)
    }
});
// QUESTIONS
viewResults = function(bot, message) {
    var found_result = _.findWhere(results, {id: message.user});
    var text = JSON.stringify(found_result)
    bot.reply(message, `${text}`);

}

askSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Do you have a moment to answer some questions about fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':`Yes`,
                'payload':`yes(start)`
                },
                {
                'type':'postback',
                'title':`No`,
                'payload':`no(survey)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askRelationship = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text':  'What would you say your relationship is with fried chicken ?',
            'buttons':[
                {
                'type':'postback',
                'title':'I love it',
                'payload':'I love it'
                },
                {
                'type':'postback',
                'title':'I hate it',
                'payload':'I hate it'
                },
                {
                'type':'postback',
                'title':'Guilty pleasure',
                'payload':'Guilty pleasure'
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });
}

askDetail = function(bot, message) {
    if (message.payload == 'I love it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'What is your favourite way to eat fried chicken ?',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'I make it myself',
                    'payload':'I make it myself'
                    },
                    {
                    'type':'postback',
                    'title':'KFC is my go to',
                    'payload':'KFC is my go to'
                    },
                    {
                    'type':'postback',
                    'title':'Any way is good',
                    'payload':'Any way is good'
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'I hate it') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text': 'Not a fan ? tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'Fried food is gross',
                    'payload':'Fried food is gross'
                    },
                    {
                    'type':'postback',
                    'title':`I don't eat animals`,
                    'payload':`I don't eat animals`
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else if (message.payload == 'Guilty pleasure') {
        var attachment = {
            'type':'template',
            'payload':{
                'template_type':'button',
                'text':  'Guilty pleasure you say, tell me more.',
                'buttons':[
                    {
                    'type':'postback',
                    'title':'When Hungover',
                    'payload':'cures hangover'
                    },
                    {
                    'type':'postback',
                    'title':'Reward for myself',
                    'payload':'reward'
                    },
                    {
                    'type':'postback',
                    'title':`It's a secret`,
                    'payload':`It's a secret`
                    }
                ]
            }
        };

        bot.reply(message, {
            attachment: attachment,
        });

    } else  {
        bot.reply(message, 'oops')
    }

}

askMood = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'What is your current mood ?',
            'buttons':[
                {
                'type':'postback',
                'title':`(•‿•)`,
                'payload':`(•‿•)`
                },
                {
                'type':'postback',
                'title':`(•︵•)`,
                'payload':`(•︵•)`
                },
                {
                'type':'postback',
                'title':`(•_•)`,
                'payload':`(•_•)`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}

askPreference = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload': {
                'template_type': 'generic',
                'elements': [
                    {
                        'title': 'Chicken Parmesan',
                        'image_url': 'http://fiber-international.com/wp-content/uploads/2015/04/800x600-chicken.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Parmesan'
                            }
                        ]
                    },
                    {
                        'title': 'Double Down',
                        'image_url': 'http://assets.bwbx.io/images/ieMg5BCeWkWU/v1/-1x-1.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Double Down'
                            }
                        ]
                    },
                    {
                        'title': 'Fried Drumsticks',
                        'image_url': 'https://i.ytimg.com/vi/G8hbFO-r2nQ/maxresdefault.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Fried Drumsticks'
                            }
                        ]
                    },
                    {
                        'title': 'Chicken Nuggets',
                        'image_url': 'http://www.urbanmommies.com/wp-content/uploads/McDonalds-Chicken-Nuggets.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Chicken Nuggets'
                            }
                        ]
                    },
                    {
                        'title': 'Veggies',
                        'image_url': 'http://www.stevensonfitness.com/wp-content/uploads/2014/10/veggies.jpg',
                        'buttons': [
                            {
                                'type': 'postback',
                                'title': 'Choose',
                                'payload': 'Veggies'
                            }
                        ]
                    }
                ]
            }
    };

    bot.reply(message, {
        attachment: attachment,
    });

    bot.reply(message, 'Which of these meals your you like to be eating right now ?');
}

askHungry = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'Have I made you hungry ?',
            'buttons':[
                {
                'type':'postback',
                'title':`yes`,
                'payload':`yes`
                },
                {
                'type':'postback',
                'title':`no`,
                'payload':`no`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// OTHER RESPONSES
sayThanks = function(bot, message) {
  bot.reply(message, 'OK! thanks for your time');
}

saveResults = function(bot, message) {
    results.push(survey_result)
    console.log(results)
    redoSurvey(bot, message)
}

redoSurvey = function(bot, message) {
    var attachment = {
        'type':'template',
        'payload':{
            'template_type':'button',
            'text': 'OK! thanks for your time',
            'buttons':[
                {
                'type':'postback',
                'title':`view results`,
                'payload':`View results`
                },
                {
                'type':'postback',
                'title':`re-do survey`,
                'payload':`Re-do survey`
                }
            ]
        }
    };

    bot.reply(message, {
        attachment: attachment,
    });

}
// GET USER INFO !!!
getProfile = function (id, cb) {
    if (!cb) cb = Function.prototype

    request({
      method: 'GET',
      uri: `https://graph.facebook.com/v2.6/${id}`,
      qs: {
        fields: 'first_name,last_name,profile_pic,gender,locale,timezone',
        access_token: process.env.page_token
      },
      json: true
    }, function(err, res, body) {
      if (err) return cb(err)
      if (body.error) return cb(body.error)

      cb(null, body)
    })
}
<|endoftext|>


<commit_before>'use strict';

import './main.less';

import angular from 'angular';
import ngRouter from 'angular-route';
import ngSanitize from 'angular-sanitize';
import angulartics from 'angulartics';
import ga from 'angulartics-google-analytics';

import shared from './shared/sharedModule';
import pages from './pages/pagesModule';
import board from './board/boardModule';

export default angular.module('app', [
    ngRouter,
    ngSanitize,
    angulartics,
    ga,
    shared,
    pages,
    board
]).name;
<commit_msg>Add require with new favicons<commit_after>'use strict';

import './main.less';

import 'file!./favicon.ico';
import 'file!./favicon-32.ico';
import 'file!./favicon-152.png';

// 123

import angular from 'angular';
import ngRouter from 'angular-route';
import ngSanitize from 'angular-sanitize';
import angulartics from 'angulartics';
import ga from 'angulartics-google-analytics';

import shared from './shared/sharedModule';
import pages from './pages/pagesModule';
import board from './board/boardModule';

export default angular.module('app', [
    ngRouter,
    ngSanitize,
    angulartics,
    ga,
    shared,
    pages,
    board
]).name;
<|endoftext|>