<commit_before>import test from './helpers'
import chan from '../src'

test.timeout(1000)

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync is false when non-buffered chan has no outstanding receives`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync is true when buffered chan's buffer is not full, and becomes false when it ` +
     `gets full`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.canSendSync == true)
  await ch.send('x')
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync on a buffered chan becomes false only when both buffered values and the ones ` +
     `from outstanding sends get consumed`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  ch.take()
  ch.take()
  await t.nextTick()
  t.ok(ch.canSendSync == true)
  await ch.send('x')
  t.ok(ch.canSendSync == true)
  await ch.send('y')
  t.ok(ch.canSendSync == true)
  await ch.send('y')
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) sends value to a waiting consumer and returns true`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  let pRecv = ch.take()
  await t.nextTick()
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.canSendSync == false)
  t.is('x', await pRecv)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) buffers value and returns true`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.canSendSync == false)
  t.is('x', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be used with #takeSync()`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.takeSync() == true)
  t.ok(ch.value == 'x')
  t.ok(ch.takeSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false and doesn't perform the send when it cannot do it ` +
     `synchronously`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch1 = chan()

  t.ok(ch1.sendSync('x') == false)
  t.ok(ch1.canTakeSync == false)
  t.ok(ch1.takeSync() == false)

  let ch2 = chan(1)

  ch2.sendSync('a')
  t.ok(ch2.sendSync('b') == false)

  t.ok(ch2.takeSync() == true && ch2.value == 'a')
  t.ok(ch2.takeSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false when called on a closed chan`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  ch.closeNow()
  t.ok(ch.sendSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false when called on a closing chan`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  await ch.send('x')
  ch.close()
  t.ok(ch.sendSync() == false)
  t.is('x', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\//
////////////////////////////////////////////////////////////////////////////////////////////////////

function sendSync(ch, t, values) {
  while (values.length) {
    let value = values.shift()
    if (!ch.sendSync(value)) {
      return t.fail(`failed to send value: ${value}`)
    }
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fill the buffer`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(3)
  sendSync(ch, t, [ 'a', 'b', 'c' ])
  t.ok(ch.canSendSync == false)
  t.is('a', await ch.take())
  t.is('b', await ch.take())
  t.is('c', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fullfill all outstanding receives`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  let recv = ''

  ch.take().then(v => recv += v).catch(t.fail)
  ch.take().then(v => recv += v).catch(t.fail)

  await t.nextTick()

  sendSync(ch, t, [ 'a', 'b' ])
  t.ok(ch.canSendSync == false)

  await t.nextTick()
  t.is('ab', recv)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fullfill all outstanding receives, and ` +
     `then fill the buffer`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(2)
  let recv = ''

  ch.take().then(v => recv += v).catch(t.fail)
  ch.take().then(v => recv += v).catch(t.fail)

  await t.nextTick()

  sendSync(ch, t, [ 'a', 'b', 'c', 'd' ])
  t.ok(ch.canSendSync == false)

  await t.nextTick()
  t.is('ab', recv)

  t.is('c', await ch.take())
  t.is('d', await ch.take())
})
<commit_msg>Add one more test for #sendSync()<commit_after>import test from './helpers'
import chan from '../src'

test.timeout(1000)

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync is false when non-buffered chan has no outstanding receives`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync is true when buffered chan's buffer is not full, and becomes false when it ` +
     `gets full`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.canSendSync == true)
  await ch.send('x')
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#canSendSync on a buffered chan becomes false only when both buffered values and the ones ` +
     `from outstanding sends get consumed`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  ch.take()
  ch.take()
  await t.nextTick()
  t.ok(ch.canSendSync == true)
  await ch.send('x')
  t.ok(ch.canSendSync == true)
  await ch.send('y')
  t.ok(ch.canSendSync == true)
  await ch.send('y')
  t.ok(ch.canSendSync == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) sends value to a waiting consumer and returns true`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  let pRecv = ch.take()
  await t.nextTick()
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.canSendSync == false)
  t.is('x', await pRecv)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) doesn't update #value property of a chan`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.sendSync('y') == true)
  t.ok(undefined === ch.value)
  await t.nextTurn()
  t.ok(undefined === ch.value)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) buffers value and returns true`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.canSendSync == false)
  t.is('x', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be used with #takeSync()`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  t.ok(ch.sendSync('x') == true)
  t.ok(ch.takeSync() == true)
  t.ok(ch.value == 'x')
  t.ok(ch.takeSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false and doesn't perform the send when it cannot do it ` +
     `synchronously`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch1 = chan()

  t.ok(ch1.sendSync('x') == false)
  t.ok(ch1.canTakeSync == false)
  t.ok(ch1.takeSync() == false)

  let ch2 = chan(1)

  ch2.sendSync('a')
  t.ok(ch2.sendSync('b') == false)

  t.ok(ch2.takeSync() == true && ch2.value == 'a')
  t.ok(ch2.takeSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false when called on a closed chan`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  ch.closeNow()
  t.ok(ch.sendSync() == false)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) returns false when called on a closing chan`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(1)
  await ch.send('x')
  ch.close()
  t.ok(ch.sendSync() == false)
  t.is('x', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\//
////////////////////////////////////////////////////////////////////////////////////////////////////

function sendSync(ch, t, values) {
  while (values.length) {
    let value = values.shift()
    if (!ch.sendSync(value)) {
      return t.fail(`failed to send value: ${value}`)
    }
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fill the buffer`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(3)
  sendSync(ch, t, [ 'a', 'b', 'c' ])
  t.ok(ch.canSendSync == false)
  t.is('a', await ch.take())
  t.is('b', await ch.take())
  t.is('c', await ch.take())
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fullfill all outstanding receives`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan()
  let recv = ''

  ch.take().then(v => recv += v).catch(t.fail)
  ch.take().then(v => recv += v).catch(t.fail)

  await t.nextTick()

  sendSync(ch, t, [ 'a', 'b' ])
  t.ok(ch.canSendSync == false)

  await t.nextTick()
  t.is('ab', recv)
})

////////////////////////////////////////////////////////////////////////////////////////////////////
test(`#sendSync(value) can be called in a loop to fullfill all outstanding receives, and ` +
     `then fill the buffer`, async t => {
////////////////////////////////////////////////////////////////////////////////////////////////////
  let ch = chan(2)
  let recv = ''

  ch.take().then(v => recv += v).catch(t.fail)
  ch.take().then(v => recv += v).catch(t.fail)

  await t.nextTick()

  sendSync(ch, t, [ 'a', 'b', 'c', 'd' ])
  t.ok(ch.canSendSync == false)

  await t.nextTick()
  t.is('ab', recv)

  t.is('c', await ch.take())
  t.is('d', await ch.take())
})
<|endoftext|>


<commit_before>$(function() {
    $('select#category_id').selectize();
    $('select#page_id').selectize();
    $('select#target').selectize();
    if ($('#tags').length) {
        axios
            .get('/api/tags-list')
            .then(function(response) {
                var tags = response.data.map(function(x) {
                    return { item: x.tag };
                });
                var oldTags = $('#tags')
                    .val()
                    .split(',');
                for (var i = oldTags.length - 1; i >= 0; i--) {
                    if (oldTags[i] !== '') {
                        tags.push({ item: oldTags[i] });
                    }
                }
                $('#tags').selectize({
                    persist: false,
                    create: true,
                    options: tags,
                    searchField: 'item',
                    labelField: 'item',
                    valueField: 'item',
                    createOnBlur: true,
                });
            })
            .catch(function() {
                alertify.error('An error occurred while getting tags.');
            });
    }
});
<commit_msg>docblock removed<commit_after>$(function() {
    $('select#category_id').selectize();
    $('select#page_id').selectize();
    $('select#target').selectize();

    /**
     * Selectize for tags
     */
    if ($('#tags').length) {
        axios
            .get('/api/tags-list')
            .then(function(response) {
                var tags = response.data.map(function(x) {
                    return { item: x.tag };
                });
                var oldTags = $('#tags')
                    .val()
                    .split(',');
                for (var i = oldTags.length - 1; i >= 0; i--) {
                    if (oldTags[i] !== '') {
                        tags.push({ item: oldTags[i] });
                    }
                }
                $('#tags').selectize({
                    persist: false,
                    create: true,
                    options: tags,
                    searchField: 'item',
                    labelField: 'item',
                    valueField: 'item',
                    createOnBlur: true,
                });
            })
            .catch(function() {
                alertify.error('An error occurred while getting tags.');
            });
    }
});
<|endoftext|>


<commit_before>/**
	_moon.ContextualPopup_ is a popup window control with Moonstone visual styling
	applied.  It extends [enyo.Popup](#enyo.Popup) and is designed to be used with
	[moon.ContextualPopupDecorator](#moon.ContextualPopupDecorator).
*/
enyo.kind({
	name: "moon.ContextualPopup",
	kind: "enyo.Popup",
	//* @protected
	layoutKind: "ContextualLayout",
	classes: "moon-body-text moon-contextual-popup",
	handlers: {
		onRequestShowPopup: "requestShow",
		onRequestHidePopup: "requestHide",
		onActivate: "decorateActivateEvent",
		onSpotlightUp: "spotlightUp",
		onSpotlightDown: "spotlightDown",
		onSpotlightLeft: "spotlightLeft",
		onSpotlightRight: "spotlightRight",
		onSpotlightSelect: "spotSelect",
		onRequestScrollIntoView: "_preventEventBubble"
	},
	//* @public
	published: {
		/**
			When true, spotlight cannot leave the constraints of the _moon.Popup_
			unless it is explicitly closed.
		*/
		spotlightModal: false,
		/**
			When false, _closeButton_ is hidden; when true, it is shown. When
			_showCloseButton_ is set to "auto" (the default), _closeButton_ is shown
			when _spotlightModal_ is true.
		*/
		showCloseButton: "auto"
	},
	//* @protected
	spotlight: "container",
	_spotlight: null,
	floating:true,
	/**
		Determines whether a scrim will appear when the popup is modal.
		Note that modal scrims are transparent, so you won't see them.
	*/
	scrimWhenModal: true,
	// Layout parameters

	//* Vertical flush layout margin
	vertFlushMargin:0,
	//* Horizontal flush layout margin
	horizFlushMargin:0,
	//* Popups wider than this value are considered wide (for layout purposes)
	widePopup: 200,
	//* Popups longer than this value are considered long (for layout purposes)
	longPopup: 200,
	//* Do not allow horizontal flush popups past spec'd amount of buffer space on left/right screen edge
	horizBuffer: 16,
	activator: null,
	tools: [
		{name: "client", classes: "moon-neutral moon-contextual-popup-client"},
		{name: "closeButton", kind: "moon.IconButton", icon: "closex", classes: "moon-popup-close", ontap: "closePopup", spotlight: false}
	],
	//* Creates chrome.
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
	},
	//* Renders the contextual popup.
	render: function() {
		this.allowHtmlChanged();
		this.contentChanged();
		this.inherited(arguments);
		this._spotlight = this.spotlight;
	},
	//* Performs control-specific tasks before/after showing _moon.ContextualPopup_.
	requestShow: function(inSender, inEvent) {
		var n = inEvent.activator.hasNode();
		this.activator = inEvent.activator;
		this.spotlight = this._spotlight;
		if (n) {
			this.activatorOffset = this.getPageOffset(n);
		}
		this.show();
		this.configCloseButton();
		this.configSpotlightBehavior(true);
		return true;
	},
	decorateActivateEvent: function(inSender, inEvent) {
		inEvent.sentFromPopup = this;
	},
	getPageOffset: function(inNode) {
		// getBoundingClientRect returns top/left values which are relative to the viewport and not absolute
		var r = inNode.getBoundingClientRect();

		var pageYOffset = (window.pageYOffset === undefined) ? document.documentElement.scrollTop : window.pageYOffset;
		var pageXOffset = (window.pageXOffset === undefined) ? document.documentElement.scrollLeft : window.pageXOffset;
		var rHeight = (r.height === undefined) ? (r.bottom - r.top) : r.height;
		var rWidth = (r.width === undefined) ? (r.right - r.left) : r.width;

		return {top: r.top + pageYOffset, left: r.left + pageXOffset, height: rHeight, width: rWidth};
	},
	//* Dismisses popup if Escape keypress is detected
	keydown: function(inSender, inEvent) {
		if (this.showing && this.autoDismiss && inEvent.keyCode == 27 /* escape */) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	//* If _this.downEvent_ is set to a spotlight event, skips normal popup
	//* _tap()_ code.
	tap: function(inSender, inEvent) {
		if (this.downEvent.type !== "onSpotlightSelect") {
			return this.inherited(arguments);
		}
	},
	closePopup: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.activator);
		this.$.closeButton.removeClass("pressed");
		this.hide();
	},
	//* Determines whether to display _closeButton_.
	configCloseButton: function() {
		if (this.showCloseButton === true || (this.spotlightModal && this.showCloseButton !== false)) {
			this.activator.keepOpen = true;
			this.$.closeButton.show();
			this.$.closeButton.spotlight = true;
			this.addClass("reserve-close");
		} else {
			this.$.closeButton.hide();
			this.$.closeButton.spotlight = false;
			this.removeClass("reserve-close");
		}
	},
	contentChanged: function() {
		this.$.client.setContent(this.content);
	},
	allowHtmlChanged: function() {
		this.$.client.setAllowHtml(this.allowHtml);
	},
	//* Spotlights the first spottable control, if possible.
	configSpotlightBehavior: function(spotChild) {
		if (enyo.Spotlight.getChildren(this).length > 0) {
			if (spotChild) {
				enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this));
			}
		} else if (!this.spotlightModal) {
			this.activator.keepOpen = false;
			this.spotlight = false;
		}
	},
	//* Called when _this.spotlight_ changes.
	spotlightChanged: function() {
		this._spotlight = this.spotlight;
		this.configSpotlightBehavior(false);
	},
	//* Called when _this.spotlightModal_ changes.
	spotlightModalChanged: function() {
		this.configCloseButton();
	},
	//* Called when _this.showCloseButton_ changes.
	showCloseButtonChanged: function() {
		this.configCloseButton();
	},
	spotSelect: function(inSender, inEvent) {
		this.downEvent = inEvent;
	},
	//* Checks whether to allow spotlight to move in a given direction.
	spotChecker: function(inDirection) {
		var neighbor = enyo.Spotlight.NearestNeighbor.getNearestNeighbor(inDirection);
		if (!enyo.Spotlight.Util.isChild(this, neighbor)) {
			if (this.spotlightModal) {
				return true;
			} else {
				enyo.Spotlight.spot(this.activator);
				this.hide();
			}
		}
	},
	/**
		When spotlight reaches top edge of popup, prevents user from
		continuing further.
	*/
	spotlightUp: function(inSender, inEvent) {
		return this.spotChecker("UP");
	},
	/**
		When spotlight reaches bottom edge of popup, prevents user from
		continuing further.
	*/
	spotlightDown: function(inSender, inEvent) {
		return this.spotChecker("DOWN");
	},
	/**
		When spotlight reaches left edge of popup, prevents user from
		continuing further.
	*/
	spotlightLeft: function(inSender, inEvent) {
		return this.spotChecker("LEFT");
	},
	/**
		When spotlight reaches right edge of popup, prevents user from
		continuing further.
	*/
	spotlightRight: function(inSender, inEvent) {
		return this.spotChecker("RIGHT");
	},
	_preventEventBubble: function(inSender, inEvent) {
		return true;
	},
	showHideScrim: function(inShow) {
		if (this.floating && (this.scrim || (this.modal && this.scrimWhenModal))) {
			var scrim = this.getScrim();
			if (inShow && this.modal && this.scrimWhenModal) {
				// move scrim to just under the popup to obscure rest of screen
				var i = this.getScrimZIndex();
				this._scrimZ = i;
				scrim.showAtZIndex(i);
			} else {
				scrim.hideAtZIndex(this._scrimZ);
			}
			enyo.call(scrim, "addRemoveClass", [this.scrimClassName, scrim.showing]);
		}
	},
	getScrimZIndex: function() {
		// Position scrim directly below popup
		return this.findZIndex()-1;
	},
	getScrim: function() {
		// show a transparent scrim for modal popups if scrimWhenModal is true
		// if scrim is true, then show a regular scrim.
		if (this.modal && this.scrimWhenModal) {
			return moon.scrimTransparent.make();
		}
		return moon.scrim.make();
	},
	findZIndex: function() {
		// a default z value
		var z = this.defaultZ;
		if (this._zIndex) {
			z = this._zIndex;
		} else if (this.hasNode()) {
			// Re-use existing zIndex if it has one
			z = Number(enyo.dom.getComputedStyleValue(this.node, "z-index")) || z;
		}
		this._zIndex = z;
		return this._zIndex;
	},
	showingChanged: function() {
		this.inherited(arguments);
		this.showHideScrim(this.showing);
	}
});
<commit_msg>GF-45055: Capture onSpotlightKeyDown to set the downEvent checked in enyo.Popup's tap handler, which is added to the `eventsToCapture` whitelist sent by enyo.Popup in the enyo.dispatcher.capture API call.<commit_after>/**
	_moon.ContextualPopup_ is a popup window control with Moonstone visual styling
	applied.  It extends [enyo.Popup](#enyo.Popup) and is designed to be used with
	[moon.ContextualPopupDecorator](#moon.ContextualPopupDecorator).
*/
enyo.kind({
	name: "moon.ContextualPopup",
	kind: "enyo.Popup",
	//* @protected
	layoutKind: "ContextualLayout",
	classes: "moon-body-text moon-contextual-popup",
	handlers: {
		onRequestShowPopup: "requestShow",
		onRequestHidePopup: "requestHide",
		onActivate: "decorateActivateEvent",
		onSpotlightUp: "spotlightUp",
		onSpotlightDown: "spotlightDown",
		onSpotlightLeft: "spotlightLeft",
		onSpotlightRight: "spotlightRight",
		onSpotlightKeyDown: "spotKeyDown",
		onRequestScrollIntoView: "_preventEventBubble"
	},
	//* @public
	published: {
		/**
			When true, spotlight cannot leave the constraints of the _moon.Popup_
			unless it is explicitly closed.
		*/
		spotlightModal: false,
		/**
			When false, _closeButton_ is hidden; when true, it is shown. When
			_showCloseButton_ is set to "auto" (the default), _closeButton_ is shown
			when _spotlightModal_ is true.
		*/
		showCloseButton: "auto"
	},
	//* @protected
	spotlight: "container",
	_spotlight: null,
	floating:true,
	eventsToCapture: { down:1, tap:1, onSpotlightKeyDown:1 },
	/**
		Determines whether a scrim will appear when the popup is modal.
		Note that modal scrims are transparent, so you won't see them.
	*/
	scrimWhenModal: true,
	// Layout parameters

	//* Vertical flush layout margin
	vertFlushMargin:0,
	//* Horizontal flush layout margin
	horizFlushMargin:0,
	//* Popups wider than this value are considered wide (for layout purposes)
	widePopup: 200,
	//* Popups longer than this value are considered long (for layout purposes)
	longPopup: 200,
	//* Do not allow horizontal flush popups past spec'd amount of buffer space on left/right screen edge
	horizBuffer: 16,
	activator: null,
	tools: [
		{name: "client", classes: "moon-neutral moon-contextual-popup-client"},
		{name: "closeButton", kind: "moon.IconButton", icon: "closex", classes: "moon-popup-close", ontap: "closePopup", spotlight: false}
	],
	//* Creates chrome.
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
	},
	//* Renders the contextual popup.
	render: function() {
		this.allowHtmlChanged();
		this.contentChanged();
		this.inherited(arguments);
		this._spotlight = this.spotlight;
	},
	//* Performs control-specific tasks before/after showing _moon.ContextualPopup_.
	requestShow: function(inSender, inEvent) {
		var n = inEvent.activator.hasNode();
		this.activator = inEvent.activator;
		this.spotlight = this._spotlight;
		if (n) {
			this.activatorOffset = this.getPageOffset(n);
		}
		this.show();
		this.configCloseButton();
		this.configSpotlightBehavior(true);
		return true;
	},
	decorateActivateEvent: function(inSender, inEvent) {
		inEvent.sentFromPopup = this;
	},
	getPageOffset: function(inNode) {
		// getBoundingClientRect returns top/left values which are relative to the viewport and not absolute
		var r = inNode.getBoundingClientRect();

		var pageYOffset = (window.pageYOffset === undefined) ? document.documentElement.scrollTop : window.pageYOffset;
		var pageXOffset = (window.pageXOffset === undefined) ? document.documentElement.scrollLeft : window.pageXOffset;
		var rHeight = (r.height === undefined) ? (r.bottom - r.top) : r.height;
		var rWidth = (r.width === undefined) ? (r.right - r.left) : r.width;

		return {top: r.top + pageYOffset, left: r.left + pageXOffset, height: rHeight, width: rWidth};
	},
	//* Dismisses popup if Escape keypress is detected
	keydown: function(inSender, inEvent) {
		if (this.showing && this.autoDismiss && inEvent.keyCode == 27 /* escape */) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	closePopup: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.activator);
		this.$.closeButton.removeClass("pressed");
		this.hide();
	},
	//* Determines whether to display _closeButton_.
	configCloseButton: function() {
		if (this.showCloseButton === true || (this.spotlightModal && this.showCloseButton !== false)) {
			this.activator.keepOpen = true;
			this.$.closeButton.show();
			this.$.closeButton.spotlight = true;
			this.addClass("reserve-close");
		} else {
			this.$.closeButton.hide();
			this.$.closeButton.spotlight = false;
			this.removeClass("reserve-close");
		}
	},
	contentChanged: function() {
		this.$.client.setContent(this.content);
	},
	allowHtmlChanged: function() {
		this.$.client.setAllowHtml(this.allowHtml);
	},
	//* Spotlights the first spottable control, if possible.
	configSpotlightBehavior: function(spotChild) {
		if (enyo.Spotlight.getChildren(this).length > 0) {
			if (spotChild) {
				enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this));
			}
		} else if (!this.spotlightModal) {
			this.activator.keepOpen = false;
			this.spotlight = false;
		}
	},
	//* Called when _this.spotlight_ changes.
	spotlightChanged: function() {
		this._spotlight = this.spotlight;
		this.configSpotlightBehavior(false);
	},
	//* Called when _this.spotlightModal_ changes.
	spotlightModalChanged: function() {
		this.configCloseButton();
	},
	//* Called when _this.showCloseButton_ changes.
	showCloseButtonChanged: function() {
		this.configCloseButton();
	},
	spotKeyDown: function(inSender, inEvent) {
		if (!inEvent.dispatchTarget.isDescendantOf(this)) {
			if (inEvent.keyCode == 13) {
				this.downEvent = inEvent;
			}
			return true;
		}
	},
	//* Checks whether to allow spotlight to move in a given direction.
	spotChecker: function(inDirection) {
		var neighbor = enyo.Spotlight.NearestNeighbor.getNearestNeighbor(inDirection);
		if (!enyo.Spotlight.Util.isChild(this, neighbor)) {
			if (this.spotlightModal) {
				return true;
			} else {
				enyo.Spotlight.spot(this.activator);
				this.hide();
			}
		}
	},
	/**
		When spotlight reaches top edge of popup, prevents user from
		continuing further.
	*/
	spotlightUp: function(inSender, inEvent) {
		return this.spotChecker("UP");
	},
	/**
		When spotlight reaches bottom edge of popup, prevents user from
		continuing further.
	*/
	spotlightDown: function(inSender, inEvent) {
		return this.spotChecker("DOWN");
	},
	/**
		When spotlight reaches left edge of popup, prevents user from
		continuing further.
	*/
	spotlightLeft: function(inSender, inEvent) {
		return this.spotChecker("LEFT");
	},
	/**
		When spotlight reaches right edge of popup, prevents user from
		continuing further.
	*/
	spotlightRight: function(inSender, inEvent) {
		return this.spotChecker("RIGHT");
	},
	_preventEventBubble: function(inSender, inEvent) {
		return true;
	},
	showHideScrim: function(inShow) {
		if (this.floating && (this.scrim || (this.modal && this.scrimWhenModal))) {
			var scrim = this.getScrim();
			if (inShow && this.modal && this.scrimWhenModal) {
				// move scrim to just under the popup to obscure rest of screen
				var i = this.getScrimZIndex();
				this._scrimZ = i;
				scrim.showAtZIndex(i);
			} else {
				scrim.hideAtZIndex(this._scrimZ);
			}
			enyo.call(scrim, "addRemoveClass", [this.scrimClassName, scrim.showing]);
		}
	},
	getScrimZIndex: function() {
		// Position scrim directly below popup
		return this.findZIndex()-1;
	},
	getScrim: function() {
		// show a transparent scrim for modal popups if scrimWhenModal is true
		// if scrim is true, then show a regular scrim.
		if (this.modal && this.scrimWhenModal) {
			return moon.scrimTransparent.make();
		}
		return moon.scrim.make();
	},
	findZIndex: function() {
		// a default z value
		var z = this.defaultZ;
		if (this._zIndex) {
			z = this._zIndex;
		} else if (this.hasNode()) {
			// Re-use existing zIndex if it has one
			z = Number(enyo.dom.getComputedStyleValue(this.node, "z-index")) || z;
		}
		this._zIndex = z;
		return this._zIndex;
	},
	showingChanged: function() {
		this.inherited(arguments);
		this.showHideScrim(this.showing);
	}
});
<|endoftext|>


