<commit_before>/*jshint node: true */
'use strict';

/*
* Name :  BarChart.js
* Module : FrontEnd::Model::GraphsModel
* Location : /frontend/app/Model/GraphsModel
*
* History :
* Version       Date        Programmer                  Description
* ===============================================================================================================
* 0.3.0         2015-05-18  Francesco Rossetto          Modified general structure, some fixes
*
* 0.2.1         2015-05-15  Francesco Rossetto          Various fixes, insert inzializeData
*
* 0.2.0         2015-05-14  Maria Giovanna Chinellato   Add all methods and fix class
*
* 0.1.0         2015-05-14  Maria Giovanna Chinellato   Add all attributes, add methods split and updateParameter
*
* 0.0.1         2015-05-14  Maria Giovanna Chinellato   Initial code
* ===============================================================================================================
*
*/

angular.module('services')
.factory('BarChart', ['Graph', 'Axis', 'BarChartFlow', function(Graph, Axis, BarChartFlow){

    var axisX = null;
    var axisY = null;
    var barOrientation = 'vertical';
    var background = '#FFF';
    var sortable = true;
    var barsGrouping = 'grouped';

    BarChart.prototype = Object.create(Graph.prototype);
    BarChart.prototype.constructor = BarChart;
    BarChart.prototype.parent = Graph.prototype;

    function split(json) {
        var graphJson = {};
        if (json.title !== undefined) {
            graphJson.title = json.title;
        }
        if (json.height !== undefined) {
            graphJson.height = json.height;
        }
        if (json.width !== undefined) {
            graphJson.width = json.width;
        }
        if (json.enabledLegend !== undefined) {
            graphJson.enabledLegend = json.enabledLegend;
            if (graphJson.enabledLegend && json.legend !== undefined) {
                graphJson.legend = json.legend;
            }
        }
        if (json.horizontalGrid !== undefined) {
            graphJson.horizontalGrid = json.horizontalGrid;
        }
        if (json.verticalGrid !== undefined) {
            graphJson.verticalGrid = json.verticalGrid;
        }

        var barJson = {};
        if (json.axisX !== undefined) {
            barJson.axisX = json.axisX;
        }
        if (json.axisY !== undefined) {
            barJson.axisY = json.axisY;
        }
        if (json.barOrientation !== undefined) {
            barJson.barOrientation = json.barOrientation;
        }
        if (json.background !== undefined) {
            barJson.background = json.background;
        }
        if (json.sortable !== undefined) {
            barJson.sortable = json.sortable;
        }
        if (json.barsGrouping !== undefined) {
            barJson.barsGrouping = json.barsGrouping;
        }

        return {
            'graphJson' : graphJson,
            'barJson' : barJson
        };
    }

    //BarChart.prototype.test = function _Test(expressionStr) { return eval(expressionStr); };

    // create our new custom object that reuse the original object constructor
    function BarChart(info) {
        this.parent.constructor.call(this, info);
    }

    BarChart.prototype.updateParameters = function(info) {
        if (info !== undefined) {
            var json = split(info);
            var gJson = json.graphJson;
            var bJson = json.barJson;
            if (Object.keys(gJson).length !== 0) {
                this.parent.updateParameters.call(this, gJson);
            }
            if (Object.keys(bJson).length !== 0) {
                if (bJson.axisX !== undefined) {
                    axisX = new Axis(bJson.axisX);
                }
                if (bJson.axisY !== undefined) {
                    axisY = new Axis(bJson.axisY);
                }
                if (bJson.barOrientation !== undefined) {
                    barOrientation = bJson.barOrientation;
                }
                if (bJson.background !== undefined) {
                    background = bJson.background;
                }
                if (bJson.sortable !== undefined) {
                    sortable = bJson.sortable;
                }
                if (bJson.barsGrouping !== undefined) {
                    barsGrouping = bJson.barsGrouping;
                }
            }
            if (info.flows !== undefined) {
                for (var i=0; i<info.flows.length; i++) {
                    var newflow = new BarChartFlow(info.flows[i]);
                    this.addFlow(info.flows[i].ID, newflow);
                }
            }
        }
        return this;
    };

    BarChart.prototype.addFlow = function(newId, newFlow) {
        if (newFlow instanceof BarChartFlow) {
            console.log('bar chart add flow');
            this.parent.addFlow.call(this, newId, newFlow);
        }
        return this;
    };

    BarChart.prototype.initializeData = function(newData) {  //inizialization data of flows
        if (newData !== undefined) {
            var flowList = this.parent.getFlowList();
            console.log('flowlist length ' + flowList.length + 'newData length ' + newData.length);
            for (var i=0; i<newData.length; i++) {
                for (var j=0; j<flowList.length; j++) {
                    if (flowList[j].id === newData[i].ID) {
                        console.log('flowlist[j].id ' + flowList[j].id);
                        flowList[j].initializeData(newData[i]);
                        console.log('flow list stampa ' + flowList[j].toString());
                    }
                }
            }
        }
        return this;
    };

    // update data
    BarChart.prototype.inPlaceUpdate = function(newData) {
        if (newData !== undefined) {
            var flowList = this.parent.getFlowList();
            for (var j=0; j<flowList.length; j++) {
                if (flowList[j].id === newData.ID) {
                    flowList[j].inPlaceUpdate(newData);
                }
            }
        }
        return this;
    };

    // get method
    BarChart.prototype.getX = function() {
        return axisX;
    };
    BarChart.prototype.getY = function() {
        return axisY;
    };
    BarChart.prototype.getBarOrientation = function() {
        return barOrientation;
    };
    BarChart.prototype.getBackground = function() {
        return background;
    };
    BarChart.prototype.getSortable = function() {
        return sortable;
    };
    BarChart.prototype.getBarsGrouping = function() {
        return barsGrouping;
    };

    return BarChart;

}]);<commit_msg>some fixes<commit_after>/*jshint node: true */
'use strict';

/*
* Name :  BarChart.js
* Module : FrontEnd::Model::GraphsModel
* Location : /frontend/app/Model/GraphsModel
*
* History :
* Version       Date        Programmer                  Description
* ===============================================================================================================
* 0.3.0         2015-05-18  Francesco Rossetto          Modified general structure, some fixes
*
* 0.2.1         2015-05-15  Francesco Rossetto          Various fixes, insert inzializeData
*
* 0.2.0         2015-05-14  Maria Giovanna Chinellato   Add all methods and fix class
*
* 0.1.0         2015-05-14  Maria Giovanna Chinellato   Add all attributes, add methods split and updateParameter
*
* 0.0.1         2015-05-14  Maria Giovanna Chinellato   Initial code
* ===============================================================================================================
*
*/

angular.module('services')
.factory('BarChart', ['Graph', 'Axis', 'BarChartFlow', function(Graph, Axis, BarChartFlow){

    var axisX = null;
    var axisY = null;
    var barOrientation = 'vertical';
    var background = '#FFF';
    var sortable = true;
    var barsGrouping = 'grouped';

    BarChart.prototype = Object.create(Graph.prototype);
    BarChart.prototype.constructor = BarChart;
    BarChart.prototype.parent = Graph.prototype;

    function split(json) {
        var graphJson = {};
        if (json.title !== undefined) {
            graphJson.title = json.title;
        }
        if (json.height !== undefined) {
            graphJson.height = json.height;
        }
        if (json.width !== undefined) {
            graphJson.width = json.width;
        }
        if (json.enabledLegend !== undefined) {
            graphJson.enabledLegend = json.enabledLegend;
            if (graphJson.enabledLegend && json.legend !== undefined) {
                graphJson.legend = json.legend;
            }
        }
        if (json.horizontalGrid !== undefined) {
            graphJson.horizontalGrid = json.horizontalGrid;
        }
        if (json.verticalGrid !== undefined) {
            graphJson.verticalGrid = json.verticalGrid;
        }

        var barJson = {};
        if (json.axisX !== undefined) {
            barJson.axisX = json.axisX;
        }
        if (json.axisY !== undefined) {
            barJson.axisY = json.axisY;
        }
        if (json.barOrientation !== undefined) {
            barJson.barOrientation = json.barOrientation;
        }
        if (json.background !== undefined) {
            barJson.background = json.background;
        }
        if (json.sortable !== undefined) {
            barJson.sortable = json.sortable;
        }
        if (json.barsGrouping !== undefined) {
            barJson.barsGrouping = json.barsGrouping;
        }

        return {
            'graphJson' : graphJson,
            'barJson' : barJson
        };
    }

    //BarChart.prototype.test = function _Test(expressionStr) { return eval(expressionStr); };

    // create our new custom object that reuse the original object constructor
    function BarChart(info) {
        this.parent.constructor.call(this, info);
    }

    BarChart.prototype.updateParameters = function(info) {
        if (info !== undefined) {
            var json = split(info);
            var gJson = json.graphJson;
            var bJson = json.barJson;
            if (Object.keys(gJson).length !== 0) {
                this.parent.updateParameters.call(this, gJson);
            }
            if (Object.keys(bJson).length !== 0) {
                if (bJson.axisX !== undefined) {
                    axisX = new Axis(bJson.axisX);
                }
                if (bJson.axisY !== undefined) {
                    axisY = new Axis(bJson.axisY);
                }
                if (bJson.barOrientation !== undefined) {
                    barOrientation = bJson.barOrientation;
                }
                if (bJson.background !== undefined) {
                    background = bJson.background;
                }
                if (bJson.sortable !== undefined) {
                    sortable = bJson.sortable;
                }
                if (bJson.barsGrouping !== undefined) {
                    barsGrouping = bJson.barsGrouping;
                }
            }
            if (info.flows !== undefined) {
                for (var i=0; i<info.flows.length; i++) {
                    var newflow = new BarChartFlow(info.flows[i]);
                    this.addFlow(info.flows[i].ID, newflow);
                }
            }
        }
        return this;
    };

    BarChart.prototype.addFlow = function(newId, newFlow) {
        if (newFlow instanceof BarChartFlow) {
            console.log('bar chart add flow');
            this.parent.addFlow.call(this, newId, newFlow);
        }
        return this;
    };

    BarChart.prototype.initializeData = function(newData) {  //inizialization data of flows
        if (newData !== undefined) {
            var fList = this.parent.getFlowList();
            console.log('flowlist length ' + fList.length + 'newData length ' + newData.length);
            for (var i=0; i<newData.length; i++) {
                for (var j=0; j<fList.length; j++) {
                    if (fList[j].id === newData[i].ID) {
                        console.log('flowlist[j].id ' + fList[j].id);
                        fList[j].initializeData(newData[i]);
                        console.log('flow list stampa ' + fList[j].toString());
                    }
                }
            }
        }
        return this;
    };

    // update data
    BarChart.prototype.inPlaceUpdate = function(newData) {
        if (newData !== undefined) {
            var fList = this.parent.getFlowList();
            for (var j=0; j<fList.length; j++) {
                if (fList[j].id === newData.ID) {
                    fList[j].inPlaceUpdate(newData);
                }
            }
        }
        return this;
    };

    // get method
    BarChart.prototype.getX = function() {
        return axisX;
    };
    BarChart.prototype.getY = function() {
        return axisY;
    };
    BarChart.prototype.getBarOrientation = function() {
        return barOrientation;
    };
    BarChart.prototype.getBackground = function() {
        return background;
    };
    BarChart.prototype.getSortable = function() {
        return sortable;
    };
    BarChart.prototype.getBarsGrouping = function() {
        return barsGrouping;
    };

    return BarChart;

}]);<|endoftext|>


