<commit_before>/* ========================================================================

	 qooxdoo - the new era of web development

	 http://qooxdoo.org

	 Copyright:
		 2008 Dihedrals.com, http://www.dihedrals.com

	 License:
		 LGPL: http://www.gnu.org/licenses/lgpl.html
		 EPL: http://www.eclipse.org/org/documents/epl-v10.php
		 See the LICENSE file in the project's top-level directory for details.

	 Authors:
		 * Chris Banford (zermattchris)
		 * Fabian Jakobs (fjakobs)

======================================================================== */

/**
 * A basic layout, which supports positioning of child widgets in a 'flowing'
 * manner, starting at the container's top/left position, placing children left to right
 * (like a HBox) until the there's no remaining room for the next child. When
 * out of room on the current line of elements, a new line is started, cleared
 * below the tallest child of the preceding line -- a bit like using 'float'
 * in CSS, except that a new line wraps all the way back to the left.
 *
 * *Features*
 *
 *

 *
 Reversing children order

 *
 Manual line breaks

 *
 Horizontal alignment of lines

 *
 Vertical alignment of individual widgets within a line

 *
 Margins with horizontal margin collapsing

 *
 Horizontal and vertical spacing

 *
 Height for width calculations

 *
 Auto-sizing

 *

 *
 * *Item Properties*
 *
 *

 *
lineBreak (Boolean): If set to true
 *   a forced line break will happen after this child widget.
 *

 *

 *
 * *Example*
 *
 * Here is a little example of how to use the Flow layout.
 *
 *

 *  var flowlayout = new qx.ui.layout.Flow();
 *
 *  flowlayout.setAlignX( "center" );  // Align children to the X axis of the container (left|center|right)
 *
 *  var container = new qx.ui.container.Composite(flowlayout);
 *  this.getRoot().add(container, {edge: 0});
 *
 *  var button1 = new qx.ui.form.Button("1. First Button", "flowlayout/test.png");
 *  container.add(button1);
 *
 *  var button2 = new qx.ui.form.Button("2. Second longer Button...", "flowlayout/test.png");
 *  // Have this child create a break in the current Line (next child will always start a new Line)
 *  container.add(button2, {lineBreak: true});
 *
 *  var button3 = new qx.ui.form.Button("3rd really, really, really long Button", "flowlayout/test.png");
 *  button3.setHeight(100);  // tall button
 *  container.add(button3);
 *
 *  var button4 = new qx.ui.form.Button("Number 4", "flowlayout/test.png");
 *  button4.setAlignY("bottom");
 *  container.add(button4);
 *
 *  var button5 = new qx.ui.form.Button("20px Margins around the great big 5th button!");
 *  button5.setHeight(100);  // tall button
 *  button5.setMargin(20);
 *  container.add(button5, {lineBreak: true});    // Line break after this button.
 *
 *  var button6 = new qx.ui.form.Button("Number 6", "flowlayout/test.png");
 *  button6.setAlignY("middle");  // Align this child to the vertical center of this line.
 *  container.add(button6);
 *
 *  var button7 = new qx.ui.form.Button("7th a wide, short button", "flowlayout/test.png");
 *  button7.setMaxHeight(20);  // short button
 *  container.add(button7);
 *

 *
 * *External Documentation*
 *
 *
 * Extended documentation and links to demos of this layout in the qooxdoo manuak.
 */
