<commit_before>CapoRSS.View.Feed = Backbone.Marionette.ItemView.extend({
	tagName: 'li',
	className: 'feed',
	template: '#tmpl-feed',
	attributes: {
		'draggable': true
	},
	events: {
		'click .markFeedReadAction' : 'markFeedRead',
		'click .markFeedUnreadAction' : 'markFeedUnread',
		'click .syncFeedAction' : 'syncFeed',
		'click .editFeedAction' : 'showFeedEditDialog',
		'click .deleteFeedAction' : 'deleteFeed',
		'click .feed-icon' : 'openMenu',
		'click .feed-title' : 'selectFeed',
		'dragstart' : 'onDragStart',
		'dragenter' : 'onDragEnter',
		'dragover' : 'onDragOver',
		'dragleave' : 'onDragLeave',
		'drop' : 'onDrop',
		'dragend' : 'onDragEnd'
	},
	modelEvents: {
		'destroy': 'remove',
		'change': 'render'
	},

	initialize: function() {
		_.bindAll(this);
	},

	/**
	 * Data sent to the template.
	 * @return {Object}
	 */
	serializeData: function() {
		return {'feed': this.model.attributes};
	},

	/**
	 * Action after feed render.
	 */
	onRender: function() {
		this.$('.favicon').on('error', this.onFaviconError);
	},

	/**
	 * Action on favicon error.
	 * Remove the favicon in the model so a placeholder is used instead
	 * of the invalid favicon.
	 */
	onFaviconError: function() {
		this.model.set('favicon_id', null);
	},

	/**
	 * Action on drag-and-drop enter.
	 * @param {eventObject} e
	 */
	onDragEnter: function(e) {
		e.preventDefault();
		this.$el.addClass('drag-hovered');
	},

	/**
	 * Action on drag-and-drop hover.
	 * @param {eventObject} e
	 */
	onDragOver: function(e) {
		e.preventDefault();
	},

	/**
	 * Action on drag-and-drop leave.
	 * @param {eventObject} e
	 */
	onDragLeave: function(e) {
		var rect = e.currentTarget.getBoundingClientRect();
		var oe = e.originalEvent;

		if(oe.clientX >= rect.right || oe.clientX <= rect.left || oe.clientY >= rect.bottom || oe.clientY <= rect.top) {
			this.$el.removeClass('drag-hovered');
		}
	},

	/**
	 * Action on drag-and-drop drop.
	 * If the dropped element is a feed, move it after this feed.
	 * @param {eventObject} e
	 */
	onDrop: function(e) {
		e.stopPropagation();
		var feed_id = e.originalEvent.dataTransfer.getData('feed_id');
		var feed = CapoRSS.folders.getFeed(feed_id);
		var dest = this.model;

		if(feed) {
			var new_position = dest.get('position');
			var old_folder = null;

			if(dest.get('folder_id') == feed.get('folder_id')) {
				if(new_position == feed.get('position')) {
					// The feed was not moved, do nothing.
					this.$el.removeClass('drag-hovered');
					return;
				}
				else if(new_position < feed.get('position')) {
					new_position += 1;
				}
			}
			else {
				new_position += 1;
				old_folder = CapoRSS.folders.get(feed.get('folder_id'));
			}

			feed.save({
				folder_id: dest.get('folder_id'),
				position: new_position
			}, { success: function() {
				CapoRSS.router.navigate("", {trigger: true});
				if(old_folder !== null) {
					old_folder.fetch();
				}
				CapoRSS.folders.get(dest.get('folder_id')).fetch();
			}});
		}

		this.$el.removeClass('drag-hovered');
	},

	/**
	 * Action on drag-and-drop start.
	 * @param {eventObject} e
	 */
	onDragStart: function(e) {
		e.stopPropagation();
		this.$el.css({opacity: 0.5});
		e.originalEvent.dataTransfer.setData('feed_id', this.model.id);
	},

	/**
	 * Action on drag-and-drop end.
	 * @param {eventObject} e
	 */
	onDragEnd: function(e) {
		this.$el.css({opacity: ""});
	},

	/**
	 * Action when the feed is selected.
	 */
	selectFeed: function() {
		CapoRSS.router.navigate("feed/" + this.model.id, {trigger: true});
	},

	/**
	 * Delete the feed.
	 * @param {eventObject} e
	 */
	deleteFeed: function(e) {
		e.stopPropagation();

		if(confirm(LANG.confirm_delete_feed)) {
			if(this.model == CapoRSS.router.currentSelection) {
				CapoRSS.router.navigate("", {trigger: true});
			}
			this.model.destroy({success: function() {
				if(CapoRSS.router.currentSelection !== null) {
					CapoRSS.router.currentSelection.items.fetch({reset: true});
				}
			}});
		}

		this.closeMenu();
	},

	/**
	 * Synchronize the feed.
	 * @param {eventObject} e
	 */
	syncFeed: function(e) {
		e.stopPropagation();

		var that = this;
		$.ajax({
			method: 'POST',
			url: '/sync/feed/' + this.model.id,
			dataType: 'json',
			success: function(result) {
				that.model.fetch({
					success: function() {
						$.pnotify({ text: result.new_items + ' new items.', type: 'success' });
					}
				});
				if(CapoRSS.router.currentSelection !== null) {
					CapoRSS.router.currentSelection.items.fetch({reset: true});
				}
			}
		});

		this.closeMenu();
	},

	/**
	 * Mark the feed as read.
	 * @param {eventObject} e
	 */
	markFeedRead: function(e) {
		e.stopPropagation();

		$.when(this.model.markRead()).then(function() {
			if(CapoRSS.router.currentSelection !== null) {
				CapoRSS.router.currentSelection.items.fetch({reset: true});
			}
		});

		this.closeMenu();
	},

	/**
	 * Mark the feed as unread.
	 * @param {eventObject} e
	 */
	markFeedUnread: function(e) {
		e.stopPropagation();

		$.when(this.model.markUnread()).then(function() {
			if(CapoRSS.router.currentSelection !== null) {
				CapoRSS.router.currentSelection.items.fetch({reset: true});
			}
		});

		this.closeMenu();
	},

	/**
	 * Show feed edition dialog.
	 * @param {eventObject} e
	 */
	showFeedEditDialog: function(e) {
		e.stopPropagation();

		var dialog = $('#editFeedModal');
		dialog.find('#feedId').val(this.model.id);
		dialog.find('#feedFolder').val(CapoRSS.folders.get(this.model.get('folder_id')).get('title'));
		dialog.find('#feedUrl').val(this.model.get('url'));

		if(this.model.get('pshb_hub') !== '') {
			dialog.find('#feedPSHBInfos').removeClass('hide');
			dialog.find('#feedPSHBHub').text(this.model.get('pshb_hub'));
			dialog.find('#feedPSHBTopic').text(this.model.get('pshb_topic'));
			dialog.find('#feedPSHBExpiration').text(this.model.get('pshb_expiration'));
			dialog.find('#feedUsePSHB').prop('disabled', !this.model.get('pshb_hub'));
			dialog.find('#feedUsePSHB').prop('checked', this.model.get('pshb'));

		}
		else {
			dialog.find('#feedPSHBInfos').addClass('hide');
		}

		dialog.modal().on('shown', function() {
			$('#feedUrl').focus();
		}).on('hidden', function() {
			$('#feedUrl').blur();
		});

		this.closeMenu();
	},

	/**
	 * Open the feed's menu.
	 * @param {eventObject} e
	 * @return {boolean} False if the menu is already open
	 */
	openMenu: function(e) {
		e.stopPropagation();

		var menu = this.$el.find('.feedMenu');
		var opened = !menu.hasClass('hide');

		// Close any opened menu
		$(document).click();

		if(opened) {
			return false;
		}

		menu.removeClass('hide');

		$(document).one('click', this.closeMenu);
	},

	/**
	 * Close the feed's menu.
	 */
	closeMenu: function() {
		var menu = this.$el.find('.feedMenu');
		menu.addClass('hide');
	}
});
<commit_msg>Small code fix<commit_after>CapoRSS.View.Feed = Backbone.Marionette.ItemView.extend({
	tagName: 'li',
	className: 'feed',
	template: '#tmpl-feed',
	attributes: {
		'draggable': true
	},
	events: {
		'click .markFeedReadAction' : 'markFeedRead',
		'click .markFeedUnreadAction' : 'markFeedUnread',
		'click .syncFeedAction' : 'syncFeed',
		'click .editFeedAction' : 'showFeedEditDialog',
		'click .deleteFeedAction' : 'deleteFeed',
		'click .feed-icon' : 'openMenu',
		'click .feed-title' : 'selectFeed',
		'dragstart' : 'onDragStart',
		'dragenter' : 'onDragEnter',
		'dragover' : 'onDragOver',
		'dragleave' : 'onDragLeave',
		'drop' : 'onDrop',
		'dragend' : 'onDragEnd'
	},
	modelEvents: {
		'destroy': 'remove',
		'change': 'render'
	},

	initialize: function() {
		_.bindAll(this);
	},

	/**
	 * Data sent to the template.
	 * @return {Object}
	 */
	serializeData: function() {
		return {'feed': this.model.attributes};
	},

	/**
	 * Action after feed render.
	 */
	onRender: function() {
		this.$('.favicon').on('error', this.onFaviconError);
	},

	/**
	 * Action on favicon error.
	 * Remove the favicon in the model so a placeholder is used instead
	 * of the invalid favicon.
	 */
	onFaviconError: function() {
		this.model.set('favicon_id', null);
	},

	/**
	 * Action on drag-and-drop enter.
	 * @param {eventObject} e
	 */
	onDragEnter: function(e) {
		e.preventDefault();
		this.$el.addClass('drag-hovered');
	},

	/**
	 * Action on drag-and-drop hover.
	 * @param {eventObject} e
	 */
	onDragOver: function(e) {
		e.preventDefault();
	},

	/**
	 * Action on drag-and-drop leave.
	 * @param {eventObject} e
	 */
	onDragLeave: function(e) {
		var rect = e.currentTarget.getBoundingClientRect();
		var oe = e.originalEvent;

		if(oe.clientX >= rect.right || oe.clientX <= rect.left || oe.clientY >= rect.bottom || oe.clientY <= rect.top) {
			this.$el.removeClass('drag-hovered');
		}
	},

	/**
	 * Action on drag-and-drop drop.
	 * If the dropped element is a feed, move it after this feed.
	 * @param {eventObject} e
	 */
	onDrop: function(e) {
		e.stopPropagation();
		var feed_id = e.originalEvent.dataTransfer.getData('feed_id');
		var feed = CapoRSS.folders.getFeed(feed_id);
		var dest = this.model;

		if(feed) {
			var new_position = dest.get('position');
			var old_folder = null;

			if(dest.get('folder_id') == feed.get('folder_id')) {
				if(new_position == feed.get('position')) {
					// The feed was not moved, do nothing.
					this.$el.removeClass('drag-hovered');
					return;
				}
				else if(new_position < feed.get('position')) {
					new_position += 1;
				}
			}
			else {
				new_position += 1;
				old_folder = CapoRSS.folders.get(feed.get('folder_id'));
			}

			feed.save({
				folder_id: dest.get('folder_id'),
				position: new_position
			}, { success: function() {
				CapoRSS.router.navigate("", {trigger: true});
				if(old_folder !== null) {
					old_folder.fetch();
				}
				CapoRSS.folders.get(dest.get('folder_id')).fetch();
			}});
		}

		this.$el.removeClass('drag-hovered');
	},

	/**
	 * Action on drag-and-drop start.
	 * @param {eventObject} e
	 */
	onDragStart: function(e) {
		e.stopPropagation();
		this.$el.css({opacity: 0.5});
		e.originalEvent.dataTransfer.setData('feed_id', this.model.id);
	},

	/**
	 * Action on drag-and-drop end.
	 * @param {eventObject} e
	 */
	onDragEnd: function(e) {
		this.$el.css({opacity: ""});
	},

	/**
	 * Action when the feed is selected.
	 */
	selectFeed: function() {
		CapoRSS.router.navigate("feed/" + this.model.id, {trigger: true});
	},

	/**
	 * Delete the feed.
	 * @param {eventObject} e
	 */
	deleteFeed: function(e) {
		e.stopPropagation();

		if(confirm(LANG.confirm_delete_feed)) {
			if(this.model == CapoRSS.router.currentSelection) {
				CapoRSS.router.navigate("", {trigger: true});
			}
			this.model.destroy({success: function() {
				if(CapoRSS.router.currentSelection !== null) {
					CapoRSS.router.currentSelection.items.fetch({reset: true});
				}
			}});
		}

		this.closeMenu();
	},

	/**
	 * Synchronize the feed.
	 * @param {eventObject} e
	 */
	syncFeed: function(e) {
		e.stopPropagation();

		var that = this;
		$.ajax({
			method: 'POST',
			url: '/sync/feed/' + this.model.id,
			dataType: 'json',
			success: function(result) {
				that.model.fetch({
					success: function() {
						$.pnotify({ text: result.new_items + ' new items.', type: 'success' });
					}
				});
				if(CapoRSS.router.currentSelection !== null) {
					CapoRSS.router.currentSelection.items.fetch({reset: true});
				}
			}
		});

		this.closeMenu();
	},

	/**
	 * Mark the feed as read.
	 * @param {eventObject} e
	 */
	markFeedRead: function(e) {
		e.stopPropagation();

		$.when(this.model.markRead()).then(function() {
			if(CapoRSS.router.currentSelection !== null) {
				CapoRSS.router.currentSelection.items.fetch({reset: true});
			}
		});

		this.closeMenu();
	},

	/**
	 * Mark the feed as unread.
	 * @param {eventObject} e
	 */
	markFeedUnread: function(e) {
		e.stopPropagation();

		$.when(this.model.markUnread()).then(function() {
			if(CapoRSS.router.currentSelection !== null) {
				CapoRSS.router.currentSelection.items.fetch({reset: true});
			}
		});

		this.closeMenu();
	},

	/**
	 * Show feed edition dialog.
	 * @param {eventObject} e
	 */
	showFeedEditDialog: function(e) {
		e.stopPropagation();

		var dialog = $('#editFeedModal');
		dialog.find('#feedId').val(this.model.id);
		dialog.find('#feedFolder').val(CapoRSS.folders.get(this.model.get('folder_id')).get('title'));
		dialog.find('#feedUrl').val(this.model.get('url'));

		if(this.model.get('pshb_hub') !== '') {
			dialog.find('#feedPSHBInfos').removeClass('hide');
			dialog.find('#feedPSHBHub').text(this.model.get('pshb_hub'));
			dialog.find('#feedPSHBTopic').text(this.model.get('pshb_topic'));
			dialog.find('#feedPSHBExpiration').text(this.model.get('pshb_expiration'));
			dialog.find('#feedUsePSHB').prop('disabled', !this.model.get('pshb_hub'));
			dialog.find('#feedUsePSHB').prop('checked', this.model.get('pshb'));
		}
		else {
			dialog.find('#feedPSHBInfos').addClass('hide');
		}

		dialog.modal().on('shown', function() {
			$('#feedUrl').focus();
		}).on('hidden', function() {
			$('#feedUrl').blur();
		});

		this.closeMenu();
	},

	/**
	 * Open the feed's menu.
	 * @param {eventObject} e
	 * @return {boolean} False if the menu is already open
	 */
	openMenu: function(e) {
		e.stopPropagation();

		var menu = this.$el.find('.feedMenu');
		var opened = !menu.hasClass('hide');

		// Close any opened menu
		$(document).click();

		if(opened) {
			return false;
		}

		menu.removeClass('hide');

		$(document).one('click', this.closeMenu);
	},

	/**
	 * Close the feed's menu.
	 */
	closeMenu: function() {
		var menu = this.$el.find('.feedMenu');
		menu.addClass('hide');
	}
});
<|endoftext|>


