<commit_before>( function ( mw, $ ) {
	/*global moment:false */
	/**
	 * Notification option widget for echo popup.
	 *
	 * @class
	 * @extends OO.ui.OptionWidget
	 *
	 * @constructor
	 * @param {Object} [config] Configuration object
	 * @cfg {boolean} [markReadWhenSeen=false] This option is marked as read when it is viewed
	 * @cfg {jQuery} [$overlay] A jQuery element functioning as an overlay
	 *  for popups.
	 * @cfg {boolean} [bundle=false] This notification item is part of a bundle.
	 */
	mw.echo.ui.NotificationItemWidget = function MwEchoUiNotificationItemWidget( model, config ) {
		var i, secondaryUrls, urlObj, linkButton, $icon, isInsideMenu, echoMoment,
			$message = $( '<div>' ).addClass( 'mw-echo-ui-notificationItemWidget-content-message' ),
			widget = this;

		config = config || {};

		// Parent constructor
		mw.echo.ui.NotificationItemWidget.parent.call( this, $.extend( { data: model.getId() }, config ) );

		this.model = model;
		this.$overlay = config.$overlay || this.$element;
		this.bundle = !!config.bundle;

		this.$content = $( '<div>' ).addClass( 'mw-echo-ui-notificationItemWidget-content' );
		this.$actions = $( '<div>' )
			.addClass( 'mw-echo-ui-notificationItemWidget-content-actions' );

		// Mark unread
		this.markAsReadButton = new OO.ui.ButtonWidget( {
			icon: 'close',
			framed: false,
			classes: [ 'mw-echo-ui-notificationItemWidget-markAsReadButton' ]
		} );

		this.markReadWhenSeen = !!config.markReadWhenSeen;

		// Icon
		if ( this.model.getIconURL() ) {
			$icon = $( '<div>' )
				.addClass( 'mw-echo-ui-notificationItemWidget-icon' )
				.append( $( '<img>' ).attr( 'src', this.model.getIconURL() ) );
		}

		// Content
		$message.append(
			$( '<div>' )
				.addClass( 'mw-echo-ui-notificationItemWidget-content-message-header' )
				.append( this.model.getContentHeader() )
		);
		if ( !this.bundle && this.model.getContentBody() ) {
			$message.append(
				$( '<div>' )
					.addClass( 'mw-echo-ui-notificationItemWidget-content-message-body' )
					.append( this.model.getContentBody() )
					// dir=auto has a similar effect to wrapping the content in <bdi>, but
					// makes text-overflow: ellipsis; behave less strangely
					.attr( 'dir', 'auto' )
			);
		}

		// Actions menu
		this.actionsButtonSelectWidget = new OO.ui.ButtonSelectWidget( {
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-buttons' ]
		} );

		// Popup menu
		this.menuPopupButtonWidget = new mw.echo.ui.ActionMenuPopupWidget( {
			framed: false,
			icon: 'ellipsis',
			$overlay: this.$overlay,
			menuWidth: 200,
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-menu' ]
		} );

		// Timestamp
		// We want to use extra-short timestamp strings; we change the locale
		// to our echo-defined one and use that instead of the normal moment locale
		echoMoment = moment.utc( this.model.getTimestamp(), 'YYYYMMDDHHmmss' );
		echoMoment.locale( 'echo-shortRelativeTime' );

		this.timestampWidget = new OO.ui.LabelWidget( {
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-timestamp' ],
			// Get the time 'fromNow' without the suffix 'ago'
			label: echoMoment.fromNow( true )
		} );

		// Build the actions line
		if ( this.bundle ) {
			// In a bundled item, the timestamp should go before the menu
			this.$actions.append(
				$( '<div>' )
					// We are wrapping the actions in a 'row' div so that the
					// internal pieces are also a table layout
					.addClass( 'mw-echo-ui-notificationItemWidget-content-actions-row' )
					.append(
						this.actionsButtonSelectWidget.$element,
						this.timestampWidget.$element,
						this.menuPopupButtonWidget.$element
					)
			);
		} else {
			this.$actions.append(
				this.actionsButtonSelectWidget.$element,
				this.menuPopupButtonWidget.$element,
				this.timestampWidget.$element
			);
		}

		// Actions
		secondaryUrls = this.model.getSecondaryUrls();
		for ( i = 0; i < secondaryUrls.length; i++ ) {
			urlObj = secondaryUrls[ i ];

			isInsideMenu = !this.bundle && urlObj.prioritized !== undefined;

			linkButton = new mw.echo.ui.MenuItemWidget( {
				icon: urlObj.icon || 'next',
				label: urlObj.label,
				tooltip: urlObj.tooltip,
				description: urlObj.description,
				url: urlObj.url,
				prioritized: isInsideMenu
			} );

			if ( isInsideMenu ) {
				this.actionsButtonSelectWidget.addItems( [ linkButton ] );
			} else {
				this.menuPopupButtonWidget.getMenu().addItems( [ linkButton ] );
			}
		}
		// Add a "mark as read" secondary action
		this.toggleReadSecondaryButton = new mw.echo.ui.MenuItemWidget( {
			data: 'toggleRead',
			prioritized: false,
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-button' ]
		} );
		this.menuPopupButtonWidget.getMenu().addItems( [ this.toggleReadSecondaryButton ] );

		// Toggle 'mark as read' functionality
		this.toggleMarkAsReadButtons( !this.markReadWhenSeen && !this.model.isRead() );

		if ( this.bundle ) {
			// In a bundle, we have table layout, so the icon is
			// inserted into the content, and the 'mark as read'
			// button is not floating, and should be at the end
			this.$content.append(
				$icon,
				$message,
				this.$actions,
				this.markAsReadButton.$element
			);
			this.$element.append( this.$content );
		} else {
			this.$content.append(
				this.markAsReadButton.$element,
				$message,
				$( '<div>' )
					.addClass( 'mw-echo-ui-notificationItemWidget-content-table' )
					.append( this.$actions )
			);
			this.$element.append( $icon, this.$content );
		}

		this.$element
			.addClass( 'mw-echo-ui-notificationItemWidget mw-echo-ui-notificationItemWidget-' + this.model.getType() )
			.toggleClass( 'mw-echo-ui-notificationItemWidget-initiallyUnseen', !this.model.isSeen() && !this.bundle )
			.toggleClass( 'mw-echo-ui-notificationItemWidget-bundle', this.bundle );

		if ( this.model.getPrimaryUrl() ) {
			this.$element.contents()
				.wrapAll(
					// HACK: Wrap the entire item with a link that takes
					// the user to the primary url. This is not perfect,
					// but it makes the behavior native to the browser rather
					// than us listening to click events and opening new
					// windows.
					$( '<a>' )
						.addClass( 'mw-echo-ui-notificationItemWidget-linkWrapper' )
						.attr( 'href', this.model.getPrimaryUrl() )
						.on( 'click', function () {
							// Log notification click

							mw.echo.logger.logInteraction(
								mw.echo.Logger.static.actions.notificationClick,
								mw.echo.Logger.static.context.popup,
								widget.getModel().getId(),
								widget.getModel().getCategory(),
								false,
								// Source of this notification if it is cross-wiki
								widget.bundle ? widget.getModel().getSource() : ''
							);
						} )
				);
		}

		// Events
		this.markAsReadButton.connect( this, { click: 'onMarkAsReadButtonClick' } );
		this.menuPopupButtonWidget.getMenu().connect( this, { choose: 'onPopupButtonWidgetChoose' } );
		this.model.connect( this, {
			seen: 'toggleSeen',
			read: 'toggleRead'
		} );

		// Initialize state
		this.toggleRead( this.model.isRead() );
		this.toggleSeen( this.model.isSeen() );

		// HACK: We have to remove the built-in label. When this
		// widget is switched to a standalone widget rather than
		// an OptionWidget we can get rid of this
		this.$label.detach();
	};

	/* Initialization */

	OO.inheritClass( mw.echo.ui.NotificationItemWidget, OO.ui.OptionWidget );

	/* Static properties */

	mw.echo.ui.NotificationItemWidget.static.pressable = false;
	mw.echo.ui.NotificationItemWidget.static.selectable = false;

	/* Events */

	/**
	 * @event markAsRead
	 *
	 * Mark this notification as read
	 */

	/* Methods */

	/**
	 * Respond to mark as read button click
	 */
	mw.echo.ui.NotificationItemWidget.prototype.onMarkAsReadButtonClick = function () {
		this.model.toggleRead( true );
	};

	/**
	 * Respond to selecting an item from the popup button widget
	 */
	mw.echo.ui.NotificationItemWidget.prototype.onPopupButtonWidgetChoose = function ( item ) {
		var action = item && item.getData();

		if ( action === 'toggleRead' ) {
			this.model.toggleRead();
		}
	};

	/**
	 * Toggle the function of the 'mark as read' secondary button from 'mark as read' to
	 * 'mark as unread' and update the visibility of the primary 'mark as read' X button.
	 *
	 *
	 * @param {boolean} [show] Show the 'mark as read' buttons
	 *  - "false" means that the item is marked as read, whereby we show the user 'mark unread'
	 *    and hide the primary 'x' button
	 *  - "true" means that the item is marked as unread and we show the user 'mark as read'
	 *    primary and secondary buttons.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleMarkAsReadButtons = function ( show ) {
		show = show !== undefined ? show : !this.model.isRead();

		this.markAsReadButton.toggle( show );

		if ( show ) {
			// Mark read
			this.toggleReadSecondaryButton.setLabel( mw.msg( 'echo-notification-markasread' ) );
			this.toggleReadSecondaryButton.setIcon( 'check' );
		} else {
			// Mark unread
			this.toggleReadSecondaryButton.setLabel( mw.msg( 'echo-notification-markasunread' ) );
			this.toggleReadSecondaryButton.setIcon( 'sun' );
		}
		this.menuPopupButtonWidget.toggle( !this.menuPopupButtonWidget.getMenu().isEmpty() );
	};

	/**
	 * Reset the status of the notification without touching its user-controlled status.
	 * For one, remove 'initiallyUnseen' which exists only for the animation to work.
	 * This is called when new notifications are added to the parent widget, having to
	 * reset the 'unseen' status from the old ones.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.reset = function () {
		this.$element.removeClass( 'mw-echo-ui-notificationItemWidget-initiallyUnseen' );
	};

	/**
	 * Toggle the read state of the widget
	 *
	 * @param {boolean} [read] The current read state. If not given, the state will
	 *  become the opposite of its current state.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleRead = function ( read ) {
		this.read = read !== undefined ? read : !this.read;

		this.$element.toggleClass( 'mw-echo-ui-notificationItemWidget-unread', !this.read );
		this.toggleMarkAsReadButtons( !this.read );
	};

	/**
	 * Toggle the seen state of the widget
	 *
	 * @param {boolean} [seen] The current seen state. If not given, the state will
	 *  become the opposite of its current state.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleSeen = function ( seen ) {
		this.seen = seen !== undefined ? seen : !this.seen;

		this.$element
			.toggleClass( 'mw-echo-ui-notificationItemWidget-unseen', !this.seen );
	};

	/**
	 * Get the notification link
	 *
	 * @return {string} Notification link
	 */
	mw.echo.ui.NotificationItemWidget.prototype.getModel = function () {
		return this.model;
	};

	/**
	 * Get the notification link
	 *
	 * @return {string} Notification link
	 */
	mw.echo.ui.NotificationItemWidget.prototype.getPrimaryUrl = function () {
		return this.model.getPrimaryUrl();
	};

	/**
	 * Disconnect events when widget is destroyed.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.destroy = function () {
		this.model.disconnect( this );
	};

} )( mediaWiki, jQuery );
<commit_msg>Clicking a marked-as-unread notification should mark it as read<commit_after>( function ( mw, $ ) {
	/*global moment:false */
	/**
	 * Notification option widget for echo popup.
	 *
	 * @class
	 * @extends OO.ui.OptionWidget
	 *
	 * @constructor
	 * @param {Object} [config] Configuration object
	 * @cfg {boolean} [markReadWhenSeen=false] This option is marked as read when it is viewed
	 * @cfg {jQuery} [$overlay] A jQuery element functioning as an overlay
	 *  for popups.
	 * @cfg {boolean} [bundle=false] This notification item is part of a bundle.
	 */
	mw.echo.ui.NotificationItemWidget = function MwEchoUiNotificationItemWidget( model, config ) {
		var i, secondaryUrls, urlObj, linkButton, $icon, isInsideMenu, echoMoment,
			$message = $( '<div>' ).addClass( 'mw-echo-ui-notificationItemWidget-content-message' ),
			widget = this;

		config = config || {};

		// Parent constructor
		mw.echo.ui.NotificationItemWidget.parent.call( this, $.extend( { data: model.getId() }, config ) );

		this.model = model;
		this.$overlay = config.$overlay || this.$element;
		this.bundle = !!config.bundle;

		this.$content = $( '<div>' ).addClass( 'mw-echo-ui-notificationItemWidget-content' );
		this.$actions = $( '<div>' )
			.addClass( 'mw-echo-ui-notificationItemWidget-content-actions' );

		// Mark unread
		this.markAsReadButton = new OO.ui.ButtonWidget( {
			icon: 'close',
			framed: false,
			classes: [ 'mw-echo-ui-notificationItemWidget-markAsReadButton' ]
		} );

		this.markReadWhenSeen = !!config.markReadWhenSeen;

		// Icon
		if ( this.model.getIconURL() ) {
			$icon = $( '<div>' )
				.addClass( 'mw-echo-ui-notificationItemWidget-icon' )
				.append( $( '<img>' ).attr( 'src', this.model.getIconURL() ) );
		}

		// Content
		$message.append(
			$( '<div>' )
				.addClass( 'mw-echo-ui-notificationItemWidget-content-message-header' )
				.append( this.model.getContentHeader() )
		);
		if ( !this.bundle && this.model.getContentBody() ) {
			$message.append(
				$( '<div>' )
					.addClass( 'mw-echo-ui-notificationItemWidget-content-message-body' )
					.append( this.model.getContentBody() )
					// dir=auto has a similar effect to wrapping the content in <bdi>, but
					// makes text-overflow: ellipsis; behave less strangely
					.attr( 'dir', 'auto' )
			);
		}

		// Actions menu
		this.actionsButtonSelectWidget = new OO.ui.ButtonSelectWidget( {
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-buttons' ]
		} );

		// Popup menu
		this.menuPopupButtonWidget = new mw.echo.ui.ActionMenuPopupWidget( {
			framed: false,
			icon: 'ellipsis',
			$overlay: this.$overlay,
			menuWidth: 200,
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-menu' ]
		} );

		// Timestamp
		// We want to use extra-short timestamp strings; we change the locale
		// to our echo-defined one and use that instead of the normal moment locale
		echoMoment = moment.utc( this.model.getTimestamp(), 'YYYYMMDDHHmmss' );
		echoMoment.locale( 'echo-shortRelativeTime' );

		this.timestampWidget = new OO.ui.LabelWidget( {
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-timestamp' ],
			// Get the time 'fromNow' without the suffix 'ago'
			label: echoMoment.fromNow( true )
		} );

		// Build the actions line
		if ( this.bundle ) {
			// In a bundled item, the timestamp should go before the menu
			this.$actions.append(
				$( '<div>' )
					// We are wrapping the actions in a 'row' div so that the
					// internal pieces are also a table layout
					.addClass( 'mw-echo-ui-notificationItemWidget-content-actions-row' )
					.append(
						this.actionsButtonSelectWidget.$element,
						this.timestampWidget.$element,
						this.menuPopupButtonWidget.$element
					)
			);
		} else {
			this.$actions.append(
				this.actionsButtonSelectWidget.$element,
				this.menuPopupButtonWidget.$element,
				this.timestampWidget.$element
			);
		}

		// Actions
		secondaryUrls = this.model.getSecondaryUrls();
		for ( i = 0; i < secondaryUrls.length; i++ ) {
			urlObj = secondaryUrls[ i ];

			isInsideMenu = !this.bundle && urlObj.prioritized !== undefined;

			linkButton = new mw.echo.ui.MenuItemWidget( {
				icon: urlObj.icon || 'next',
				label: urlObj.label,
				tooltip: urlObj.tooltip,
				description: urlObj.description,
				url: urlObj.url,
				prioritized: isInsideMenu
			} );

			if ( isInsideMenu ) {
				this.actionsButtonSelectWidget.addItems( [ linkButton ] );
			} else {
				this.menuPopupButtonWidget.getMenu().addItems( [ linkButton ] );
			}
		}
		// Add a "mark as read" secondary action
		this.toggleReadSecondaryButton = new mw.echo.ui.MenuItemWidget( {
			data: 'toggleRead',
			prioritized: false,
			classes: [ 'mw-echo-ui-notificationItemWidget-content-actions-button' ]
		} );
		this.menuPopupButtonWidget.getMenu().addItems( [ this.toggleReadSecondaryButton ] );

		// Toggle 'mark as read' functionality
		this.toggleMarkAsReadButtons( !this.markReadWhenSeen && !this.model.isRead() );

		if ( this.bundle ) {
			// In a bundle, we have table layout, so the icon is
			// inserted into the content, and the 'mark as read'
			// button is not floating, and should be at the end
			this.$content.append(
				$icon,
				$message,
				this.$actions,
				this.markAsReadButton.$element
			);
			this.$element.append( this.$content );
		} else {
			this.$content.append(
				this.markAsReadButton.$element,
				$message,
				$( '<div>' )
					.addClass( 'mw-echo-ui-notificationItemWidget-content-table' )
					.append( this.$actions )
			);
			this.$element.append( $icon, this.$content );
		}

		this.$element
			.addClass( 'mw-echo-ui-notificationItemWidget mw-echo-ui-notificationItemWidget-' + this.model.getType() )
			.toggleClass( 'mw-echo-ui-notificationItemWidget-initiallyUnseen', !this.model.isSeen() && !this.bundle )
			.toggleClass( 'mw-echo-ui-notificationItemWidget-bundle', this.bundle );

		if ( this.model.getPrimaryUrl() ) {
			this.$element.contents()
				.wrapAll(
					// HACK: Wrap the entire item with a link that takes
					// the user to the primary url. This is not perfect,
					// but it makes the behavior native to the browser rather
					// than us listening to click events and opening new
					// windows.
					$( '<a>' )
						.addClass( 'mw-echo-ui-notificationItemWidget-linkWrapper' )
						.attr( 'href', this.model.getPrimaryUrl() )
						.on( 'click', function () {
							// Log notification click

							mw.echo.logger.logInteraction(
								mw.echo.Logger.static.actions.notificationClick,
								mw.echo.Logger.static.context.popup,
								widget.getModel().getId(),
								widget.getModel().getCategory(),
								false,
								// Source of this notification if it is cross-wiki
								widget.bundle ? widget.getModel().getSource() : ''
							);

							// Toggle the notification as read
							widget.model.toggleRead( true );
						} )
				);
		}

		// Events
		this.markAsReadButton.connect( this, { click: 'onMarkAsReadButtonClick' } );
		this.menuPopupButtonWidget.getMenu().connect( this, { choose: 'onPopupButtonWidgetChoose' } );
		this.model.connect( this, {
			seen: 'toggleSeen',
			read: 'toggleRead'
		} );

		// Initialize state
		this.toggleRead( this.model.isRead() );
		this.toggleSeen( this.model.isSeen() );

		// HACK: We have to remove the built-in label. When this
		// widget is switched to a standalone widget rather than
		// an OptionWidget we can get rid of this
		this.$label.detach();
	};

	/* Initialization */

	OO.inheritClass( mw.echo.ui.NotificationItemWidget, OO.ui.OptionWidget );

	/* Static properties */

	mw.echo.ui.NotificationItemWidget.static.pressable = false;
	mw.echo.ui.NotificationItemWidget.static.selectable = false;

	/* Events */

	/**
	 * @event markAsRead
	 *
	 * Mark this notification as read
	 */

	/* Methods */

	/**
	 * Respond to mark as read button click
	 */
	mw.echo.ui.NotificationItemWidget.prototype.onMarkAsReadButtonClick = function () {
		this.model.toggleRead( true );
	};

	/**
	 * Respond to selecting an item from the popup button widget
	 */
	mw.echo.ui.NotificationItemWidget.prototype.onPopupButtonWidgetChoose = function ( item ) {
		var action = item && item.getData();

		if ( action === 'toggleRead' ) {
			this.model.toggleRead();
		}
	};

	/**
	 * Toggle the function of the 'mark as read' secondary button from 'mark as read' to
	 * 'mark as unread' and update the visibility of the primary 'mark as read' X button.
	 *
	 *
	 * @param {boolean} [show] Show the 'mark as read' buttons
	 *  - "false" means that the item is marked as read, whereby we show the user 'mark unread'
	 *    and hide the primary 'x' button
	 *  - "true" means that the item is marked as unread and we show the user 'mark as read'
	 *    primary and secondary buttons.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleMarkAsReadButtons = function ( show ) {
		show = show !== undefined ? show : !this.model.isRead();

		this.markAsReadButton.toggle( show );

		if ( show ) {
			// Mark read
			this.toggleReadSecondaryButton.setLabel( mw.msg( 'echo-notification-markasread' ) );
			this.toggleReadSecondaryButton.setIcon( 'check' );
		} else {
			// Mark unread
			this.toggleReadSecondaryButton.setLabel( mw.msg( 'echo-notification-markasunread' ) );
			this.toggleReadSecondaryButton.setIcon( 'sun' );
		}
		this.menuPopupButtonWidget.toggle( !this.menuPopupButtonWidget.getMenu().isEmpty() );
	};

	/**
	 * Reset the status of the notification without touching its user-controlled status.
	 * For one, remove 'initiallyUnseen' which exists only for the animation to work.
	 * This is called when new notifications are added to the parent widget, having to
	 * reset the 'unseen' status from the old ones.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.reset = function () {
		this.$element.removeClass( 'mw-echo-ui-notificationItemWidget-initiallyUnseen' );
	};

	/**
	 * Toggle the read state of the widget
	 *
	 * @param {boolean} [read] The current read state. If not given, the state will
	 *  become the opposite of its current state.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleRead = function ( read ) {
		this.read = read !== undefined ? read : !this.read;

		this.$element.toggleClass( 'mw-echo-ui-notificationItemWidget-unread', !this.read );
		this.toggleMarkAsReadButtons( !this.read );
	};

	/**
	 * Toggle the seen state of the widget
	 *
	 * @param {boolean} [seen] The current seen state. If not given, the state will
	 *  become the opposite of its current state.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.toggleSeen = function ( seen ) {
		this.seen = seen !== undefined ? seen : !this.seen;

		this.$element
			.toggleClass( 'mw-echo-ui-notificationItemWidget-unseen', !this.seen );
	};

	/**
	 * Get the notification link
	 *
	 * @return {string} Notification link
	 */
	mw.echo.ui.NotificationItemWidget.prototype.getModel = function () {
		return this.model;
	};

	/**
	 * Get the notification link
	 *
	 * @return {string} Notification link
	 */
	mw.echo.ui.NotificationItemWidget.prototype.getPrimaryUrl = function () {
		return this.model.getPrimaryUrl();
	};

	/**
	 * Disconnect events when widget is destroyed.
	 */
	mw.echo.ui.NotificationItemWidget.prototype.destroy = function () {
		this.model.disconnect( this );
	};

} )( mediaWiki, jQuery );
<|endoftext|>