core.Class("unify.ui.layout.Flow",
{
	include : [unify.ui.layout.Base],

	/*
	----------------------------------------------------------------------------
		 CONSTRUCTOR
	----------------------------------------------------------------------------
	*/

	/**
	 * @param spacingX {Integer?0} The spacing between child widgets {@link #spacingX}.
	 * @param spacingY {Integer?0} The spacing between the lines {@link #spacingY}.
	 * @param alignX {String?"left"} Horizontal alignment of the whole children
	 *     block {@link #alignX}.
	 */
	construct : function(spacingX, spacingY, alignX)
	{
		unify.ui.layout.Base.call(this);

		if (spacingX) {
			this.setSpacingX(spacingX);
		}

		if (spacingY) {
			this.setSpacingY(spacingY);
		}

		if (alignX) {
			this.setAlignX(alignX);
		}
	},

	/*
	----------------------------------------------------------------------------
		 PROPERTIES
	----------------------------------------------------------------------------
	*/

	properties :
	{
		/**
		 * Horizontal alignment of the whole children block. The horizontal
		 * alignment of the child is completely ignored in HBoxes (
		 * {@link qx.ui.core.LayoutItem#alignX}).
		 */
		alignX :
		{
			type : [ "left", "center", "right" ],
			init : "left",
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/**
		 * Vertical alignment of each child. Can be overridden through
		 * {@link qx.ui.core.LayoutItem#alignY}.
		 */
		alignY :
		{
			type : [ "top", "middle", "bottom"],
			init : "top",
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/** Horizontal spacing between two children */
		spacingX :
		{
			type : "Integer",
			init : 0,
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/**
		 * The vertical spacing between the lines.
		 */
		spacingY :
		{
			type : "Integer",
			init : 0,
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/** Whether the actual children list should be laid out in reversed order. */
		reversed :
		{
			type : "Boolean",
			init : false,
			apply : function(value) { this._applyLayoutChange(value); }
		}

	},

	/*
	----------------------------------------------------------------------------
		 MEMBERS
	----------------------------------------------------------------------------
	*/

	members :
	{
		/*
		---------------------------------------------------------------------------
			LAYOUT INTERFACE
		---------------------------------------------------------------------------
		*/

		// overridden
		/*verifyLayoutProperty : qx.jasy.Environment.select("qx.debug",
		{
			"true" : function(item, name, value) {
				this.assertEquals("lineBreak", name, "The property '"+name+"' is not supported by the flow layout!" );
			},

			"false" : null
		}),*/

		// overridden
		connectWidget : function(widget)
		{
			unify.ui.layout.Base.prototype.connectWidget.call(this, widget);

			// Necessary to be able to calculate the lines for the flow layout.
			// Otherwise the layout calculates the needed width and height by using
			// only one line of items which is leading to the wrong height. This
			// wrong height does e.g. surpress scrolling since the scroll pane does
			// not know about the correct needed height.
			widget.setAllowShrinkY(false);
		},

		/**
		 * The FlowLayout tries to add as many Children as possible to the current 'Line'
		 * and when it sees that the next Child won't fit, it starts on a new Line, continuing
		 * until all the Children have been added.
		 * To enable alignX "left", "center", "right" renderLayout has to calculate the positions
		 * of all a Line's children before it draws them.
		 *
		 * @param availWidth {Integer} Final width available for the content (in pixel)
		 * @param availHeight {Integer} Final height available for the content (in pixel)
		 * @return {void}
		 */
		renderLayout : function(availWidth, availHeight)
		{
			var children = this._getLayoutChildren();

			if (this.getReversed()) {
				children = children.concat().reverse();
			}

			var lineCalculator = new unify.ui.layout.LineSizeIterator(
				children,
				this.getSpacingX()
			);

			var lineTop = 0;
			while (lineCalculator.hasMoreLines())
			{
				var line = lineCalculator.computeNextLine(availWidth);
				this.__renderLine(line, lineTop, availWidth);
				lineTop += line.height + this.getSpacingY();
			}
		},

		/**
		 * Render a line in the flow layout
		 *
		 * @param line {Map} A line configuration as returned by
		 *    {@link LineSizeIterator#computeNextLine}.
		 * @param lineTop {Integer} The line's top position
		 * @param availWidth {Integer} The available line width
		 */
		__renderLine : function(line, lineTop, availWidth)
		{
			var util = unify.ui.layout.Util;

			var left = 0;
			if (this.getAlignX() != "left") {
				left = availWidth - line.width;
				if (this.getAlignX() == "center") {
					left = Math.round(left / 2);
				}
			}

			for (var i=0; i<line.children.length; i++)
			{
				var child = line.children[i];
				var size = child.getSizeHint();
				var marginTop = child.getMarginTop();
				var marginBottom = child.getMarginBottom();

				var top = util.computeVerticalAlignOffset(
					child.getAlignY() || this.getAlignY(),
					marginTop + size.height + marginBottom,
					line.height,
					marginTop, marginBottom
				);

				child.renderLayout(
					left + line.gapsBefore[i],
					lineTop + top,
					size.width,
					size.height
				);

				left += line.gapsBefore[i] + size.width;
			}
		},

		// overridden
		_computeSizeHint : function() {
			return this.__computeSize(Infinity);
		},

		// overridden
		hasHeightForWidth : function() {
			return true;
		},

		// overridden
		getHeightForWidth : function(width) {
			return this.__computeSize(width).height;
		},

		/**
		 * Compute the preferred size optionally constrained by the available width
		 *
		 * @param availWidth {Integer} The available width
		 * @return {Map} Map containing the preferred height and width of the layout
		 */
		__computeSize : function(availWidth)
		{
			var lineCalculator = new unify.ui.layout.LineSizeIterator(
				this._getLayoutChildren(),
				this.getSpacingX()
			);

			var height = 0;
			var width = 0;
			var lineCount = 0;

			while (lineCalculator.hasMoreLines())
			{
				var line = lineCalculator.computeNextLine(availWidth);
				lineCount += 1;
				width = Math.max(width, line.width);
				height += line.height;
			}

			return {
				width : width,
				height : height + this.getSpacingY() * (lineCount-1)
			};
		}
	}
});<commit_msg>Fix unsetting widget connection of layout<commit_after>/* ========================================================================

	 qooxdoo - the new era of web development

	 http://qooxdoo.org

	 Copyright:
		 2008 Dihedrals.com, http://www.dihedrals.com

	 License:
		 LGPL: http://www.gnu.org/licenses/lgpl.html
		 EPL: http://www.eclipse.org/org/documents/epl-v10.php
		 See the LICENSE file in the project's top-level directory for details.

	 Authors:
		 * Chris Banford (zermattchris)
		 * Fabian Jakobs (fjakobs)

======================================================================== */

/**
 * A basic layout, which supports positioning of child widgets in a 'flowing'
 * manner, starting at the container's top/left position, placing children left to right
 * (like a HBox) until the there's no remaining room for the next child. When
 * out of room on the current line of elements, a new line is started, cleared
 * below the tallest child of the preceding line -- a bit like using 'float'
 * in CSS, except that a new line wraps all the way back to the left.
 *
 * *Features*
 *
 *

 *
 Reversing children order

 *
 Manual line breaks

 *
 Horizontal alignment of lines

 *
 Vertical alignment of individual widgets within a line

 *
 Margins with horizontal margin collapsing

 *
 Horizontal and vertical spacing

 *
 Height for width calculations

 *
 Auto-sizing

 *

 *
 * *Item Properties*
 *
 *

 *
lineBreak (Boolean): If set to true
 *   a forced line break will happen after this child widget.
 *

 *

 *
 * *Example*
 *
 * Here is a little example of how to use the Flow layout.
 *
 *

 *  var flowlayout = new qx.ui.layout.Flow();
 *
 *  flowlayout.setAlignX( "center" );  // Align children to the X axis of the container (left|center|right)
 *
 *  var container = new qx.ui.container.Composite(flowlayout);
 *  this.getRoot().add(container, {edge: 0});
 *
 *  var button1 = new qx.ui.form.Button("1. First Button", "flowlayout/test.png");
 *  container.add(button1);
 *
 *  var button2 = new qx.ui.form.Button("2. Second longer Button...", "flowlayout/test.png");
 *  // Have this child create a break in the current Line (next child will always start a new Line)
 *  container.add(button2, {lineBreak: true});
 *
 *  var button3 = new qx.ui.form.Button("3rd really, really, really long Button", "flowlayout/test.png");
 *  button3.setHeight(100);  // tall button
 *  container.add(button3);
 *
 *  var button4 = new qx.ui.form.Button("Number 4", "flowlayout/test.png");
 *  button4.setAlignY("bottom");
 *  container.add(button4);
 *
 *  var button5 = new qx.ui.form.Button("20px Margins around the great big 5th button!");
 *  button5.setHeight(100);  // tall button
 *  button5.setMargin(20);
 *  container.add(button5, {lineBreak: true});    // Line break after this button.
 *
 *  var button6 = new qx.ui.form.Button("Number 6", "flowlayout/test.png");
 *  button6.setAlignY("middle");  // Align this child to the vertical center of this line.
 *  container.add(button6);
 *
 *  var button7 = new qx.ui.form.Button("7th a wide, short button", "flowlayout/test.png");
 *  button7.setMaxHeight(20);  // short button
 *  container.add(button7);
 *

 *
 * *External Documentation*
 *
 *
 * Extended documentation and links to demos of this layout in the qooxdoo manuak.
 */
core.Class("unify.ui.layout.Flow",
{
	include : [unify.ui.layout.Base],

	/*
	----------------------------------------------------------------------------
		 CONSTRUCTOR
	----------------------------------------------------------------------------
	*/

	/**
	 * @param spacingX {Integer?0} The spacing between child widgets {@link #spacingX}.
	 * @param spacingY {Integer?0} The spacing between the lines {@link #spacingY}.
	 * @param alignX {String?"left"} Horizontal alignment of the whole children
	 *     block {@link #alignX}.
	 */
	construct : function(spacingX, spacingY, alignX)
	{
		unify.ui.layout.Base.call(this);

		if (spacingX) {
			this.setSpacingX(spacingX);
		}

		if (spacingY) {
			this.setSpacingY(spacingY);
		}

		if (alignX) {
			this.setAlignX(alignX);
		}
	},

	/*
	----------------------------------------------------------------------------
		 PROPERTIES
	----------------------------------------------------------------------------
	*/

	properties :
	{
		/**
		 * Horizontal alignment of the whole children block. The horizontal
		 * alignment of the child is completely ignored in HBoxes (
		 * {@link qx.ui.core.LayoutItem#alignX}).
		 */
		alignX :
		{
			type : [ "left", "center", "right" ],
			init : "left",
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/**
		 * Vertical alignment of each child. Can be overridden through
		 * {@link qx.ui.core.LayoutItem#alignY}.
		 */
		alignY :
		{
			type : [ "top", "middle", "bottom"],
			init : "top",
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/** Horizontal spacing between two children */
		spacingX :
		{
			type : "Integer",
			init : 0,
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/**
		 * The vertical spacing between the lines.
		 */
		spacingY :
		{
			type : "Integer",
			init : 0,
			apply : function(value) { this._applyLayoutChange(value); }
		},

		/** Whether the actual children list should be laid out in reversed order. */
		reversed :
		{
			type : "Boolean",
			init : false,
			apply : function(value) { this._applyLayoutChange(value); }
		}

	},

	/*
	----------------------------------------------------------------------------
		 MEMBERS
	----------------------------------------------------------------------------
	*/

	members :
	{
		/*
		---------------------------------------------------------------------------
			LAYOUT INTERFACE
		---------------------------------------------------------------------------
		*/

		// overridden
		/*verifyLayoutProperty : qx.jasy.Environment.select("qx.debug",
		{
			"true" : function(item, name, value) {
				this.assertEquals("lineBreak", name, "The property '"+name+"' is not supported by the flow layout!" );
			},

			"false" : null
		}),*/

		// overridden
		connectWidget : function(widget)
		{
			unify.ui.layout.Base.prototype.connectWidget.call(this, widget);

			if (widget) {
				// Necessary to be able to calculate the lines for the flow layout.
				// Otherwise the layout calculates the needed width and height by using
				// only one line of items which is leading to the wrong height. This
				// wrong height does e.g. surpress scrolling since the scroll pane does
				// not know about the correct needed height.
				widget.setAllowShrinkY(false);
			}
		},

		/**
		 * The FlowLayout tries to add as many Children as possible to the current 'Line'
		 * and when it sees that the next Child won't fit, it starts on a new Line, continuing
		 * until all the Children have been added.
		 * To enable alignX "left", "center", "right" renderLayout has to calculate the positions
		 * of all a Line's children before it draws them.
		 *
		 * @param availWidth {Integer} Final width available for the content (in pixel)
		 * @param availHeight {Integer} Final height available for the content (in pixel)
		 * @return {void}
		 */
		renderLayout : function(availWidth, availHeight)
		{
			var children = this._getLayoutChildren();

			if (this.getReversed()) {
				children = children.concat().reverse();
			}

			var lineCalculator = new unify.ui.layout.LineSizeIterator(
				children,
				this.getSpacingX()
			);

			var lineTop = 0;
			while (lineCalculator.hasMoreLines())
			{
				var line = lineCalculator.computeNextLine(availWidth);
				this.__renderLine(line, lineTop, availWidth);
				lineTop += line.height + this.getSpacingY();
			}
		},

		/**
		 * Render a line in the flow layout
		 *
		 * @param line {Map} A line configuration as returned by
		 *    {@link LineSizeIterator#computeNextLine}.
		 * @param lineTop {Integer} The line's top position
		 * @param availWidth {Integer} The available line width
		 */
		__renderLine : function(line, lineTop, availWidth)
		{
			var util = unify.ui.layout.Util;

			var left = 0;
			if (this.getAlignX() != "left") {
				left = availWidth - line.width;
				if (this.getAlignX() == "center") {
					left = Math.round(left / 2);
				}
			}

			for (var i=0; i<line.children.length; i++)
			{
				var child = line.children[i];
				var size = child.getSizeHint();
				var marginTop = child.getMarginTop();
				var marginBottom = child.getMarginBottom();

				var top = util.computeVerticalAlignOffset(
					child.getAlignY() || this.getAlignY(),
					marginTop + size.height + marginBottom,
					line.height,
					marginTop, marginBottom
				);

				child.renderLayout(
					left + line.gapsBefore[i],
					lineTop + top,
					size.width,
					size.height
				);

				left += line.gapsBefore[i] + size.width;
			}
		},

		// overridden
		_computeSizeHint : function() {
			return this.__computeSize(Infinity);
		},

		// overridden
		hasHeightForWidth : function() {
			return true;
		},

		// overridden
		getHeightForWidth : function(width) {
			return this.__computeSize(width).height;
		},

		/**
		 * Compute the preferred size optionally constrained by the available width
		 *
		 * @param availWidth {Integer} The available width
		 * @return {Map} Map containing the preferred height and width of the layout
		 */
		__computeSize : function(availWidth)
		{
			var lineCalculator = new unify.ui.layout.LineSizeIterator(
				this._getLayoutChildren(),
				this.getSpacingX()
			);

			var height = 0;
			var width = 0;
			var lineCount = 0;

			while (lineCalculator.hasMoreLines())
			{
				var line = lineCalculator.computeNextLine(availWidth);
				lineCount += 1;
				width = Math.max(width, line.width);
				height += line.height;
			}

			return {
				width : width,
				height : height + this.getSpacingY() * (lineCount-1)
			};
		}
	}
});
<|endoftext|>


<commit_before>var timeout;

jQuery(function() {
    console.log("jQuery function");
    loadTop10();
});

function loadTop10() {
    jQuery.ajax("./index.php", {
        success : function(htmlData) {
            jQuery("#infoAjax").html("");
            jQuery("#infoAjax").html(htmlData);
            var h = document.getElementById("Grid-map").scrollHeight + 10;
            alert(window.name);
            if (h){
                parent.iResize(window.name, h);
            } else {
                parent.iResize(window.name, 200);
            }
        }
    });
    if (autoRefresh) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(loadTop10, (30 * 1000));
    }
}
<commit_msg>Update data_js.js<commit_after>var timeout;

jQuery(function() {
    console.log("jQuery function");
    loadTop10();
});

function loadTop10() {
    jQuery.ajax("./index.php", {
        success : function(htmlData) {
            jQuery("#infoAjax").html("");
            jQuery("#infoAjax").html(htmlData);
            var h = document.getElementById("Grid-map").scrollHeight + 10;
            if (h){
                parent.iResize(window.name, h);
            } else {
                parent.iResize(window.name, 200);
            }
        }
    });
    if (autoRefresh) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(loadTop10, (30 * 1000));
    }
}
<|endoftext|>


<commit_before>//__BEGIN_LICENSE__
//Copyright (C) 2008-2010 United States Government as represented by
//the Administrator of the National Aeronautics and Space Administration.
//All Rights Reserved.
//__END_LICENSE__

/*
 * Handlers for websocket that connects tornado server to client
 * for displaying rover images.
 */

xgds_video = {}; //namespace

$.extend(xgds_video, {
    haveNewData: false,
//  client side websocket event handlers
    onopen: function(zmq) {
        $('#socketStatus').html('connected');
//      there is a topic per camera source. I'm assuming that we'll know these sources beforehand.
        var topic1 = 'RapidImagesensorSampleHazCamLeft';
        var topic2 = 'RapidImagesensorSampleGroundCam';
        var topic3 = 'RapidImagesensorSampleNirvss';
        var topic4 = 'RapidImagesensorSampleHazCamRight';
        var handler = function() {
            return function(zmq, topic, obj) {
//              upon receiving the image, display it.
                var data = obj.data.split(':');
                var imgType = data[0];
                var imgContent = data[1];
                haveNewData = true;
                if (topic == topic1) {
                    $('#cameraImageHZL').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic2) {
                    $('#cameraImageGND').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic3) {
                    $('#cameraImageTEX').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic4) {
                    $('#cameraImageHZR').attr('src', 'data:image/jpeg;base64,' + imgContent);
                }
		$container.masonry();
            };
        }();
        zmq.subscribeJson(topic1, handler);
        zmq.subscribeJson(topic2, handler);
        zmq.subscribeJson(topic3, handler);
        zmq.subscribeJson(topic4, handler);
    },

    onclose: function(zmq) {
        $('#socketStatus').html('disconnected');
    },

    zmqInit: function() {
        var zmqUrl = zmqURL.replace('{{host}}', window.location.hostname);
        var zmq = new ZmqManager(zmqUrl, {onopen: xgds_video.onopen, onclose: xgds_video.onclose, autoReconnect: true});
        zmq.start();
    }
});
<commit_msg>nirvss topic name change<commit_after>//__BEGIN_LICENSE__
//Copyright (C) 2008-2010 United States Government as represented by
//the Administrator of the National Aeronautics and Space Administration.
//All Rights Reserved.
//__END_LICENSE__

/*
 * Handlers for websocket that connects tornado server to client
 * for displaying rover images.
 */

xgds_video = {}; //namespace

$.extend(xgds_video, {
    haveNewData: false,
//  client side websocket event handlers
    onopen: function(zmq) {
        $('#socketStatus').html('connected');
//      there is a topic per camera source. I'm assuming that we'll know these sources beforehand.
        var topic1 = 'RapidImagesensorSampleHazCamLeft';
        var topic2 = 'RapidImagesensorSampleGroundCam';
        var topic3 = 'RapidImagesensorSamplenirvss';
        var topic4 = 'RapidImagesensorSampleHazCamRight';
        var handler = function() {
            return function(zmq, topic, obj) {
//              upon receiving the image, display it.
                var data = obj.data.split(':');
                var imgType = data[0];
                var imgContent = data[1];
                haveNewData = true;
                if (topic == topic1) {
                    $('#cameraImageHZL').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic2) {
                    $('#cameraImageGND').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic3) {
                    $('#cameraImageTEX').attr('src', 'data:image/jpeg;base64,' + imgContent);
                } else if (topic == topic4) {
                    $('#cameraImageHZR').attr('src', 'data:image/jpeg;base64,' + imgContent);
                }
		$container.masonry();
            };
        }();
        zmq.subscribeJson(topic1, handler);
        zmq.subscribeJson(topic2, handler);
        zmq.subscribeJson(topic3, handler);
        zmq.subscribeJson(topic4, handler);
    },

    onclose: function(zmq) {
        $('#socketStatus').html('disconnected');
    },

    zmqInit: function() {
        var zmqUrl = zmqURL.replace('{{host}}', window.location.hostname);
        var zmq = new ZmqManager(zmqUrl, {onopen: xgds_video.onopen, onclose: xgds_video.onclose, autoReconnect: true});
        zmq.start();
    }
});
<|endoftext|>


<commit_before>
jQuery(document).ready(function() {

    VIE.EntityManager.initializeCollection();

    VIE.EntityManager.entities.bind('add', function(model) {
        model.url = vie_phpcr_path + model.id;
        model.toJSON = model.toJSONLD;
    });

    // Load all RDFa entities into VIE
    VIE.RDFaEntities.getInstances();

    // Make all RDFa entities editable
    jQuery('[typeof][about]').each(function() {
        jQuery(this).hallo({
            plugins: {
                halloformat: {},
                hallolinkimg: {},
                halloheadings: {},
                hallojustify: {},
                hallolists: {},
            }
        });
        jQuery(this).bind('halloactivated', function() {
            jQuery('#savebutton').show();
        });
        jQuery(this).bind('hallodeactivated', function() {
            jQuery('#savebutton').hide();
        });
    });

    jQuery('#savebutton').bind('click', function() {
        // Go through all Backbone model instances loaded for the page
        VIE.EntityManager.entities.each(function(objectInstance) {
            // TODO: check if was modified

            // Set the modified properties to the model instance
            objectInstance.save(null, {
                success: function(savedModel, response) {
                    alert(savedModel.id + " was saved, see JS console for details");
                    jQuery('#savebutton').hide();
                },
                error: function(response) {
                    console.log("Save failed");
                }
            });
        });
    });

});<commit_msg>Adjusted the invocation of hallo according to the invocation of aloha<commit_after>(function($){
    $.fn.vieSemanticHallo = function(options) {

        // Default settings
        var opt = {};
        $.extend(opt, options);

        this.each(function() {
            var containerInstance = VIE.RDFaEntities.getInstance($(this));
            if (!containerInstance) {
                return;
            }
            if (typeof containerInstance.editables === 'undefined') {
                containerInstance.editables = {};
            }

            VIE.RDFa.findPredicateElements(containerInstance.id, this, false).each(function() {
                var containerProperty = $(this);

                var propertyName = containerProperty.attr('property');
                if (propertyName === undefined) {
                    return true;
                }

                if (containerInstance.get(propertyName) instanceof Array) {
                    // For now we don't deal with multivalued properties in Aloha
                    return true;
                }

                containerInstance.editables[propertyName] = $(this).hallo({
                    plugins: {
                        'halloformat': {}
                    },
                    floating: false,
                    offset: {
                        'x':5,
                        'y':45
                    }
                });
                //console.log(containerInstance.editables[propertyName]);
                containerInstance.editables[propertyName].vieContainerInstance = containerInstance;
            });
        });
    };
})(jQuery);<|endoftext|>


<commit_before>'use strict';

class Plotter {

    constructor () {
        this.path = document.querySelector('svg path');
        this.page = document.querySelector('.plotter');

        const recalc = () => {
          const BCR = this.page.getBoundingClientRect();
          this.pageDimensions = {
            top: BCR.top + window.scrollY,
            left: BCR.left + window.scrollX,
            width: BCR.width,
            height: BCR.height
          }
        }

        recalc();

        document.addEventListener('click', this._onPageClick.bind(this));
        window.addEventListener('resize', () => {
          recalc();
        });

        this.line = '';
        this.log = [];
    }

    _onPageClick(event) {

      let x = event.pageX - this.pageDimensions.left;
      let y = event.pageY - this.pageDimensions.top;

      if (x < 0) {
        x = 0;
      }

      if (x > this.pageDimensions.width) {
        x = this.pageDimensions.width;
      }

      if (y < 0) {
        y = 0;
      }

      if (y > this.pageDimensions.height) {
        y = this.pageDimensions.height;
      }

      const percentageX = Math.round((x * 100) / this.pageDimensions.width * 100) / 100;
      const percentageY = Math.round((y * 100) / this.pageDimensions.height * 100) / 100;

      if (this.log.length == 0) {
        this.line += ` M${x} ${y} `;
      } else {
        this.line += ` L${x} ${y} `;
      }

      this.path.setAttribute('d', this.line + ' Z');
      this.log.push(`${percentageX}% ${percentageY}%`);

      let panel = this.calculateRectangle(this.log);
      panel.path = this.log.join(',');

      console.log(JSON.stringify(panel));
    }

    calculateRectangle(panel) {

      var x = panel.map(coards => {
        coards = coards.replace('%', '');
        coards = coards.split(' ');
        return parseFloat(coards[0]);
      });

      var y = panel.map(coards => {
        coards = coards.replace('%', '');
        coards = coards.split(' ');
        return parseFloat(coards[1]);
      });

      const lowestX = Math.min.apply(Math, x);
      const lowestY = Math.min.apply(Math, y);
      const highestX = Math.max.apply(Math, x);
      const highestY = Math.max.apply(Math, y);

      return {
        x: lowestX,
        y: lowestY,
        width:  Math.round((highestX - lowestX) * 100) / 100,
        height: Math.round((highestY - lowestY) * 100) / 100
      }

    }

}

window.addEventListener('load', _ => new Plotter);
<commit_msg>cleanup<commit_after>'use strict';

class Plotter {

    constructor () {
        this.path = document.querySelector('svg path');
        this.page = document.querySelector('.plotter');

        const recalc = () => {
          const BCR = this.page.getBoundingClientRect();
          this.pageDimensions = {
            top: BCR.top + window.scrollY,
            left: BCR.left + window.scrollX,
            width: BCR.width,
            height: BCR.height
          }
        }

        recalc();

        document.addEventListener('click', this._onPageClick.bind(this));
        document.addEventListener('keydown', event => {
          if (event.keyCode == 13) {
            console.log(this.data);
            this.log= [];
            this.line ='';
            this.path.setAttribute('d', '');
          }
        });
        window.addEventListener('resize', () => {
          recalc();
        });

        this.line = '';
        this.log = [];
    }

    _onPageClick(event) {

      let x = event.pageX - this.pageDimensions.left;
      let y = event.pageY - this.pageDimensions.top;

      if (x < 0) {
        x = 0;
      }

      if (x > this.pageDimensions.width) {
        x = this.pageDimensions.width;
      }

      if (y < 0) {
        y = 0;
      }

      if (y > this.pageDimensions.height) {
        y = this.pageDimensions.height;
      }

      const percentageX = Math.round((x * 100) / this.pageDimensions.width * 100) / 100;
      const percentageY = Math.round((y * 100) / this.pageDimensions.height * 100) / 100;

      if (this.log.length == 0) {
        this.line += ` M${x} ${y} `;
      } else {
        this.line += ` L${x} ${y} `;
      }

      this.path.setAttribute('d', this.line + ' Z');
      this.log.push(`${percentageX} ${percentageY}`);

      let panel = this.calculateRectangle(this.log);
      panel.path = this.log.join(',');

      this.data = JSON.stringify(panel);
    }

    calculateRectangle(panel) {

      var x = panel.map(coards => {
        coards = coards.split(' ');
        return parseFloat(coards[0]);
      });

      var y = panel.map(coards => {
        coards = coards.split(' ');
        return parseFloat(coards[1]);
      });

      const lowestX = Math.min.apply(Math, x);
      const lowestY = Math.min.apply(Math, y);
      const highestX = Math.max.apply(Math, x);
      const highestY = Math.max.apply(Math, y);

      return {
        x: lowestX,
        y: lowestY,
        width:  Math.round((highestX - lowestX) * 100) / 100,
        height: Math.round((highestY - lowestY) * 100) / 100
      }

    }

}

window.addEventListener('load', _ => new Plotter);
<|endoftext|>


<commit_before>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = false;
var hideVideo = false;
var userList = true;

// DJ Battles
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		if (userList)
			populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		if (userList)
			populateUserlist();
		if (isBoris())
			API.sendChat("Welcome to " + $("#current-room-value").text() + ", " + user.username + "!");
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		if (userList)
			populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));
		if (!userList) {
			$("#plugbot-userlist").empty();
		}
		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();
		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		$("#yt-frame").animate({"height": (hideVideo ? "0px" : "271px")}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		$("#button-dj-waitlist-" + (autoqueue ? "join" : "leave")).click();
		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});
}

function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$('#plugbot-btn-hidevideo').attr('src', 'http://i.imgur.com/jbJDe.png');
	hideVideo = false;

	points = 0;
	highScore = 0;
	if (userList)
		populateUserlist();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array()
	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}
	//userNames.sort();
	$('#plugbot-userlist').empty();
	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}
	if(points > highScore)
	{
		highScore = points;
	}
	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	var colour;
	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			break;
		case 0:
			colour = "FFFFFF";
			break;
		case -1:
			colour = "ED1C24";
			break;
	}
	$('#plugbot-userlist').append('
' + username + '
');
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();

if (isBoris())
{
	window.setInterval(function() {
		API.sendChat("Please remember to view our rules at http://goo.gl/YoFDH");
	}, (1000 * 60 * 30));
}
<commit_msg>The userlist now recognises moderators of the room, and gives them the mod insignia associated with them in chat, enboldens their name, and changes the colour of the insignia based on their vote.<commit_after>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = false;
var hideVideo = false;
var userList = true;

// DJ Battles
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		if (userList)
			populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		if (userList)
			populateUserlist();
		if (isBoris())
			API.sendChat("Welcome to " + $("#current-room-value").text() + ", " + user.username + "!");
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		if (userList)
			populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));
		if (!userList) {
			$("#plugbot-userlist").empty();
		}
		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();
		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		$("#yt-frame").animate({"height": (hideVideo ? "0px" : "271px")}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		$("#button-dj-waitlist-" + (autoqueue ? "join" : "leave")).click();
		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});
}