<commit_before>define(function(require, exports) {
  'use strict';

  var redis = require('../database/redis'),
      express = require('express'),
      router = express.Router();

  router.post('/:email', function (req, res) {
    var email = req.params.email,
        subscriber = req.body.subscriber;

    redis.addSubscriber(email, subscriber,
      function (err, result) {
      if (!!err) {
        res.status(500).json(null);
        return;
      }
      if(result !== 1) {
        res.status(409).json({
          message: 'Email ' + email + ' already exists in database.'
        });
        return;
      }
      res.status(201).json({
        email: email,
        subscriber: subscriber
      })
    });
  });

  router.delete('/:email', function (req, res) {
    var email = req.params.email;

    redis.deleteSubscriber(email, function (err, data) {
      if (!!err) { throw new Error(err); }
      res.json({});
    });
  });

  router.get('/:email', function(req, res) {
    var email = req.params.email;

    redis.getSubscriber(email, function (err, data) {
      if (!!err) { throw new Error(err); }
      data = !!data ? JSON.parse(data) : {};
      res.json(data);
    });
  });

  router.get('/', function(req, res) {
    redis.getAllSubscribers(function (err, data) {
      var result = [], i;
      if (!!err) { throw new Error(err); }

      for (i in data) {
        if (data.hasOwnProperty(i)) {
          result.push(JSON.parse(data[i]));
        }
      }
      res.json(result);
    });
  });

  exports.router = router;
});
<commit_msg>add status function<commit_after>define(function(require, exports) {
  'use strict';

  var redis = require('../database/redis'),
      express = require('express'),
      router = express.Router();

  var internal = function (err, result, res) {
    if (!!err) {
      res.status(500).json(null);
      return false;
    }
    return true;
  };

  router.post('/:email', function (req, res) {
    var email = req.params.email,
        subscriber = req.body.subscriber;

    redis.addSubscriber(email, subscriber,
      function (err, result) {

      var conflict = function (err, result, res) {
        if(result !== 1) {
          res.status(409).json({
            message: 'Email ' + email + ' already exists in database.'
          });
          return false;
        }
        return true;
      },
      created = function (err, result, res) {
        res.status(201).json({
          email: email,
          subscriber: subscriber
        })
        return true;
      };

      [internal, conflict, created].every(function (fn) {
        return fn(err, result, res);
      });
    });
  });

  router.delete('/:email', function (req, res) {
    var email = req.params.email;

    redis.deleteSubscriber(email, function (err, data) {
      if (!!err) { throw new Error(err); }
      res.json({});
    });
  });

  router.get('/:email', function(req, res) {
    var email = req.params.email;

    redis.getSubscriber(email, function (err, data) {
      if (!!err) { throw new Error(err); }
      data = !!data ? JSON.parse(data) : {};
      res.json(data);
    });
  });

  router.get('/', function(req, res) {
    redis.getAllSubscribers(function (err, data) {
      var result = [], i;
      if (!!err) { throw new Error(err); }

      for (i in data) {
        if (data.hasOwnProperty(i)) {
          result.push(JSON.parse(data[i]));
        }
      }
      res.json(result);
    });
  });

  exports.router = router;
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * Generate topojson file for the 50 states and DC.
 *
 * Designed to generate an output file of around 100kb,
 * with as much detail retained as practical.
 *
 * Run 'generate.js --help' for available options.
 */

const commander = require('commander')
const process = require('process')
const request = require('request-promise')
const topojson = require('topojson')
const winston = require('winston')
const wof = require('mapzen-whosonfirst')

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))