<commit_before>angular
	.module('ngSharepoint.Lists')
	.factory('SelectQuery', ['$spList', 'CamlBuilder', 'Query', 'WhereQuery', function($spList, CamlBuilder, Query, WhereQuery) {
        var SelectQuery = function(fields) {
            this.__values = fields;
            this.__where = [];
            this.__limit = null;
            this.__order = [];
            //this.__queries.where = [];
            //this.__queries.limit = [];
            return this;
        };
        SelectQuery.prototype = new Query();
        SelectQuery.prototype.from = function(list) {
        	this.__list = list;
        	return this;
        };
        SelectQuery.prototype.where = function(field) {
            var query = new WhereQuery(this, field);
            this.__where.push(query);
            return query;
        };
        SelectQuery.prototype.limit = function(amount) {
            this.__limit = amount;
            return this;
        };
        SelectQuery.prototype.orderBy = function(field, asc) {
            if (angular.isUndefined(asc)) {
                asc = true;
            }
            this.__order.push({field: field, asc: asc});
            return this;
        };
        SelectQuery.prototype.__execute = function() {
            var camlBuilder = new CamlBuilder();
            var camlView = camlBuilder.push('View');
            if (query.__where.length > 0 || query.__order.length > 0) {
                var queryTag = camlView.push('Query');
                if (query.__where.length === 1) {
                    var camlWhere = queryTag.push('Where');
                    query.__where[0].push(camlWhere);
                }else if (query.__where.length > 1) {
                    var camlAnd = queryTag.push('Where').push('And');
                    query.__where.forEach(function(where) {
                        where.push(camlAnd);
                    });
                }
                if (query.__order.length > 0) {
                    var camlOrder = queryTag.push('OrderBy');
                    query.__order.forEach(function(order) {
                        camlOrder.push('FieldRef', {Name: order.field, Ascending: order.asc});
                    });
                }
            }
            var viewFields = camlView.push('ViewFields');
            query.__values.forEach(function(field) {
                viewFields.push('FieldRef', {Name: field});
            });
            if (query.__limit !== null) {
                camlView.push('RowLimit', {}, query.__limit);
            }
            return $spList.getList(this.__list).select(camlBuilder.build());
        };
		return (SelectQuery);
	}]);<commit_msg>use this instead of query<commit_after>angular
	.module('ngSharepoint.Lists')
	.factory('SelectQuery', ['$spList', 'CamlBuilder', 'Query', 'WhereQuery', function($spList, CamlBuilder, Query, WhereQuery) {
        var SelectQuery = function(fields) {
            this.__values = fields;
            this.__where = [];
            this.__limit = null;
            this.__order = [];
            //this.__queries.where = [];
            //this.__queries.limit = [];
            return this;
        };
        SelectQuery.prototype = new Query();
        SelectQuery.prototype.from = function(list) {
        	this.__list = list;
        	return this;
        };
        SelectQuery.prototype.where = function(field) {
            var query = new WhereQuery(this, field);
            this.__where.push(query);
            return query;
        };
        SelectQuery.prototype.limit = function(amount) {
            this.__limit = amount;
            return this;
        };
        SelectQuery.prototype.orderBy = function(field, asc) {
            if (angular.isUndefined(asc)) {
                asc = true;
            }
            this.__order.push({field: field, asc: asc});
            return this;
        };
        SelectQuery.prototype.__execute = function() {
            var camlBuilder = new CamlBuilder();
            var camlView = camlBuilder.push('View');
            if (this.__where.length > 0 || this.__order.length > 0) {
                var queryTag = camlView.push('Query');
                if (this.__where.length === 1) {
                    var camlWhere = queryTag.push('Where');
                    this.__where[0].push(camlWhere);
                }else if (this.__where.length > 1) {
                    var camlAnd = queryTag.push('Where').push('And');
                    this.__where.forEach(function(where) {
                        where.push(camlAnd);
                    });
                }
                if (this.__order.length > 0) {
                    var camlOrder = queryTag.push('OrderBy');
                    this.__order.forEach(function(order) {
                        camlOrder.push('FieldRef', {Name: order.field, Ascending: order.asc});
                    });
                }
            }
            var viewFields = camlView.push('ViewFields');
            this.__values.forEach(function(field) {
                viewFields.push('FieldRef', {Name: field});
            });
            if (this.__limit !== null) {
                camlView.push('RowLimit', {}, this.__limit);
            }
            return $spList.getList(this.__list).select(camlBuilder.build());
        };
		return (SelectQuery);
	}]);<|endoftext|>