<commit_before>import React from 'react';
import app from '../Firebase';
import TripsContainer from './trips-container'

const db = app.firestore();

/**
 * Temporary hardcoded function that returns the current users email.
 *
 * The hardcoded string was created based on one of the manually created test
 * Trip Documents. This function will be implemented in the user authentication
 * JS module using Firebase's Authentication API.
 *
 * TODO(Issue 16): Remove this function once implemented in authentication
 *                 module.
 */
function getUserEmail() {
  return 'matt.murdock';
}

/**
 * ViewTrips component.
 */
const ViewTrips = () => {
  return (
    <TripsContainer db={db} userEmail={getUserEmail()} />
  );
};

export default ViewTrips;

<commit_msg>Add more descriptive component documentation.<commit_after>import React from 'react';
import app from '../Firebase';
import TripsContainer from './trips-container'

const db = app.firestore();

/**
 * Temporary hardcoded function that returns the current users email.
 *
 * The hardcoded string was created based on one of the manually created test
 * Trip Documents. This function will be implemented in the user authentication
 * JS module using Firebase's Authentication API.
 *
 * TODO(Issue 16): Remove this function once implemented in authentication
 *                 module.
 */
function getUserEmail() {
  return 'matt.murdock';
}

/**
 * ViewTrips component that defines the page where a user can view and manage
 * their current trips.
 */
const ViewTrips = () => {
  return (
    <TripsContainer db={db} userEmail={getUserEmail()} />
  );
};

export default ViewTrips;

<|endoftext|>


<commit_before>(function (exports) {

	/**
	 * Controls
	 *
	 */

	exports.Controls = Controls;
	exports.Controls.Slider = SliderControls;
	exports.Controls.Radio	= RadioControls;

	function Controls (options) {
		this.name = 'Controls'
		this.version = '0.1';

		this.options = options;
		this.id = options.id || this.name;
		this.root = null;

		this.listRoot = null;
		this.fieldset = null;
		this.submit = null;

		this.init(options);
	};

	Controls.prototype.add = function (root, id, attributes) {
		// TODO: node.window.addTextInput
		//return node.window.addTextInput(root, id, attributes);
	};

	Controls.prototype.init = function (options) {
//		if (options.fieldset) {
//			this.list = new node.window.List();
//		}
//		else {
//			this.list = new node.window.List(this.id);
//		}

		this.list = new node.window.List(options);
		this.listRoot = this.list.getRoot();

		if (!options.features) return;

		this.features = options.features;
		this.populate();
	};

	Controls.prototype.append = function (root) {
		this.root = root;
		var toReturn = this.listRoot;

//		if (this.options.fieldset) {
//			var idFieldset = this.options.fieldset.id || this.id;
//			var legend = this.options.fieldset.legend || 'Input';
//			var attributes = this.options.fieldset.attributes || {};
//			this.fieldset = node.window.addFieldset(this.root, idFieldset, legend, attributes);
//			// Updating root and return element
//			root = this.fieldset;
//			toReturn = this.fieldset;
//		}

		root.appendChild(this.listRoot);

		if (this.options.submit) {
			var idButton = 'submit_' + this.id;
			if (this.options.submit.id) {
				var idButton = this.options.submit.id;
				delete this.options.submit.id;
			}
			this.submit = node.window.addButton(root, idButton, this.options.submit, this.options.attributes);

			var that = this;
			this.submit.onclick = function() {
				if (that.options.change) {
					node.emit(that.options.change);
				}
			};
		}

		return toReturn;
	};

	Controls.prototype.populate = function () {
		var that = this;

		for (var key in this.features) {
			if (this.features.hasOwnProperty(key)) {
				// Prepare the attributes vector
				var attributes = this.features[key];
				var id = key;
				if (attributes.id) {
					var id = attributes.id;
					delete attributes.id;
				}

				var item = this.list.createItem();
				this.listRoot.appendChild(item);

				// Add a different element according to the subclass instantiated
				var elem = this.add(item, id, attributes);

				// Fire the onChange event, if one defined
				if (this.options.change) {
					elem.onchange = function() {
						node.emit(that.options.change);
					};
				}

				// If a label element is present it checks whether it is an
				// object literal or a string.
				// In the former case it scans the obj for additional properties
//				if (attributes.label) {
//					var labelId = 'label_' + id;
//					var labelText = attributes.label;
//
//					if (typeof(attributes.label) === 'object') {
//						var labelText = attributes.label.text;
//						if (attributes.label.id) {
//							labelId = attributes.label.id;
//						}
//					}
//					node.window.addLabel(elem, labelId, labelText, id);
//				}
			}
		}
	};

	Controls.prototype.listeners = function() {
		var that = this;

	};

	Controls.prototype.getAllValues = function() {
		var out = {};
		for (var key in this.features) {

			if (this.features.hasOwnProperty(key)) {
				//console.log('STE ' + key + ' ' + node.window.getElementById(key).value);
				out[key] = Number(node.window.getElementById(key).value);
			}
		}

		return out;
	};

	// Sub-classes

	SliderControls.prototype.__proto__ = Controls.prototype;
	SliderControls.prototype.constructor = SliderControls;

	function SliderControls (options) {
		Controls.call(this,options);
		this.name = 'SliderControls'
		this.version = '0.2';
		this.id = options.id || this.name;
	};

	SliderControls.prototype.add = function (root, id, attributes) {
		return node.window.addSlider(root, id, attributes);
	};

	RadioControls.prototype.__proto__ = Controls.prototype;
	RadioControls.prototype.constructor = RadioControls;

	function RadioControls (options) {
		Controls.call(this,options);
		this.name = 'RadioControls'
		this.version = '0.1';
		this.id = options.id || this.name;
		this.groupName = options.name || Math.floor(Math.random(0,1)*10000);
	};

	RadioControls.prototype.add = function (root, id, attributes) {
		// add the group name if not specified
		if (!attributes.name) {
			attributes.name = this.groupName;
		}
		return node.window.addRadioButton(root, id, attributes);
	};

})(node.window.widgets);<commit_msg>Enhanced support for GameStorage. Controls widgets knows if somebody used them. Advanced in peer-review game<commit_after>(function (exports) {

	/**
	 * Controls
	 *
	 */

	exports.Controls = Controls;
	exports.Controls.Slider = SliderControls;
	exports.Controls.Radio	= RadioControls;

	function Controls (options) {
		this.name = 'Controls'
		this.version = '0.2';

		this.options = options;
		this.id = options.id || this.name;
		this.root = null;

		this.listRoot = null;
		this.fieldset = null;
		this.submit = null;

		this.init(options);
	};

	Controls.prototype.add = function (root, id, attributes) {
		// TODO: node.window.addTextInput
		//return node.window.addTextInput(root, id, attributes);
	};

	Controls.prototype.init = function (options) {
//		if (options.fieldset) {
//			this.list = new node.window.List();
//		}
//		else {
//			this.list = new node.window.List(this.id);
//		}
		this.hasChanged = false; // TODO: should this be inherited?
		this.changeEvent = options.change || this.id + '_change';
		this.list = new node.window.List(options);
		this.listRoot = this.list.getRoot();

		if (!options.features) return;

		this.features = options.features;
		this.populate();
	};

	Controls.prototype.append = function (root) {
		this.root = root;
		var toReturn = this.listRoot;

//		if (this.options.fieldset) {
//			var idFieldset = this.options.fieldset.id || this.id;
//			var legend = this.options.fieldset.legend || 'Input';
//			var attributes = this.options.fieldset.attributes || {};
//			this.fieldset = node.window.addFieldset(this.root, idFieldset, legend, attributes);
//			// Updating root and return element
//			root = this.fieldset;
//			toReturn = this.fieldset;
//		}

		root.appendChild(this.listRoot);

		if (this.options.submit) {
			var idButton = 'submit_' + this.id;
			if (this.options.submit.id) {
				var idButton = this.options.submit.id;
				delete this.options.submit.id;
			}
			this.submit = node.window.addButton(root, idButton, this.options.submit, this.options.attributes);

			var that = this;
			this.submit.onclick = function() {
				if (that.options.change) {
					node.emit(that.options.change);
				}
			};
		}

		return toReturn;
	};

	Controls.prototype.populate = function () {
		var that = this;

		for (var key in this.features) {
			if (this.features.hasOwnProperty(key)) {
				// Prepare the attributes vector
				var attributes = this.features[key];
				var id = key;
				if (attributes.id) {
					var id = attributes.id;
					delete attributes.id;
				}

				var item = this.list.createItem();
				this.listRoot.appendChild(item);

				// Add a different element according to the subclass instantiated
				var elem = this.add(item, id, attributes);

				// Fire the onChange event, if one defined
				if (this.changeEvent) {
					elem.onchange = function() {
						node.emit(that.changeEvent);
					};
				}

				// If a label element is present it checks whether it is an
				// object literal or a string.
				// In the former case it scans the obj for additional properties
//				if (attributes.label) {
//					var labelId = 'label_' + id;
//					var labelText = attributes.label;
//
//					if (typeof(attributes.label) === 'object') {
//						var labelText = attributes.label.text;
//						if (attributes.label.id) {
//							labelId = attributes.label.id;
//						}
//					}
//					node.window.addLabel(elem, labelId, labelText, id);
//				}
			}
		}
	};

	Controls.prototype.listeners = function() {
		var that = this;
		// TODO: should this be inherited?
		node.on(this.changeEvent, function(){
			that.hasChanged = true;
		});

	};

	Controls.prototype.getAllValues = function() {
		var out = {};
		for (var key in this.features) {

			if (this.features.hasOwnProperty(key)) {
				//console.log('STE ' + key + ' ' + node.window.getElementById(key).value);
				out[key] = Number(node.window.getElementById(key).value);
			}
		}

		return out;
	};

	// Sub-classes

	SliderControls.prototype.__proto__ = Controls.prototype;
	SliderControls.prototype.constructor = SliderControls;

	function SliderControls (options) {
		Controls.call(this,options);
		this.name = 'SliderControls'
		this.version = '0.2';
		this.id = options.id || this.name;
	};

	SliderControls.prototype.add = function (root, id, attributes) {
		return node.window.addSlider(root, id, attributes);
	};

	RadioControls.prototype.__proto__ = Controls.prototype;
	RadioControls.prototype.constructor = RadioControls;

	function RadioControls (options) {
		Controls.call(this,options);
		this.name = 'RadioControls'
		this.version = '0.1';
		this.id = options.id || this.name;
		this.groupName = options.name || Math.floor(Math.random(0,1)*10000);
	};

	RadioControls.prototype.add = function (root, id, attributes) {
		// add the group name if not specified
		if (!attributes.name) {
			attributes.name = this.groupName;
		}
		return node.window.addRadioButton(root, id, attributes);
	};

})(node.window.widgets);<|endoftext|>