const Cache = require('async-disk-cache')
const cache = new Cache('wof-geojson')

const defaultFilename = 'usa-50-states-and-dc.topojson'
const defaultMinFeature = '1'
commander
  .version('0.1.0')
  .option('-o, --out <filename>', `Output filename [${defaultFilename}]`, defaultFilename)
  .option('-c, --clear', 'Clear cache of WOF geojson')
  .option('-m, --min <1|10|100>', `Approx. min feature size, in km^2 [${defaultMinFeature}]`, defaultMinFeature)
  .parse(process.argv)

const outputFilename = commander.out
const wofIdsFile = 'wof-ids'
const wofAlternateGeom = 'uscensus-display-terrestrial-zoom-10'
const concurrency = 4

// If given a min feature size, ensure it's one of our allowed values
// Is this validation/parsing of input really not built into commander already?
if (['1', '10', '100'].indexOf(commander.min) === -1) {
  // copying commander error format
  console.error()
  console.error("  error: invalid value `%s' for argument `%s'", commander.min, 'min')
  console.error()
  process.exit(1)
}

const tjsonSimplification = {
  1: 0.01 * 0.01,
  10: 0.03 * 0.03,
  100: 0.1 * 0.1
}[commander.min]

const tjsonQuantization = {
  1: 1e5,
  10: 1e4,
  100: 1e4
}[commander.min]