<commit_before>'use strict';

module.exports = {
	"recipe": {
		"type": "string", "required": true,
	},
	"deployConfig": {
		"type": "object",
		"required": true,
		"properties": {
			"memoryLimit": {"required": false, "type": "number", "default": 209715200},
			"cpuLimit": {"required": false, "type": "string"},
			"isKubernetes": {"required": false, "type": "boolean"},
			"replication": {
				"required": false,
				"type": "object",
				"properties": {
					"mode": {
						"required": true,
						"type": "string",
						"enum": ['replicated', 'global', 'deployment', 'daemonset']
					},
					"replicas": {"required": false, "type": "number", "minimum": 1}
				}
			},
			"region": {"required": false, "type": "string"},
			"infra": {"required": false, "type": "string"},
			"type": {"required": true, "type": "string", "enum": ["container", "vm"], "default": "container"},
			"vmConfiguration": {
				"required": false,
				"type": "object",
				"properties": {
					"vmLayer": {"required": true, "type": "string"},
				}
			},
		}
	},
	"autoScale": {
		"type": "object",
		"required": false,
		"properties": {
			"replicas": {
				"required": true,
				"type": "object",
				"properties": {
					"min": {"required": true, "type": "integer", "min": 1},
					"max": {"required": true, "type": "integer", "min": 1}
				},
				"additionalProperties": false
			},
			"metrics": {
				"required": true,
				"type": "object",
				"properties": {
					"cpu": {
						"required": true,
						"type": "object",
						"properties": {
							"percent": {"required": true, "type": "number"}
						},
						"additionalProperties": false
					}
				},
				"additionalProperties": false
			}
		},
		"additionalProperties": false
	},
	"custom": {
		"type": "object",
		"required": false,
		"properties": {
			"sourceCode" : {
				"type": "object",
				"required": false,
				"properties" : {
					"configuration" : {
						"type": "object",
						"required": false,
						"properties" : {
							"repo" : {"type": "string", "required": true},
							"branch" : {"type": "string", "required": true},
							"commit" : {"type": "string", "required": false},
							"path" : {"type": "string", "required": false}
						}
					},
					"custom" : {
						"type": "object",
						"required": false,
						"properties" : {
							"repo" : {"type": "string", "required": true},
							"branch" : {"type": "string", "required": true},
							"commit" : {"type": "string", "required": false},
							"path" : {"type": "string", "required": false}
						}
					}
				}
			},
			"image": {
				"type": "object",
				"required": false,
				"properties": {
					"prefix": {"required": false, "type": "string"},
					"name": {"required": false, "type": "string"},
					"tag": {"required": false, "type": "string"},
				}
			},
			"env": {
				"type": "object",
				"required": false,
				"additionalProperties": {"type": "string"}
			},
			"type": {
				"required": true,
				"type": "string"
			},
			"name": {
				"required": true,
				"type": "string"
			},
			"secrets": {
				"type": "array",
				"required": false,
				"items":{
					"type": "object",
					"required": true,
					"properties":{
						"name": {"type":"string", "required": true},
						"type": {"type":"string", "required": false},
						"mountPath": {"type":"string", "required": false}
					}
				}
			}
		}
	}
};
<commit_msg>Added group value to IMFV of deploy resource<commit_after>'use strict';