<commit_before>/**
 * Author: Vova Zaytsev <zaytsev@usc.edu>
 */

app.controller("NlcdClientController", ["$scope", "$location", "$sce", "NcldApiFactory",
    function ($scope, $location, $sce, NcldApiFactory) {
        /**
        **/

        var graphId = $location.search().g;

        $scope.central              = null;
        $scope.related              = [];
        $scope.meta                 = null;
        $scope.selection            = [];
        $scope.textSelection        = null;
        $scope.display = {

            // Tab 'ALL'
            relatedTabAllReversed:        false,
            relatedTabAllPredicate:       "inSelection",

            // Tab 'SELECTION'
            relatedTabSelectionReversed:  false,
            relatedTabSelectionPredicate: "pubDate",

            // Tab 'SOURCES'
            relatedTabSourcesReversed:    false,
            relatedTabSourcesPredicate:   "referenceCount",

            // Tab 'AUTHORS'
            relatedTabAuthorsReversed:    false,
            relatedTabAuthorsPredicate:   "referenceCount"

        };

        // Init bootstrap javascript
        $("#relatedTabs a").click(function (e) {
            e.preventDefault();
            $(this).tab("show");
        });
        $("#relatedTabs a:first").tab("show");

        // Init tooltipe
        $(".tip-tooltip").tooltip({
            "animation": true,
            "placement": "top",
        });

        $("body").popover({
              "container": "body",
              "trigger": "hover",
              "delay": 1,
              "html": true,
              "placement": "right",
              "selector": ".tip-popover"
        });

        NcldApiFactory.getTestGraph(graphId).success(function(data){

            $scope.sg = new StoryGraph(data);
            $scope.central = $scope.sg.getCentralNode();
            $scope.related = $scope.sg.getNodes();
            $scope.meta = data.meta;

            var distrPlaceId = "storyDistribution";
            var nwPlaceId = "storyNetwork";

            var distrWidth = document.getElementById(distrPlaceId).offsetWidth;
            var nwWidth = document.getElementById(nwPlaceId).offsetWidth;

            console.log(nwWidth);

            var height = 300;

            $scope.sg.drawDistribution(distrPlaceId, distrWidth, height);
            $scope.sg.drawNetwork(nwPlaceId, nwWidth, height);
        });

        //
        $scope.RelatedAllTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabAllPredicate == predicate) {
                $scope.display.relatedTabAllReversed = !$scope.display.relatedTabAllReversed;
            }
            $scope.display.relatedTabAllPredicate = predicate;
        }

        //
        $scope.RelatedSelectionTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabSelectionPredicate == predicate) {
                $scope.display.relatedTabSelectionReversed = !$scope.display.relatedTabSelectionReversed;
            }
            $scope.display.relatedTabSelectionPredicate = predicate;
        }

        //
        $scope.SetSelection = function(referencesList) {
            for (var i in $scope.selection) {
                $scope.selection[i].inSelection = null;
            };
            $scope.selection = [];
            for (var i in referencesList) {
                var refId = referencesList[i];
                var item = $scope.sg.getNode(refId);
                item.inSelection = true;
                $scope.selection.push(item);
            };
            $scope.sg.gfx.SetDistributionSelection(referencesList);
            $scope.sg.gfx.SetNetworkSelection(referencesList);
        };

        //
        $scope.TextSelection = function(chunk, referencesList) {
            if ($scope.textSelection) {
                $scope.textSelection.isSelected = false;
                if ($scope.textSelection.tagId == chunk.tagId) {
                    $scope.textSelection = null;
                    $scope.SetSelection([]);
                    return;
                }
            }
            $scope.textSelection = chunk;
            $scope.textSelection.isSelected = true;
            $scope.SetSelection(referencesList);
        };

        //
        $scope.toolPopoverContent = function(node) {

            var authors = node.authors.join(", ").toTitleCase();
            var source = "";
            var len = 10000;
            for (var i in node.sources) {
                if (node.sources[i].length < len) {
                    source = node.sources[i];
                    len = node.sources[i].length;
                }
            }

            return "

authror: "
                   + authors
                   + "

source: "
                   + source
                   + "

"
                   + String.prototype.CutStr(node.body, true, 256, "...")
                   + "
";
        }

}]);<commit_msg>update contrib data<commit_after>/**
 * Author: Vova Zaytsev <zaytsev@usc.edu>
 */