function readWofIdsFile (contents) {
  winston.info('Reading WOF Ids from %s ', wofIdsFile)
  return fs
    .readFileAsync(wofIdsFile, 'utf8')
    .then(contents => contents.trim().split('\n'))
}

function getCachedWofGeojson (wofId) {
  return cache
    .get(wofId)
    .then(cacheEntry => {
      if (cacheEntry.isCached) {
        winston.info('Using cached geojson for %s', wofId)
        return cacheEntry.value
      }

      winston.info('Calling out to WOF for %s', wofId)
      const url = wof.uri.id2abspath(wofId, {alt: true, source: wofAlternateGeom})
      return request
        .get(url)
        .then(gjsonStr => {
          winston.info('Filling cache for %s', wofId)
          cache.set(wofId, gjsonStr)
          return gjsonStr
        })
    })
    .then(gjsonStr => {
      const gjson = JSON.parse(gjsonStr)
      // pass on only the minimal parts we need
      return {
        type: gjson['type'],
        id: gjson['id'],
        geometry: gjson['geometry']
      }
    })
}

function buildTopojson (gjsons) {
  winston.info('Merging together %d geojsons into one topojson', gjsons.length)

  // Deferring quantizatiing till after composition and simplification
  let tjson = topojson.topology(gjsons)

  winston.info('Simplifying topojson to features of at least ~%s km^2', commander.min)
  tjson = topojson.presimplify(tjson)
  tjson = topojson.simplify(tjson, tjsonSimplification)
  tjson = topojson.quantize(tjson, tjsonQuantization)
  return tjson
}

function writeOutTopojson (tjson) {
  winston.info('Writing out topojson to %s', outputFilename)
  return fs.writeFileAsync(outputFilename, JSON.stringify(tjson))
}

// clear cache if requested
let cacheCleared
if (commander.clear) {
  winston.info('Clearing cache of WOF geojson')
  cacheCleared = cache.clear()
}

Promise.resolve(cacheCleared)
  .then(readWofIdsFile)
  .map(getCachedWofGeojson, {concurrency: concurrency})
  .then(buildTopojson)
  .then(writeOutTopojson)
<commit_msg>Use a few es6 features<commit_after>#!/usr/bin/env node
/**
 * Generate topojson file for the 50 states and DC.
 *
 * Designed to generate an output file of around 100kb,
 * with as much detail retained as practical.
 *
 * Run 'generate.js --help' for available options.
 */

const commander = require('commander')
const process = require('process')
const request = require('request-promise')
const topojson = require('topojson')
const winston = require('winston')
const wof = require('mapzen-whosonfirst')

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))

const Cache = require('async-disk-cache')
const cache = new Cache('wof-geojson')