module.exports = {
	"recipe": {
		"type": "string", "required": true,
	},
	"deployConfig": {
		"type": "object",
		"required": true,
		"properties": {
			"memoryLimit": {"required": false, "type": "number", "default": 209715200},
			"cpuLimit": {"required": false, "type": "string"},
			"isKubernetes": {"required": false, "type": "boolean"},
			"replication": {
				"required": false,
				"type": "object",
				"properties": {
					"mode": {
						"required": true,
						"type": "string",
						"enum": ['replicated', 'global', 'deployment', 'daemonset']
					},
					"replicas": {"required": false, "type": "number", "minimum": 1}
				}
			},
			"region": {"required": false, "type": "string"},
			"infra": {"required": false, "type": "string"},
			"type": {"required": true, "type": "string", "enum": ["container", "vm"], "default": "container"},
			"vmConfiguration": {
				"required": false,
				"type": "object",
				"properties": {
					"vmLayer": {"required": true, "type": "string"},
					"group": {"required": true, "type": "string"}
				}
			},
		}
	},
	"autoScale": {
		"type": "object",
		"required": false,
		"properties": {
			"replicas": {
				"required": true,
				"type": "object",
				"properties": {
					"min": {"required": true, "type": "integer", "min": 1},
					"max": {"required": true, "type": "integer", "min": 1}
				},
				"additionalProperties": false
			},
			"metrics": {
				"required": true,
				"type": "object",
				"properties": {
					"cpu": {
						"required": true,
						"type": "object",
						"properties": {
							"percent": {"required": true, "type": "number"}
						},
						"additionalProperties": false
					}
				},
				"additionalProperties": false
			}
		},
		"additionalProperties": false
	},
	"custom": {
		"type": "object",
		"required": false,
		"properties": {
			"sourceCode" : {
				"type": "object",
				"required": false,
				"properties" : {
					"configuration" : {
						"type": "object",
						"required": false,
						"properties" : {
							"repo" : {"type": "string", "required": true},
							"branch" : {"type": "string", "required": true},
							"commit" : {"type": "string", "required": false},
							"path" : {"type": "string", "required": false}
						}
					},
					"custom" : {
						"type": "object",
						"required": false,
						"properties" : {
							"repo" : {"type": "string", "required": true},
							"branch" : {"type": "string", "required": true},
							"commit" : {"type": "string", "required": false},
							"path" : {"type": "string", "required": false}
						}
					}
				}
			},
			"image": {
				"type": "object",
				"required": false,
				"properties": {
					"prefix": {"required": false, "type": "string"},
					"name": {"required": false, "type": "string"},
					"tag": {"required": false, "type": "string"},
				}
			},
			"env": {
				"type": "object",
				"required": false,
				"additionalProperties": {"type": "string"}
			},
			"type": {
				"required": true,
				"type": "string"
			},
			"name": {
				"required": true,
				"type": "string"
			},
			"secrets": {
				"type": "array",
				"required": false,
				"items":{
					"type": "object",
					"required": true,
					"properties":{
						"name": {"type":"string", "required": true},
						"type": {"type":"string", "required": false},
						"mountPath": {"type":"string", "required": false}
					}
				}
			}
		}
	}
};
<|endoftext|>


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