function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$('#plugbot-btn-hidevideo').attr('src', 'http://i.imgur.com/jbJDe.png');
	hideVideo = false;

	points = 0;
	highScore = 0;

	if (userList)
		populateUserlist();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array();

	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}

	$('#plugbot-userlist').empty();

	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}

	if (points > highScore)
		highScore = points;

	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	var colour;
	var currentDj = false;
	var moderator = false;
	var img;

	for (var i = 0; i < API.getModerators().length; i++) {
		if (API.getModerators()[i].username == username) {
			moderator = true;
		}
	}

	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			if (moderator)
				img = "http://i.imgur.com/T5G4f.png";
			break;
		case 0:
			colour = "FFFFFF";
			if (moderator)
				img = "http://i.imgur.com/sRsU0.png";
			break;
		case -1:
			colour = "ED1C24";
			if (moderator)
				img = "http://i.imgur.com/JPA1Q.png";
			break;
	}

	if (API.getDJs()[0].username == username) {
		currentDj = true;
		colour = "42A5DC";
	}

	$('#plugbot-userlist').append(
		(moderator ? '' : '')
		+ '
'
		+ username + '
'
	);
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();

if (isBoris())
{
	window.setInterval(function() {
		API.sendChat("Please remember to view our rules at http://goo.gl/YoFDH");
	}, (1000 * 60 * 30));
}
<|endoftext|>