const defaultFilename = 'usa-50-states-and-dc.topojson'
const defaultMinFeature = '1'
const minFeatureOpts = ['1', '10', '100']
commander
  .version('0.1.0')
  .option('-o, --out <filename>', `Output filename [${defaultFilename}]`, defaultFilename)
  .option('-c, --clear', 'Clear cache of WOF geojson')
  .option(`-m, --min <${minFeatureOpts.join('|')}>`,
          `Approx. min feature size, in km^2 [${defaultMinFeature}]`, defaultMinFeature)
  .parse(process.argv)

const outputFilename = commander.out
const wofIdsFile = 'wof-ids'
const wofAlternateGeom = 'uscensus-display-terrestrial-zoom-10'
const concurrency = 4

// If given a min feature size, ensure it's one of our allowed values
// Is this validation/parsing of input really not built into commander already?
if (!minFeatureOpts.includes(commander.min)) {
  // copying commander error format
  console.error()
  console.error("  error: invalid value `%s' for argument `%s'", commander.min, 'min')
  console.error()
  process.exit(1)
}

const tjsonSimplification = {
  1: 0.01 * 0.01,
  10: 0.03 * 0.03,
  100: 0.1 * 0.1
}[commander.min]

const tjsonQuantization = {
  1: 1e5,
  10: 1e4,
  100: 1e4
}[commander.min]

function readWofIdsFile (contents) {
  winston.info('Reading WOF Ids from %s ', wofIdsFile)
  return fs
    .readFileAsync(wofIdsFile, 'utf8')
    .then(contents => contents.trim().split('\n'))
}

function getCachedWofGeojson (wofId) {
  return cache
    .get(wofId)
    .then(cacheEntry => {
      if (cacheEntry.isCached) {
        winston.info('Using cached geojson for %s', wofId)
        return cacheEntry.value
      }

      winston.info('Calling out to WOF for %s', wofId)
      const url = wof.uri.id2abspath(wofId, {alt: true, source: wofAlternateGeom})
      return request
        .get(url)
        .then(gjsonStr => {
          winston.info('Filling cache for %s', wofId)
          cache.set(wofId, gjsonStr)
          return gjsonStr
        })
    })
    .then(gjsonStr => {
      const gjson = JSON.parse(gjsonStr)
      // pass on only the minimal parts we need
      return {
        type: gjson['type'],
        id: gjson['id'],
        geometry: gjson['geometry']
      }
    })
}

function buildTopojson (gjsons) {
  winston.info('Merging together %d geojsons into one topojson', gjsons.length)

  // Deferring quantizatiing till after composition and simplification
  let tjson = topojson.topology(gjsons)

  winston.info('Simplifying topojson to features of at least ~%s km^2', commander.min)
  tjson = topojson.presimplify(tjson)
  tjson = topojson.simplify(tjson, tjsonSimplification)
  tjson = topojson.quantize(tjson, tjsonQuantization)
  return tjson
}

function writeOutTopojson (tjson) {
  winston.info('Writing out topojson to %s', outputFilename)
  return fs.writeFileAsync(outputFilename, JSON.stringify(tjson))
}

// clear cache if requested
let cacheCleared
if (commander.clear) {
  winston.info('Clearing cache of WOF geojson')
  cacheCleared = cache.clear()
}

Promise.resolve(cacheCleared)
  .then(readWofIdsFile)
  .map(getCachedWofGeojson, {concurrency: concurrency})
  .then(buildTopojson)
  .then(writeOutTopojson)
<|endoftext|>


<commit_before>import { isObject } from "lodash"
import valueParser from "postcss-value-parser"

import {
  declarationValueIndexOffset,
  report,
  ruleMessages,
  validateOptions,
} from "../../utils"

export const ruleName = "property-unit-blacklist"

export const messages = ruleMessages(ruleName, {
  rejected: (p, u) => `Unexpected unit "${u}" for property "${p}"`,
})

export default function (blacklist) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: blacklist,
      possible: [isObject],
    })
    if (!validOptions) { return }

    root.walkDecls(decl => {

      const { prop, value } = decl
      const blacklistInProp = blacklist[prop]

      valueParser(value).walk(function (node) {
        const unit = valueParser.unit(node.value).unit

        if (blacklistInProp && blacklistInProp.indexOf(unit) !== -1 && node.type !== "string") {
          report({
            message: messages.rejected(prop, unit),
            node: decl,
            index: declarationValueIndexOffset(decl) + node.sourceIndex,
            result,
            ruleName,
          })
        }
      })
    })
  }
}
<commit_msg>Retrun early in same way as property-unit-whitelist<commit_after>import { isObject } from "lodash"
import valueParser from "postcss-value-parser"

import {
  declarationValueIndexOffset,
  report,
  ruleMessages,
  validateOptions,
} from "../../utils"

export const ruleName = "property-unit-blacklist"

export const messages = ruleMessages(ruleName, {
  rejected: (p, u) => `Unexpected unit "${u}" for property "${p}"`,
})

export default function (blacklist) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: blacklist,
      possible: [isObject],
    })
    if (!validOptions) { return }

    root.walkDecls(decl => {

      const { prop, value } = decl
      const propBlacklist = blacklist[prop]

      if (!propBlacklist) { return }

      valueParser(value).walk(function (node) {
        if (node.type === "string") { return }

        const unit = valueParser.unit(node.value).unit

        if (propBlacklist.indexOf(unit) !== -1) {
          report({
            message: messages.rejected(prop, unit),
            node: decl,
            index: declarationValueIndexOffset(decl) + node.sourceIndex,
            result,
            ruleName,
          })
        }
      })
    })
  }
}
<|endoftext|>


<commit_before>var fs = require('fs'),
  path = require('path'),
  qs = require('querystring'),
  request = require('request'),
  crypto = require('crypto'),
  util = require('util'),
  Tuppari = require('../lib/tuppari'),
  sign = require('../lib/sign');

/*
 * path.{exists,existsSync} was moved to fs.{exists,existsSync} at Node.js v0.8
 *
 * @see https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8
 */

exports.fileExists = (function () {
  if (path.exists) return path.exists;
  else return fs.exists;
})();

exports.fileExistsSync = (function () {
  if (path.existsSync) return path.existsSync;
  else return fs.existsSync;
})();

/**
 * Load config file from file.
 *
 * @param {String} configFile The path of configuration file
 * @return {Object}
 */
exports.loadConfig = function (configFile) {
  if (!exports.fileExistsSync(configFile)) {
    fs.writeFileSync(configFile, '{}');
    fs.lchmodSync(configFile, 0600);
  }

  var content = fs.readFileSync(configFile);
  return JSON.parse(content);
};

/**
 * POST request
 */
exports.post = function(program) {
  return function(options, callback) {
    var uri = program.endpoint(options.path);

    var config =
      options.authRequired ?
        sign.createSignedRequestConfig('POST', uri, options.operation, options.body, program.credentials.id, program.credentials.secret) :
        { uri: uri, json: options.body };

    program.debug('POST %s', uri, config);

    request.post(config, function (err, res, body) {
      program.abortIfError(err, res, body);
      program.debug('response:\n%s', program.prettyFormat(body));
      if (callback) {
        callback(res, body);
      }
      process.exit(0);
    });
  };
};

/**
 * GET request
 */
exports.get = function (program) {
  return function(options, callback) {
    var uri = program.endpoint(options.path);

    var config =
      options.authRequired ?
        sign.createSignedRequestConfig('GET', uri, options.operation, '', program.credentials.id, program.credentials.secret) :
        { uri: uri };

    program.debug('GET %s', uri, config);

    request(config, function (err, res, body) {
      program.abortIfError(err, res, body);
      program.debug('response:\n%s', program.prettyFormat(body));
      if (callback) {
        callback(res, body);
      }
      process.exit(0);
    });
  };
};<commit_msg>Prevent show warning message when Node.js >= 0.8.0<commit_after>var fs = require('fs'),
  path = require('path'),
  qs = require('querystring'),
  request = require('request'),
  crypto = require('crypto'),
  util = require('util'),
  Tuppari = require('../lib/tuppari'),
  sign = require('../lib/sign');

/*
 * path.{exists,existsSync} was moved to fs.{exists,existsSync} at Node.js v0.8
 *
 * @see https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8
 */

exports.fileExists = (function () {
  if (fs.exists) return fs.exists;
  else return path.exists;
})();

exports.fileExistsSync = (function () {
  if (fs.existsSync) return fs.existsSync;
  else return path.existsSync;
})();

/**
 * Load config file from file.
 *
 * @param {String} configFile The path of configuration file
 * @return {Object}
 */