<commit_before>export const USI_BLACK_PIECES = ['P', 'L', 'N', 'S', 'G', 'K', 'R', 'B'];
export const USI_WHITE_PIECES = ['p', 'l', 'n', 's', 'g', 'k', 'r', 'b'];

export const USI_BLACK_TEAM = 'black';
export const USI_WHITE_TEAM = 'white';

export const USI_PAWN_BLACK_TYPE = 'P';
export const USI_PAWN_BLACK_PROMOTE_TYPE = 'P+';
export const USI_PAWN_WHITE_TYPE = 'p';
export const USI_PAWN_WHITE_PROMOTE_TYPE = 'p+';

export const USI_LANCE_BLACK_TYPE = 'L';
export const USI_LANCE_BLACK_PROMOTE_TYPE = 'L+';
export const USI_LANCE_WHITE_TYPE = 'l';
export const USI_LANCE_WHITE_PROMOTE_TYPE = 'l+';

export const USI_KNIGHT_BLACK_TYPE = 'N';
export const USI_KNIGHT_BLACK_PROMOTE_TYPE = 'N+';
export const USI_KNIGHT_WHITE_TYPE = 'n';
export const USI_KNIGHT_WHITE_PROMOTE_TYPE = 'n+';

export const USI_SILVER_BLACK_TYPE = 'S';
export const USI_SILVER_BLACK_PROMOTE_TYPE = 'S+';
export const USI_SILVER_WHITE_TYPE = 's';
export const USI_SILVER_WHITE_PROMOTE_TYPE = 's+';

export const USI_GOLD_BLACK_TYPE = 'G';
export const USI_GOLD_WHITE_TYPE = 'g';

export const USI_ROOK_BLACK_TYPE = 'R';
export const USI_ROOK_BLACK_PROMOTE_TYPE = 'R+';
export const USI_ROOK_WHITE_TYPE = 'r';
export const USI_ROOK_WHITE_PROMOTE_TYPE = 'r+';

export const USI_BISHOP_BLACK_TYPE = 'B';
export const USI_BISHOP_BLACK_PROMOTE_TYPE = 'B+';
export const USI_BISHOP_WHITE_TYPE = 'b';
export const USI_BISHOP_WHITE_PROMOTE_TYPE = 'b+';

export const USI_KING_BLACK_TYPE = 'K';
export const USI_KING_WHITE_TYPE = 'k';
<commit_msg>Add Constant of nullPiece.<commit_after>export const USI_BLACK_PIECES = ['P', 'L', 'N', 'S', 'G', 'K', 'R', 'B'];
export const USI_WHITE_PIECES = ['p', 'l', 'n', 's', 'g', 'k', 'r', 'b'];

export const USI_BLACK_TEAM = 'black';
export const USI_WHITE_TEAM = 'white';

export const USI_NULL_TYPE = '*';

export const USI_PAWN_BLACK_TYPE = 'P';
export const USI_PAWN_BLACK_PROMOTE_TYPE = 'P+';
export const USI_PAWN_WHITE_TYPE = 'p';
export const USI_PAWN_WHITE_PROMOTE_TYPE = 'p+';

export const USI_LANCE_BLACK_TYPE = 'L';
export const USI_LANCE_BLACK_PROMOTE_TYPE = 'L+';
export const USI_LANCE_WHITE_TYPE = 'l';
export const USI_LANCE_WHITE_PROMOTE_TYPE = 'l+';

export const USI_KNIGHT_BLACK_TYPE = 'N';
export const USI_KNIGHT_BLACK_PROMOTE_TYPE = 'N+';
export const USI_KNIGHT_WHITE_TYPE = 'n';
export const USI_KNIGHT_WHITE_PROMOTE_TYPE = 'n+';

export const USI_SILVER_BLACK_TYPE = 'S';
export const USI_SILVER_BLACK_PROMOTE_TYPE = 'S+';
export const USI_SILVER_WHITE_TYPE = 's';
export const USI_SILVER_WHITE_PROMOTE_TYPE = 's+';

export const USI_GOLD_BLACK_TYPE = 'G';
export const USI_GOLD_WHITE_TYPE = 'g';

export const USI_ROOK_BLACK_TYPE = 'R';
export const USI_ROOK_BLACK_PROMOTE_TYPE = 'R+';
export const USI_ROOK_WHITE_TYPE = 'r';
export const USI_ROOK_WHITE_PROMOTE_TYPE = 'r+';

export const USI_BISHOP_BLACK_TYPE = 'B';
export const USI_BISHOP_BLACK_PROMOTE_TYPE = 'B+';
export const USI_BISHOP_WHITE_TYPE = 'b';
export const USI_BISHOP_WHITE_PROMOTE_TYPE = 'b+';

export const USI_KING_BLACK_TYPE = 'K';
export const USI_KING_WHITE_TYPE = 'k';
<|endoftext|>


<commit_before>"use strict";

const os = require('os');
const util = require('util');

//const debug = require('debug')('cardinal:discord');
const Discordie = require('discordie');

//const Actions = require('./actions');
//const Dispatcher = require('./dispatcher');
const Settings = require('../settings');

const oath = require('../hubot_oath.json');