define(function(require) {
  /*
    DEPENDENCIES
   */

  var TabDataTable = require('utils/tab-datatable');
  var SunstoneConfig = require('sunstone-config');
  var Sunstone = require('sunstone');
  var Locale = require('utils/locale');
  var Humanize = require('utils/humanize');
  var LabelsUtils = require('utils/labels/utils');
  var Tree = require('utils/labels/tree');

  /*
    CONSTANTS
   */

  var RESOURCE = "Template";
  var XML_ROOT = "VMTEMPLATE";
  var TAB_NAME = require('./tabId');
  var LABELS_COLUMN = 6;

  /*
    CONSTRUCTOR
   */

  function Table(dataTableId, conf) {
    this.conf = conf || {};
    this.tabId = TAB_NAME;
    this.dataTableId = dataTableId;
    this.resource = RESOURCE;
    this.xmlRoot = XML_ROOT;

    this.dataTableOptions = {
      "bAutoWidth": false,
      "bSortClasses" : false,
      "bDeferRender": true,
      "aoColumnDefs": [
          {"bSortable": false, "aTargets": ["check"]},
          {"sWidth": "35px", "aTargets": [0]},
          {"bVisible": true, "aTargets": SunstoneConfig.tabTableColumns(TAB_NAME)},
          {"bVisible": false, "aTargets": ['_all']}
      ]
    }

    this.columns = [
      Locale.tr("ID") ,
      Locale.tr("Owner") ,
      Locale.tr("Group"),
      Locale.tr("Name"),
      Locale.tr("Registration time"),
      Locale.tr("Labels")
    ];

    this.selectOptions = {
      "id_index": 1,
      "name_index": 4,
      "select_resource": Locale.tr("Please select a Template from the list"),
      "you_selected": Locale.tr("You selected the following Template:"),
      "select_resource_multiple": Locale.tr("Please select one or more Templates from the list"),
      "you_selected_multiple": Locale.tr("You selected the following Templates:")
    };

    this.labels = [];

    TabDataTable.call(this);
  };

  Table.prototype = Object.create(TabDataTable.prototype);
  Table.prototype.constructor = Table;
  Table.prototype.elementArray = _elementArray;
  Table.prototype.preUpdateView = _preUpdateView;
  Table.prototype.postUpdateView = _postUpdateView;
  Table.prototype.clearLabelsFilter = _clearLabelsFilter;
  Table.prototype.setLabelsFilter = _setLabelsFilter;

  return Table;

  /*
    FUNCTION DEFINITIONS
   */

  function _elementArray(element_json) {
    var element = element_json[XML_ROOT];

    var labelsStr = LabelsUtils.labelsStr(element);
    if (labelsStr) {
      this.labels.push(labelsStr);
    }

    return [
        '<input class="check_item" type="checkbox" id="' + RESOURCE.toLowerCase() + '_' +
                             element.ID + '" name="selected_items" value="' +
                             element.ID + '"/>',
        element.ID,
        element.UNAME,
        element.GNAME,
        element.NAME,
        Humanize.prettyTime(element.REGTIME),
        (labelsStr||'')
    ];
  }

  function _preUpdateView() {
    this.labels = [];
  }

  function _postUpdateView() {
    var that = this;
    var labels = LabelsUtils.deserializeLabels(this.labels.join(','));

    /*
      Add labels tree to the left menu
     */
    $('.labels-tree', '#li_' + TAB_NAME).remove();
    $('#li_' + TAB_NAME).append(Tree.html(LabelsUtils.makeTree(labels), true));
    Tree.setup($('.labels-tree', '#li_' + TAB_NAME));

    /*
      Filter datatable when a label in the left menu is clicked
     */
    $('#li_' + TAB_NAME).off('click', '.one-label');
    $('#li_' + TAB_NAME).on('click', '.one-label', function() {
      var regExp = [];
      var label = $(this).attr('one-label-full-name');
      regExp.push('^' + label + '$');
      regExp.push(',' + label + '$');
      regExp.push('^' + label + ',');
      regExp.push(',' + label + ',');
      that.setLabelsFilter(regExp.join('|'));
      return false;
    });

    /*
      Generate labels dropdown content
     */
    $('#' + TAB_NAME + 'LabelsDropdown').html(
      '
' +
      '
' + Locale.tr('Edit Labels') + '
' +
      Tree.html(LabelsUtils.makeTree(labels), false) +
      '
' +
        '<input type="text" placeholder="' + Locale.tr("Add Label") + '"/>' +
      '
' +
      '
');

    recountLabels();

    // Check label & Update Templates
    $('#' + TAB_NAME + 'LabelsDropdown').off('click');
    $('#' + TAB_NAME + 'LabelsDropdown').on('click', '.labelsCheckbox', function() {
      var action;
      if ($(this).hasClass('fa-square-o')) {
        action = 'add';
        $(this).removeClass('fa-square-o').addClass('fa-check-square-o');
      } else {
        action = 'remove';
        $(this).removeClass('fa-check-square-o fa-minus-square-o').addClass('fa-square-o');
      }

      var labelName = $('.one-label', $(this).parent('li')).attr('one-label-full-name');
      var resourceId, aData, labelsArray, labelIndex;
      $('.check_item:checked', that.dataTable).each(function() {
        resourceId = $(this).val();
        aData = that.dataTable.fnGetData($(this).closest('tr'));
        labelsArray = aData[LABELS_COLUMN] != '' ? aData[LABELS_COLUMN].split(',') : [];
        labelIndex = $.inArray(labelName, labelsArray);
        if (action == 'add' && labelIndex == -1) {
          labelsArray.push(labelName)
          updateResouceLabels(resourceId, labelsArray);
        } else if (action == 'remove' && labelIndex != -1) {
          labelsArray.splice(labelIndex, 1);
          updateResouceLabels(resourceId, labelsArray);
        }
      });
    });

    function updateResouceLabels(resourceId, labelsArray) {
      var templateStr = LabelsUtils.LABELS_ATTR + '="' + labelsArray.join(',') + '"';
      Sunstone.runAction(RESOURCE + '.append_template', resourceId, templateStr);
    }

    /*
      DataTable Checkbox Listener
     */
    that.dataTable.on('change', 'tbody .check_item', recountLabels);

    /*
      Update Dropdown with selected items
      [v] If all the selected items has a label
      [-] If any of the selected items has a label
      [ ] If no selected item has an existing label
     */
    function recountLabels() {
      // Generate Hash with labels and number of items
      var aData, labelsStr, labelsIndexed = {};
      var selectedItems = $('.check_item:checked', that.dataTable);
      selectedItems.each(function() {
        aData = that.dataTable.fnGetData($(this).closest('tr'));
        labelsStr = aData[LABELS_COLUMN];
        if (labelsStr != '') {
          $.each(labelsStr.split(','), function(){
            if (labelsIndexed[this]) {
              labelsIndexed[this] += 1
            } else {
              labelsIndexed[this] = 1
            }
          })
        }
      });

      // Reset label checkboxes
      $('.labelsCheckbox', labelsDropdown)
        .removeClass('fa-minus-square-o')
        .removeClass('fa-check-square-o')
        .addClass('fa-square-o');

      // Set checkboxes (check|minus) depending on the number of items
      var selectedItemsLength = selectedItems.length;
      var labelsCheckbox;
      var labelsDropdown = $('#' + TAB_NAME + 'LabelsDropdown');
      $.each(labelsIndexed, function(labelName, numberOfItems) {
        labelsCheckbox = $('.labelsCheckbox',
          $('[one-label-full-name="' + labelName + '"]', labelsDropdown).closest('li'));
        if (labelsCheckbox.length > 0) {
          if (numberOfItems == selectedItemsLength) {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-check-square-o');
          } else {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-minus-square-o');
          }
        }
      });
    }
  }

  function _setLabelsFilter(regExp) {
    this.dataTable.fnFilter(regExp, LABELS_COLUMN, true, false);
  }

  function _clearLabelsFilter() {
    this.dataTable.fnFilter('', LABELS_COLUMN, true, false);
  }
});
<commit_msg>feature #4184: Add new label<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var TabDataTable = require('utils/tab-datatable');
  var SunstoneConfig = require('sunstone-config');
  var Sunstone = require('sunstone');
  var OpenNebula = require('opennebula');
  var Locale = require('utils/locale');
  var Humanize = require('utils/humanize');
  var LabelsUtils = require('utils/labels/utils');
  var Tree = require('utils/labels/tree');
  var Notifier = require('utils/notifier');

  /*
    CONSTANTS
   */

  var RESOURCE = "Template";
  var XML_ROOT = "VMTEMPLATE";
  var TAB_NAME = require('./tabId');
  var LABELS_COLUMN = 6;

  /*
    CONSTRUCTOR
   */

  function Table(dataTableId, conf) {
    this.conf = conf || {};
    this.tabId = TAB_NAME;
    this.dataTableId = dataTableId;
    this.resource = RESOURCE;
    this.xmlRoot = XML_ROOT;

    this.dataTableOptions = {
      "bAutoWidth": false,
      "bSortClasses" : false,
      "bDeferRender": true,
      "aoColumnDefs": [
          {"bSortable": false, "aTargets": ["check"]},
          {"sWidth": "35px", "aTargets": [0]},
          {"bVisible": true, "aTargets": SunstoneConfig.tabTableColumns(TAB_NAME)},
          {"bVisible": false, "aTargets": ['_all']}
      ]
    }

    this.columns = [
      Locale.tr("ID") ,
      Locale.tr("Owner") ,
      Locale.tr("Group"),
      Locale.tr("Name"),
      Locale.tr("Registration time"),
      Locale.tr("Labels")
    ];

    this.selectOptions = {
      "id_index": 1,
      "name_index": 4,
      "select_resource": Locale.tr("Please select a Template from the list"),
      "you_selected": Locale.tr("You selected the following Template:"),
      "select_resource_multiple": Locale.tr("Please select one or more Templates from the list"),
      "you_selected_multiple": Locale.tr("You selected the following Templates:")
    };

    this.labels = [];

    TabDataTable.call(this);
  };

  Table.prototype = Object.create(TabDataTable.prototype);
  Table.prototype.constructor = Table;
  Table.prototype.elementArray = _elementArray;
  Table.prototype.preUpdateView = _preUpdateView;
  Table.prototype.postUpdateView = _postUpdateView;
  Table.prototype.clearLabelsFilter = _clearLabelsFilter;
  Table.prototype.setLabelsFilter = _setLabelsFilter;

  return Table;

  /*
    FUNCTION DEFINITIONS
   */

  function _elementArray(element_json) {
    var element = element_json[XML_ROOT];

    var labelsStr = LabelsUtils.labelsStr(element);
    if (labelsStr) {
      this.labels.push(labelsStr);
    }

    return [
        '<input class="check_item" type="checkbox" id="' + RESOURCE.toLowerCase() + '_' +
                             element.ID + '" name="selected_items" value="' +
                             element.ID + '"/>',
        element.ID,
        element.UNAME,
        element.GNAME,
        element.NAME,
        Humanize.prettyTime(element.REGTIME),
        (labelsStr||'')
    ];
  }

  function _preUpdateView() {
    this.labels = [];
  }

  function _postUpdateView() {
    var that = this;
    var labels = LabelsUtils.deserializeLabels(that.labels.join(','));

    /*
      Add labels tree to the left menu
     */
    $('.labels-tree', '#li_' + TAB_NAME).remove();
    $('#li_' + TAB_NAME).append(Tree.html(LabelsUtils.makeTree(labels), true));
    Tree.setup($('.labels-tree', '#li_' + TAB_NAME));

    /*
      Filter datatable when a label in the left menu is clicked
     */
    $('#li_' + TAB_NAME).off('click', '.one-label');
    $('#li_' + TAB_NAME).on('click', '.one-label', function() {
      var regExp = [];
      var label = $(this).attr('one-label-full-name');
      regExp.push('^' + label + '$');
      regExp.push(',' + label + '$');
      regExp.push('^' + label + ',');
      regExp.push(',' + label + ',');
      that.setLabelsFilter(regExp.join('|'));
      return false;
    });

    /*
      Generate labels dropdown content
     */
    $('#' + TAB_NAME + 'LabelsDropdown').html(
      '
' +
      '
' + Locale.tr('Edit Labels') + '
' +
      Tree.html(LabelsUtils.makeTree(labels), false) +
      '
' +
        '<input type="text" class="newLabelInput" placeholder="' + Locale.tr("Add Label") + '"/>' +
      '
' +
      '
');

    recountLabels();

    // Check label & Update Templates
    $('#' + TAB_NAME + 'LabelsDropdown').off('click');
    $('#' + TAB_NAME + 'LabelsDropdown').on('click', '.labelsCheckbox', function() {
      var action;
      if ($(this).hasClass('fa-square-o')) {
        action = 'add';
        $(this).removeClass('fa-square-o').addClass('fa-check-square-o');
      } else {
        action = 'remove';
        $(this).removeClass('fa-check-square-o fa-minus-square-o').addClass('fa-square-o');
      }

      var labelName = $('.one-label', $(this).parent('li')).attr('one-label-full-name');
      var resourceId, aData, labelsArray, labelIndex;
      $('.check_item:checked', that.dataTable).each(function() {
        resourceId = $(this).val();
        aData = that.dataTable.fnGetData($(this).closest('tr'));
        labelsArray = aData[LABELS_COLUMN] != '' ? aData[LABELS_COLUMN].split(',') : [];
        labelIndex = $.inArray(labelName, labelsArray);

        if (action == 'add' && labelIndex == -1) {
          labelsArray.push(labelName)
          updateResouceLabels(resourceId, labelsArray);
        } else if (action == 'remove' && labelIndex != -1) {
          labelsArray.splice(labelIndex, 1);
          updateResouceLabels(resourceId, labelsArray);
        }
      });
    });

    // Capture the enter key
    $('#' + TAB_NAME + 'LabelsDropdown').off('keypress', '.newLabelInput');
    $('#' + TAB_NAME + 'LabelsDropdown').on('keypress', '.newLabelInput', function(e) {
      var ev = e || window.event;
      var key = ev.keyCode;

      if (key == 13 && !ev.altKey) {
        var labelName = $(this).val();
        var resourceId, aData, labelsArray, labelIndex;
        $('.check_item:checked', that.dataTable).each(function() {
          resourceId = $(this).val();
          aData = that.dataTable.fnGetData($(this).closest('tr'));
          labelsArray = aData[LABELS_COLUMN] != '' ? aData[LABELS_COLUMN].split(',') : [];
          labelIndex = $.inArray(labelName, labelsArray);
          if (labelIndex == -1) {
            labelsArray.push(labelName)
            that.labels.push(labelName)
            updateResouceLabels(resourceId, labelsArray);
          }
        });

        ev.preventDefault();
      }
    });

    function updateResouceLabels(resourceId, labelsArray) {
      var templateStr = LabelsUtils.LABELS_ATTR + '="' + labelsArray.join(',') + '"';

      OpenNebula[RESOURCE].append({
        timeout: true,
        data : {
            id: resourceId,
            extra_param: templateStr
        },
        success: function(request) {
          OpenNebula[RESOURCE].show({
            timeout: true,
            data : {
                id: resourceId
            },
            success: function(request, response) {
              that.updateElement(request, response);
              that.postUpdateView();
            },
            error: Notifier.onError
          });
        },
        error: Notifier.onError
      })
    }

    /*
      DataTable Checkbox Listener
     */
    that.dataTable.on('change', 'tbody .check_item', recountLabels);

    /*
      Update Dropdown with selected items
      [v] If all the selected items has a label
      [-] If any of the selected items has a label
      [ ] If no selected item has an existing label
     */
    function recountLabels() {
      // Generate Hash with labels and number of items
      var aData, labelsStr, labelsIndexed = {};
      var selectedItems = $('.check_item:checked', that.dataTable);
      selectedItems.each(function() {
        aData = that.dataTable.fnGetData($(this).closest('tr'));
        labelsStr = aData[LABELS_COLUMN];
        if (labelsStr != '') {
          $.each(labelsStr.split(','), function(){
            if (labelsIndexed[this]) {
              labelsIndexed[this] += 1
            } else {
              labelsIndexed[this] = 1
            }
          })
        }
      });

      // Reset label checkboxes
      $('.labelsCheckbox', labelsDropdown)
        .removeClass('fa-minus-square-o')
        .removeClass('fa-check-square-o')
        .addClass('fa-square-o');

      // Set checkboxes (check|minus) depending on the number of items
      var selectedItemsLength = selectedItems.length;
      var labelsCheckbox;
      var labelsDropdown = $('#' + TAB_NAME + 'LabelsDropdown');
      $.each(labelsIndexed, function(labelName, numberOfItems) {
        labelsCheckbox = $('.labelsCheckbox',
          $('[one-label-full-name="' + labelName + '"]', labelsDropdown).closest('li'));
        if (labelsCheckbox.length > 0) {
          if (numberOfItems == selectedItemsLength) {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-check-square-o');
          } else {
            $(labelsCheckbox[0])
              .removeClass('fa-square-o')
              .addClass('fa-minus-square-o');
          }
        }
      });
    }
  }

  function _setLabelsFilter(regExp) {
    this.dataTable.fnFilter(regExp, LABELS_COLUMN, true, false);
  }

  function _clearLabelsFilter() {
    this.dataTable.fnFilter('', LABELS_COLUMN, true, false);
  }
});
<|endoftext|>