<commit_before>$(function() {
    $(".js-PostLink").click(function (eventObject) {
        var confirmText = $(this).data('confirm');
        if (confirmText && !confirm(confirmText)) {
            return false;
        }
        eventObject.preventDefault();
        var form = document.createElement("form");
        form.method = "POST";
        form.action = this.href;
        document.body.appendChild(form);
        form.submit();
    });
});
<commit_msg>[COLAB-2191] add support for dynamic postLinks<commit_after>$(function() {
    $(document).on("click", "a.js-PostLink", function (eventObject) {
        var confirmText = $(this).data('confirm');
        if (confirmText && !confirm(confirmText)) {
            return false;
        }
        eventObject.preventDefault();
        var form = document.createElement("form");
        form.method = "POST";
        form.action = this.href;
        document.body.appendChild(form);
        form.submit();
    });
});
<|endoftext|>


<commit_before>var topic = require('../../Model/TopicModel');
var user = require('../../Model/UserModel');
var Summary = require('../../Model/SummaryModel');
var quiz = require('../../Model/QuizModel');
var error = require('../../Model/ErrorModel');

exports.searchUser=function(req, res) {
    user.getUsers(req.params.keyword, function(err, users){
        if(err) return res.status(500).json({code:88, title: "Errore Utente", message: "Nessuna utente trovato"});
        else return res.send(users);
    })
};