class Bot {
  constructor(container) {
    this.container = container;
    this.commandManager = container.get('commandManager');
    this.logger = container.get('logger');

    this.client = new Discordie();
    this.primaryGuild = null;

    this.setupEventHandlers();
  }

  setupEventHandlers() {
    this.client.Dispatcher.on(Discordie.Events.GATEWAY_READY, this.onGatewayReady.bind(this));
    this.client.Dispatcher.on(Discordie.Events.VOICE_DISCONNECTED, this.onVoiceDisconnected.bind(this));
    this.client.Dispatcher.on(Discordie.Events.DISCONNECTED, this.onDisconnect.bind(this));
    this.client.Dispatcher.on(Discordie.Events.MESSAGE_CREATE, this.onMessageCreate.bind(this));
  }

  start() {
    this.client.connect({
      token: oath.response.token
    });
  }

  reconnect(channel) {
    const channelName = channel.name;

    // this example will stop reconnecting after 1 attempt
    // you can continue trying to reconnect
    // TODO: implement this.onConnected
    channel.join()
      .then(info => this.onConnected(info))
      .catch(err => console.log(`Failed to connect to ${channelName}`));
  }

  onGatewayReady(e) {
    this.logger.info(`Connected as: ${this.client.User.username}`);

    this.primaryGuild = this.client.Guilds.getBy('name', Settings.SERVER_NAME);

    if (this.primaryGuild) {
      this.logger.debug('Found correct server!');
      //Dispatcher.emit(Actions.DISCORD_FOUND_CORRECT_SERVER, guild);
    } else {
      this.logger.debug('Guild not found!');
      //shutdownCb();
    }
  }

  onVoiceDisconnected(e) {
    this.logger.debug('Disconnected from voice server', e.error);

    if (e.endpointAwait) {
      // handle reconnect instantly if it's a server-switch disconnect
      // transparently creates same promise as `oldChannel.join()`
      // see the `reconnect` function below

      // Note: During Discord outages it will act like the official client
      //       and wait for an endpoint. Sometimes this can take a very
      //       long time. To cancel pending reconnect just call leave on
      //       the voice channel. Pending promise will reject with
      //       `Error` message "Cancelled".

      e.endpointAwait.catch((err) => {
        // server switching failed, do a regular backoff
        setTimeout(() => this.reconnect(channel), 5000);
      });
      return;
    }

    // normal disconnect
    if (!e.manual) {
      setTimeout(() => this.reconnect(channel), 5000);
    }
  }

  onDisconnect(e) {
    const delay = 5000;
    const sdelay = Math.floor(delay / 100) / 10;

    if (e.error.message.indexOf('gateway') !== -1) {
      this.logger.debug(`Disconnected from gw, resuming in ${sdelay} seconds`);
    } else {
      this.logger.debug(`Failed to log in or get gateway, reconnecting in ${sdelay} seconds`);
    }
    setTimeout(this.start, delay);
  }

  onCommandError(m, err) {
    this.logger.error(`Error processing command: ${err && err.stack}`);
    m.reply(`Oops. An error occurred handling that command.\n\`\`\`${err.stack}\`\`\``);
  }

  onMessageCreate(e) {
    if (!e.message.content) return;

    const m = e.message;
    const content = m.content;
    const c = content.toLowerCase();
    //const args = content.split(' ').filter(x => x.length);

    if (c === 'ping' && m.author.id !== this.client.User.id) {
      e.message.channel.sendMessage('pong');
    } else if (c === 'pong' && m.author.id !== this.client.User.id) {
      e.message.channel.sendMessage('ping');
    //} else if (c === '`help') {
    //  e.message.channel.sendMessage(helpText);
    //} else if (c === '`sys' || c === '`sysinfo') {
    //  Dispatcher.emit(Actions.STATUS_SYS_INFO, m);
    //} else if (c === '`user' || c === '`userinfo') {
    //  Dispatcher.emit(Actions.STATUS_USER_INFO, m);
    //} else if (c === '`nicehash') {
    //  Dispatcher.emit(Actions.NICEHASH_DISPLAY, m);
    //} else if (c === '`summon') {
    //  Dispatcher.emit(Actions.START_MUSIC_PLAYBACK, e);
    //} else if (c === '`leave') {
    //  Dispatcher.emit(Actions.STOP_MUSIC_PLAYBACK, e);
    //} else if (e.message.author.id === '142098955818369024' && c === '`next') {
    //  Dispatcher.emit(Actions.QUEUE_SKIP, m);
    //} else if (args[0].toLowerCase() === '`queue') {
    //  Dispatcher.emit(Actions.QUEUE_ITEM, m, args.slice(1).join(' '));
    //} else if (e.message.author.id === '142098955818369024' && args[0].toLowerCase() === '`eval') {
    //  executeJS(m, args);
    }

    this.commandManager.handle(m, (err) => this.onCommandError(m, err));
  }
}

// bot.on('debug', (msg) => {
//   debug(msg);
// });
//function shutdownCb(err) {
//  console.log(err && err.stack);
//
//  try {
//    bot.logout();
//  } finally {
//    return process.exit(1);
//  }
//}
//Dispatcher.on('ctrlc', shutdownCb);

const helpText = `This is *Cardinal*. A general purpose robot.

\`\`\`
Commands:
- ping|pong
  Simple ping and pong to see if bot is responding
- \`play
  Resume and play a song in the playlist.
- \`pause
  Pause the music until reenabling.
- \`next
  Play the next song in the playlist.
  If the song is the last song in the playlist, then Cardinal will wrap around to the beginning of the playlist.
- \`np
  Displays information about the currently playing song.
- \`li
  Displays 25 entries from current playlist from the current song.
\`\`\``;

/*
client.Dispatcher.onAny((type, args) => {
  console.log("\nevent "+type);

  if (args.type == "READY" || args.type == "READY" ||
      type == "GATEWAY_READY" || type == "ANY_GATEWAY_READY" ||
      type == "GATEWAY_DISPATCH") {
    return console.log("e " + (args.type || type));
  }

  console.log("args " + JSON.stringify(args));
});
*/

module.exports = function createBot(container) {
  return new Bot(container);
};
<commit_msg>Bot: make log levels more appropriate<commit_after>"use strict";

const os = require('os');
const util = require('util');

//const debug = require('debug')('cardinal:discord');
const Discordie = require('discordie');

//const Actions = require('./actions');
//const Dispatcher = require('./dispatcher');
const Settings = require('../settings');

const oath = require('../hubot_oath.json');

class Bot {
  constructor(container) {
    this.container = container;
    this.commandManager = container.get('commandManager');
    this.logger = container.get('logger');

    this.client = new Discordie();
    this.primaryGuild = null;

    this.setupEventHandlers();
  }

  setupEventHandlers() {
    this.client.Dispatcher.on(Discordie.Events.GATEWAY_READY, this.onGatewayReady.bind(this));
    this.client.Dispatcher.on(Discordie.Events.VOICE_DISCONNECTED, this.onVoiceDisconnected.bind(this));
    this.client.Dispatcher.on(Discordie.Events.DISCONNECTED, this.onDisconnect.bind(this));
    this.client.Dispatcher.on(Discordie.Events.MESSAGE_CREATE, this.onMessageCreate.bind(this));
  }

  start() {
    this.client.connect({
      token: oath.response.token
    });
  }

  reconnect(channel) {
    const channelName = channel.name;

    // this example will stop reconnecting after 1 attempt
    // you can continue trying to reconnect
    // TODO: implement this.onConnected
    channel.join()
      .then(info => this.onConnected(info))
      .catch(err => this.logger.warn(`Failed to connect to ${channelName}`));
  }

  onGatewayReady(e) {
    this.logger.info(`Connected as: ${this.client.User.username}`);

    this.primaryGuild = this.client.Guilds.getBy('name', Settings.SERVER_NAME);

    if (this.primaryGuild) {
      this.logger.info('Found correct server!');
      //Dispatcher.emit(Actions.DISCORD_FOUND_CORRECT_SERVER, guild);
    } else {
      this.logger.warn('Guild not found!');
      //shutdownCb();
    }
  }

  onVoiceDisconnected(e) {
    this.logger.info('Disconnected from voice server', e.error);

    if (e.endpointAwait) {
      // handle reconnect instantly if it's a server-switch disconnect
      // transparently creates same promise as `oldChannel.join()`
      // see the `reconnect` function below

      // Note: During Discord outages it will act like the official client
      //       and wait for an endpoint. Sometimes this can take a very
      //       long time. To cancel pending reconnect just call leave on
      //       the voice channel. Pending promise will reject with
      //       `Error` message "Cancelled".

      e.endpointAwait.catch((err) => {
        // server switching failed, do a regular backoff
        setTimeout(() => this.reconnect(channel), 5000);
      });
      return;
    }

    // normal disconnect
    if (!e.manual) {
      setTimeout(() => this.reconnect(channel), 5000);
    }
  }

  onDisconnect(e) {
    const delay = 5000;
    const sdelay = Math.floor(delay / 100) / 10;

    if (e.error.message.indexOf('gateway') !== -1) {
      this.logger.info(`Disconnected from gw, resuming in ${sdelay} seconds`);
    } else {
      this.logger.warn(`Failed to log in or get gateway, reconnecting in ${sdelay} seconds`);
    }
    setTimeout(this.start.bind(this), delay);
  }