<commit_before>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
// jshint esversion: 6

import Cart from './modules/cart';
import products from './modules/products';
import processPayment from './modules/payment';

(function() {
'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  let cart = new Cart();

  // Your custom JavaScript goes here
  document.addEventListener('DOMContentLoaded', e => {
    let dialog = document.querySelector('#dialog');
    document.querySelector('#close').addEventListener('click', e => {
      dialog.close();
    });

    if (location.pathname == '/cart.html') {
      let _cart = document.querySelector('#cart');
      let total = 0;
      for (let product of cart.cart) {
        let item = document.createElement('template');
        item.innerHTML = `

  ${product.title}
  ${product.quantity}
  $${product.price}

`;
        item.content.querySelector('.delete').addEventListener('click', e => {
          cart.remove(product);
          location.reload();
        });
        _cart.appendChild(item.content);

        total += product.total;
      }
      let item = document.createElement('template');
      item.innerHTML = `

  Total

  $${total}

`;
      _cart.appendChild(item.content);

      if (!window.PaymentRequest) {
        document.querySelector('#form').style = 'display:block;';
      }

      let checkout_form = document.querySelector('#checkout_form');

      checkout_form.addEventListener('submit', e => {
        e.preventDefault();

        var data = new FormData(e.target);

        if (!window.PaymentRequest) {
          fetch('/checkout', {
            method: 'POST',
            credentials: 'include',
            body: data
          }).then(result => {
            if (result.status === 200) {
              return result.json();
            } else {
              throw 'Payment failure';
            }
          }).then(result => {
            console.log('Payment response: ' + JSON.stringify(result));
            location.href = '/checkout.html';
          }).catch(e => {
            console.log('Payment failed due to exception: ' + e);
            dialog.showModal();
          });
          return;
        }

        processPayment(cart)
        .then(result => {
          location.href = '/checkout.html';
        }).catch(e => {
          // TODO: failure notice
          dialog.showModal();
        });
      });

    } else {
      let items = document.querySelector('#items');
      for (let product of products) {
        let item = document.createElement('template');
        item.innerHTML = `

${product.title}

    Enim labore aliqua consequat ut quis ad occaecat aliquip incididunt.

    Add to Cart

`;
        item.content.querySelector('.add-to-cart').addEventListener('click', e => {
          cart.add(product);
          dialog.showModal();
        });
        items.appendChild(item.content);
      }
    }
  });
})();
<commit_msg>Remove path prefixes from modules<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
// jshint esversion: 6

import Cart from 'cart';
import products from 'product';
import processPayment from 'payment';

(function() {
'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  let cart = new Cart();

  // Your custom JavaScript goes here
  document.addEventListener('DOMContentLoaded', e => {
    let dialog = document.querySelector('#dialog');
    document.querySelector('#close').addEventListener('click', e => {
      dialog.close();
    });

    if (location.pathname == '/cart.html') {
      let _cart = document.querySelector('#cart');
      let total = 0;
      for (let product of cart.cart) {
        let item = document.createElement('template');
        item.innerHTML = `

  ${product.title}
  ${product.quantity}
  $${product.price}

`;
        item.content.querySelector('.delete').addEventListener('click', e => {
          cart.remove(product);
          location.reload();
        });
        _cart.appendChild(item.content);

        total += product.total;
      }
      let item = document.createElement('template');
      item.innerHTML = `

  Total

  $${total}

`;
      _cart.appendChild(item.content);

      if (!window.PaymentRequest) {
        document.querySelector('#form').style = 'display:block;';
      }

      let checkout_form = document.querySelector('#checkout_form');

      checkout_form.addEventListener('submit', e => {
        e.preventDefault();

        var data = new FormData(e.target);

        if (!window.PaymentRequest) {
          fetch('/checkout', {
            method: 'POST',
            credentials: 'include',
            body: data
          }).then(result => {
            if (result.status === 200) {
              return result.json();
            } else {
              throw 'Payment failure';
            }
          }).then(result => {
            console.log('Payment response: ' + JSON.stringify(result));
            location.href = '/checkout.html';
          }).catch(e => {
            console.log('Payment failed due to exception: ' + e);
            dialog.showModal();
          });
          return;
        }

        processPayment(cart)
        .then(result => {
          location.href = '/checkout.html';
        }).catch(e => {
          // TODO: failure notice
          dialog.showModal();
        });
      });

    } else {
      let items = document.querySelector('#items');
      for (let product of products) {
        let item = document.createElement('template');
        item.innerHTML = `

${product.title}

    Enim labore aliqua consequat ut quis ad occaecat aliquip incididunt.

    Add to Cart

`;
        item.content.querySelector('.add-to-cart').addEventListener('click', e => {
          cart.add(product);
          dialog.showModal();
        });
        items.appendChild(item.content);
      }
    }
  });
})();
<|endoftext|>


<commit_before>
/*
  Controls for the sidebar, its icons, and click events.
*/