app.controller("NlcdClientController", ["$scope", "$location", "$sce", "NcldApiFactory",
    function ($scope, $location, $sce, NcldApiFactory) {
        /**
        **/

        var graphId = $location.search().g;

        console.log(graphId);
        console.log($location.search());

        $scope.central              = null;
        $scope.related              = [];
        $scope.meta                 = null;
        $scope.selection            = [];
        $scope.textSelection        = null;
        $scope.display = {

            // Tab 'ALL'
            relatedTabAllReversed:        false,
            relatedTabAllPredicate:       "inSelection",

            // Tab 'SELECTION'
            relatedTabSelectionReversed:  false,
            relatedTabSelectionPredicate: "pubDate",

            // Tab 'SOURCES'
            relatedTabSourcesReversed:    false,
            relatedTabSourcesPredicate:   "referenceCount",

            // Tab 'AUTHORS'
            relatedTabAuthorsReversed:    false,
            relatedTabAuthorsPredicate:   "referenceCount"

        };

        // Init bootstrap javascript
        $("#relatedTabs a").click(function (e) {
            e.preventDefault();
            $(this).tab("show");
        });
        $("#relatedTabs a:first").tab("show");

        // Init tooltipe
        $(".tip-tooltip").tooltip({
            "animation": true,
            "placement": "top",
        });

        $("body").popover({
              "container": "body",
              "trigger": "hover",
              "delay": 1,
              "html": true,
              "placement": "right",
              "selector": ".tip-popover"
        });

        NcldApiFactory.getTestGraph(graphId).success(function(data){

            $scope.sg = new StoryGraph(data);
            $scope.central = $scope.sg.getCentralNode();
            $scope.related = $scope.sg.getNodes();
            $scope.meta = data.meta;

            var distrPlaceId = "storyDistribution";
            var nwPlaceId = "storyNetwork";

            var distrWidth = document.getElementById(distrPlaceId).offsetWidth;
            var nwWidth = document.getElementById(nwPlaceId).offsetWidth;

            console.log(nwWidth);

            var height = 300;

            $scope.sg.drawDistribution(distrPlaceId, distrWidth, height);
            $scope.sg.drawNetwork(nwPlaceId, nwWidth, height);
        });

        //
        $scope.RelatedAllTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabAllPredicate == predicate) {
                $scope.display.relatedTabAllReversed = !$scope.display.relatedTabAllReversed;
            }
            $scope.display.relatedTabAllPredicate = predicate;
        }

        //
        $scope.RelatedSelectionTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabSelectionPredicate == predicate) {
                $scope.display.relatedTabSelectionReversed = !$scope.display.relatedTabSelectionReversed;
            }
            $scope.display.relatedTabSelectionPredicate = predicate;
        }

        //
        $scope.SetSelection = function(referencesList) {
            for (var i in $scope.selection) {
                $scope.selection[i].inSelection = null;
            };
            $scope.selection = [];
            for (var i in referencesList) {
                var refId = referencesList[i];
                var item = $scope.sg.getNode(refId);
                item.inSelection = true;
                $scope.selection.push(item);
            };
            $scope.sg.gfx.SetDistributionSelection(referencesList);
            $scope.sg.gfx.SetNetworkSelection(referencesList);
        };

        //
        $scope.TextSelection = function(chunk, referencesList) {
            if ($scope.textSelection) {
                $scope.textSelection.isSelected = false;
                if ($scope.textSelection.tagId == chunk.tagId) {
                    $scope.textSelection = null;
                    $scope.SetSelection([]);
                    return;
                }
            }
            $scope.textSelection = chunk;
            $scope.textSelection.isSelected = true;
            $scope.SetSelection(referencesList);
        };

        //
        $scope.toolPopoverContent = function(node) {

            var authors = node.authors.join(", ").toTitleCase();
            var source = "";
            var len = 10000;
            for (var i in node.sources) {
                if (node.sources[i].length < len) {
                    source = node.sources[i];
                    len = node.sources[i].length;
                }
            }

            return "

authror: "
                   + authors
                   + "

source: "
                   + source
                   + "

"
                   + String.prototype.CutStr(node.body, true, 256, "...")
                   + "
";
        }

}]);<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, max-len */

// Validates and defaults the options
function validateOptions(options) {
  // Default options to our preferred value
  options.dest = options.dest || 'carte-blanche';
  // HACK: Webpack can embed this regex verbatim and the .? makes it not insert a comment terminator
  options.filter = options.filter || /([A-Z][a-zA-Z]*.?\/index|[A-Z][a-zA-Z]*)\.(jsx?|es6|react\.jsx?)$/;

  // Assert that the componentRoot option was specified
  if (!options.componentRoot) {
    throw new Error(
      'You need to specify where your components are in the "componentRoot" option!\n\n'
    );
  }

  // Assert that the plugins option is an array if specified
  if (options.plugins && !Array.isArray(options.plugins)) {
    throw new Error('The "plugins" option needs to be an array!\n\n');
  }

  // Assert that the files option is an array if specified
  if (options.files && !Array.isArray(options.files)) {
    throw new Error('The "files" option needs to be an array!\n\n');
  }
}

export default validateOptions;
<commit_msg>Make dest '/test' work<commit_after>/* eslint-disable no-param-reassign, max-len */

// Validates and defaults the options
function validateOptions(options) {
  // Default options to our preferred value
  options.dest = options.dest || 'carte-blanche';
  // Remove a prefixed slash from the dest option, i.e. /test/ -> test/
  options.dest = options.dest.replace(/^\/|\\/gi, '');
  // HACK: Webpack can embed this regex verbatim and the .? makes it not insert a comment terminator
  options.filter = options.filter || /([A-Z][a-zA-Z]*.?\/index|[A-Z][a-zA-Z]*)\.(jsx?|es6|react\.jsx?)$/;

  // Assert that the componentRoot option was specified
  if (!options.componentRoot) {
    throw new Error(
      'You need to specify where your components are in the "componentRoot" option!\n\n'
    );
  }

  // Assert that the plugins option is an array if specified
  if (options.plugins && !Array.isArray(options.plugins)) {
    throw new Error('The "plugins" option needs to be an array!\n\n');
  }

  // Assert that the files option is an array if specified
  if (options.files && !Array.isArray(options.files)) {
    throw new Error('The "files" option needs to be an array!\n\n');
  }
}

export default validateOptions;
<|endoftext|>


<commit_before>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserPublications
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserPublications
  * #@extends Ext.Panel
  * Shows a user's publications
  *
  */