exports.updateDataUser = function(req, res, next) {
    req.user.editUser(req.content,function(err){
        if (err) return res.status(500).json(error.findOne({code:700}));
        return res.send(200);
    })
};

exports.updatePasswordUser = function(req, res, next) {

};

exports.updateStatisticUser = function(req, res) {
    if(req.body.userId) {
        user.updateTopicLevel(req.body.userId, req.body.userLevel, req.body.topic, req.body.difficultyLevel, req.body.isCorrected, function (err, userLevel) {
            if (err)
                return res.status(500).json({code: 733, title: "Errore", message: "Livello utente non aggiornato"});
            user.addTotal(req.body.userId, req.body.topic, function (err) {
                if (err)
                    return res.status(500).json({
                        code: 734,
                        title: "Errore",
                        message: "Contatore risposte non aggiornato"
                    });
                if (req.body.isCorrected) {
                    user.addCorrect(req.body.userId, req.body.topic, function (err) {
                        if (err)
                            return res.status(500).json({
                                code: 735,
                                title: "Errore",
                                message: "Contatore risposte corrette non aggiornato"
                            });
                        userLevel.statistics.forEach(function(stat){
                            if(stat.topicName==req.body.topic)
                                res.send({userLevel: stat.topicLevel});
                        });
                    })
                }
                else {
                    userLevel.statistics.forEach(function(stat){
                        if(stat.topicName==req.body.topic)
                            res.send({userLevel: stat.topicLevel});
                    });
                }
            })
        })
    }
    else {
        var level = user.updateTopicLevel(req.body.userId, req.body.userLevel, req.body.topic, req.body.difficultyLevel, req.body.isCorrected);
        return res.send({userLevel: level});
    }
};

exports.getQuizzes = function(req, res) {
    user.getUser(req.user._id, function(err,user){
        if(err)
            return res.status(500).json({code:478, title: "Errore Utente", message: "Utente non trovato"});
        else {
            if(user.quizSummaries.length!=0) {
                var summaries = [];
                user.quizSummaries.forEach(function (summaryId) {
                    Summary.findOne({'_id': summaryId}, function (err, summary) {
                        if (err)
                            return res.status(500).json({
                                code: 478,
                                title: "Errore Utente",
                                message: "Utente non trovato"
                            });
                        else {
                            console.log(summary);
                            quiz.findOne({'_id': summary.quiz}, function (err, quiz) {
                                summaries.push({
                                    'title': quiz.title,
                                    'author': quiz.author,
                                    'topic': quiz.topic,
                                    'mark': summary.mark
                                });
                                if (summaries.length == user.quizSummaries.length)
                                    return res.send(summaries);
                            })
                        }
                    })
                });
            }
            else
                return res.status(500).json({code:914, title: "Errore Utente", message: "Nessuno Questionario compilato "});
        }
    })

};

exports.deleteUser = function(req, res, next) {
    req.user.deleteUser(function(err,user){
        if (err)
            return handleError(err)
        else
            return res.send(user)
    })
};

exports.getInfo = function(req, res, next) {
    userId=req.params.userId.replace(':','');
    user.findOne({'_id':userId},'name surname userImg experienceLevel', function(err,info){
        /*if (err) return res.status(522).json({
            code: 2,
            title: 'visualizzazione-quiz-fallita',
            message: 'la visualizzazione dei quiz è fallita'
        });*/
        if (err)
            return err;
        else
            return res.send(info);
    })
};

exports.getSummary= function(req, res, next) {
    summary.findOne({_id:req.param('summaryId')},'quiz givenAnswers data mark', function(summaryJson){
        var quizJson=summary.getQuiz(summaryJson.quiz)
        summaryJson.quizJson=quizJson;
        return res.send(summaryJson);
    })
};

exports.getSummaries = function(req, res, next) {
    req.user.getSummaries(function(error,summaries){
        if(err) return res.status(500).json(err.findOne({code:700}));
        var query=summary.find({'quiz':{$in:summaries.quizSummaries.quiz}});
        var query2=quiz.find({'_id':{$in:query.quiz}});
        var dataSummaries={
            id: query2._id,
            title: query2.title,
            date: query.date
        };
        return res.send(dataSummaries);
    });
};

exports.getUsers = function(req, res, next) {

};

exports.getStatistics = function(req, res, next) {

};<commit_msg>getQuizzes ritorna obj vuoto in caso l'utente non abbia compilato quiz<commit_after>var topic = require('../../Model/TopicModel');
var user = require('../../Model/UserModel');
var Summary = require('../../Model/SummaryModel');
var quiz = require('../../Model/QuizModel');
var error = require('../../Model/ErrorModel');

exports.searchUser=function(req, res) {
    user.getUsers(req.params.keyword, function(err, users){
        if(err) return res.status(500).json({code:88, title: "Errore Utente", message: "Nessuna utente trovato"});
        else return res.send(users);
    })
};

exports.updateDataUser = function(req, res, next) {
    req.user.editUser(req.content,function(err){
        if (err) return res.status(500).json(error.findOne({code:700}));
        return res.send(200);
    })
};

exports.updatePasswordUser = function(req, res, next) {

};

exports.updateStatisticUser = function(req, res) {
    if(req.body.userId) {
        user.updateTopicLevel(req.body.userId, req.body.userLevel, req.body.topic, req.body.difficultyLevel, req.body.isCorrected, function (err, userLevel) {
            if (err)
                return res.status(500).json({code: 733, title: "Errore", message: "Livello utente non aggiornato"});
            user.addTotal(req.body.userId, req.body.topic, function (err) {
                if (err)
                    return res.status(500).json({
                        code: 734,
                        title: "Errore",
                        message: "Contatore risposte non aggiornato"
                    });
                if (req.body.isCorrected) {
                    user.addCorrect(req.body.userId, req.body.topic, function (err) {
                        if (err)
                            return res.status(500).json({
                                code: 735,
                                title: "Errore",
                                message: "Contatore risposte corrette non aggiornato"
                            });
                        userLevel.statistics.forEach(function(stat){
                            if(stat.topicName==req.body.topic)
                                res.send({userLevel: stat.topicLevel});
                        });
                    })
                }
                else {
                    userLevel.statistics.forEach(function(stat){
                        if(stat.topicName==req.body.topic)
                            res.send({userLevel: stat.topicLevel});
                    });
                }
            })
        })
    }
    else {
        var level = user.updateTopicLevel(req.body.userId, req.body.userLevel, req.body.topic, req.body.difficultyLevel, req.body.isCorrected);
        return res.send({userLevel: level});
    }
};

exports.getQuizzes = function(req, res) {
    user.getUser(req.user._id, function(err,user){
        if(err)
            return res.status(500).json({code:478, title: "Errore Utente", message: "Utente non trovato"});
        else {
            if(user.quizSummaries.length!=0) {
                var summaries = [];
                user.quizSummaries.forEach(function (summaryId) {
                    Summary.findOne({'_id': summaryId}, function (err, summary) {
                        if (err)
                            return res.status(500).json({
                                code: 478,
                                title: "Errore Utente",
                                message: "Utente non trovato"
                            });
                        else {
                            quiz.findOne({'_id': summary.quiz}, function (err, quiz) {
                                summaries.push({
                                    'title': quiz.title,
                                    'author': quiz.author,
                                    'topic': quiz.topic,
                                    'mark': summary.mark
                                });
                                if (summaries.length == user.quizSummaries.length)
                                    return res.send(summaries);
                            })
                        }
                    })
                });
            }
            else
                return res.send({});
        }
    })

};

exports.deleteUser = function(req, res, next) {
    req.user.deleteUser(function(err,user){
        if (err)
            return handleError(err)
        else
            return res.send(user)
    })
};