(function(){

    function updateSidebar () {
        $("#projects-list").empty();

        var indicatorColor = "";
        var indicatorStatus = "";
        var indicatorDisable = "";
        var title = "";
        //Create list of projects in sidebar
        for (var i = 0; i < scout.projects.length; i++) {
            var id = scout.projects[i].projectID;
            indicatorColor = "btn-info";
            indicatorStatus = "glyphicon-play";
            indicatorDisable = "";
            title = "";

            if (scout.projects[i].indicator == "stop") {
                indicatorColor = "btn-danger";
                indicatorStatus = "glyphicon-stop";
            } else if (scout.projects[i].indicator == "gray-play") {
                indicatorColor = "btn-info gray";
                indicatorStatus = "glyphicon-question-sign";
                indicatorDisable = "disable";
                title = scout.localize("MISSING_DATA");
            }

            var standardProject =
              '
' +
                '' +
                '' + scout.projects[i].projectName + '' +
                '<button class="btn ' + indicatorColor + '" ' + indicatorDisable + '>' +
                  '' +
                '</button>' +
              '
';

            $("#projects-list").append(standardProject);
        }

        //Register click events for sidebar buttons
        $("#projects-list div").click(function (evt) {
            evt.stopPropagation();
            $("#sidebar .active").removeClass('active');
            $(evt.currentTarget).addClass('active');
            var id = $(evt.currentTarget).data('id');
            for (var j = 0; j < scout.projects.length; j++) {
                if (id == scout.projects[j].projectID) {
                    scout.helpers.updateProjectSettingsView(scout.projects[j]);
                }
            }
        });

        $("#projects-list .btn .btn").click(function (evt) {
            evt.stopPropagation();
            //Make sure the button isn't disabled
            if (!$(evt.currentTarget).hasClass('gray')) {
                var id = $(evt.currentTarget).parent().data("id");
                //
                if ($(evt.currentTarget).children().hasClass('glyphicon-stop')) {
                    scout.helpers.stopWatching(id);
                } else if ($(evt.currentTarget).children().hasClass('glyphicon-play')) {
                    scout.helpers.startWatching(id);
                }
            }
        });
    }

    //Run once on start
    scout.helpers.updateSidebar = updateSidebar;

})();
<commit_msg>Correct comment<commit_after>
/*
  Controls for the sidebar, its icons, and click events.
*/

(function(){

    function updateSidebar () {
        $("#projects-list").empty();

        var indicatorColor = "";
        var indicatorStatus = "";
        var indicatorDisable = "";
        var title = "";
        //Create list of projects in sidebar
        for (var i = 0; i < scout.projects.length; i++) {
            var id = scout.projects[i].projectID;
            indicatorColor = "btn-info";
            indicatorStatus = "glyphicon-play";
            indicatorDisable = "";
            title = "";

            if (scout.projects[i].indicator == "stop") {
                indicatorColor = "btn-danger";
                indicatorStatus = "glyphicon-stop";
            } else if (scout.projects[i].indicator == "gray-play") {
                indicatorColor = "btn-info gray";
                indicatorStatus = "glyphicon-question-sign";
                indicatorDisable = "disable";
                title = scout.localize("MISSING_DATA");
            }

            var standardProject =
              '
' +
                '' +
                '' + scout.projects[i].projectName + '' +
                '<button class="btn ' + indicatorColor + '" ' + indicatorDisable + '>' +
                  '' +
                '</button>' +
              '
';

            $("#projects-list").append(standardProject);
        }

        //Register click events for sidebar buttons
        $("#projects-list div").click(function (evt) {
            evt.stopPropagation();
            $("#sidebar .active").removeClass('active');
            $(evt.currentTarget).addClass('active');
            var id = $(evt.currentTarget).data('id');
            for (var j = 0; j < scout.projects.length; j++) {
                if (id == scout.projects[j].projectID) {
                    scout.helpers.updateProjectSettingsView(scout.projects[j]);
                }
            }
        });

        $("#projects-list .btn .btn").click(function (evt) {
            evt.stopPropagation();
            //Make sure the button isn't disabled
            if (!$(evt.currentTarget).hasClass('gray')) {
                var id = $(evt.currentTarget).parent().data("id");
                //
                if ($(evt.currentTarget).children().hasClass('glyphicon-stop')) {
                    scout.helpers.stopWatching(id);
                } else if ($(evt.currentTarget).children().hasClass('glyphicon-play')) {
                    scout.helpers.startWatching(id);
                }
            }
        });
    }

    //Empties the sidebar of projects
    //loops through the scout.projects object to recreate the sidebar
    scout.helpers.updateSidebar = updateSidebar;

})();
<|endoftext|>


<commit_before>/*!
  * =============================================================
  * Ender: open module JavaScript framework (https://ender.no.de)
  * Build: ender build nut
  * =============================================================
  */

/*!
  * Ender: open module JavaScript framework (client-lib)
  * copyright Dustin Diaz & Jacob Thornton 2011 (@ded @fat)
  * http://ender.no.de
  * License MIT
  */
!function (context) {

  // a global object for node.js module compatiblity
  // ============================================

  context['global'] = context

  // Implements simple module system
  // losely based on CommonJS Modules spec v1.1.1
  // ============================================

  var modules = {}
    , old = context.$

  function require (identifier) {
    // modules can be required from ender's build system, or found on the window
    var module = modules[identifier] || window[identifier]
    if (!module) throw new Error("Requested module '" + identifier + "' has not been defined.")
    return module
  }

  function provide (name, what) {
    return (modules[name] = what)
  }

  context['provide'] = provide
  context['require'] = require

  function aug(o, o2) {
    for (var k in o2) k != 'noConflict' && k != '_VERSION' && (o[k] = o2[k])
    return o
  }

  function boosh(s, r, els) {
    // string || node || nodelist || window
    if (typeof s == 'string' || s.nodeName || (s.length && 'item' in s) || s == window) {
      els = ender._select(s, r)
      els.selector = s
    } else els = isFinite(s.length) ? s : [s]
    return aug(els, boosh)
  }

  function ender(s, r) {
    return boosh(s, r)
  }

  aug(ender, {
      _VERSION: '0.3.6'
    , fn: boosh // for easy compat to jQuery plugins
    , ender: function (o, chain) {
        aug(chain ? boosh : ender, o)
      }
    , _select: function (s, r) {
        return (r || document).querySelectorAll(s)
      }
  })

  aug(boosh, {
    forEach: function (fn, scope, i) {
      // opt out of native forEach so we can intentionally call our own scope
      // defaulting to the current item and be able to return self
      for (i = 0, l = this.length; i < l; ++i) i in this && fn.call(scope || this[i], this[i], i, this)
      // return self for chaining
      return this
    },
    $: ender // handy reference to self
  })

  ender.noConflict = function () {
    context.$ = old
    return this
  }

  if (typeof module !== 'undefined' && module.exports) module.exports = ender
  // use subscript notation as extern for Closure compilation
  context['ender'] = context['$'] = context['ender'] || ender

}(this);