  onCommandError(m, err) {
    this.logger.error(`Error processing command: ${err && err.stack}`);
    m.reply(`Oops. An error occurred handling that command.\n\`\`\`${err.stack}\`\`\``);
  }

  onMessageCreate(e) {
    if (!e.message.content) return;

    const m = e.message;
    const content = m.content;
    const c = content.toLowerCase();
    //const args = content.split(' ').filter(x => x.length);

    if (c === 'ping' && m.author.id !== this.client.User.id) {
      e.message.channel.sendMessage('pong');
    } else if (c === 'pong' && m.author.id !== this.client.User.id) {
      e.message.channel.sendMessage('ping');
    //} else if (c === '`help') {
    //  e.message.channel.sendMessage(helpText);
    //} else if (c === '`sys' || c === '`sysinfo') {
    //  Dispatcher.emit(Actions.STATUS_SYS_INFO, m);
    //} else if (c === '`user' || c === '`userinfo') {
    //  Dispatcher.emit(Actions.STATUS_USER_INFO, m);
    //} else if (c === '`nicehash') {
    //  Dispatcher.emit(Actions.NICEHASH_DISPLAY, m);
    //} else if (c === '`summon') {
    //  Dispatcher.emit(Actions.START_MUSIC_PLAYBACK, e);
    //} else if (c === '`leave') {
    //  Dispatcher.emit(Actions.STOP_MUSIC_PLAYBACK, e);
    //} else if (e.message.author.id === '142098955818369024' && c === '`next') {
    //  Dispatcher.emit(Actions.QUEUE_SKIP, m);
    //} else if (args[0].toLowerCase() === '`queue') {
    //  Dispatcher.emit(Actions.QUEUE_ITEM, m, args.slice(1).join(' '));
    //} else if (e.message.author.id === '142098955818369024' && args[0].toLowerCase() === '`eval') {
    //  executeJS(m, args);
    }

    this.commandManager.handle(m, (err) => this.onCommandError(m, err));
  }
}

// bot.on('debug', (msg) => {
//   debug(msg);
// });
//function shutdownCb(err) {
//  console.log(err && err.stack);
//
//  try {
//    bot.logout();
//  } finally {
//    return process.exit(1);
//  }
//}
//Dispatcher.on('ctrlc', shutdownCb);

const helpText = `This is *Cardinal*. A general purpose robot.

\`\`\`
Commands:
- ping|pong
  Simple ping and pong to see if bot is responding
- \`play
  Resume and play a song in the playlist.
- \`pause
  Pause the music until reenabling.
- \`next
  Play the next song in the playlist.
  If the song is the last song in the playlist, then Cardinal will wrap around to the beginning of the playlist.
- \`np
  Displays information about the currently playing song.
- \`li
  Displays 25 entries from current playlist from the current song.
\`\`\``;

/*
client.Dispatcher.onAny((type, args) => {
  console.log("\nevent "+type);

  if (args.type == "READY" || args.type == "READY" ||
      type == "GATEWAY_READY" || type == "ANY_GATEWAY_READY" ||
      type == "GATEWAY_DISPATCH") {
    return console.log("e " + (args.type || type));
  }

  console.log("args " + JSON.stringify(args));
});
*/

module.exports = function createBot(container) {
  return new Bot(container);
};
<|endoftext|>


<commit_before>"use strict";

const {strict: assert} = require("assert");

const {mock_module, set_global, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const message_store = mock_module("message_store");
mock_module("muting", {
    is_topic_muted: () => false,
});
set_global("page_params", {});

const {Filter} = zrequire("../js/filter");
const people = zrequire("people");
const stream_data = zrequire("stream_data");
const unread = zrequire("unread");
// The main code we are testing lives here.
const narrow_state = zrequire("narrow_state");

const alice = {
    email: "alice@example.com",
    user_id: 11,
    full_name: "Alice",
};

people.init();
people.add_active_user(alice);
people.is_my_user_id = () => false;

function set_filter(terms) {
    const filter = new Filter(terms);
    narrow_state.set_current_filter(filter);
}

function assert_unread_info(expected) {
    assert.deepEqual(narrow_state.get_first_unread_info(), expected);
}

function candidate_ids() {
    return narrow_state._possible_unread_message_ids();
}

run_test("get_unread_ids", () => {
    let unread_ids;
    let terms;

    const sub = {
        name: "My Stream",
        stream_id: 55,
    };

    const stream_msg = {
        id: 101,
        type: "stream",
        stream_id: sub.stream_id,
        topic: "my topic",
        unread: true,
        mentioned: true,
        mentioned_me_directly: true,
    };

    const private_msg = {
        id: 102,
        type: "private",
        unread: true,
        display_recipient: [{id: alice.user_id}],
    };

    message_store.get = (msg_id) => {
        if (msg_id === stream_msg.id) {
            return stream_msg;
        } else if (msg_id === private_msg.id) {
            return private_msg;
        }
        throw new Error("unexpected id");
    };

    stream_data.add_sub(sub);

    unread_ids = candidate_ids();
    assert.equal(unread_ids, undefined);

    terms = [{operator: "search", operand: "whatever"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.equal(unread_ids, undefined);
    assert_unread_info({flavor: "cannot_compute"});

    terms = [{operator: "bogus_operator", operand: "me@example.com"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);
    assert_unread_info({flavor: "not_found"});

    terms = [{operator: "stream", operand: "bogus"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "stream", operand: sub.name}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);
    assert_unread_info({flavor: "not_found"});

    unread.process_loaded_messages([stream_msg]);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);
    assert_unread_info({
        flavor: "found",
        msg_id: stream_msg.id,
    });

    terms = [
        {operator: "stream", operand: "bogus"},
        {operator: "topic", operand: "my topic"},
    ];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [
        {operator: "stream", operand: sub.name},
        {operator: "topic", operand: "my topic"},
    ];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    terms = [{operator: "is", operand: "mentioned"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    terms = [{operator: "sender", operand: "me@example.com"}];
    set_filter(terms);
    // note that our candidate ids are just "all" ids now
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    // this actually does filtering
    assert_unread_info({flavor: "not_found"});

    terms = [{operator: "pm-with", operand: "alice@example.com"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    unread.process_loaded_messages([private_msg]);

    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [private_msg.id]);

    assert_unread_info({
        flavor: "found",
        msg_id: private_msg.id,
    });

    terms = [{operator: "is", operand: "private"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [private_msg.id]);

    // For a negated search, our candidate ids will be all
    // unread messages, even ones that don't pass the filter.
    terms = [{operator: "is", operand: "private", negated: true}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id, private_msg.id]);

    terms = [{operator: "pm-with", operand: "bob@example.com"}];
    set_filter(terms);

    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "is", operand: "starred"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "search", operand: "needle"}];
    set_filter(terms);

    assert_unread_info({
        flavor: "cannot_compute",
    });

    narrow_state.reset_current_filter();
    blueslip.expect("error", "unexpected call to get_first_unread_info");
    assert_unread_info({
        flavor: "cannot_compute",
    });
});

run_test("defensive code", (override) => {
    // Test defensive code.  We actually avoid calling
    // _possible_unread_message_ids for any case where we
    // couldn't compute the unread message ids, but that
    // invariant is hard to future-proof.
    override(narrow_state, "_possible_unread_message_ids", () => undefined);
    const terms = [{operator: "some-unhandled-case", operand: "whatever"}];
    set_filter(terms);
    assert_unread_info({
        flavor: "cannot_compute",
    });
});
<commit_msg>node tests: Clear state in narrow_unread test.<commit_after>"use strict";

const {strict: assert} = require("assert");

const {mock_module, set_global, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const message_store = mock_module("message_store");
mock_module("muting", {
    is_topic_muted: () => false,
});
set_global("page_params", {});

const {Filter} = zrequire("../js/filter");
const people = zrequire("people");
const stream_data = zrequire("stream_data");
const unread = zrequire("unread");
// The main code we are testing lives here.
const narrow_state = zrequire("narrow_state");

const alice = {
    email: "alice@example.com",
    user_id: 11,
    full_name: "Alice",
};

people.init();
people.add_active_user(alice);
people.is_my_user_id = () => false;

function set_filter(terms) {
    const filter = new Filter(terms);
    narrow_state.set_current_filter(filter);
}

function assert_unread_info(expected) {
    assert.deepEqual(narrow_state.get_first_unread_info(), expected);
}

function candidate_ids() {
    return narrow_state._possible_unread_message_ids();
}

run_test("get_unread_ids", () => {
    unread.declare_bankruptcy();
    narrow_state.reset_current_filter();

    let unread_ids;
    let terms;

    const sub = {
        name: "My Stream",
        stream_id: 55,
    };

    const stream_msg = {
        id: 101,
        type: "stream",
        stream_id: sub.stream_id,
        topic: "my topic",
        unread: true,
        mentioned: true,
        mentioned_me_directly: true,
    };

    const private_msg = {
        id: 102,
        type: "private",
        unread: true,
        display_recipient: [{id: alice.user_id}],
    };

    message_store.get = (msg_id) => {
        if (msg_id === stream_msg.id) {
            return stream_msg;
        } else if (msg_id === private_msg.id) {
            return private_msg;
        }
        throw new Error("unexpected id");
    };

    stream_data.add_sub(sub);

    unread_ids = candidate_ids();
    assert.equal(unread_ids, undefined);

    terms = [{operator: "search", operand: "whatever"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.equal(unread_ids, undefined);
    assert_unread_info({flavor: "cannot_compute"});

    terms = [{operator: "bogus_operator", operand: "me@example.com"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);
    assert_unread_info({flavor: "not_found"});

    terms = [{operator: "stream", operand: "bogus"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "stream", operand: sub.name}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);
    assert_unread_info({flavor: "not_found"});

    unread.process_loaded_messages([stream_msg]);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);
    assert_unread_info({
        flavor: "found",
        msg_id: stream_msg.id,
    });

    terms = [
        {operator: "stream", operand: "bogus"},
        {operator: "topic", operand: "my topic"},
    ];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [
        {operator: "stream", operand: sub.name},
        {operator: "topic", operand: "my topic"},
    ];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    terms = [{operator: "is", operand: "mentioned"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    terms = [{operator: "sender", operand: "me@example.com"}];
    set_filter(terms);
    // note that our candidate ids are just "all" ids now
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id]);

    // this actually does filtering
    assert_unread_info({flavor: "not_found"});

    terms = [{operator: "pm-with", operand: "alice@example.com"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    unread.process_loaded_messages([private_msg]);

    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [private_msg.id]);

    assert_unread_info({
        flavor: "found",
        msg_id: private_msg.id,
    });

    terms = [{operator: "is", operand: "private"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [private_msg.id]);

    // For a negated search, our candidate ids will be all
    // unread messages, even ones that don't pass the filter.
    terms = [{operator: "is", operand: "private", negated: true}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, [stream_msg.id, private_msg.id]);

    terms = [{operator: "pm-with", operand: "bob@example.com"}];
    set_filter(terms);

    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "is", operand: "starred"}];
    set_filter(terms);
    unread_ids = candidate_ids();
    assert.deepEqual(unread_ids, []);

    terms = [{operator: "search", operand: "needle"}];
    set_filter(terms);

    assert_unread_info({
        flavor: "cannot_compute",
    });

    narrow_state.reset_current_filter();
    blueslip.expect("error", "unexpected call to get_first_unread_info");
    assert_unread_info({
        flavor: "cannot_compute",
    });
});

run_test("defensive code", (override) => {
    // Test defensive code.  We actually avoid calling
    // _possible_unread_message_ids for any case where we
    // couldn't compute the unread message ids, but that
    // invariant is hard to future-proof.
    override(narrow_state, "_possible_unread_message_ids", () => undefined);
    const terms = [{operator: "some-unhandled-case", operand: "whatever"}];
    set_filter(terms);
    assert_unread_info({
        flavor: "cannot_compute",
    });
});
<|endoftext|>


<commit_before>zrequire('poll_widget');

set_global('$', global.make_zjquery());
set_global('i18n', global.stub_i18n);

set_global('people', {});
set_global('blueslip', global.make_zblueslip());

const noop = () => {};
const return_false = () => false;
const return_true = () => true;

run_test('poll_data_holder my question', () => {
    const is_my_poll = true;
    const question = 'Favorite color?';

    const sender_id = 99;
    people.my_current_user_id = () => sender_id;

    const data_holder = poll_widget.poll_data_holder(is_my_poll, question);

    let data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [],
        question: 'Favorite color?',
    });

    const question_event = {
        type: 'question',
        question: 'best plan?',
    };

    data_holder.handle_event(sender_id, question_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [],
        question: 'best plan?',
    });

    const option_event = {
        type: 'new_option',
        idx: 1,
        option: 'release now',
    };

    people.safe_full_names = () => '';

    data_holder.handle_event(sender_id, option_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 0,
                key: '99,1',
                current_user_vote: false,
            },
        ],
        question: 'best plan?',
    });

    let  vote_event = {
        type: 'vote',
        key: '99,1',
        vote: 1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 1,
                key: '99,1',
                current_user_vote: true,
            },
        ],
        question: 'best plan?',
    });

    const invalid_vote_event = {
        type: 'vote',
        key: '98,1',
        vote: 1,
    };

    blueslip.set_test_data('warn', `unknown key for poll: ${invalid_vote_event.key}`);
    data_holder.handle_event(sender_id, invalid_vote_event);
    data = data_holder.get_widget_data();
    assert.equal(blueslip.get_test_logs('warn').length, 1);
    blueslip.clear_test_data();

    const option_outbound_event = data_holder.handle.new_option.outbound('new option');
    assert.deepEqual(option_outbound_event, {
        type: 'new_option',
        idx: 2,
        option: 'new option',
    });

    const new_question = 'Any new plan?';
    const question_outbound_event = data_holder.handle.question.outbound(new_question);
    assert.deepEqual(question_outbound_event, {
        type: 'question',
        question: new_question,
    });

    const vote_outbound_event = data_holder.handle.vote.outbound('99,1');
    assert.deepEqual(vote_outbound_event, { type: 'vote', key: '99,1', vote: -1 });

    vote_event = {
        type: 'vote',
        key: '99,1',
        vote: -1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 0,
                key: '99,1',
                current_user_vote: false,
            },
        ],
        question: 'best plan?',
    });
});