Ext.namespace( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserPublications = Ext.extend(Ext.Panel, {
    title: 'Papers'
    ,autoHeight: true
    ,preventBodyReset: true
    ,initComponent: function(){
        Ext.apply(this, this.initialConfig);

        this.store = new Ext.data.JsonStore({
            proxy : new Ext.data.HttpProxy({
                method: 'GET',
                url: 'fbk/publiks/listpubsbylogin'
            }),
            root: 'pubs',
            fields: ['ID_PRODOTTO', 'TITOLO', 'TITOLO_UFFICIALE', 'TITOLO_LIBRO', 'AUTORE_LIBRO', 'STRINGA_AUTORI', 'ANNO', 'MESE', 'NUM_AUTORI', 'COGNOME_AUTORE', 'NOME_AUTORE', 'NUM_PAGINE', 'PAG_INIZIO', 'PAG_FINE', 'TITOLO_CONVEGNO', 'PERIODO_CONVEGNO', 'VOLUME']
            ,listeners: {
                beforeload: function(){
                    if (!this.parent.rendered) return;
                    var su = westPanel.showedUser
                        ,user_id = su.id
                        ,user_name = su.name
                        ,user_surname = su.surname
                        ,user_email = get(su, 'email', su.login+'@fbk');

                    var emptytext = '

No publications for this user

You might suggest '+user_name+' to add publications using FBK publik repository.

But did you remember to add your publications at the website http://www.itc.it/publik/ ?
';

                    this.parent.items.first().emptyText = emptytext;
                }
                ,load: function(){
                    this.parent.setTitle(
                        this.parent.prevTitle+' ('+this.totalLength+')'
                    );
                }
            }
            ,parent: this
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.initComponent.apply(this, arguments);

        //save title to use it later (on load)
        this.prevTitle = this.title;
    }
    ,onRender: function(){
        var tpl = new Ext.XTemplate(
            '
',
                '
',
                '<tpl for=".">',
                    // Lists found publications. Eac publik has a link to FBK paper repository
                    '
',
                        '
',
                            '
{STRINGA_AUTORI},
',
                            '
{TITOLO}
',
                            '<tpl if="TITOLO_UFFICIALE">
, in «{TITOLO_UFFICIALE}»
</tpl>',
                            '<tpl if="TITOLO_LIBRO && AUTORE_LIBRO">
, in {AUTORE_LIBRO}, {TITOLO_LIBRO}
</tpl>',
                            '<tpl if="VOLUME">
, vol. {VOLUME}
</tpl>',
                            '<tpl if="ANNO">
, {ANNO}
</tpl>',
                            '<tpl if="PAG_INIZIO && PAG_FINE">
, pp {PAG_INIZIO}-{PAG_FINE}
</tpl>',
                            '<tpl if="TITOLO_CONVEGNO">
 ({TITOLO_CONVEGNO}',
                                '<tpl if="PERIODO_CONVEGNO">
 {PERIODO_CONVEGNO}
</tpl>',
                            ')
</tpl>',
                        '
',
                    '
',
                '</tpl>',
                '
',
            '
'
            ,{
                months: new Array("January","February","March","April","May","June","July","August","September","October","November","December")
                ,pdate: function(m, y){
                    var month = get(this.months, m, '');
                    return month + ' ' + y;
                }
            }
        );
        tpl.compile();

        var dv = new Ext.DataView({
            tpl: tpl,
            store: this.store,
            itemSelector: 'div.publik-wrapper',
            deferEmptyText:false
        });

        this.add(dv);

        this.store.load({
            params: {
                u_id: westPanel.showedUser.id
                //,login: westPanel.showedUser.login
            }
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.onRender.apply(
            this, arguments
        );
    }
});

Ext.reg('userpublications', Ext.ux.fbk.sonet.UserPublications);
<commit_msg>Correcting wrong link<commit_after>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserPublications
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserPublications
  * #@extends Ext.Panel
  * Shows a user's publications
  *
  */

Ext.namespace( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserPublications = Ext.extend(Ext.Panel, {
    title: 'Papers'
    ,autoHeight: true
    ,preventBodyReset: true
    ,initComponent: function(){
        Ext.apply(this, this.initialConfig);

        this.store = new Ext.data.JsonStore({
            proxy : new Ext.data.HttpProxy({
                method: 'GET',
                url: 'fbk/publiks/listpubsbylogin'
            }),
            root: 'pubs',
            fields: ['ID_PRODOTTO', 'TITOLO', 'TITOLO_UFFICIALE', 'TITOLO_LIBRO', 'AUTORE_LIBRO', 'STRINGA_AUTORI', 'ANNO', 'MESE', 'NUM_AUTORI', 'COGNOME_AUTORE', 'NOME_AUTORE', 'NUM_PAGINE', 'PAG_INIZIO', 'PAG_FINE', 'TITOLO_CONVEGNO', 'PERIODO_CONVEGNO', 'VOLUME']
            ,listeners: {
                beforeload: function(){
                    if (!this.parent.rendered) return;
                    var su = westPanel.showedUser
                        ,user_id = su.id
                        ,user_name = su.name
                        ,user_surname = su.surname
                        ,user_email = get(su, 'email', su.login+'@fbk');

                    var emptytext = '

No publications for this user

You might suggest '+user_name+' to add publications using FBK publik repository.

But did you remember to add your publications at the website http://u-gov.fbk.eu/ ?
';

                    this.parent.items.first().emptyText = emptytext;
                }
                ,load: function(){
                    this.parent.setTitle(
                        this.parent.prevTitle+' ('+this.totalLength+')'
                    );
                }
            }
            ,parent: this
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.initComponent.apply(this, arguments);

        //save title to use it later (on load)
        this.prevTitle = this.title;
    }
    ,onRender: function(){
        var tpl = new Ext.XTemplate(
            '
',
                '
',
                '<tpl for=".">',
                    // Lists found publications. Eac publik has a link to FBK paper repository
                    '
',
                        '
',
                            '
{STRINGA_AUTORI},
',
                            '
{TITOLO}
',
                            '<tpl if="TITOLO_UFFICIALE">
, in «{TITOLO_UFFICIALE}»
</tpl>',
                            '<tpl if="TITOLO_LIBRO && AUTORE_LIBRO">
, in {AUTORE_LIBRO}, {TITOLO_LIBRO}
</tpl>',
                            '<tpl if="VOLUME">
, vol. {VOLUME}
</tpl>',
                            '<tpl if="ANNO">
, {ANNO}
</tpl>',
                            '<tpl if="PAG_INIZIO && PAG_FINE">
, pp {PAG_INIZIO}-{PAG_FINE}
</tpl>',
                            '<tpl if="TITOLO_CONVEGNO">
 ({TITOLO_CONVEGNO}',
                                '<tpl if="PERIODO_CONVEGNO">
 {PERIODO_CONVEGNO}
</tpl>',
                            ')
</tpl>',
                        '
',
                    '
',
                '</tpl>',
                '
',
            '
'
            ,{
                months: new Array("January","February","March","April","May","June","July","August","September","October","November","December")
                ,pdate: function(m, y){
                    var month = get(this.months, m, '');
                    return month + ' ' + y;
                }
            }
        );
        tpl.compile();

        var dv = new Ext.DataView({
            tpl: tpl,
            store: this.store,
            itemSelector: 'div.publik-wrapper',
            deferEmptyText:false
        });

        this.add(dv);

        this.store.load({
            params: {
                u_id: westPanel.showedUser.id
                //,login: westPanel.showedUser.login
            }
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.onRender.apply(
            this, arguments
        );
    }
});

Ext.reg('userpublications', Ext.ux.fbk.sonet.UserPublications);
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';

const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config.js')[env];

const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(
    config.database, config.username, config.password, config
  );
}

fs
  .readdirSync(__dirname)
  .filter(file =>
    (file.indexOf('.') !== 0) &&
    (file !== basename) &&
    (file.slice(-3) === '.js'))
  .forEach((file) => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;
<commit_msg>sequelize config<commit_after>import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';

const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config.js')[env];

const db = {};

let sequelize;
if (process.env.DATABASE_URL) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(
    config.database, config.username, config.password, config
  );
}

fs
  .readdirSync(__dirname)
  .filter(file =>
    (file.indexOf('.') !== 0) &&
    (file !== basename) &&
    (file.slice(-3) === '.js'))
  .forEach((file) => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;
<|endoftext|>


<commit_before>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserPublications
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserPublications
  * #@extends Ext.Panel
  * Shows a user's publications
  *
  */

Ext.namespace( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserPublications = Ext.extend(Ext.Panel, {
    title: 'Papers'
    ,autoHeight: true
    ,initComponent: function(){
        var config = {
        };
        Ext.apply(this, Ext.apply(this.initialConfig, config));

        this.store = new Ext.data.JsonStore({
            url: 'publiks/listpubsbylogin',
            root: 'pubs',
            fields: ['ID', 'INS_DATE', 'MOD_DATE', 'Title', 'PTitle', 'Pub_Type', 'PUBTIME_YEAR', 'Relevance']
            ,listeners: {
                beforeload: function(){
                    if (!this.parent.rendered) return;

                    var user_id = westPanel.showedUser.id;
                    var user_name = westPanel.showedUser.name;
                    var user_surname = westPanel.showedUser.surname;
                    var user_email = westPanel.showedUser.email ? westPanel.showedUser.email : westPanel.showedUser.login+'@fbk';

                    var emptytext = '

No publications for this user

You might suggest '+user_name+' to add publications using FBK publik repository.

But did you remember to add your publication at http://www.itc.it/publik/ ?
';

                    this.parent.items.first().emptyText = emptytext;
                }
                ,load: function(){
                    this.parent.setTitle(
                        this.parent.prevTitle+' ('+this.totalLength+')'
                    );
                }
            }
            ,parent: this
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.initComponent.apply(this, arguments);

        //save title to use it later (on load)
        this.prevTitle = this.title;
    }
    ,onRender: function(){
        var tpl = new Ext.XTemplate(
            '
',
            '<tpl for=".">',
                // Lists found publications. Eac publik has a link to FBK paper repository
                '
{PTitle}
{Title}

',
            '</tpl>',
            '
'
        );
        tpl.compile();

        var dv = new Ext.DataView({
            tpl: tpl,
            store: this.store,
            itemSelector: 'div.publik-wrapper',
            deferEmptyText:false
        });

        this.add(dv);

        this.store.load({
            params: {
                login: westPanel.showedUser.login
            }
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.onRender.apply(
            this, arguments
        );
    }
});
Ext.reg('userpublications', Ext.ux.fbk.sonet.UserPublications);
<commit_msg>Adding more text to the Publications tab in the user profile<commit_after>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserPublications
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserPublications
  * #@extends Ext.Panel
  * Shows a user's publications
  *
  */

Ext.namespace( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserPublications = Ext.extend(Ext.Panel, {
    title: 'Papers'
    ,autoHeight: true
    ,initComponent: function(){
        var config = {
        };
        Ext.apply(this, Ext.apply(this.initialConfig, config));

        this.store = new Ext.data.JsonStore({
            url: 'publiks/listpubsbylogin',
            root: 'pubs',
            fields: ['ID', 'INS_DATE', 'MOD_DATE', 'Title', 'PTitle', 'Pub_Type', 'PUBTIME_YEAR', 'Relevance']
            ,listeners: {
                beforeload: function(){
                    if (!this.parent.rendered) return;

                    var user_id = westPanel.showedUser.id;
                    var user_name = westPanel.showedUser.name;
                    var user_surname = westPanel.showedUser.surname;
                    var user_email = westPanel.showedUser.email ? westPanel.showedUser.email : westPanel.showedUser.login+'@fbk';

                    var emptytext = '

No publications for this user

You might suggest '+user_name+' to add publications using FBK publik repository.

But did you remember to add your publications at the website http://www.itc.it/publik/ ?
';

                    this.parent.items.first().emptyText = emptytext;
                }
                ,load: function(){
                    this.parent.setTitle(
                        this.parent.prevTitle+' ('+this.totalLength+')'
                    );
                }
            }
            ,parent: this
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.initComponent.apply(this, arguments);

        //save title to use it later (on load)
        this.prevTitle = this.title;
    }
    ,onRender: function(){
        var tpl = new Ext.XTemplate(
            '
',
            '<tpl for=".">',
                // Lists found publications. Eac publik has a link to FBK paper repository
                '
{PTitle}
{Title}

',
            '</tpl>',
            '
'
        );
        tpl.compile();

        var dv = new Ext.DataView({
            tpl: tpl,
            store: this.store,
            itemSelector: 'div.publik-wrapper',
            deferEmptyText:false
        });

        this.add(dv);

        this.store.load({
            params: {
                login: westPanel.showedUser.login
            }
        });

        Ext.ux.fbk.sonet.UserPublications.superclass.onRender.apply(
            this, arguments
        );
    }
});
Ext.reg('userpublications', Ext.ux.fbk.sonet.UserPublications);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var pg = require('pg');
var knex = require('knex');
var queries = require("../../../queries");

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<commit_msg>added routes to index.js for index, register, login, cultures, cultures:id, public/user/id<commit_after>var express = require('express');
var router = express.Router();
var pg = require('pg');
var knex = require('knex');
var queries = require("../../../queries");

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/register', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/login', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/cultures', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/cultures/:id', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/public/user/:id', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
<|endoftext|>


<commit_before>// http://docs.travis-ci.com/user/notifications/#Webhook-notification

var bot = require('../bot');
var config = require('../config');
var crypto = require('crypto');
var util = require('util');

var isValidRequest = function (headers) {
  var digest = crypto.createHash('sha256').update(headers['travis-repo-slug'] + config.travisUserToken).digest('hex');
  return digest === headers['authorization'];
};

var getChatMessageText = function (payload) {
  var commit_details;
  if (payload.type === 'pull_request') {
    commit_details = util.format('pull-request #%d : %s', payload.pull_request_number, payload.author_name);
  } else {
    commit_details = util.format('%s - %s : %s', payload.branch, payload.commit, payload.author_name);
  }
  return util.format('Travis CI - %s - build #%d (%s): %s.\nBuild url: %s',
    payload.repository.name, payload.number, commit_details, payload.status_message, payload.build_url);
};

module.exports = function (registerRoute) {
  registerRoute('post', '/travisci', function (headers, requestBody) {
    var payload;
    if (!(typeof headers === 'object' && headers && typeof requestBody === 'object' && requestBody)) {
      return;
    }

    if (!isValidRequest(headers)) {
      console.log('Invalid payload request for repository', headers['travis-repo-slug']);
      return;
    }

    try {
      payload = JSON.parse(requestBody.payload);
    } catch (e) {
      console.log('Travis hook error while parsing JSON:', e);
      console.log('Travis CI notification hook request body:', requestBody);
      return;
    }
    if (!payload) {
      return;
    }

    bot.postMessageWithGroupLocalID('1', getChatMessageText(payload));
  });
};
<commit_msg>Update Travis CI status message<commit_after>// http://docs.travis-ci.com/user/notifications/#Webhook-notification

var bot = require('../bot');
var config = require('../config');
var crypto = require('crypto');
var util = require('util');

var isValidRequest = function (headers) {
  var digest = crypto.createHash('sha256').update(headers['travis-repo-slug'] + config.travisUserToken).digest('hex');
  return digest === headers['authorization'];
};

var getChatMessageText = function (payload) {
  var commit_details;
  if (payload.type === 'pull_request') {
    commit_details = util.format('pull-request #%d by %s', payload.pull_request_number, payload.author_name);
  } else {
    commit_details = util.format('commit to %s by %s', payload.branch, payload.author_name);
  }
  return util.format('Travis CI - %s - build #%d (%s): %s.\nBuild url: %s',
    payload.repository.name, payload.number, commit_details, payload.status_message, payload.build_url);
};

module.exports = function (registerRoute) {
  registerRoute('post', '/travisci', function (headers, requestBody) {
    var payload;
    if (!(typeof headers === 'object' && headers && typeof requestBody === 'object' && requestBody)) {
      return;
    }

    if (!isValidRequest(headers)) {
      console.log('Invalid payload request for repository', headers['travis-repo-slug']);
      return;
    }

    try {
      payload = JSON.parse(requestBody.payload);
    } catch (e) {
      console.log('Travis hook error while parsing JSON:', e);
      console.log('Travis CI notification hook request body:', requestBody);
      return;
    }
    if (!payload) {
      return;
    }

    bot.postMessageWithGroupLocalID('1', getChatMessageText(payload));
  });
};
<|endoftext|>


<commit_before>// @flow
import React, {PropTypes as t, Component} from 'react';
import {Dropdown} from 'bootstrap.native';

type BtnKindType =
  | 'danger'
  | 'default'
  | 'info'
  | 'link'
  | 'primary'
  | 'success';

type BtnLinkType = {
  className?: string,
  onClick: () => any,
  separator: boolean,
  text?: string
};

/* eslint-disable react/no-unused-prop-types */
type BtnType = {
  disabled: boolean,
  kind: BtnKindType,
  btnText: string
};
/* eslint-enable react/no-unused-prop-types */

type PropsType = {btn: BtnType, links: Array<BtnLinkType>};

class DropupBtn extends Component {
  top = {};
  toggleElement = () => {
    const dropdown = document.querySelector('.dropdown-toggle');
    // this was done to support testing because we cannot query the dom from a
    // test
    if (dropdown) {
      new Dropdown(dropdown).toggle();
    } else {
      this.top.className += ' open';
    }
  };

  render() {
    const {btn, links}: PropsType = this.props;
    return (

 this.top = top}>
        <button
          className={`btn btn-${btn.kind} dropdown-toggle`}
          disabled={btn.disabled}
          onClick={this.toggleElement}
          type="button"
        >
          {btn.btnText + ' '}

          Toggle Dropdown
        </button>

          {links.map(l => (

              {l.text}

          ))}

    );
  }
}

DropupBtn.propTypes = {
  btn: t.shape({
    kind: t.oneOf([
      'danger',
      'default',
      'info',
      'link',
      'primary',
      'success',
    ]).isRequired,
    btnText: t.string.isRequired,
    disabled: t.bool.isRequired,
  }),
  links: t.arrayOf(
    t.shape({
      className: t.string,
      onClick: t.func.isRequired,
      separator: t.bool.isRequired,
      text: t.string,
    }).isRequired,
  ),
};

export default DropupBtn;
<commit_msg>(DropupBtn) change classNames to project convention<commit_after>// @flow
import React, {PropTypes as t, Component} from 'react';
import {Dropdown} from 'bootstrap.native';

type BtnKindType =
  | 'danger'
  | 'default'
  | 'info'
  | 'link'
  | 'primary'
  | 'success';

type BtnLinkType = {
  className?: string,
  onClick: () => any,
  separator: boolean,
  text?: string
};

/* eslint-disable react/no-unused-prop-types */
type BtnType = {
  disabled: boolean,
  kind: BtnKindType,
  btnText: string
};
/* eslint-enable react/no-unused-prop-types */

type PropsType = {btn: BtnType, links: Array<BtnLinkType>};

class DropupBtn extends Component {
  top = {};
  toggleElement = () => {
    const dropdown = document.querySelector('.dropdown-toggle');
    // this was done to support testing because we cannot query the dom from a
    // test
    if (dropdown) {
      new Dropdown(dropdown).toggle();
    } else {
      this.top.className += ' open';
    }
  };

  render() {
    const {btn, links}: PropsType = this.props;
    return (

 this.top = top}
      >
        <button
          className={`btn btn-${btn.kind} dropdown-toggle`}
          disabled={btn.disabled}
          onClick={this.toggleElement}
          type="button"
        >
          {btn.btnText + ' '}

          Toggle Dropdown
        </button>

          {links.map(l => (

              {l.text}

          ))}

    );
  }
}

DropupBtn.propTypes = {
  btn: t.shape({
    kind: t.oneOf([
      'danger',
      'default',
      'info',
      'link',
      'primary',
      'success',
    ]).isRequired,
    btnText: t.string.isRequired,
    disabled: t.bool.isRequired,
  }),
  links: t.arrayOf(
    t.shape({
      className: t.string,
      onClick: t.func.isRequired,
      separator: t.bool.isRequired,
      text: t.string,
    }).isRequired,
  ),
};

export default DropupBtn;
<|endoftext|>


<commit_before>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    var util = ch.util,

        /**
         * Global instantiation widget id.
         * @private
         * @type {Number}
         */
        uid = 0;

    /**
     * Represents the abstract class of all widgets.
     * @abstract
     * @name Widget
     * @class Widget
     * @memberOf ch
     */
    function Widget($el, options) {
        this.init($el, options);

        return this;
    }

    ch.util.inherits(Widget, ch.EventEmitter);

    Widget.prototype.name = 'widget';
    Widget.prototype.constructor = Widget;

    /**
     * Initialize the instance and merges the user options with defaults options.
     * @public
     * @function
     * @name ch.Widget#init
     */
    Widget.prototype.init = function ($el, options) {

        // Clones defaults or creates a defaults object
        var defaults = (this._defaults) ? util.clone(this._defaults) : {};

        // Clones the defaults options or creates a new object
        if (options === undefined) {
            if ($el === undefined) {
                this._options = defaults;

            } else if (util.is$($el)) {
                this._$el = $el;
                this._el = $el[0];
                this._options = defaults;

            } else if (typeof $el === 'object') {
                options = $el;
                $el = undefined;
                this._options = $.extend(defaults, options);
            }

        } else if (typeof options === 'object') {
            if ($el === undefined) {
                this._options = $.extend(defaults, options);

            } else if (util.is$($el)) {
                this._$el = $el;
                this._el = $el[0];
                this._options = $.extend(defaults, options);
            }

        } else {
            throw new window.Error('Unexpected parameters were found in the component instantiation.');
        }

        this.uid = (uid += 1);

        this._enabled = true;
    };

    /**
     * Adds functionality or abilities from other classes.
     * @public
     * @function
     * @name ch.Widget#require
     */
    Widget.prototype.require = function () {

        var that = this;

        $.each(arguments, function (i, arg) {
            if (that[arg.toLowerCase()] === undefined) {
                ch[arg].call(that);
            }
        });
    };

    /**
     * Turn on the Widget.
     * @public
     * @name ch.Widget#enable
     * @function
     * @returns itself
     */
    Widget.prototype.enable = function () {
        this._enabled = true;

        /**
         * Triggers when the widget is enable.
         * @name ch.Widget#enable
         * @event
         * @public
         * @exampleDescription
         * @example
         * widget.on("enable", function(){
         *  // Some code here!
         * });
         */
        this.emit('enable');

        return this;
    };

    /**
     * Turn off the Widget.
     * @public
     * @name ch.Widget#disable
     * @function
     * @returns itself
     */
    Widget.prototype.disable = function () {
        this._enabled = false;

        /**
         * Triggers when the widget is disable.
         * @name ch.Widget#disable
         * @event
         * @public
         * @exampleDescription
         * @example
         * widget.on("disable", function(){
         *  // Some code here!
         * });
         */
        this.emit('disable');

        return this;
    };

    /**
     * Destroys a widget instance and remove data from its element.
     * @public
     * @function
     * @name ch.Widget#destroy
     */
    Widget.prototype.destroy = function () {

        this.disable();

        if (this._el !== undefined) {
            this._$el.removeData(this.name);
        }

        this.emit('destroy');
    };

    ch.Widget = Widget;

}(this, this.ch.$, this.ch));<commit_msg>Updated the error message of Widget.init.<commit_after>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    var util = ch.util,

        /**
         * Global instantiation widget id.
         * @private
         * @type {Number}
         */
        uid = 0;

    /**
     * Represents the abstract class of all widgets.
     * @abstract
     * @name Widget
     * @class Widget
     * @memberOf ch
     */
    function Widget($el, options) {
        this.init($el, options);

        return this;
    }

    ch.util.inherits(Widget, ch.EventEmitter);

    Widget.prototype.name = 'widget';
    Widget.prototype.constructor = Widget;

    /**
     * Initialize the instance and merges the user options with defaults options.
     * @public
     * @function
     * @name ch.Widget#init
     */
    Widget.prototype.init = function ($el, options) {

        // Clones defaults or creates a defaults object
        var defaults = (this._defaults) ? util.clone(this._defaults) : {};

        // Clones the defaults options or creates a new object
        if (options === undefined) {
            if ($el === undefined) {
                this._options = defaults;

            } else if (util.is$($el)) {
                this._$el = $el;
                this._el = $el[0];
                this._options = defaults;

            } else if (typeof $el === 'object') {
                options = $el;
                $el = undefined;
                this._options = $.extend(defaults, options);
            }

        } else if (typeof options === 'object') {
            if ($el === undefined) {
                this._options = $.extend(defaults, options);

            } else if (util.is$($el)) {
                this._$el = $el;
                this._el = $el[0];
                this._options = $.extend(defaults, options);
            }

        } else {
            throw new window.Error('Unexpected parameters were found in the \'' + this.name + '\' instantiation.');
        }

        this.uid = (uid += 1);

        this._enabled = true;
    };

    /**
     * Adds functionality or abilities from other classes.
     * @public
     * @function
     * @name ch.Widget#require
     */
    Widget.prototype.require = function () {

        var that = this;

        $.each(arguments, function (i, arg) {
            if (that[arg.toLowerCase()] === undefined) {
                ch[arg].call(that);
            }
        });
    };

    /**
     * Turn on the Widget.
     * @public
     * @name ch.Widget#enable
     * @function
     * @returns itself
     */
    Widget.prototype.enable = function () {
        this._enabled = true;

        /**
         * Triggers when the widget is enable.
         * @name ch.Widget#enable
         * @event
         * @public
         * @exampleDescription
         * @example
         * widget.on("enable", function(){
         *  // Some code here!
         * });
         */
        this.emit('enable');

        return this;
    };

    /**
     * Turn off the Widget.
     * @public
     * @name ch.Widget#disable
     * @function
     * @returns itself
     */
    Widget.prototype.disable = function () {
        this._enabled = false;

        /**
         * Triggers when the widget is disable.
         * @name ch.Widget#disable
         * @event
         * @public
         * @exampleDescription
         * @example
         * widget.on("disable", function(){
         *  // Some code here!
         * });
         */
        this.emit('disable');

        return this;
    };

    /**
     * Destroys a widget instance and remove data from its element.
     * @public
     * @function
     * @name ch.Widget#destroy
     */
    Widget.prototype.destroy = function () {

        this.disable();

        if (this._el !== undefined) {
            this._$el.removeData(this.name);
        }

        this.emit('destroy');
    };

    ch.Widget = Widget;

}(this, this.ch.$, this.ch));<|endoftext|>


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

  function ready () {
    $.removeNodes('iframe, #adblock_detect, .popupOverlay');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      _.wait(500).then(function () {
        node.removeAttribute('disabled');
        return _.wait(500);
      }).then(function () {
        // tricky hack, some sites can not receive the click event without focus
        node.focus();
        node.click();
        node.click();
      });
      return;
    }

    // second pass
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa|horse)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(icy|next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz|binbou|2share|22|cover|hit|main|trial)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.img(blow|lemon|4sharing)\.com$/,
          /^www\.imagefolks\.com$/,
          // starts with xxx
          /^xxx(\.pornprimehd|imagenow|screens)\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|lexiit|thumbnailus|newimagepost|fapingpics|dimtus|tinizo)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nim(plus|zshare)\.com$/,
          /^nudeximg\.com$/,
          /imgseeds?\.com$/,
          /xxxsparrow?\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom|project|python|pics)\.net$/,
          /^(naughtygate|gallerycloud|imagelaser|picture-bang|project-photo|pix-link|funimg|golfpit|xximg)\.net$/,
          // org
          /^(shot|adult)img\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^img(cloud|mag)\.co$/,
          /^pixup\.us$/,
          /^(bulkimg|photo-up|myimg|pop-img|img-pop|ads-img)\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload|fapat)\.me$/,
          /^(pic2pic|porno-pirat|24avarii|loftlm|18pron|imgplus)\.ru$/,
          /^www\.hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
          /^pic2pic\.site$/,
          /^darpix\.ga$/,
          /^sxpics\.nl$/,
          /^darpix\.desi$/,
          /^pic4you\.top$/,
          /^imgsen\.se$/,
        ],
        path: /^\/img-.*\.html/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
        ],
        path: /^\/t\/img-.*\.html/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.html/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
      {
        host: /^cdn\.javtotal\.com$/,
        path: /^\/img\/.+$/,
      },
    ],
    ready: ready,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult|wallet)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img3-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img-.*\.html/,
      },
    ],
    ready: function () {
      var url = $.window.linkid;
      $.openImage(url);
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img4-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img2-.*\.html/,
      },
    ],
    ready: ready,
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>imgblank.com<commit_after>(function () {
  'use strict';

  function ready () {
    $.removeNodes('iframe, #adblock_detect, .popupOverlay');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      _.wait(500).then(function () {
        node.removeAttribute('disabled');
        return _.wait(500);
      }).then(function () {
        // tricky hack, some sites can not receive the click event without focus
        node.focus();
        node.click();
        node.click();
      });
      return;
    }

    // second pass
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          // com
          // starts with image
          /^image(ontime|corn|picsa|horse)\.com$/,
          // ends with image
          /^(zonezeed|zelje|croft|myhot|bok|hostur|greasy)image\.com$/,
          // starts with img
          /^img(icy|next|savvy|\.spicyzilla|twyti|xyz|devil|tzar|ban|pu|beer|wet|tornado|kicks|-pay|nimz|binbou|2share|22|cover|hit|main|trial|blank)\.com$/,
          // starts with img-
          /^img-(zone|planet)\.com$/,
          // starts with www
          /^www\.img(blow|lemon|4sharing)\.com$/,
          /^www\.imagefolks\.com$/,
          // starts with xxx
          /^xxx(\.pornprimehd|imagenow|screens)\.com$/,
          // else
          /^(picstwist|ericsony|wpc8|uplimg|lexiit|thumbnailus|newimagepost|fapingpics|dimtus|tinizo)\.com$/,
          /^((i|hentai)\.)?imgslip\.com$/,
          /^(i|xxx)\.hentaiyoutube\.com$/,
          /^(go|er)imge\.com$/,
          /^(like\.)?08lkk\.com$/,
          /^(www\.)?\.imgult\.com$/,
          /^nim(plus|zshare)\.com$/,
          /^nudeximg\.com$/,
          /imgseeds?\.com$/,
          /xxxsparrow?\.com$/,
          /damimage\.com$/,
          /imagedecode\.com$/,
          // net
          /^img(serve|coin|fap|candy|master|-view|run|boom|project|python|pics)\.net$/,
          /^(naughtygate|gallerycloud|imagelaser|picture-bang|project-photo|pix-link|funimg|golfpit|xximg)\.net$/,
          // org
          /^(shot|adult)img\.org$/,
          /^img(studio|spot)\.org$/,
          /^image(\.adlock|on|team)\.org$/,
          /^(drag|teen|mega)image\.org$/,
          /^teenshot\.org$/,
          // else
          /^(hotimages|55888)\.eu$/,
          /^img(cloud|mag)\.co$/,
          /^pixup\.us$/,
          /^(bulkimg|photo-up|myimg|pop-img|img-pop|ads-img)\.info$/,
          /^img\.yt$/,
          /^vava\.in$/,
          /^(pixxx|picspornfree|imgload|fapat)\.me$/,
          /^(pic2pic|porno-pirat|24avarii|loftlm|18pron|imgplus)\.ru$/,
          /^www\.hotimage\.uk$/,
          /^imgease\.re$/,
          /^goimg\.xyz$/,
          /^pic2pic\.site$/,
          /^darpix\.ga$/,
          /^sxpics\.nl$/,
          /^darpix\.desi$/,
          /^pic4you\.top$/,
          /^imgsen\.se$/,
        ],
        path: /^\/img-.*\.html/,
      },
      {
        host: [
          /^img(run|twyti)\.net$/,
          /^imgtwyti\.com$/,
        ],
        path: /^\/t\/img-.*\.html/,
      },
      {
        host: /^imgking\.co$/,
        path: /^\/img-.*\.html/,
      },
      {
        host: /^imgbb\.net$/,
        path: /^\/.-.+$/,
      },
      {
        host: /^cdn\.javtotal\.com$/,
        path: /^\/img\/.+$/,
      },
    ],
    ready: ready,
  });

  // TODO need to refactor the cookie rule
  $.register({
    rule: {
      host: [
        /^www\.img(taxi|adult|wallet)\.com$/,
        /^www\.imgdrive\.net$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('img_c_d') || $.getCookie('img_p_d');
      if (c) {
        return;
      }
      $.post(window.location.href.toString(), {
        cti: 1,
        ref: '',
        rc: 1,
      }).then(function (data) {
        window.location.reload();
      });
    },
    ready: function () {
      $.removeNodes('iframe');

      var node = $.$('#continuetoimage > form input');
      if (node) {
        // first pass
        node.click();
        // somehow imgrun.net need to click twice
        node.click();
        return;
      }

      // the cookies are shared in the whole domain
      // we have to reset cookies to prevent wrong state
      $.resetCookies();

      // second pass
      var i = $('img[class^=centred]');
      $.openImage(i.src);
    },
  });

  function helper () {
    // crack the shitty qqc.co visitScript 5440
    $.window.setTimeout = _.nop;

    // this site checks cookie that caculate from session
    // do an AJAX to skip checking
    return $.get(window.location.toString()).then(function (data) {
      return $.toDOM(data);
    });
  }

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var i = $('img[class^=centred]', page);
        $.openImage(i.src);
      });
    },
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      helper().then(function (page) {
        var bbcode = $.$('#imagecodes input', page);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img3-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img-.*\.html/,
      },
    ],
    ready: function () {
      var url = $.window.linkid;
      $.openImage(url);
    },
  });

  $.register({
    rule: [
      {
        host: /^imgking\.co$/,
        path: /^\/img4-.*\.html/,
      },
      {
        host: /^imgkings\.com$/,
        path: /^\/img2-.*\.html/,
      },
    ],
    ready: ready,
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

/**
 * @class easyXDM.stack.HashTransport
 * HashTransport is a transport class that uses the IFrame URL Technique for communication.

 * http://msdn.microsoft.com/en-us/library/bb735305.aspx

 * @extends easyXDM.stack.TransportStackElement
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} config The transports configuration.
 * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
 * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
 * @cfg {Number} interval The interval used when polling for messages.
 */
easyXDM.stack.HashTransport = function(config){
    // #ifdef debug
    var trace = easyXDM.Debug.getTracer("easyXDM.stack.HashTransport");
    trace("constructor");
    // #endif
    var pub;
    var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
    var usePolling, useParent, useResize, _remoteOrigin;

    function _sendMessage(message){
        // #ifdef debug
        trace("sending message '" + (_msgNr + 1) + " " + message + "' to " + _remoteOrigin);
        // #endif
        if (!_callerWindow) {
            // #ifdef debug
            trace("no caller window");
            // #endif
            return;
        }
        var url = config.remote + "#" + (_msgNr++) + "_" + message;

        if (isHost || !useParent) {
            // We are referencing an iframe
            _callerWindow.contentWindow.location = url;
            if (useResize) {
                // #ifdef debug
                trace("resizing to new size " + (_callerWindow.width > 75 ? 50 : 100));
                // #endif
                _callerWindow.width = _callerWindow.width > 75 ? 50 : 100;
            }
        }
        else {
            // We are referencing the parent window
            _callerWindow.location = url;
        }
    }

    function _handleHash(hash){
        _lastMsg = hash;
        // #ifdef debug
        trace("received message '" + _lastMsg + "' from " + _remoteOrigin);
        // #endif
        pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
    }

    function _onResize(e){
        // #ifdef debug
        trace("onresize: new message");
        // #endif
        _handleHash(_listenerWindow.location.hash);
    }

    /**
     * Checks location.hash for a new message and relays this to the receiver.
     * @private
     */
    function _pollHash(){
        if (_listenerWindow.location.hash && _listenerWindow.location.hash != _lastMsg) {
            // #ifdef debug
            trace("poll: new message");
            // #endif
            _handleHash(_listenerWindow.location.hash);
        }
    }

    function _attachListeners(){
        if (usePolling) {
            // #ifdef debug
            trace("starting polling");
            // #endif
            _timer = window.setInterval(_pollHash, pollInterval);
        }
        else {
            easyXDM.DomHelper.on(_listenerWindow, "resize", _onResize);
        }
    }

    return (pub = {
        outgoing: function(message, domain){
            _sendMessage(encodeURIComponent(message));
        },
        destroy: function(){
            if (usePolling) {
                window.clearInterval(_timer);
            }
            else if (_listenerWindow) {
                easyXDM.DomHelper.un(_listenerWindow, "resize", _pollHash);
            }
            if (isHost || !useParent) {
                _callerWindow.parentNode.removeChild(_callerWindow);
            }
            _callerWindow = null;
        },
        init: function(){
            isHost = config.isHost;
            pollInterval = config.interval;
            _lastMsg = "#" + config.channel;
            _msgNr = 0;
            usePolling = config.usePolling;
            useParent = config.useParent;
            useResize = config.useResize;
            _remoteOrigin = easyXDM.Url.getLocation(config.remote);

            if (!isHost && useParent) {
                _listenerWindow = window;
                _callerWindow = parent;
                _attachListeners();
                pub.up.callback(true);
            }
            else {
                _callerWindow = easyXDM.DomHelper.createFrame((isHost ? config.remote : config.remote + "#" + config.channel), config.container, (isHost && useParent || !isHost) ? function(){
                    _listenerWindow = window;
                    _attachListeners();
                    pub.up.callback(true);
                }
 : null, (isHost ? "local_" : "remote_") + config.channel);

                if (isHost && !useParent) {
                    var tries = 0, max = config.delay / 50;
                    (function getRef(){
                        if (++tries > max) {
                            // #ifdef debug
                            trace("unable to get reference to _listenerWindow, giving up");
                            // #endif
                            throw new Error("Unable to reference listenerwindow");
                        }
                        if (_listenerWindow) {
                            return;
                        }
                        try {
                            // This works in IE6
                            _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                            // #ifdef debug
                            trace("got a reference to _listenerWindow");
                            // #endif
                            window.clearTimeout(_timer);
                            _attachListeners();
                            pub.up.callback(true);
                            return;
                        }
                        catch (ex) {
                            window.setTimeout(getRef, 50);
                        }
                    }());
                }
            }
        }
    });
};
<commit_msg>Minor change<commit_after>/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape */

/**
 * @class easyXDM.stack.HashTransport
 * HashTransport is a transport class that uses the IFrame URL Technique for communication.

 * http://msdn.microsoft.com/en-us/library/bb735305.aspx

 * @extends easyXDM.stack.TransportStackElement
 * @namespace easyXDM.stack
 * @constructor
 * @param {Object} config The transports configuration.
 * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
 * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
 * @cfg {Number} interval The interval used when polling for messages.
 */
easyXDM.stack.HashTransport = function(config){
    // #ifdef debug
    var trace = easyXDM.Debug.getTracer("easyXDM.stack.HashTransport");
    trace("constructor");
    // #endif
    var pub;
    var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
    var usePolling, useParent, useResize, _remoteOrigin;

    function _sendMessage(message){
        // #ifdef debug
        trace("sending message '" + (_msgNr + 1) + " " + message + "' to " + _remoteOrigin);
        // #endif
        if (!_callerWindow) {
            // #ifdef debug
            trace("no caller window");
            // #endif
            return;
        }
        var url = config.remote + "#" + (_msgNr++) + "_" + message;

        if (isHost || !useParent) {
            // We are referencing an iframe
            _callerWindow.contentWindow.location = url;
            if (useResize) {
                // #ifdef debug
                trace("resizing to new size " + (_callerWindow.width > 75 ? 50 : 100));
                // #endif
                _callerWindow.width = _callerWindow.width > 75 ? 50 : 100;
            }
        }
        else {
            // We are referencing the parent window
            _callerWindow.location = url;
        }
    }

    function _handleHash(hash){
        _lastMsg = hash;
        // #ifdef debug
        trace("received message '" + _lastMsg + "' from " + _remoteOrigin);
        // #endif
        pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
    }

    function _onResize(e){
        // #ifdef debug
        trace("onresize: new message");
        // #endif
        _handleHash(_listenerWindow.location.hash);
    }

    /**
     * Checks location.hash for a new message and relays this to the receiver.
     * @private
     */
    function _pollHash(){
        if (_listenerWindow.location.hash && _listenerWindow.location.hash != _lastMsg) {
            // #ifdef debug
            trace("poll: new message");
            // #endif
            _handleHash(_listenerWindow.location.hash);
        }
    }

    function _attachListeners(){
        if (usePolling) {
            // #ifdef debug
            trace("starting polling");
            // #endif
            _timer = window.setInterval(_pollHash, pollInterval);
        }
        else {
            easyXDM.DomHelper.on(_listenerWindow, "resize", _onResize);
        }
    }

    return (pub = {
        outgoing: function(message, domain){
            _sendMessage(encodeURIComponent(message));
        },
        destroy: function(){
            if (usePolling) {
                window.clearInterval(_timer);
            }
            else if (_listenerWindow) {
                easyXDM.DomHelper.un(_listenerWindow, "resize", _pollHash);
            }
            if (isHost || !useParent) {
                _callerWindow.parentNode.removeChild(_callerWindow);
            }
            _callerWindow = null;
        },
        init: function(){
            isHost = config.isHost;
            pollInterval = config.interval;
            _lastMsg = "#" + config.channel;
            _msgNr = 0;
            usePolling = config.usePolling;
            useParent = config.useParent;
            useResize = config.useResize;
            _remoteOrigin = easyXDM.Url.getLocation(config.remote);

            if (!isHost && useParent) {
                _listenerWindow = window;
                _callerWindow = parent;
                _attachListeners();
                pub.up.callback(true);
            }
            else {
                _callerWindow = easyXDM.DomHelper.createFrame((isHost ? config.remote : config.remote + "#" + config.channel), config.container, (isHost && useParent || !isHost) ? function(){
                    _listenerWindow = window;
                    _attachListeners();
                    pub.up.callback(true);
                }
 : null, (isHost ? "local_" : "remote_") + config.channel);

                if (isHost && !useParent) {
                    var tries = 0, max = config.delay / 50;
                    (function getRef(){
                        if (++tries > max) {
                            // #ifdef debug
                            trace("unable to get reference to _listenerWindow, giving up");
                            // #endif
                            throw new Error("Unable to reference listenerwindow");
                        }
                        if (_listenerWindow) {
                            return;
                        }
                        try {
                            // This works in IE6
                            _listenerWindow = _callerWindow.contentWindow.frames["remote_" + config.channel];
                            window.clearTimeout(_timer);
                            _attachListeners();
                            // #ifdef debug
                            trace("got a reference to _listenerWindow");
                            // #endif
                            pub.up.callback(true);
                            return;
                        }
                        catch (ex) {
                            window.setTimeout(getRef, 50);
                        }
                    }());
                }
            }
        }
    });
};
<|endoftext|>


<commit_before>const urlExists = require('url-exists');
const fs = require('fs');
const files = require('../lib/files.js');

(function () {
  'use strict';

  module.exports = {
    topic: 'source',
    command: 'oss',
    description: 'Easily pulls in open source from a Github repository',
    help: 'help text for waw:source:oss',
    flags: [{
        name: 'repository',
        char: 'r',
        description: 'Git repository (e.g. "wadewegner/Strike-Components")',
        required: true,
        hasValue: true
      },
      {
        name: 'path',
        char: 'p',
        description: 'Path for downloaded source',
        required: true,
        hasValue: true
      },
      {
        name: 'branch',
        char: 'b',
        description: 'Git repository branch (default is "master")',
        required: false,
        hasValue: true
      },
      {
        name: 'server',
        char: 's',
        description: 'Git host server url (default is "github.com")',
        required: false,
        hasValue: true
      }
    ],
    run(context) {

      const targetPath = context.flags.path;

      // if host is not specified then use github.com
      let server = context.flags.server;
      if (!server) {
        server = 'github.com';
      }

      const url = `https://${server}/${context.flags.repository}`;

      // ensure source folder exists
      if (!fs.existsSync(targetPath)) {
        console.log("Specifiec file path doesn't exists"); // eslint-disable-line no-console
        return;
      }

      // if branch not specified, default to master
      let branch = context.flags.branch;
      if (!branch) {
        branch = 'master';
      }

      // check to ensure Github repo exists
      urlExists(url, (err1, repoExists) => {
        if (!repoExists) {
          console.log('Github repository not found'); // eslint-disable-line no-console
          return;
        }

        const rawUrlManifestFolder = `https://raw.githubusercontent.com/${context.flags.repository}/${branch}`;
        const rawUrlManifest = `${rawUrlManifestFolder}/sfdx-oss-manifest.json`;
        const rawApiUrl = `https://api.github.com/repos/${context.flags.repository}/git/trees/${branch}?recursive=1`;

        // check to ensure sfdx-oss-manifest.json exists
        urlExists(rawUrlManifest, (err2, manifestExists) => {
          if (!manifestExists) {
            console.log('sfdx-oss-manifest.json not found in repository'); // eslint-disable-line no-console
            return;
          }

          files.getManifest(rawUrlManifest, (body) => {

            const manifestJson = JSON.parse(body);
            const version = manifestJson.version;
            const sourceFolder = manifestJson.sourceFolder;

            // check version
            if (version === '1.0.0') {

              const sfdxSource = manifestJson.sfdxSource;

              // currently only support SFDX source
              if (!sfdxSource) {
                console.log('Currently only sfdx source is supported'); // eslint-disable-line no-console
                return;
              }

              const manifestFolders = manifestJson.folders;

              files.writeFolders(manifestFolders, targetPath, rawUrlManifestFolder, rawApiUrl, sourceFolder, (outputFiles) => {

                console.log('Writing files for folders ...'); // eslint-disable-line no-console

                for (let i = 0, len = outputFiles.length; i < len; i++) {
                  console.log(`  ${outputFiles[i]}`); // eslint-disable-line no-console
                }

              });

              // grab the files
              const manifestFiles = manifestJson.files;

              files.writeFiles(manifestFiles, targetPath, rawUrlManifestFolder, (outputFiles) => {

                console.log('Writing files ...'); // eslint-disable-line no-console

                for (let i = 0, len = outputFiles.length; i < len; i++) {
                  console.log(`  ${outputFiles[i]}`); // eslint-disable-line no-console
                }

              });

            } else {
              console.log('Only version 1.0.0 is currently supported'); // eslint-disable-line no-console
            }
          });
        });
      });
    }
  };
}());
<commit_msg>Addes support for tags<commit_after>const urlExists = require('url-exists');
const fs = require('fs');
const files = require('../lib/files.js');

(function () {
  'use strict';

  module.exports = {
    topic: 'source',
    command: 'oss',
    description: 'Easily pulls in open source from a Github repository',
    help: 'help text for waw:source:oss',
    flags: [{
        name: 'repository',
        char: 'r',
        description: 'Git repository (e.g. "wadewegner/Strike-Components")',
        required: true,
        hasValue: true
      },
      {
        name: 'path',
        char: 'p',
        description: 'Path for downloaded source',
        required: true,
        hasValue: true
      },
      {
        name: 'branch',
        char: 'b',
        description: 'Git repository branch (default is "master")',
        required: false,
        hasValue: true
      },
      {
        name: 'tag',
        char: 't',
        description: 'Git repository tag',
        required: false,
        hasValue: true
      },
      {
        name: 'server',
        char: 's',
        description: 'Git host server url (default is "github.com")',
        required: false,
        hasValue: true
      }
    ],
    run(context) {

      const targetPath = context.flags.path;

      // if host is not specified then use github.com
      let server = context.flags.server;
      if (!server) {
        server = 'github.com';
      }

      const url = `https://${server}/${context.flags.repository}`;

      // ensure source folder exists
      if (!fs.existsSync(targetPath)) {
        console.log("Specifiec file path doesn't exists"); // eslint-disable-line no-console
        return;
      }

      // if branch not specified, default to master
      let branch = context.flags.branch;
      if (!branch) {
        branch = 'master';
      }

      let tag = context.flags.tag;
      if (!tag) {
        branch = tag;
      }

      // check to ensure Github repo exists
      urlExists(url, (err1, repoExists) => {
        if (!repoExists) {
          console.log('Github repository not found'); // eslint-disable-line no-console
          return;
        }

        const rawUrlManifestFolder = `https://raw.githubusercontent.com/${context.flags.repository}/${branch}`;
        const rawUrlManifest = `${rawUrlManifestFolder}/sfdx-oss-manifest.json`;
        const rawApiUrl = `https://api.github.com/repos/${context.flags.repository}/git/trees/${branch}?recursive=1`;

        // check to ensure sfdx-oss-manifest.json exists
        urlExists(rawUrlManifest, (err2, manifestExists) => {
          if (!manifestExists) {
            console.log('sfdx-oss-manifest.json not found in repository'); // eslint-disable-line no-console
            return;
          }

          files.getManifest(rawUrlManifest, (body) => {

            const manifestJson = JSON.parse(body);
            const version = manifestJson.version;
            const sourceFolder = manifestJson.sourceFolder;

            // check version
            if (version === '1.0.0') {

              const sfdxSource = manifestJson.sfdxSource;

              // currently only support SFDX source
              if (!sfdxSource) {
                console.log('Currently only sfdx source is supported'); // eslint-disable-line no-console
                return;
              }

              const manifestFolders = manifestJson.folders;

              files.writeFolders(manifestFolders, targetPath, rawUrlManifestFolder, rawApiUrl, sourceFolder, (outputFiles) => {

                console.log('Writing files for folders ...'); // eslint-disable-line no-console

                for (let i = 0, len = outputFiles.length; i < len; i++) {
                  console.log(`  ${outputFiles[i]}`); // eslint-disable-line no-console
                }

              });

              // grab the files
              const manifestFiles = manifestJson.files;

              files.writeFiles(manifestFiles, targetPath, rawUrlManifestFolder, (outputFiles) => {

                console.log('Writing files ...'); // eslint-disable-line no-console

                for (let i = 0, len = outputFiles.length; i < len; i++) {
                  console.log(`  ${outputFiles[i]}`); // eslint-disable-line no-console
                }

              });

            } else {
              console.log('Only version 1.0.0 is currently supported'); // eslint-disable-line no-console
            }
          });
        });
      });
    }
  };
}());
<|endoftext|>


<commit_before>const Uppy = require('../../../../src/core/Core.js')
const DragDrop = require('../../../../src/plugins/DragDrop/index.js')
const ProgressBar = require('../../../../src/plugins/ProgressBar.js')
const Tus10 = require('../../../../src/plugins/Tus10.js')

const uppyOne = new Uppy({debug: true})
uppyOne
  .use(DragDrop, {target: '.UppyDragDrop-One'})
  .use(Tus10, {endpoint: '//master.tus.io/files/'})
  .use(ProgressBar, {target: '.UppyDragDrop-One-Progress'})
  .run()

const uppyTwo = new Uppy({debug: true, autoProceed: false})
uppyTwo
  .use(DragDrop, {target: '#UppyDragDrop-Two'})
  .use(Tus10, {endpoint: '//tusd.tus.io/files/'})
  .use(ProgressBar, {target: '.UppyDragDrop-Two-Progress'})
  .run()

var uploadBtn = document.querySelector('.UppyDragDrop-Two-Upload')
uploadBtn.addEventListener('click', function () {
  uppyTwo.startUpload()
})
<commit_msg>change endpoint to master.tus.io in second DnD example<commit_after>const Uppy = require('../../../../src/core/Core.js')
const DragDrop = require('../../../../src/plugins/DragDrop/index.js')
const ProgressBar = require('../../../../src/plugins/ProgressBar.js')
const Tus10 = require('../../../../src/plugins/Tus10.js')

const uppyOne = new Uppy({debug: true})
uppyOne
  .use(DragDrop, {target: '.UppyDragDrop-One'})
  .use(Tus10, {endpoint: '//master.tus.io/files/'})
  .use(ProgressBar, {target: '.UppyDragDrop-One-Progress'})
  .run()

const uppyTwo = new Uppy({debug: true, autoProceed: false})
uppyTwo
  .use(DragDrop, {target: '#UppyDragDrop-Two'})
  .use(Tus10, {endpoint: '://master.tus.io/files/'})
  .use(ProgressBar, {target: '.UppyDragDrop-Two-Progress'})
  .run()

var uploadBtn = document.querySelector('.UppyDragDrop-Two-Upload')
uploadBtn.addEventListener('click', function () {
  uppyTwo.startUpload()
})
<|endoftext|>