!function () {

  var module = { exports: {} }, exports = module.exports;

  /*
      nut, the concise CSS selector engine

      Version     : 0.1.18
      Author      : Aurélien Delogu (dev@dreamysource.fr)
      Homepage    : https://github.com/pyrsmk/nut
      License     : MIT
  */

  (function(def){
      if(typeof module!='undefined'){
          module.exports=def;
      }
      else{
          this.nut=def;
      }
  }(function(){

      var doc=document,
          firstChild='firstChild',
          nextSibling='nextSibling',
          getElementsByClassName='getElementsByClassName',
          length='length',

      /*
          Get all nodes

          Parameters
              string selector : a selector
              context         : a context

          Return
              object          : nodes
      */
      getAllNodes=function(selector,context){
          var node=context[firstChild],
              nodes=[];
          // Reduce
          if(node){
              do{
                  if(node.nodeType==1){
                      nodes.push(node);
                  }
              }
              while(node=node[nextSibling]);
          }
          return nodes;
      },

      /*
          Get id node

          Parameters
              string selector : a selector
              context         : a context

          Return
              object          : nodes
      */
      getNodesFromIdSelector=function(selector,context){
          var node=doc.getElementById(selector);
          if(!node){
              return [];
          }
          else{
              return [node];
          }
      },

      /*
          Get nodes corresponding to a class name (for IE<9)

          Parameters
              string name     : class name
              object context  : contextual node

          Return
              array           : found nodes
      */
      getNodesByClassName=function(name,context){
          // Init vars
          var node=context[firstChild],
              nodes=[],
              elements;
          // Browse children
          if(node){
              do{
                  if(node.nodeType==1){
                      // Match the class
                      if(node.className && node.className.match('\\b'+name+'\\b')){
                          nodes.push(node);
                      }
                      // Get nodes from node's children
                      if((elements=getNodesByClassName(name,node))[length]){
                          nodes=nodes.concat(elements);
                      }
                  }
              }
              while(node=node[nextSibling]);
          }
          return nodes;
      },

      /*
          Get nodes from a class selector

          Parameters
              string selector : a selector
              context         : a context

          Return
              object          : nodes
      */
      getNodesFromClassSelector=function(selector,context){
          if(context[getElementsByClassName]){
              return context[getElementsByClassName](selector);
          }
          else{
              return getNodesByClassName(selector,context);
          }
      },

      /*
          Get nodes from a tag selector

          Parameters
              string selector : a selector
              context         : a context

          Return
              object          : nodes
      */
      getNodesFromTagSelector=function(selector,context){
          return context.getElementsByTagName(selector);
      };

      /*
          Select DOM nodes

          Parameters
              string selectors        : CSS selectors
              array, object contexts  : contextual nodes

          Return
              array                   : found nodes
      */
      return function(selectors,contexts){
          // Format contexts
          if(!contexts){
              contexts=[doc];
          }
          else if(!contexts.pop){
              contexts=[contexts];
          }
          // Init vars
          var context,
              local_contexts,
              future_local_contexts,
              selector,
              elements,
              nodes=[],
              i=-1,
              j,k,l,m,n,o,
              getNodesFromSelector;
          // Prepare selectors
          selectors=selectors.split(',');
          n=-1;
          while(selector=selectors[++n]){
              selectors[n]=selector.split(/\s+/);
          }
          // Evaluate selectors for each global context
          while(context=contexts[++i]){
              j=selectors[length];
              while(j){
                  // Init local context
                  local_contexts=[context];
                  // Evaluate selectors
                  k=-1;
                  l=selectors[--j][length];
                  while(++k<l){
                      // Drop empty selectors
                      if(selector=selectors[j][k]){
                          // Id
                          if(selector.charAt(0)=='#'){
                              selector=selector.substr(1);
                              getNodesFromSelector=getNodesFromIdSelector;
                          }
                          // Class
                          else if(selector.charAt(0)=='.'){
                              selector=selector.substr(1);
                              getNodesFromSelector=getNodesFromClassSelector;
                          }
                          // Joker
                          else if(selector=='*'){
                              getNodesFromSelector=getAllNodes;
                          }
                          // Tag
                          else{
                              getNodesFromSelector=getNodesFromTagSelector;
                          }
                          // Evaluate current selector for each local context
                          future_local_contexts=[];
                          m=local_contexts[length];
                          while(m){
                              elements=getNodesFromSelector(selector,local_contexts[--m]);
                              n=-1;
                              o=elements[length];
                              while(++n<o){
                                  future_local_contexts.push(elements[n]);
                              }
                          }
                          // Set new local contexts
                          local_contexts=future_local_contexts;
                      }
                  }
                  // Append new nodes
                  nodes=nodes.concat(local_contexts);
              }
          }
          return nodes;
      };

  }()));

  provide("nut", module.exports);

  // inspired from https://github.com/ded/qwery/blob/master/src/ender.js

  $._select=function(selectors,contexts){
      // Nodes
      if(typeof selectors!='string'){
          return selectors;
      }
      // New element
      else if(selectors.match(/^\s*</)){
          var tag=selectors.match(/^\s*<\s*([a-z]+)/i)[1],
              table='table',
              nodeMap={
                  thead:      table,
                  tbody:      table,
                  tfoot:      table,
                  tr:         'tbody',
                  th:         'tr',
                  td:         'tr',
                  fieldset:   'form',
                  option:     'select'
              },
              root=document.createElement(nodeMap[tag] || 'div'),
              element,
              elements=[],
              i=-1;
          root.innerHTML=selectors;
          element=root.firstChild;
          do{
              element.nodeType==1 && elements.push(element);
          }
          while(element=element.nextSibling)
          return elements;
      }
      // Selectors
      else{
          return require('nut')(selectors,contexts);
      }
  };

}();<commit_msg>Update unit's ender file<commit_after>/*!
  * =============================================================
  * Ender: open module JavaScript framework (https://ender.no.de)
  * Build: ender build nut
  * =============================================================
  */

/*!
  * Ender: open module JavaScript framework (client-lib)
  * copyright Dustin Diaz & Jacob Thornton 2011-2012 (@ded @fat)
  * http://ender.jit.su
  * License MIT
  */
(function (context) {

  // a global object for node.js module compatiblity
  // ============================================

  context['global'] = context

  // Implements simple module system
  // losely based on CommonJS Modules spec v1.1.1
  // ============================================

  var modules = {}
    , old = context['$']
    , oldEnder = context['ender']
    , oldRequire = context['require']
    , oldProvide = context['provide']

  function require (identifier) {
    // modules can be required from ender's build system, or found on the window
    var module = modules['$' + identifier] || window[identifier]
    if (!module) throw new Error("Ender Error: Requested module '" + identifier + "' has not been defined.")
    return module
  }

  function provide (name, what) {
    return (modules['$' + name] = what)
  }

  context['provide'] = provide
  context['require'] = require

  function aug(o, o2) {
    for (var k in o2) k != 'noConflict' && k != '_VERSION' && (o[k] = o2[k])
    return o
  }

  /**
   * main Ender return object
   * @constructor
   * @param {Array|Node|string} s a CSS selector or DOM node(s)
   * @param {Array.|Node} r a root node(s)
   */
  function Ender(s, r) {
    var elements
      , i

    this.selector = s
    // string || node || nodelist || window
    if (typeof s == 'undefined') {
      elements = []
      this.selector = ''
    } else if (typeof s == 'string' || s.nodeName || (s.length && 'item' in s) || s == window) {
      elements = ender._select(s, r)
    } else {
      elements = isFinite(s.length) ? s : [s]
    }
    this.length = elements.length
    for (i = this.length; i--;) this[i] = elements[i]
  }

  /**
   * @param {function(el, i, inst)} fn
   * @param {Object} opt_scope
   * @returns {Ender}
   */
  Ender.prototype['forEach'] = function (fn, opt_scope) {
    var i, l
    // opt out of native forEach so we can intentionally call our own scope
    // defaulting to the current item and be able to return self
    for (i = 0, l = this.length; i < l; ++i) i in this && fn.call(opt_scope || this[i], this[i], i, this)
    // return self for chaining
    return this
  }

  Ender.prototype.$ = ender // handy reference to self

  function ender(s, r) {
    return new Ender(s, r)
  }

  ender['_VERSION'] = '0.4.3-dev'

  ender.fn = Ender.prototype // for easy compat to jQuery plugins

  ender.ender = function (o, chain) {
    aug(chain ? Ender.prototype : ender, o)
  }

  ender._select = function (s, r) {
    if (typeof s == 'string') return (r || document).querySelectorAll(s)
    if (s.nodeName) return [s]
    return s
  }

  // use callback to receive Ender's require & provide and remove them from global
  ender.noConflict = function (callback) {
    context['$'] = old
    if (callback) {
      context['provide'] = oldProvide
      context['require'] = oldRequire
      context['ender'] = oldEnder
      if (typeof callback == 'function') callback(require, provide, this)
    }
    return this
  }

  if (typeof module !== 'undefined' && module.exports) module.exports = ender
  // use subscript notation as extern for Closure compilation
  context['ender'] = context['$'] = ender

}(this));

<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom';
import ShInputText from '../bin/sh-input-text'

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: {
        one: 'Hamster',
        two: '',
        three: ''
      }
    };
    this.handleOneChange = this.handleOneChange.bind(this);
    this.handleTwoChange = this.handleTwoChange.bind(this);
    this.handleThreeChange = this.handleThreeChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleOneChange(event) {
    this.state.formData.one = event.target.value;
    this.setState(this.state);
  }

  handleTwoChange(event) {
    this.state.formData.two = event.target.value;
    this.setState(this.state);
  }

  handleThreeChange(event) {
    this.state.formData.three = event.target.value;
    this.setState(this.state);
  }

  handleSubmit() {
    alert(this.state.formData.one + ' ' + this.state.formData.two + ' ' + this.state.formData.three);
    return false;
  }

  render() {
    return

      <form name="test" onSubmit={this.handleSubmit}>
        <ShInputText label="Example Pre Filled Data" value={this.state.formData.one} onChange={this.handleOneChange}></ShInputText>
        <ShInputText label="Example With Required Field" value="" onChange={this.handleTwoChange} required></ShInputText>
        <ShInputText label="Example Text Three" value="" onChange={this.handleThreeChange}></ShInputText>
        <button type="submit">go</button>
      </form>

  }
}

ReactDOM.render(<App/>, document.getElementById('app'));<commit_msg>fix example<commit_after>import React from 'react'
import ReactDOM from 'react-dom';
import ShInputText from '../bin/sh-input-text';
import ShForm from 'sh-form';
import ShSelect from 'sh-input-select';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            formData: {
                one: 'Pre filled Text',
                two: '',
                three: ''
            }
        };
        this.handleOneChange = this.handleOneChange.bind(this);
        this.handleTwoChange = this.handleTwoChange.bind(this);
        this.handleThreeChange = this.handleThreeChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleOneChange(event) {
        this.state.formData.one = event.target.value;
        this.setState(this.state);
    }

    handleTwoChange(event) {
        this.state.formData.two = event.target.value;
        this.setState(this.state);
    }

    handleThreeChange(event) {
        this.state.formData.three = event.target.value;
        this.setState(this.state);
    }

    handleSubmit() {
        alert(this.state.formData.one + ' ' + this.state.formData.two + ' ' + this.state.formData.three);
        return false;
    }

    render() {
        return

            <ShForm name="test" onSubmit={this.handleSubmit}>
                <ShInputText label="Example With Required Field" value={this.state.formData.one} onChange={this.handleOneChange} />
                <ShInputText label="Example With Required Field" value="" onChange={this.handleTwoChange} required />
                <ShInputText label="Example Text Three" className="spam" value="" onChange={this.handleThreeChange} />
                <button type="submit">go</button>
            </ShForm>

    }
}

ReactDOM.render(<App/>, document.getElementById('app'));<|endoftext|>


<commit_before>var number_to_dial = "123456790" // CHANGE THIS
// open a single window
var window = Ti.UI.createWindow({
	backgroundColor:'white'
});
var but = Ti.UI.createButton({
    title: "Dial Static Number";
});
but.addEventListener("click", function () {
    Ti.Platform.openURL('tel:' + number_to_dial);
    if	(Titanium.Platform.name == 'iPhone OS' && parseInt(Titanium.Platform.version.split(".")[0], 10) >=4) {
        Ti.App.iOS.registerBackgroundService({
            url:'bg.js'
        });
    }
});
window.add(but);
window.open();<commit_msg>Fix semicolon<commit_after>var number_to_dial = "123456790" // CHANGE THIS
// open a single window
var window = Ti.UI.createWindow({
	backgroundColor:'white'
});
var but = Ti.UI.createButton({
    title: "Dial Static Number"
});
but.addEventListener("click", function () {
    Ti.Platform.openURL('tel:' + number_to_dial);
    if	(Titanium.Platform.name == 'iPhone OS' && parseInt(Titanium.Platform.version.split(".")[0], 10) >=4) {
        Ti.App.iOS.registerBackgroundService({
            url:'bg.js'
        });
    }
});
window.add(but);
window.open();
<|endoftext|>


<commit_before><commit_msg>Force get push<commit_after><|endoftext|>