run_test('activate another person poll', () => {
    people.is_my_user_id = return_false;
    global.stub_templates((template_name) => {
        if (template_name === 'widgets/poll_widget') {
            return 'widgets/poll_widget';
        }
        if (template_name === 'widgets/poll_widget_results') {
            return 'widgets/poll_widget_results';
        }
    });

    const widget_elem = $('<div>').addClass('widget-content');

    let out_data;   // Used to check the event data sent to the server
    const callback = (data) => {
        out_data = data;
    };

    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
        extra_data: {
            question: 'What do you want?',
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_option = set_widget_find_result('button.poll-option');
    const poll_option_input = set_widget_find_result('input.poll-option');
    const widget_option_container = set_widget_find_result('ul.poll-widget');

    const poll_question_submit = set_widget_find_result('button.poll-question-check');
    const poll_edit_question = set_widget_find_result('.poll-edit-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_option_container = set_widget_find_result('.poll-option-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');
    const poll_please_wait = set_widget_find_result('.poll-please-wait');
    const poll_author_help = set_widget_find_result('.poll-author-help');

    set_widget_find_result('button.poll-question-remove');
    set_widget_find_result('input.poll-question');

    let option_button_callback;
    let vote_button_callback;

    poll_option.on = (event, func) => {
        assert.equal(event, 'click');
        option_button_callback = func;
    };

    poll_vote_button.on = (event, func) => {
        assert.equal(event, 'click');
        vote_button_callback = func;
    };

    poll_question_header.toggle = (show) => {
        assert(show);
    };

    poll_edit_question.toggle = (show) => {
        assert(!show);
    };

    const show_submit = false;
    poll_question_submit.toggle = (show) => {
        assert.equal(show, show_submit);
    };

    poll_question_container.toggle = (show) => {
        assert(!show);
    };

    poll_option_container.toggle = (show) => {
        assert.equal(show, true);
    };

    poll_please_wait.toggle = (show) => {
        assert.equal(show, false);
    };

    poll_author_help.toggle = (show) => {
        assert(!show);
    };

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'widgets/poll_widget');
    assert.equal(widget_option_container.html(), 'widgets/poll_widget_results');
    assert.equal(poll_question_header.text(), 'What do you want?');

    const e = {
        stopPropagation: noop,
    };

    {
        /* Testing data sent to server on adding option */
        poll_option_input.val('cool choice');
        out_data = undefined;
        option_button_callback(e);
        assert.deepEqual(out_data,  { type: 'new_option', idx: 1, option: 'cool choice' });

        poll_option_input.val('');
        out_data = undefined;
        option_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }

    const vote_events = [
        {
            sender_id: 100,
            data: {
                type: 'new_option',
                idx: 1,
                option: 'release now',
            },
        },
        {
            sender_id: 100,
            data: {
                type: 'vote',
                key: '100,1',
                vote: 1,
            },
        },
    ];

    widget_elem.handle_events(vote_events);

    {
        /* Testing data sent to server on voting */
        poll_vote_button.attr('data-key', '100,1');
        const e = {
            stopPropagation: noop,
            target: poll_vote_button,
        };
        out_data = undefined;
        vote_button_callback(e);
        assert.deepEqual(out_data, { type: 'vote', key: '100,1', vote: 1 });
    }

    const add_question_event = [
        {
            sender_id: 100,
            data: {
                type: 'question',
                question: 'best plan?',
            },
        },
    ];

    widget_elem.handle_events(add_question_event);
});

run_test('activate own poll', () => {
    $.clear_all_elements();

    people.is_my_user_id = return_true;
    global.stub_templates((template_name) => {
        if (template_name === 'widgets/poll_widget') {
            return 'widgets/poll_widget';
        }
        if (template_name === 'widgets/poll_widget_results') {
            return 'widgets/poll_widget_results';
        }
    });

    const widget_elem = $('<div>').addClass('widget-content');
    let out_data;
    const callback = (data) => {
        out_data = data;
    };
    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
        extra_data: {
            question: 'Where to go?',
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_option = set_widget_find_result('button.poll-option');
    const poll_option_input = set_widget_find_result('input.poll-option');
    const widget_option_container = set_widget_find_result('ul.poll-widget');

    const poll_question_submit = set_widget_find_result('button.poll-question-check');
    const poll_edit_question = set_widget_find_result('.poll-edit-question');
    const poll_question_input = set_widget_find_result('input.poll-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_option_container = set_widget_find_result('.poll-option-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');
    const poll_please_wait = set_widget_find_result('.poll-please-wait');
    const poll_author_help = set_widget_find_result('.poll-author-help');

    set_widget_find_result('button.poll-question-remove');

    let question_button_callback;

    poll_question_submit.on = (event, func) => {
        assert.equal(event, 'click');
        question_button_callback = func;
    };

    // Following event handler are already tested and doesn't make sense
    // to test them again
    poll_option.on = noop;
    poll_vote_button.on = noop;

    poll_question_header.toggle = (show) => {
        assert(show);
    };

    poll_edit_question.toggle = (show) => {
        assert(show);
    };

    let show_submit = false;
    poll_question_submit.toggle = (show) => {
        assert.equal(show, show_submit);
    };

    poll_question_container.toggle = (show) => {
        assert(!show);
    };

    poll_option_container.toggle = (show) => {
        assert(show);
    };

    poll_please_wait.toggle = (show) => {
        assert(!show);
    };

    poll_author_help.toggle = (show) => {
        assert(!show);
    };

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'widgets/poll_widget');
    assert.equal(widget_option_container.html(), 'widgets/poll_widget_results');
    assert.equal(poll_question_header.text(), 'Where to go?');

    {
        /* Testing data sent to server on editing question */
        const e = {
            stopPropagation: noop,
        };

        poll_question_input.val('Is it new?');
        out_data = undefined;
        show_submit = true;
        question_button_callback(e);
        assert.deepEqual(out_data,  { type: 'question', question: 'Is it new?' });

        poll_option_input.val('');
        out_data = undefined;
        question_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }
});
<commit_msg>tests: Add missing options argument to poll_data_holder.<commit_after>zrequire('poll_widget');

set_global('$', global.make_zjquery());
set_global('i18n', global.stub_i18n);

set_global('people', {});
set_global('blueslip', global.make_zblueslip());

const noop = () => {};
const return_false = () => false;
const return_true = () => true;

run_test('poll_data_holder my question', () => {
    const is_my_poll = true;
    const question = 'Favorite color?';

    const sender_id = 99;
    people.my_current_user_id = () => sender_id;

    const data_holder = poll_widget.poll_data_holder(is_my_poll, question, []);

    let data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [],
        question: 'Favorite color?',
    });

    const question_event = {
        type: 'question',
        question: 'best plan?',
    };

    data_holder.handle_event(sender_id, question_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [],
        question: 'best plan?',
    });

    const option_event = {
        type: 'new_option',
        idx: 1,
        option: 'release now',
    };

    people.safe_full_names = () => '';

    data_holder.handle_event(sender_id, option_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 0,
                key: '99,1',
                current_user_vote: false,
            },
        ],
        question: 'best plan?',
    });

    let  vote_event = {
        type: 'vote',
        key: '99,1',
        vote: 1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 1,
                key: '99,1',
                current_user_vote: true,
            },
        ],
        question: 'best plan?',
    });

    const invalid_vote_event = {
        type: 'vote',
        key: '98,1',
        vote: 1,
    };

    blueslip.set_test_data('warn', `unknown key for poll: ${invalid_vote_event.key}`);
    data_holder.handle_event(sender_id, invalid_vote_event);
    data = data_holder.get_widget_data();
    assert.equal(blueslip.get_test_logs('warn').length, 1);
    blueslip.clear_test_data();

    const option_outbound_event = data_holder.handle.new_option.outbound('new option');
    assert.deepEqual(option_outbound_event, {
        type: 'new_option',
        idx: 2,
        option: 'new option',
    });

    const new_question = 'Any new plan?';
    const question_outbound_event = data_holder.handle.question.outbound(new_question);
    assert.deepEqual(question_outbound_event, {
        type: 'question',
        question: new_question,
    });

    const vote_outbound_event = data_holder.handle.vote.outbound('99,1');
    assert.deepEqual(vote_outbound_event, { type: 'vote', key: '99,1', vote: -1 });

    vote_event = {
        type: 'vote',
        key: '99,1',
        vote: -1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        options: [
            {
                option: 'release now',
                names: '',
                count: 0,
                key: '99,1',
                current_user_vote: false,
            },
        ],
        question: 'best plan?',
    });
});