exports.loadConfig = function (configFile) {
  if (!exports.fileExistsSync(configFile)) {
    fs.writeFileSync(configFile, '{}');
    fs.lchmodSync(configFile, 0600);
  }

  var content = fs.readFileSync(configFile);
  return JSON.parse(content);
};

/**
 * POST request
 */
exports.post = function(program) {
  return function(options, callback) {
    var uri = program.endpoint(options.path);

    var config =
      options.authRequired ?
        sign.createSignedRequestConfig('POST', uri, options.operation, options.body, program.credentials.id, program.credentials.secret) :
        { uri: uri, json: options.body };

    program.debug('POST %s', uri, config);

    request.post(config, function (err, res, body) {
      program.abortIfError(err, res, body);
      program.debug('response:\n%s', program.prettyFormat(body));
      if (callback) {
        callback(res, body);
      }
      process.exit(0);
    });
  };
};

/**
 * GET request
 */
exports.get = function (program) {
  return function(options, callback) {
    var uri = program.endpoint(options.path);

    var config =
      options.authRequired ?
        sign.createSignedRequestConfig('GET', uri, options.operation, '', program.credentials.id, program.credentials.secret) :
        { uri: uri };

    program.debug('GET %s', uri, config);

    request(config, function (err, res, body) {
      program.abortIfError(err, res, body);
      program.debug('response:\n%s', program.prettyFormat(body));
      if (callback) {
        callback(res, body);
      }
      process.exit(0);
    });
  };
};<|endoftext|>


<commit_before>enyo.kind({
	name: "bootstrap.NotificationBar",
	// ...........................
	// PUBLIC PROPERTIES
  classes: "notification-bar alert",
  published: {
    type: "info",  // info || warning || danger || success
    dismissable: false,
    displayTime: 5,
    position: "top",
    content: ""
  },
	handlers: {
		onDismissAlert: "dismissAlert"
	},
  components: [
    {name: "alertMessage", tag: 'span'}
  ],
  bindings: [
    {from: ".content", to: ".$.alertMessage.content"}
  ],
	// ...........................
	// PROTECTED METHODS
	create: function() {
    this.inherited(arguments);
    this.setupClasses();
		if(this.dismissable){
			this.createComponent({kind:"bootstrap.AlertCloseIcon", addBefore: null});
		} else {
      var that = this;
      setTimeout(function() { that.dismissAlert(); } , that.displayTime * 1000);
    }
	},
	setupClasses: function(){
		var classes = [this.getAttribute('class')];
		classes.push("alert-" + this.type);
    classes.push(this.position);
		if(this.dismissable){
			classes.push('alert-dismissable');
		}
		this.setAttribute('class', classes.join(' '));
	},
	dismissAlert: function(){
		this.destroy();
	}
});
<commit_msg>NotificationBar now passes down the allowHtml prop<commit_after>enyo.kind({
	name: "bootstrap.NotificationBar",
	// ...........................
	// PUBLIC PROPERTIES
  classes: "notification-bar alert",
  published: {
    type: "info",  // info || warning || danger || success
    dismissable: false,
    displayTime: 5,
    position: "top",
    content: ""
  },
	handlers: {
		onDismissAlert: "dismissAlert"
	},
  components: [
    {name: "alertMessage", tag: 'span'}
  ],
  bindings: [
    {from: ".content", to: ".$.alertMessage.content"},
    {from: ".allowHtml", to: ".$.alertMessage.allowHtml"}
  ],
	// ...........................
	// PROTECTED METHODS
	create: function() {
    this.inherited(arguments);
    this.setupClasses();
		if(this.dismissable){
			this.createComponent({kind:"bootstrap.AlertCloseIcon", addBefore: null});
		} else {
      var that = this;
      setTimeout(function() { that.dismissAlert(); } , that.displayTime * 1000);
    }
	},
	setupClasses: function(){
		var classes = [this.getAttribute('class')];
		classes.push("alert-" + this.type);
    classes.push(this.position);
		if(this.dismissable){
			classes.push('alert-dismissable');
		}
		this.setAttribute('class', classes.join(' '));
	},
	dismissAlert: function(){
		this.destroy();
	}
});
<|endoftext|>


<commit_before>/*globals describe it beforeEach afterEach */
"use strict";

require("should");
const path = require("path");
const TestHelper = require("./helpers/TestHelper");
const Watchpack = require("../lib/watchpack");
const watchEventSource = require("../lib/watchEventSource");

const fixtures = path.join(__dirname, "fixtures");
const testHelper = new TestHelper(fixtures);

describe("ManyWatchers", function() {
	this.timeout(180000);
	beforeEach(testHelper.before);
	afterEach(testHelper.after);

	it("should watch more than 4096 directories", done => {
		const files = [];
		for (let i = 1; i <= 5000; i++) {
			let highBit = 1;
			let j = i;
			while (j > 1) {
				highBit <<= 1;
				j >>= 1;
			}
			const dir = `${i & highBit}/${i & ~highBit}`;
			if (i === highBit) testHelper.dir(`${i}`);
			testHelper.dir(dir);
			testHelper.file(`${dir}/file`);
			files.push(path.join(fixtures, dir, "file"));
		}
		testHelper.tick(1000, () => {
			const w = new Watchpack({
				aggregateTimeout: 1000
			});
			w.on("aggregated", function(changes) {
				Array.from(changes).should.be.eql([
					path.join(fixtures, "4096/900/file")
				]);
				w.close();
				done();
			});
			for (let i = 100; i < files.length; i += 987) {
				for (let j = 0; j < files.length - i; j += 987) {
					w.watch({ files: files.slice(j, j + i) });
				}
			}
			w.watch({ files });
			testHelper.tick(10000, () => {
				testHelper.file("4096/900/file");
			});
		});
	});
});
<commit_msg>improve test case for multiple files<commit_after>/*globals describe it beforeEach afterEach */
"use strict";

require("should");
const path = require("path");
const TestHelper = require("./helpers/TestHelper");
const Watchpack = require("../lib/watchpack");
const watchEventSource = require("../lib/watchEventSource");

const fixtures = path.join(__dirname, "fixtures");
const testHelper = new TestHelper(fixtures);

describe("ManyWatchers", function() {
	this.timeout(180000);
	beforeEach(testHelper.before);
	afterEach(testHelper.after);

	it("should watch more than 4096 directories", done => {
		const files = [];
		for (let i = 1; i <= 5000; i++) {
			let highBit = 1;
			let j = i;
			while (j > 1) {
				highBit <<= 1;
				j >>= 1;
			}
			const dir = `${i & highBit}/${i & ~highBit}`;
			if (i === highBit) {
				testHelper.dir(`${i}`);
				testHelper.file(`${i}/file`);
				files.push(path.join(fixtures, `${i}`, "file"));
			}
			testHelper.dir(dir);
			testHelper.file(`${dir}/file`);
			files.push(path.join(fixtures, dir, "file"));
			if (i === highBit) {
				testHelper.file(`${dir}/file2`);
				files.push(path.join(fixtures, dir, "file2"));
			}
		}
		testHelper.tick(1000, () => {
			const w = new Watchpack({
				aggregateTimeout: 1000
			});
			w.on("aggregated", function(changes) {
				Array.from(changes).should.be.eql([
					path.join(fixtures, "4096/900/file")
				]);
				w.close();
				done();
			});
			for (let i = 100; i < files.length; i += 987) {
				for (let j = 0; j < files.length - i; j += 987) {
					w.watch({ files: files.slice(j, j + i) });
				}
			}
			w.watch({ files });
			testHelper.tick(10000, () => {
				testHelper.file("4096/900/file");
			});
		});
	});
});
<|endoftext|>


<commit_before>
const { readFileSync, writeFileSync, existsSync } = require('fs')
const { sep, normalize, join, resolve, extname } = require('path')
const { emptyDirSync, ensureDirSync, ensureFileSync, copySync } = require('fs-extra')
const prompts = require('prompts')
const compileTemplate = require('lodash/template')
const fglob = require('fast-glob')
const { yellow, green } = require('kolorist')
const exec = require('child_process').execSync
const spawn = require('child_process').spawn

const logger = require('./logger')

const TEMPLATING_FILE_EXTENSIONS = [ '', '.json', '.js', '.ts', '.vue', '.md', '.html', '.sass' ]

module.exports.join = join
module.exports.logger = logger