exports.getInfo = function(req, res, next) {
    userId=req.params.userId.replace(':','');
    user.findOne({'_id':userId},'name surname userImg experienceLevel', function(err,info){
        /*if (err) return res.status(522).json({
            code: 2,
            title: 'visualizzazione-quiz-fallita',
            message: 'la visualizzazione dei quiz è fallita'
        });*/
        if (err)
            return err;
        else
            return res.send(info);
    })
};

exports.getSummary= function(req, res, next) {
    summary.findOne({_id:req.param('summaryId')},'quiz givenAnswers data mark', function(summaryJson){
        var quizJson=summary.getQuiz(summaryJson.quiz)
        summaryJson.quizJson=quizJson;
        return res.send(summaryJson);
    })
};

exports.getSummaries = function(req, res, next) {
    req.user.getSummaries(function(error,summaries){
        if(err) return res.status(500).json(err.findOne({code:700}));
        var query=summary.find({'quiz':{$in:summaries.quizSummaries.quiz}});
        var query2=quiz.find({'_id':{$in:query.quiz}});
        var dataSummaries={
            id: query2._id,
            title: query2.title,
            date: query.date
        };
        return res.send(dataSummaries);
    });
};

exports.getUsers = function(req, res, next) {

};

exports.getStatistics = function(req, res, next) {

};<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.Loader.setConfig({enabled:true});
Ext.require([
    'Ext.tree.*',
    'Ext.data.*',
    'Ext.tab.*',
    'Ext.panel.*'
]);

Ext.onReady(function() {

    var collapsed = false;
    var editPanelItems = [];
    var filterPanelItems = [];
    var defaults = {
        width: '100%',
        animCollapse: false,
        collapsible: true,
        titleCollapse: true,
        hideCollapseTool: true,
        fieldDefaults: {
            labelWidth: 150,
            size: 40
        },
        listeners: {
            beforeexpand: function(panel){
                Ext.Array.each(panel.findParentByType('container').items.items, function(item) {
                    item.collapse();
                });
            }
        }
    };
    var editAllowed = false;
    var filterAllowed = false;
    if(Ext.isArray(attributes) && attributes.length > 0) {
        editAllowed = true;
        filterAllowed = true;
        Ext.Array.each(attributes, function(attribute) {
            var name = attribute.alias || attribute.name;
            if(editable) {

                editPanelItems.push(Ext.create('Ext.form.Panel', Ext.apply(defaults, {
                    id: 'edit' + attribute.id,
                    title: name + (attribute.editable ? ' (×)' : ''),
                    collapsed: collapsed,
                    items: [
                        { fieldLabel: 'Bewerkbaar', name: 'editable', inputValue: 1, checked: attribute.editable, xtype: 'checkbox', listeners: {
                                change: function(field, newval) {
                                    editPanelTitle(field.findParentByType('form'), name, newval)
                                }
                            }
                        },
                        { fieldLabel: 'Alias', name: 'editalias', value: attribute.editalias, xtype: 'textfield' },
                        {
                            xtype: 'container',
                            layout: 'hbox',
                            items: [
                                { fieldLabel: 'Mogelijke waarden',
                                    name: 'editvalues', id: 'editvalues' + attribute.id, value: attribute.editvalues, xtype: 'textfield', size: 100 },
                                { xtype: 'button', text: 'DB', style: { marginLeft: '10px' }, listeners: {
                                    click: function() {
                                        getDBValues(attribute.id);
                                    }
                                }}
                            ]
                        },
                        { fieldLabel: 'Hoogte', name: 'editheight', value: attribute.editheight, xtype: 'textfield' }
                    ]
                })));
            }
            var isEnabled = (attribute.filterable || attribute.selectable) || false;
            filterPanelItems.push(Ext.create('Ext.form.Panel', Ext.apply(defaults, {
                id: 'filter' + attribute.id,
                title: name + (isEnabled ? ' (×)' : ''),
                collapsed: collapsed,
                items: [
                    { fieldLabel: 'Filterbaar / Selecteerbaar', name: 'filterable_selectable', inputValue: 1, checked: isEnabled, xtype: 'checkbox',  labelWidth: 150, listeners: {
                        change: function(field, newval) {
                            var panel = field.findParentByType('form');
                            var filterRadio = Ext.getCmp('filterable' + attribute.id);
                            filterRadio.setDisabled(!newval); filterRadio.setValue(false);
                            var selectRadio = Ext.getCmp('selectable' + attribute.id);
                            selectRadio.setDisabled(!newval); selectRadio.setValue(false);
                            editPanelTitle(panel, name, newval);
                        }
                    }},
                    {
                        xtype: 'container',
                        layout: 'hbox',
                        items: [
                            { xtype: 'displayfield', fieldLabel: 'Attribuut gebruiken bij' },
                            { id: 'filterable' + attribute.id, fieldLabel: 'Filteren', name: 'filterable' + attribute.id, inputValue: 'filter', checked: attribute.filterable, disabled: !isEnabled, xtype: 'radio', labelAlign: 'right' },
                            { id: 'selectable' + attribute.id, fieldLabel: '  Dataselectie', name: 'filterable' + attribute.id, inputValue: 'select', checked: attribute.selectable, disabled: !isEnabled, xtype: 'radio',  labelAlign: 'right' }
                        ]
                    }
                ]
            })));
            collapsed = true;
        });
    }
    var tabconfig = [{
        contentEl:'rights-tab',
        title: 'Rechten'
    },{
        contentEl:'attributes-tab',
        title: 'Attributen'
    },{
        contentEl:'settings-tab',
        title: 'Instellingen'
    }];
    if(editAllowed && editable) {
        tabconfig.push({
            xtype: 'container',
            width: '100%',
            title: 'Edit',
            padding: 10,
            height: 550,
            layout: 'auto',
            autoScroll: true,
            items: editPanelItems
        });
    } else {
        tabconfig.push({
            contentEl:'edit-tab',
            title: 'Edit'
        });
    }
    if(filterAllowed) {
        tabconfig.push({
            xtype: 'container',
            width: '100%',
            title: 'Filter / Selectie',
            padding: 10,
            height: 550,
            layout: 'auto',
            autoScroll: true,
            items: filterPanelItems
        });
    } else {
        tabconfig.push({
            contentEl:'filter-tab',
            title: 'Filter / Selectie'
        });
    }

    Ext.create('Ext.tab.Panel', {

        renderTo: 'tabs',
        width: '100%',
        activeTab: 0,
        defaults :{
            bodyPadding: 10
        },
        layoutOnTabChange: false,
        items: tabconfig
    });

    Ext.get('apptreelayerform').on('submit', function(e) {
        Ext.get('attributesJSON').dom.value = getJson();
    });

});

function editPanelTitle(panel, name, checked) {
    panel.setTitle(name + (checked ? ' (×)' : ''));
}

function getJson() {
    var currentAttributes = [];
    Ext.Array.each(attributes, function(attribute) {
        var newAttribute = attribute;
        if (Ext.getCmp('edit' + attribute.id)!=undefined){
            Ext.getCmp('edit' + attribute.id).getForm().getFields().each(function(field) {
                newAttribute[field.getName()] = field.getValue();
            });
        }
        newAttribute.filterable = Ext.getCmp('filterable' + attribute.id).getValue();
        newAttribute.selectable = Ext.getCmp('selectable' + attribute.id).getValue();
        currentAttributes.push(newAttribute);
    });
    return Ext.JSON.encode(currentAttributes);
}

function getDBValues(attributeid) {
    if(getDBValuesUrl != '') {
        Ext.Ajax.request({
            url: getDBValuesUrl,
            params: {
                attributeid: attributeid
            },
            success: function ( result, request ) {
                var result = Ext.JSON.decode(result.responseText);
                Ext.getCmp('editvalues' + attributeid).setValue(result.join(','));
            },
            failure: function ( result, request) {
                Ext.MessageBox.alert('Foutmelding', result.responseText);
            }
        });
    }
}<commit_msg>Save and retrieve possible values as array (At edit)<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.Loader.setConfig({enabled:true});
Ext.require([
    'Ext.tree.*',
    'Ext.data.*',
    'Ext.tab.*',
    'Ext.panel.*'
]);