run_test('activate another person poll', () => {
    people.is_my_user_id = return_false;
    global.stub_templates((template_name) => {
        if (template_name === 'widgets/poll_widget') {
            return 'widgets/poll_widget';
        }
        if (template_name === 'widgets/poll_widget_results') {
            return 'widgets/poll_widget_results';
        }
    });

    const widget_elem = $('<div>').addClass('widget-content');

    let out_data;   // Used to check the event data sent to the server
    const callback = (data) => {
        out_data = data;
    };

    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
        extra_data: {
            question: 'What do you want?',
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_option = set_widget_find_result('button.poll-option');
    const poll_option_input = set_widget_find_result('input.poll-option');
    const widget_option_container = set_widget_find_result('ul.poll-widget');

    const poll_question_submit = set_widget_find_result('button.poll-question-check');
    const poll_edit_question = set_widget_find_result('.poll-edit-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_option_container = set_widget_find_result('.poll-option-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');
    const poll_please_wait = set_widget_find_result('.poll-please-wait');
    const poll_author_help = set_widget_find_result('.poll-author-help');

    set_widget_find_result('button.poll-question-remove');
    set_widget_find_result('input.poll-question');

    let option_button_callback;
    let vote_button_callback;

    poll_option.on = (event, func) => {
        assert.equal(event, 'click');
        option_button_callback = func;
    };

    poll_vote_button.on = (event, func) => {
        assert.equal(event, 'click');
        vote_button_callback = func;
    };

    poll_question_header.toggle = (show) => {
        assert(show);
    };

    poll_edit_question.toggle = (show) => {
        assert(!show);
    };

    const show_submit = false;
    poll_question_submit.toggle = (show) => {
        assert.equal(show, show_submit);
    };

    poll_question_container.toggle = (show) => {
        assert(!show);
    };

    poll_option_container.toggle = (show) => {
        assert.equal(show, true);
    };

    poll_please_wait.toggle = (show) => {
        assert.equal(show, false);
    };

    poll_author_help.toggle = (show) => {
        assert(!show);
    };

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'widgets/poll_widget');
    assert.equal(widget_option_container.html(), 'widgets/poll_widget_results');
    assert.equal(poll_question_header.text(), 'What do you want?');

    const e = {
        stopPropagation: noop,
    };

    {
        /* Testing data sent to server on adding option */
        poll_option_input.val('cool choice');
        out_data = undefined;
        option_button_callback(e);
        assert.deepEqual(out_data,  { type: 'new_option', idx: 1, option: 'cool choice' });

        poll_option_input.val('');
        out_data = undefined;
        option_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }

    const vote_events = [
        {
            sender_id: 100,
            data: {
                type: 'new_option',
                idx: 1,
                option: 'release now',
            },
        },
        {
            sender_id: 100,
            data: {
                type: 'vote',
                key: '100,1',
                vote: 1,
            },
        },
    ];

    widget_elem.handle_events(vote_events);

    {
        /* Testing data sent to server on voting */
        poll_vote_button.attr('data-key', '100,1');
        const e = {
            stopPropagation: noop,
            target: poll_vote_button,
        };
        out_data = undefined;
        vote_button_callback(e);
        assert.deepEqual(out_data, { type: 'vote', key: '100,1', vote: 1 });
    }

    const add_question_event = [
        {
            sender_id: 100,
            data: {
                type: 'question',
                question: 'best plan?',
            },
        },
    ];

    widget_elem.handle_events(add_question_event);
});

run_test('activate own poll', () => {
    $.clear_all_elements();

    people.is_my_user_id = return_true;
    global.stub_templates((template_name) => {
        if (template_name === 'widgets/poll_widget') {
            return 'widgets/poll_widget';
        }
        if (template_name === 'widgets/poll_widget_results') {
            return 'widgets/poll_widget_results';
        }
    });

    const widget_elem = $('<div>').addClass('widget-content');
    let out_data;
    const callback = (data) => {
        out_data = data;
    };
    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
        extra_data: {
            question: 'Where to go?',
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_option = set_widget_find_result('button.poll-option');
    const poll_option_input = set_widget_find_result('input.poll-option');
    const widget_option_container = set_widget_find_result('ul.poll-widget');

    const poll_question_submit = set_widget_find_result('button.poll-question-check');
    const poll_edit_question = set_widget_find_result('.poll-edit-question');
    const poll_question_input = set_widget_find_result('input.poll-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_option_container = set_widget_find_result('.poll-option-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');
    const poll_please_wait = set_widget_find_result('.poll-please-wait');
    const poll_author_help = set_widget_find_result('.poll-author-help');

    set_widget_find_result('button.poll-question-remove');

    let question_button_callback;

    poll_question_submit.on = (event, func) => {
        assert.equal(event, 'click');
        question_button_callback = func;
    };

    // Following event handler are already tested and doesn't make sense
    // to test them again
    poll_option.on = noop;
    poll_vote_button.on = noop;

    poll_question_header.toggle = (show) => {
        assert(show);
    };

    poll_edit_question.toggle = (show) => {
        assert(show);
    };

    let show_submit = false;
    poll_question_submit.toggle = (show) => {
        assert.equal(show, show_submit);
    };

    poll_question_container.toggle = (show) => {
        assert(!show);
    };

    poll_option_container.toggle = (show) => {
        assert(show);
    };

    poll_please_wait.toggle = (show) => {
        assert(!show);
    };

    poll_author_help.toggle = (show) => {
        assert(!show);
    };

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'widgets/poll_widget');
    assert.equal(widget_option_container.html(), 'widgets/poll_widget_results');
    assert.equal(poll_question_header.text(), 'Where to go?');

    {
        /* Testing data sent to server on editing question */
        const e = {
            stopPropagation: noop,
        };

        poll_question_input.val('Is it new?');
        out_data = undefined;
        show_submit = true;
        question_button_callback(e);
        assert.deepEqual(out_data,  { type: 'question', question: 'Is it new?' });

        poll_option_input.val('');
        out_data = undefined;
        question_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }
});
<|endoftext|>


<commit_before>
var multiplier = 1;
var cir_dim = 600 * multiplier;
var sq_dim = 450 * multiplier;
var offset = 100 * multiplier;
var canvasSize = 500 * multiplier;

function setup() {
  createCanvas(canvasSize+offset, canvasSize+offset);
  frameRate(0.5); // Attempt to refresh at starting FPS
  stroke(255);
  noFill();
}

function draw() {

  background(255);
  stroke(0);
  strokeWeight(4);

  rect(0, 0, cir_dim, cir_dim); // outer, circumscribing rect
  ellipse((canvasSize+offset)/2, (canvasSize+offset)/2, canvasSize+offset, canvasSize+offset);

  translate(offset*(sq_dim/cir_dim), offset*(sq_dim/cir_dim));
  print(mouseX, mouseY)

  // rect(cir_dim/18, cir_dim/18, sq_dim - 2*cir_dim/18, sq_dim - 2*cir_dim/18); // inner rect - complique
  rect(0, 0, sq_dim, sq_dim); // better rect

  // rect 1 (left top/rect2

  // randomly select a bounding line for rect1
  rect1_lower_bound_y = random(50, 300)
  rect1_offset_from_top = random(0, rect1_lower_bound_y)
  line(0, rect1_lower_bound_y, sq_dim, rect1_lower_bound_y);
  rect1_height = rect1_lower_bound_y - rect1_offset_from_top
  fill(100);
  rect(0, rect1_offset_from_top, rect1_height, rect1_height);
  noFill();

  // rect 2 (right rect1/rect3)
  rect2_left_bound_x = random(200, sq_dim);
  rect2_height = sq_dim - rect2_left_bound_x;
  fill(100);
  rect(rect2_left_bound_x, rect1_lower_bound_y, rect2_height, 50);
  noFill();

  // rect 3 (bottom rect2)
  rect3_top_bound_y = sq_dim - 150; // random(sq_dim - 200, sq_dim);
  rect3_width = random(150,450);
  fill(100);
  // rect(sq_dim/2, sq_dim, sq_dim - rect3_width/2, sq_dim - rect3_top_bound_y);
  rect(sq_dim/2 - 50, sq_dim - 50, sq_dim/2 - 50, 50);

  noFill();

}<commit_msg>[DEBUG] last rectangle, 3 ...point 2's behaviour and position iss unexpected<commit_after>
var multiplier = 1;
var cir_dim = 600 * multiplier;
var sq_dim = 450 * multiplier;
var offset = 100 * multiplier;
var canvasSize = 500 * multiplier;

function setup() {
  createCanvas(canvasSize+offset, canvasSize+offset);
  frameRate(0.5); // Attempt to refresh at starting FPS
  stroke(255);
  noFill();
}

function draw() {

  background(255);
  stroke(0);
  strokeWeight(4);

  rect(0, 0, cir_dim, cir_dim); // outer, circumscribing rect
  ellipse((canvasSize+offset)/2, (canvasSize+offset)/2, canvasSize+offset, canvasSize+offset);

  translate(offset*(sq_dim/cir_dim), offset*(sq_dim/cir_dim));
  print(mouseX, mouseY)

  // rect(cir_dim/18, cir_dim/18, sq_dim - 2*cir_dim/18, sq_dim - 2*cir_dim/18); // inner rect - complique
  rect(0, 0, sq_dim, sq_dim); // better rect

  // rect 1 (left top/rect2

  // randomly select a bounding line for rect1
  rect1_lower_bound_y = random(50, 300)
  rect1_offset_from_top = random(0, rect1_lower_bound_y)
  line(0, rect1_lower_bound_y, sq_dim, rect1_lower_bound_y);
  rect1_height = rect1_lower_bound_y - rect1_offset_from_top
  fill(100);
  rect(0, rect1_offset_from_top, rect1_height, rect1_height);
  noFill();

  // rect 2 (right rect1/rect3)
  rect2_left_bound_x = random(200, sq_dim);
  rect2_height = sq_dim - rect2_left_bound_x;
  fill(100);
  rect(rect2_left_bound_x, rect1_lower_bound_y, rect2_height, 50);
  noFill();

  // rect 3 (bottom rect2)
  rect3_top_bound_y = sq_dim - 150; // random(sq_dim - 200, sq_dim);
  rect3_height = random(20,100);
  rect3_width = 60; // random(40,60);
  fill(100);
  // rect((sq_dim - rect3_width)/2, sq_dim - rect3_height, (sq_dim + rect3_width)/2, rect3_height);
  rect(200, 350, 250, 100)
  noFill();

}<|endoftext|>


<commit_before><commit_msg>Added colors to subscription script<commit_after><|endoftext|>


<commit_before>/*jshint -W079*/
'use strict';

var _ = require('lodash'),
    Promise = require('promise'),
    exec = require('child_process').exec,
    fs = require('fs-extra'),
    path = require('path');
var config = require('../../config/environment');
var readDir = Promise.denodeify(fs.readdir);

// Get list of repositories
exports.index = function(req, res) {
  readDir(config.git.directory)
    .then(function (files) {
      var result = [];
      for (var f = 0; f < files.length; ++f) {
        result.push({ name: files[f], url: 'git://honeycomb.hive/' + files[f], location: '/git/' + files[f] });
      }

      return res.json(result);
    });
};

// Creates a new repository
exports.create = function(req, res) {
  var repoDir = path.join(config.git.directory, req.body.name);
  console.log(repoDir);
  fs.ensureDirSync(repoDir);
  fs.chownSync(repoDir, config.git.uid, config.git.gid)
  var command = 'git init --bare --share';
  exec(command, { cwd: repoDir }, function(error, stdout, stderr) {
    if (error || stderr) {
      return handleError(res, 'exec error: ' + stderr);
    }
    console.log(stdout);
    return res.json(201, stdout);
  });
};

// Deletes a repository
exports.destroy = function(req, res) {
  var repoDir = config.git.directory + '/' + req.params.id;
  if (fs.existsSync(repoDir)) {
    fs.remove(repoDir, function (error) {
      if (error) { return handleError(res, error); }
      return res.send(204);
    });
  }
};

function handleError(res, err) {
  console.log(err);
  return res.send(500, err);
}<commit_msg>running git init as git user<commit_after>/*jshint -W079*/
'use strict';

var _ = require('lodash'),
    Promise = require('promise'),
    exec = require('child_process').exec,
    fs = require('fs-extra'),
    path = require('path');
var config = require('../../config/environment');
var readDir = Promise.denodeify(fs.readdir);

// Get list of repositories
exports.index = function(req, res) {
  readDir(config.git.directory)
    .then(function (files) {
      var result = [];
      for (var f = 0; f < files.length; ++f) {
        result.push({ name: files[f], url: 'git://honeycomb.hive/' + files[f], location: '/git/' + files[f] });
      }

      return res.json(result);
    });
};

// Creates a new repository
exports.create = function(req, res) {
  var repoDir = path.join(config.git.directory, req.body.name);
  console.log(repoDir);
  fs.ensureDirSync(repoDir);
  fs.chownSync(repoDir, config.git.uid, config.git.gid)
  var command = 'su -c "git init --bare --share" git';
  exec(command, { cwd: repoDir }, function(error, stdout, stderr) {
    if (error || stderr) {
      return handleError(res, 'exec error: ' + stderr);
    }
    console.log(stdout);
    return res.json(201, stdout);
  });
};

// Deletes a repository
exports.destroy = function(req, res) {
  var repoDir = config.git.directory + '/' + req.params.id;
  if (fs.existsSync(repoDir)) {
    fs.remove(repoDir, function (error) {
      if (error) { return handleError(res, error); }
      return res.send(204);
    });
  }
};

function handleError(res, err) {
  console.log(err);
  return res.send(500, err);
}<|endoftext|>