module.exports.prompts = async function (scope, questions, opts) {
  const options = opts || {
    onCancel: () => {
      logger.fatal('Scaffolding cancelled')
    }
  }

  const answers = await prompts(questions, options)
  Object.assign(scope, answers)
}

module.exports.createTargetDir = function (scope) {
  console.log()
  logger.log('Generating files...')
  console.log()

  const fn = scope.overwrite ? emptyDirSync : ensureDirSync
  fn(scope.projectFolder)
}

module.exports.convertArrayToObject = function (arr) {
  const acc = {}
  arr.forEach(key => {
    acc[key] = true
  })
  return acc
}

module.exports.runningPackageManager = (() => {
  const userAgent = process.env.npm_config_user_agent

  if (userAgent) {
    return userAgent.split(' ')[0].split('/')[0]
  }
})()

module.exports.renderTemplate = function (templateDir, scope) {
  const files = fglob.sync(['**/*'], { cwd: templateDir })

  for (const rawPath of files) {
    const targetRelativePath = rawPath.split('/').map(name => {
      // dotfiles are ignored when published to npm, therefore in templates
      // we need to prefix them with an underscore (e.g. "_.gitignore")
      // Also, some tools like ESLint excepts valid config files, therefore
      // we also prefix files like "package.json" too. (e.g. "_.package.json")
      return name.startsWith('_')
        ? name.slice(1)
        : name
    }).join('/')

    const targetPath = resolve(scope.projectFolder, targetRelativePath)
    const sourcePath = resolve(templateDir, rawPath)
    const extension = extname(targetRelativePath)

    ensureFileSync(targetPath)

    console.log(` ${green('-')} ${targetRelativePath}`)

    if (TEMPLATING_FILE_EXTENSIONS.includes(extension)) {
      const rawContent = readFileSync(sourcePath, 'utf-8')
      const template = compileTemplate(rawContent, { 'interpolate': /<%=([\s\S]+?)%>/g })

      const newContent = extension === '.json'
        ? JSON.stringify(JSON.parse(template(scope)), null, 2)
        : template(scope)

      writeFileSync(targetPath, newContent, 'utf-8')
    }
    else {
      copySync(sourcePath, targetPath)
    }
  }
}

module.exports.isValidPackageName = function (projectName) {
  return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(
    projectName
  )
}

module.exports.inferPackageName = function (projectFolder) {
  return projectFolder
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/^[._]/, '')
    .replace(/[^a-z0-9-~]+/g, '-')
}

module.exports.escapeString = function (val) {
  return JSON.stringify(val).slice(1, -1)
}

function getGitUser () {
  let name
  let email

  try {
    name = exec('git config --get user.name')
    email = exec('git config --get user.email')
  }
  catch (e) {}

  name = name && JSON.stringify(name.toString().trim()).slice(1, -1)
  email = email && (' <' + email.toString().trim() + '>')

  return (name || '') + (email || '')
}

/**
 * Prints the final message with instructions of necessary next steps.
 *
 * @param {Object} scope Data from questionnaire.
 */
module.exports.printFinalMessage = function (scope) {
  const verPrefix = scope.quasarVersion ? scope.quasarVersion + '.' : ''
  const message = `
To get started:
${yellow(`
  cd ${scope.projectFolderName}${ scope.skipDepsInstall !== true && scope.packageManager === false ? `
  yarn #or: npm install
  yarn lint --fix # or: npm run lint -- --fix` : '' }${ scope.skipDepsInstall !== true ? `
  quasar dev # or: yarn quasar dev # or: npx quasar dev` : '' }
`)}
Documentation can be found at: https://${verPrefix}quasar.dev

Quasar is relying on donations to evolve. We'd be very grateful if you can
read our manifest on "Why donations are important": https://${verPrefix}quasar.dev/why-donate
Donation campaign: https://donate.quasar.dev
Any amount is very welcome.
If invoices are required, please first contact Razvan Stoenescu.

Please give us a star on Github if you appreciate our work:
  https://github.com/quasarframework/quasar

Enjoy! - Quasar Team
`

  console.log(message)
}

function runCommand (cmd, args, options) {
  console.log()
  return new Promise((resolve, reject) => {
    const runner = spawn(
      cmd,
      args,
      Object.assign({
        cwd: process.cwd(),
        stdio: 'inherit',
        shell: true,
      }, options)
    )

    runner.on('exit', code => {
      console.log()

      if (code) {
        console.log(` ${cmd} FAILED...`)
        console.log()
        reject()
      }
      else {
        resolve()
      }
    })
  })
}

module.exports.installDeps = function (scope) {
  return runCommand(
    scope.packageManager,
    [ 'install' ],
    { cwd: scope.projectFolder }
  )
}

module.exports.lintFolder = function (scope) {
  return runCommand(
    scope.packageManager,
    scope.packageManager === 'npm'
      ? ['run', 'lint', '--', '--fix']
      : ['run', 'lint', '--fix'],
    { cwd: scope.projectFolder }
  )
}

module.exports.ensureOutsideProject = function () {
  let dir = process.cwd()

  while (dir.length && dir[dir.length - 1] !== sep) {
    if (
      existsSync(join(dir, 'quasar.conf.js')) ||
      existsSync(join(dir, 'quasar.config.js'))
    ) {
      logger.fatal(`Error. This command must NOT be executed inside of a Quasar project folder.`)
    }

    dir = normalize(join(dir, '..'))
  }
}

const QUASAR_VERSIONS = [
  { title: 'Quasar v2 (Vue 3 | latest and greatest)', value: 'v2', description: 'recommended' },
  { title: 'Quasar v1 (Vue 2)', value: 'v1' }
]
const SCRIPT_TYPES = [
  { title: 'Javascript', value: 'js' },
  { title: 'Typescript', value: 'ts' }
]

module.exports.commonPrompts = {
  quasarVersion: {
    type: 'select',
    name: 'quasarVersion',
    message: 'Pick Quasar version:',
    initial: 0,
    choices: QUASAR_VERSIONS
  },

  scriptType: {
    type: 'select',
    name: 'scriptType',
    message: 'Pick script type:',
    initial: 0,
    choices: SCRIPT_TYPES
  },

  productName: {
    type: 'text',
    name: 'productName',
    message: 'Project product name: (must start with letter if building mobile apps)',
    initial: 'Quasar App',
    validate: val =>
      val && val.length > 0 || 'Invalid product name'
  },

  description: {
    type: 'text',
    name: 'description',
    message: 'Project description:',
    initial: 'A Quasar Project',
    format: module.exports.escapeString,
    validate: val =>
      val.length > 0 || 'Invalid project description'
  },

  author: {
    type: 'text',
    name: 'author',
    initial: () => getGitUser(),
    message: 'Author:'
  },

  license: {
    type: 'text',
    name: 'license',
    message: 'License type',
    initial: 'MIT'
  },

  repositoryType: {
    type: 'text',
    name: 'repositoryType',
    message: 'Repository type:',
    initial: 'git'
  },
  repositoryURL: {
    type: 'text',
    name: 'repositoryURL',
    message: 'Repository URL: (eg https://github.com/quasarframework/quasar)'
  },
  homepage: {
    type: 'text',
    name: 'homepage',
    message: 'Homepage URL:'
  },
  bugs: {
    type: 'text',
    name: 'bugs',
    message: 'Issue reporting URL: (eg https://github.com/quasarframework/quasar/issues)'
  }
}
<commit_msg>chore(create-quasar): Update renderTemplate explanation<commit_after>
const { readFileSync, writeFileSync, existsSync } = require('fs')
const { sep, normalize, join, resolve, extname } = require('path')
const { emptyDirSync, ensureDirSync, ensureFileSync, copySync } = require('fs-extra')
const prompts = require('prompts')
const compileTemplate = require('lodash/template')
const fglob = require('fast-glob')
const { yellow, green } = require('kolorist')
const exec = require('child_process').execSync
const spawn = require('child_process').spawn

const logger = require('./logger')

const TEMPLATING_FILE_EXTENSIONS = [ '', '.json', '.js', '.ts', '.vue', '.md', '.html', '.sass' ]

module.exports.join = join
module.exports.logger = logger

module.exports.prompts = async function (scope, questions, opts) {
  const options = opts || {
    onCancel: () => {
      logger.fatal('Scaffolding cancelled')
    }
  }

  const answers = await prompts(questions, options)
  Object.assign(scope, answers)
}