Ext.onReady(function() {

    var collapsed = false;
    var editPanelItems = [];
    var filterPanelItems = [];
    var defaults = {
        width: '100%',
        animCollapse: false,
        collapsible: true,
        titleCollapse: true,
        hideCollapseTool: true,
        fieldDefaults: {
            labelWidth: 150,
            size: 40
        },
        listeners: {
            beforeexpand: function(panel){
                Ext.Array.each(panel.findParentByType('container').items.items, function(item) {
                    item.collapse();
                });
            }
        }
    };
    var editAllowed = false;
    var filterAllowed = false;
    if(Ext.isArray(attributes) && attributes.length > 0) {
        editAllowed = true;
        filterAllowed = true;
        Ext.Array.each(attributes, function(attribute) {
            var name = attribute.alias || attribute.name;
            if(editable) {
                var possibleValues = Ext.JSON.decode(attribute.editvalues);
                editPanelItems.push(Ext.create('Ext.form.Panel', Ext.apply(defaults, {
                    id: 'edit' + attribute.id,
                    title: name + (attribute.editable ? ' (×)' : ''),
                    collapsed: collapsed,
                    items: [
                        { fieldLabel: 'Bewerkbaar', name: 'editable', inputValue: 1, checked: attribute.editable, xtype: 'checkbox', listeners: {
                                change: function(field, newval) {
                                    editPanelTitle(field.findParentByType('form'), name, newval)
                                }
                            }
                        },
                        { fieldLabel: 'Alias', name: 'editalias', value: attribute.editalias, xtype: 'textfield' },
                        {
                            xtype: 'container',
                            layout: 'hbox',
                            items: [
                                { fieldLabel: 'Mogelijke waarden',
                                    name: 'editvalues', id: 'editvalues' + attribute.id, value: possibleValues, xtype: 'textfield', size: 100 },
                                { xtype: 'button', text: 'DB', style: { marginLeft: '10px' }, listeners: {
                                    click: function() {
                                        getDBValues(attribute.id);
                                    }
                                }}
                            ]
                        },
                        { fieldLabel: 'Hoogte', name: 'editheight', value: attribute.editheight, xtype: 'textfield' }
                    ]
                })));
            }
            var isEnabled = (attribute.filterable || attribute.selectable) || false;
            filterPanelItems.push(Ext.create('Ext.form.Panel', Ext.apply(defaults, {
                id: 'filter' + attribute.id,
                title: name + (isEnabled ? ' (×)' : ''),
                collapsed: collapsed,
                items: [
                    { fieldLabel: 'Filterbaar / Selecteerbaar', name: 'filterable_selectable', inputValue: 1, checked: isEnabled, xtype: 'checkbox',  labelWidth: 150, listeners: {
                        change: function(field, newval) {
                            var panel = field.findParentByType('form');
                            var filterRadio = Ext.getCmp('filterable' + attribute.id);
                            filterRadio.setDisabled(!newval); filterRadio.setValue(false);
                            var selectRadio = Ext.getCmp('selectable' + attribute.id);
                            selectRadio.setDisabled(!newval); selectRadio.setValue(false);
                            editPanelTitle(panel, name, newval);
                        }
                    }},
                    {
                        xtype: 'container',
                        layout: 'hbox',
                        items: [
                            { xtype: 'displayfield', fieldLabel: 'Attribuut gebruiken bij' },
                            { id: 'filterable' + attribute.id, fieldLabel: 'Filteren', name: 'filterable' + attribute.id, inputValue: 'filter', checked: attribute.filterable, disabled: !isEnabled, xtype: 'radio', labelAlign: 'right' },
                            { id: 'selectable' + attribute.id, fieldLabel: '  Dataselectie', name: 'filterable' + attribute.id, inputValue: 'select', checked: attribute.selectable, disabled: !isEnabled, xtype: 'radio',  labelAlign: 'right' }
                        ]
                    }
                ]
            })));
            collapsed = true;
        });
    }
    var tabconfig = [{
        contentEl:'rights-tab',
        title: 'Rechten'
    },{
        contentEl:'attributes-tab',
        title: 'Attributen'
    },{
        contentEl:'settings-tab',
        title: 'Instellingen'
    }];
    if(editAllowed && editable) {
        tabconfig.push({
            xtype: 'container',
            width: '100%',
            title: 'Edit',
            padding: 10,
            height: 550,
            layout: 'auto',
            autoScroll: true,
            items: editPanelItems
        });
    } else {
        tabconfig.push({
            contentEl:'edit-tab',
            title: 'Edit'
        });
    }
    if(filterAllowed) {
        tabconfig.push({
            xtype: 'container',
            width: '100%',
            title: 'Filter / Selectie',
            padding: 10,
            height: 550,
            layout: 'auto',
            autoScroll: true,
            items: filterPanelItems
        });
    } else {
        tabconfig.push({
            contentEl:'filter-tab',
            title: 'Filter / Selectie'
        });
    }

    Ext.create('Ext.tab.Panel', {

        renderTo: 'tabs',
        width: '100%',
        activeTab: 0,
        defaults :{
            bodyPadding: 10
        },
        layoutOnTabChange: false,
        items: tabconfig
    });

    Ext.get('apptreelayerform').on('submit', function(e) {
        Ext.get('attributesJSON').dom.value = getJson();
    });

});

function editPanelTitle(panel, name, checked) {
    panel.setTitle(name + (checked ? ' (×)' : ''));
}

function getJson() {
    var currentAttributes = [];
    Ext.Array.each(attributes, function(attribute) {
        var newAttribute = attribute;
        if (Ext.getCmp('edit' + attribute.id)!=undefined){
            Ext.getCmp('edit' + attribute.id).getForm().getFields().each(function(field) {
                newAttribute[field.getName()] = field.getValue();
            });
            if(newAttribute["editvalues"] != undefined && newAttribute["editvalues"] != ""){
                newAttribute["editvalues"]= newAttribute["editvalues"].split(",");
            }
        }
        newAttribute.filterable = Ext.getCmp('filterable' + attribute.id).getValue();
        newAttribute.selectable = Ext.getCmp('selectable' + attribute.id).getValue();
        currentAttributes.push(newAttribute);
    });
    return Ext.JSON.encode(currentAttributes);
}

function getDBValues(attributeid) {
    if(getDBValuesUrl != '') {
        Ext.Ajax.request({
            url: getDBValuesUrl,
            params: {
                attributeid: attributeid
            },
            success: function ( result, request ) {
                var result = Ext.JSON.decode(result.responseText);
                Ext.getCmp('editvalues' + attributeid).setValue(result.join(','));
            },
            failure: function ( result, request) {
                Ext.MessageBox.alert('Foutmelding', result.responseText);
            }
        });
    }
}<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { withStyles } from '@material-ui/core/styles'
import Divider from '@material-ui/core/Divider'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'

const styles = () => ({
  container: {
    padding: 20,
    marginBottom: 26,
  },
  otherCityTimesDivider: {
    margin: '20px 0px',
  },
  otherCityTime: {
    color: 'rgba(0, 0, 0, 0.46)',
    textAlign: 'right',
  },
  otherCityTimeLocation: {
    color: 'rgba(0, 0, 0, 0.46)',
    marginLeft: 20,
  },
})

const TimeZoneSearchResult = props => {
  const {
    classes,
    item: {
      otherCityTimes,
      primaryCityTime: { location, time, utcOffset },
    },
  } = props

  // If any required props are missing, don't render anything.
  if (!(location && utcOffset && time)) {
    return null
  }
  const formatDate = isoTime => moment(isoTime).format('dddd, MMMM D, YYYY')
  const formatTime = isoTime =>
    moment(isoTime)
      .utc()
      .format('h:mm A')
  return (
    <Paper className={classes.container} elevation={1}>
      <Typography
        variant={'h4'}
        data-test-id={'search-result-time-zone-time'}
        gutterBottom
      >
        {formatTime(time)}
      </Typography>
      <Typography
        variant={'body2'}
        data-test-id={'search-result-time-zone-date'}
      >
        {formatDate(time)}
      </Typography>
      <Typography
        variant={'body2'}
        data-test-id={'search-result-time-zone-location'}
      >
        Time in {location} ({utcOffset})
      </Typography>
      {otherCityTimes && otherCityTimes.length ? (

          <Divider className={classes.otherCityTimesDivider} />

              {otherCityTimes.map(cityTime => {
                return (

                      <Typography
                        variant={'body2'}
                        className={classes.otherCityTime}
                        gutterBottom
                      >
                        {formatTime(cityTime.time)}
                      </Typography>

                      <Typography
                        variant={'body2'}
                        className={classes.otherCityTimeLocation}
                      >
                        {cityTime.location} ({cityTime.utcOffset})
                      </Typography>

                )
              })}

      ) : null}
    </Paper>
  )
}

TimeZoneSearchResult.propTypes = {
  classes: PropTypes.object.isRequired,
  item: PropTypes.shape({
    id: PropTypes.string.isRequired,
    otherCityTimes: PropTypes.arrayOf(
      PropTypes.shape({
        location: PropTypes.string.isRequired,
        time: PropTypes.string.isRequired,
        utcOffset: PropTypes.string.isRequired,
      })
    ),
    primaryCityTime: PropTypes.shape({
      location: PropTypes.string.isRequired,
      time: PropTypes.string.isRequired,
      utcOffset: PropTypes.string.isRequired,
    }).isRequired,
  }).isRequired,
}

TimeZoneSearchResult.defaultProps = {}

export default withStyles(styles)(TimeZoneSearchResult)
<commit_msg>Tweak styling<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { withStyles } from '@material-ui/core/styles'
import Divider from '@material-ui/core/Divider'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'