module.exports.createTargetDir = function (scope) {
  console.log()
  logger.log('Generating files...')
  console.log()

  const fn = scope.overwrite ? emptyDirSync : ensureDirSync
  fn(scope.projectFolder)
}

module.exports.convertArrayToObject = function (arr) {
  const acc = {}
  arr.forEach(key => {
    acc[key] = true
  })
  return acc
}

module.exports.runningPackageManager = (() => {
  const userAgent = process.env.npm_config_user_agent

  if (userAgent) {
    return userAgent.split(' ')[0].split('/')[0]
  }
})()

module.exports.renderTemplate = function (templateDir, scope) {
  const files = fglob.sync(['**/*'], { cwd: templateDir })

  for (const rawPath of files) {
    const targetRelativePath = rawPath.split('/').map(name => {
      // dotfiles are ignored when published to npm, therefore in templates
      // we need to prefix them with an underscore (e.g. "_.gitignore")
      // Also, some tools like ESLint expect valid config files, therefore
      // we also prefix files like "package.json" too. (e.g. "_package.json")
      return name.startsWith('_')
        ? name.slice(1)
        : name
    }).join('/')

    const targetPath = resolve(scope.projectFolder, targetRelativePath)
    const sourcePath = resolve(templateDir, rawPath)
    const extension = extname(targetRelativePath)

    ensureFileSync(targetPath)

    console.log(` ${green('-')} ${targetRelativePath}`)

    if (TEMPLATING_FILE_EXTENSIONS.includes(extension)) {
      const rawContent = readFileSync(sourcePath, 'utf-8')
      const template = compileTemplate(rawContent, { 'interpolate': /<%=([\s\S]+?)%>/g })

      const newContent = extension === '.json'
        ? JSON.stringify(JSON.parse(template(scope)), null, 2)
        : template(scope)

      writeFileSync(targetPath, newContent, 'utf-8')
    }
    else {
      copySync(sourcePath, targetPath)
    }
  }
}

module.exports.isValidPackageName = function (projectName) {
  return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(
    projectName
  )
}

module.exports.inferPackageName = function (projectFolder) {
  return projectFolder
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/^[._]/, '')
    .replace(/[^a-z0-9-~]+/g, '-')
}

module.exports.escapeString = function (val) {
  return JSON.stringify(val).slice(1, -1)
}

function getGitUser () {
  let name
  let email

  try {
    name = exec('git config --get user.name')
    email = exec('git config --get user.email')
  }
  catch (e) {}

  name = name && JSON.stringify(name.toString().trim()).slice(1, -1)
  email = email && (' <' + email.toString().trim() + '>')

  return (name || '') + (email || '')
}

/**
 * Prints the final message with instructions of necessary next steps.
 *
 * @param {Object} scope Data from questionnaire.
 */
module.exports.printFinalMessage = function (scope) {
  const verPrefix = scope.quasarVersion ? scope.quasarVersion + '.' : ''
  const message = `
To get started:
${yellow(`
  cd ${scope.projectFolderName}${ scope.skipDepsInstall !== true && scope.packageManager === false ? `
  yarn #or: npm install
  yarn lint --fix # or: npm run lint -- --fix` : '' }${ scope.skipDepsInstall !== true ? `
  quasar dev # or: yarn quasar dev # or: npx quasar dev` : '' }
`)}
Documentation can be found at: https://${verPrefix}quasar.dev

Quasar is relying on donations to evolve. We'd be very grateful if you can
read our manifest on "Why donations are important": https://${verPrefix}quasar.dev/why-donate
Donation campaign: https://donate.quasar.dev
Any amount is very welcome.
If invoices are required, please first contact Razvan Stoenescu.

Please give us a star on Github if you appreciate our work:
  https://github.com/quasarframework/quasar

Enjoy! - Quasar Team
`

  console.log(message)
}

function runCommand (cmd, args, options) {
  console.log()
  return new Promise((resolve, reject) => {
    const runner = spawn(
      cmd,
      args,
      Object.assign({
        cwd: process.cwd(),
        stdio: 'inherit',
        shell: true,
      }, options)
    )

    runner.on('exit', code => {
      console.log()

      if (code) {
        console.log(` ${cmd} FAILED...`)
        console.log()
        reject()
      }
      else {
        resolve()
      }
    })
  })
}

module.exports.installDeps = function (scope) {
  return runCommand(
    scope.packageManager,
    [ 'install' ],
    { cwd: scope.projectFolder }
  )
}

module.exports.lintFolder = function (scope) {
  return runCommand(
    scope.packageManager,
    scope.packageManager === 'npm'
      ? ['run', 'lint', '--', '--fix']
      : ['run', 'lint', '--fix'],
    { cwd: scope.projectFolder }
  )
}

module.exports.ensureOutsideProject = function () {
  let dir = process.cwd()

  while (dir.length && dir[dir.length - 1] !== sep) {
    if (
      existsSync(join(dir, 'quasar.conf.js')) ||
      existsSync(join(dir, 'quasar.config.js'))
    ) {
      logger.fatal(`Error. This command must NOT be executed inside of a Quasar project folder.`)
    }

    dir = normalize(join(dir, '..'))
  }
}

const QUASAR_VERSIONS = [
  { title: 'Quasar v2 (Vue 3 | latest and greatest)', value: 'v2', description: 'recommended' },
  { title: 'Quasar v1 (Vue 2)', value: 'v1' }
]
const SCRIPT_TYPES = [
  { title: 'Javascript', value: 'js' },
  { title: 'Typescript', value: 'ts' }
]

module.exports.commonPrompts = {
  quasarVersion: {
    type: 'select',
    name: 'quasarVersion',
    message: 'Pick Quasar version:',
    initial: 0,
    choices: QUASAR_VERSIONS
  },

  scriptType: {
    type: 'select',
    name: 'scriptType',
    message: 'Pick script type:',
    initial: 0,
    choices: SCRIPT_TYPES
  },

  productName: {
    type: 'text',
    name: 'productName',
    message: 'Project product name: (must start with letter if building mobile apps)',
    initial: 'Quasar App',
    validate: val =>
      val && val.length > 0 || 'Invalid product name'
  },

  description: {
    type: 'text',
    name: 'description',
    message: 'Project description:',
    initial: 'A Quasar Project',
    format: module.exports.escapeString,
    validate: val =>
      val.length > 0 || 'Invalid project description'
  },

  author: {
    type: 'text',
    name: 'author',
    initial: () => getGitUser(),
    message: 'Author:'
  },

  license: {
    type: 'text',
    name: 'license',
    message: 'License type',
    initial: 'MIT'
  },

  repositoryType: {
    type: 'text',
    name: 'repositoryType',
    message: 'Repository type:',
    initial: 'git'
  },
  repositoryURL: {
    type: 'text',
    name: 'repositoryURL',
    message: 'Repository URL: (eg https://github.com/quasarframework/quasar)'
  },
  homepage: {
    type: 'text',
    name: 'homepage',
    message: 'Homepage URL:'
  },
  bugs: {
    type: 'text',
    name: 'bugs',
    message: 'Issue reporting URL: (eg https://github.com/quasarframework/quasar/issues)'
  }
}
<|endoftext|>


<commit_before>// require esphinx/main

var
    esPhinx;

(function($) {
  "use strict";

    $.extend(false, {
        ui: {
            extend: function() {
                // Extensor.new(this, arguments[0], arguments[1]);
                $.Extensor.new(this, arguments[0], arguments[1]);
            }
        }
    });

}(esPhinx));
<commit_msg>comment<commit_after>// require esphinx/main

var
    esPhinx;

(function($) {
  "use strict";

    $.extend(false, {
        ui: {
            extend: function() {
                $.Extensor.new(this, arguments[0], arguments[1]);
            }
        }
    });

}(esPhinx));
<|endoftext|>


<commit_before>'use strict';

$(document).on('online', function() {
	console.log('Application got online event, reloading');
	window.location.reload();
});

$(document).ready(function() {
	console.log('Application got ready event');
	window.Nightscout.client.init();
});<commit_msg>see if document ready is the problem when testing on travis<commit_after>'use strict';

$(document).on('online', function() {
	console.log('Application got online event, reloading');
	window.location.reload();
});

//$(document).ready(function() {
//	console.log('Application got ready event');
//	window.Nightscout.client.init();
//});
window.Nightscout.client.init();
<|endoftext|>


<commit_before><commit_msg>run grunt app.js bundle<commit_after><|endoftext|>