const styles = () => ({
  container: {
    padding: 20,
    marginBottom: 26,
  },
  otherCityTimesDivider: {
    margin: '20px 0px',
  },
  otherCityTime: {
    color: 'rgba(0, 0, 0, 0.46)',
    textAlign: 'right',
  },
  otherCityTimeLocation: {
    color: 'rgba(0, 0, 0, 0.46)',
    marginLeft: 20,
  },
})

const TimeZoneSearchResult = props => {
  const {
    classes,
    item: {
      otherCityTimes,
      primaryCityTime: { location, time, utcOffset },
    },
  } = props

  // If any required props are missing, don't render anything.
  if (!(location && utcOffset && time)) {
    return null
  }
  const formatDate = isoTime => moment(isoTime).format('dddd, MMMM D, YYYY')
  const formatTime = isoTime =>
    moment(isoTime)
      .utc()
      .format('h:mm A')
  return (
    <Paper className={classes.container} elevation={1}>
      <Typography
        variant={'h4'}
        data-test-id={'search-result-time-zone-time'}
        gutterBottom
      >
        {formatTime(time)}
      </Typography>
      <Typography
        variant={'body2'}
        data-test-id={'search-result-time-zone-date'}
      >
        {formatDate(time)}
      </Typography>
      <Typography
        variant={'body2'}
        data-test-id={'search-result-time-zone-location'}
      >
        Time in {location} ({utcOffset})
      </Typography>
      {otherCityTimes && otherCityTimes.length ? (

          <Divider className={classes.otherCityTimesDivider} />

              {otherCityTimes.map(cityTime => {
                return (

                      <Typography
                        variant={'body2'}
                        className={classes.otherCityTime}
                        gutterBottom
                      >
                        {formatTime(cityTime.time)}
                      </Typography>

                      <Typography
                        variant={'body2'}
                        className={classes.otherCityTimeLocation}
                        gutterBottom
                      >
                        {cityTime.location} ({cityTime.utcOffset})
                      </Typography>

                )
              })}

      ) : null}
    </Paper>
  )
}

TimeZoneSearchResult.propTypes = {
  classes: PropTypes.object.isRequired,
  item: PropTypes.shape({
    id: PropTypes.string.isRequired,
    otherCityTimes: PropTypes.arrayOf(
      PropTypes.shape({
        location: PropTypes.string.isRequired,
        time: PropTypes.string.isRequired,
        utcOffset: PropTypes.string.isRequired,
      })
    ),
    primaryCityTime: PropTypes.shape({
      location: PropTypes.string.isRequired,
      time: PropTypes.string.isRequired,
      utcOffset: PropTypes.string.isRequired,
    }).isRequired,
  }).isRequired,
}

TimeZoneSearchResult.defaultProps = {}

export default withStyles(styles)(TimeZoneSearchResult)
<|endoftext|>


<commit_before>/*globals d3*/

isic.views.ImagesViewSubViews = isic.views.ImagesViewSubViews || {};

isic.views.ImagesViewSubViews.DatasetPane = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.model, 'change:overviewHistogram', this.render);
        this.listenTo(this.model, 'change:filteredSetHistogram', this.render);
    },
    render: function () {
        var svg;

        if (!this.addedSvgElement) {
            this.$el.html(isic.templates.imageDatasetPage({
                title: 'Dataset'
            }));
            var histogramContainer = this.$('.isic-image-dataset-histogram-container');
            svg = d3.select(histogramContainer.get(0)).append('svg')
                .attr('class', 'content');
            this.histogram = new isic.views.ImagesViewSubViews.IndividualHistogram({
                el: svg.node(),
                model: this.model,
                attributeName: 'folderId',
                showCheckbox: false
            });
            this.addedSvgElement = true;
        } else {
            svg = d3.select(this.el).select('svg.content');
        }
        this.histogram.render();

        // Add special listeners to open a modal about each dataset
        svg.select('.bins').selectAll('.bin')
            .on('click', _.bind(function (d) {
                var dataset = this.model.datasetCollection.find(function (dataset) {
                    return dataset.name() === d;
                });
                console.log('TODO: show a modal, describing the ' +
                    d + ' dataset (id: ' + dataset.id + ')');
            }, this));
        return this;
    }
});
<commit_msg>Display dataset histogram checkboxes and update name matching logic<commit_after>/*globals d3*/

isic.views.ImagesViewSubViews = isic.views.ImagesViewSubViews || {};

isic.views.ImagesViewSubViews.DatasetPane = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.model, 'change:overviewHistogram', this.render);
        this.listenTo(this.model, 'change:filteredSetHistogram', this.render);
    },
    render: function () {
        var svg;

        if (!this.addedSvgElement) {
            this.$el.html(isic.templates.imageDatasetPage({
                title: 'Dataset'
            }));
            var histogramContainer = this.$('.isic-image-dataset-histogram-container');
            svg = d3.select(histogramContainer.get(0)).append('svg')
                .attr('class', 'content');
            this.histogram = new isic.views.ImagesViewSubViews.IndividualHistogram({
                el: svg.node(),
                model: this.model,
                attributeName: 'folderId',
                showCheckbox: true
            });
            this.addedSvgElement = true;
        } else {
            svg = d3.select(this.el).select('svg.content');
        }
        this.histogram.render();

        // Add special listeners to open a modal about each dataset
        var self = this;
        svg.select('.bins').selectAll('.bin')
            .on('click', _.bind(function (d) {
                var dataset = self.model.datasetCollection.find(function (dataset) {
                    return dataset.name() === d.label;
                });
                console.log('TODO: show a modal, describing the ' +
                    d + ' dataset (id: ' + dataset.id + ')');
            }, this));
        return this;
    }
});
<|endoftext|>


<commit_before>(function () {
  "use strict";
  var componentConfig = {
    templateUrl: "js/work-orders/order-documents-list-component.template.html",
    bindings: {
      barcode: "<"
    },
    controller: ["$scope", "work-orders-factory", "fpm-utilities-factory", "fieldPromaxConfig",
      function ($scope, workOrdersFactory, fpmUtilitiesFactory, fieldPromaxConfig) {
        var vm = this;
        var baseUrl = fieldPromaxConfig.fieldPromaxApi;
        var alerts = fpmUtilitiesFactory.alerts;
        vm.docUrl = "";
        vm.gettinDocuments = false;
        vm.events = {
          onDocumentClicked: function (doc) {
            window.open(baseUrl + "Handlers/GetImageFromBlob.ashx?imageId=" + doc.num + "&dateStamp=" + new Date() + "&flag=viewTarget&cust=" + doc.customerNumber, "_system", "location=yes");
          }
        };
        vm.$onInit = function () {
          if (vm.barcode) {
            vm.barcodeDocuments = [];
            vm.gettinDocuments = true;
            workOrdersFactory.getUploadedDocuments(vm.barcode).then(function (response) {
              if (angular.isArray(response) && response.length > 0) {
                var pdfs = _.where(response, { extension: ".pdf" });
                vm.barcodeDocuments = pdfs;
              }
              vm.gettinDocuments = false;
            });
          } else {
            vm.gettinDocuments = false;
          }
        }
      }
    ],
    controllerAs: "vm"
  };
  angular.module("fpm").component("orderDocumentsListComponent", componentConfig);
})();
<commit_msg>resolved error doc<commit_after>(function () {
  "use strict";
  var componentConfig = {
    templateUrl: "js/work-orders/order-documents-list-component.template.html",
    bindings: {
      barcode: "<",
    },
    controller: [
      "$scope",
      "work-orders-factory",
      "fpm-utilities-factory",
      "fieldPromaxConfig",
      function (
        $scope,
        workOrdersFactory,
        fpmUtilitiesFactory,
        fieldPromaxConfig
      ) {
        var vm = this;
        var baseUrl = fieldPromaxConfig.fieldPromaxApi;
        var alerts = fpmUtilitiesFactory.alerts;
        vm.docUrl = "";
        vm.gettinDocuments = false;
        vm.events = {
          onDocumentClicked: function (doc) {
            cordova.InAppBrowser.open(
              baseUrl +
                "Handlers/GetImageFromBlob.ashx?imageId=" +
                doc.num +
                "&dateStamp=" +
                new Date() +
                "&flag=viewTarget&cust=" +
                doc.customerNumber,
              "_system",
              "location=yes"
            );
          },
        };
        vm.$onInit = function () {
          if (vm.barcode) {
            vm.barcodeDocuments = [];
            vm.gettinDocuments = true;
            workOrdersFactory
              .getUploadedDocuments(vm.barcode)
              .then(function (response) {
                if (angular.isArray(response) && response.length > 0) {
                  var pdfs = _.where(response, { extension: ".pdf" });
                  vm.barcodeDocuments = pdfs;
                }
                vm.gettinDocuments = false;
              });
          } else {
            vm.gettinDocuments = false;
          }
        };
      },
    ],
    controllerAs: "vm",
  };
  angular
    .module("fpm")
    .component("orderDocumentsListComponent", componentConfig);
})();
<|endoftext|>