text:
// wrapped by build app
define("dojox/widget/RollingList", ["dijit","dojo","dojox","dojo/i18n!dijit/nls/common","dojo/require!dojo/window,dijit/layout/ContentPane,dijit/_Templated,dijit/_Contained,dijit/layout/_LayoutWidget,dijit/Menu,dijit/form/Button,dijit/focus,dijit/_base/focus,dojox/html/metrics,dojo/i18n"], function(dijit,dojo,dojox){
dojo.provide("dojox.widget.RollingList");
dojo.experimental("dojox.widget.RollingList");

dojo.require("dojo.window");

dojo.require("dijit.layout.ContentPane");
dojo.require("dijit._Templated");
dojo.require("dijit._Contained");
dojo.require("dijit.layout._LayoutWidget");
dojo.require("dijit.Menu");
dojo.require("dijit.form.Button");
dojo.require("dijit.focus");		// dijit.focus()
dojo.require("dijit._base.focus");	// dijit.getFocus()

dojo.require("dojox.html.metrics");

dojo.require("dojo.i18n");
dojo.requireLocalization("dijit", "common");

dojo.declare("dojox.widget._RollingListPane",
	[dijit.layout.ContentPane, dijit._Templated, dijit._Contained], {
	// summary:
	//		a core pane that can be attached to a RollingList.  All panes
	//		should extend this one

	// templateString: string
	//		our template
	templateString: '

',

	// parentWidget: dojox.widget.RollingList
	//		Our rolling list widget
	parentWidget: null,

	// parentPane: dojox.widget._RollingListPane
	//		The pane that immediately precedes ours
	parentPane: null,

	// store: store
	//		the store we must use
	store: null,

	// items: item[]
	//		an array of (possibly not-yet-loaded) items to display in this.
	//		If this array is null, then the query and query options are used to
	//		get the top-level items to use.  This array is also used to watch and
	//		see if the pane needs to be reloaded (store notifications are handled)
	//		by the pane
	items: null,

	// query: object
	//		a query to pass to the datastore.  This is only used if items are null
	query: null,

	// queryOptions: object
	//		query options to be passed to the datastore
	queryOptions: null,

	// focusByNode: boolean
	//		set to false if the subclass will handle its own node focusing
	_focusByNode: true,

	// minWidth: integer
	//		the width (in px) for this pane
	minWidth: 0,

	_setContentAndScroll: function(/*String|DomNode|Nodelist*/cont, /*Boolean?*/isFakeContent){
		// summary:
		//		sets the value of the content and scrolls it into view
		this._setContent(cont, isFakeContent);
		this.parentWidget.scrollIntoView(this);
	},

	_updateNodeWidth: function(n, min){
		// summary:
		//		updates the min width of the pane to be minPaneWidth
		n.style.width = "";
		var nWidth = dojo.marginBox(n).w;
		if(nWidth < min){
			dojo.marginBox(n, {w: min});
		}
	},

	_onMinWidthChange: function(v){
		// Called when the min width of a pane has changed
		this._updateNodeWidth(this.domNode, v);
	},

	_setMinWidthAttr: function(v){
		if(v !== this.minWidth){
			this.minWidth = v;
			this._onMinWidthChange(v);
		}
	},

	startup: function(){
		if(this._started){ return; }
		if(this.store && this.store.getFeatures()["dojo.data.api.Notification"]){
			window.setTimeout(dojo.hitch(this, function(){
				// Set connections after a slight timeout to avoid getting in the
				// condition where we are setting them while events are still
				// being fired
				this.connect(this.store, "onSet", "_onSetItem");
				this.connect(this.store, "onNew", "_onNewItem");
				this.connect(this.store, "onDelete", "_onDeleteItem");
			}), 1);
		}
		this.connect(this.focusNode||this.domNode, "onkeypress", "_focusKey");
		this.parentWidget._updateClass(this.domNode, "Pane");
		this.inherited(arguments);
		this._onMinWidthChange(this.minWidth);
	},

	_focusKey: function(/*Event*/e){
		// summary:
		//		called when a keypress happens on the widget
		if(e.charOrCode == dojo.keys.BACKSPACE){
			dojo.stopEvent(e);
			return;
		}else if(e.charOrCode == dojo.keys.LEFT_ARROW && this.parentPane){
			this.parentPane.focus();
			this.parentWidget.scrollIntoView(this.parentPane);
		}else if(e.charOrCode == dojo.keys.ENTER){
			this.parentWidget._onExecute();
		}
	},

	focus: function(/*boolean*/force){
		// summary:
		//		sets the focus to this current widget
		if(this.parentWidget._focusedPane != this){
			this.parentWidget._focusedPane = this;
			this.parentWidget.scrollIntoView(this);
			if(this._focusByNode && (!this.parentWidget._savedFocus || force)){
				try{(this.focusNode||this.domNode).focus();}catch(e){}
			}
		}
	},

	_onShow: function(){
		// summary:
		//		checks that the store is loaded
		this.inherited(arguments);
		if((this.store || this.items) && ((this.refreshOnShow && this.domNode) || (!this.isLoaded && this.domNode))){
			this.refresh();
		}
	},

	_load: function(){
		// summary:
		//		sets the "loading" message and then kicks off a query asyncronously
		this.isLoaded = false;
		if(this.items){
			this._setContentAndScroll(this.onLoadStart(), true);
			window.setTimeout(dojo.hitch(this, "_doQuery"), 1);
		}else{
			this._doQuery();
		}
	},

	_doLoadItems: function(/*item[]*/items, /*function*/callback){
		// summary:
		//		loads the given items, and then calls the callback when they
		//		are finished.
		var _waitCount = 0, store = this.store;
		dojo.forEach(items, function(item){
			if(!store.isItemLoaded(item)){ _waitCount++; }
		});
		if(_waitCount === 0){
			callback();
		}else{
			var onItem = function(item){
				_waitCount--;
				if((_waitCount) === 0){
					callback();
				}
			};
			dojo.forEach(items, function(item){
				if(!store.isItemLoaded(item)){
					store.loadItem({item: item, onItem: onItem});
				}
			});
		}
	},

	_doQuery: function(){
		// summary:
		//		either runs the query or loads potentially not-yet-loaded items.
		if(!this.domNode){return;}
		var preload = this.parentWidget.preloadItems;
		preload = (preload === true || (this.items && this.items.length <= Number(preload)));
		if(this.items && preload){
			this._doLoadItems(this.items, dojo.hitch(this, "onItems"));
		}else if(this.items){
			this.onItems();
		}else{
			this._setContentAndScroll(this.onFetchStart(), true);
			this.store.fetch({query: this.query,
				onComplete: function(items){
					this.items = items;
					this.onItems();
				},
				onError: function(e){
					this._onError("Fetch", e);
				},
				scope: this});
		}
	},

	_hasItem: function(/* item */ item){
		// summary:
		//		returns whether or not the given item is handled by this
		//		pane
		var items = this.items || [];
		for(var i = 0, myItem; (myItem = items[i]); i++){
			if(this.parentWidget._itemsMatch(myItem, item)){
				return true;
			}
		}
		return false;
	},

	_onSetItem: function(/* item */ item,
					/* attribute-name-string */ attribute,
					/* Object|Array */ oldValue,
					/* Object|Array */ newValue){
		// summary:
		//		called when an item in the store has changed
		if(this._hasItem(item)){
			this.refresh();
		}
	},

	_onNewItem: function(/* item */ newItem, /*object?*/ parentInfo){
		// summary:
		//		called when an item is added to the store
		var sel;
		if((!parentInfo && !this.parentPane) ||
			(parentInfo && this.parentPane && this.parentPane._hasItem(parentInfo.item) &&
			(sel = this.parentPane._getSelected()) && this.parentWidget._itemsMatch(sel.item, parentInfo.item))){
			this.items.push(newItem);
			this.refresh();
		}else if(parentInfo && this.parentPane && this._hasItem(parentInfo.item)){
			this.refresh();
		}
	},

	_onDeleteItem: function(/* item */ deletedItem){
		// summary:
		//		called when an item is removed from the store
		if(this._hasItem(deletedItem)){
			this.items = dojo.filter(this.items, function(i){
				return (i != deletedItem);
			});
			this.refresh();
		}
	},

	onFetchStart: function(){
		// summary:
		//		called before a fetch starts
		return this.loadingMessage;
	},

	onFetchError: function(/*Error*/ error){
		// summary:
		//		called when a fetch error occurs.
		return this.errorMessage;
	},

	onLoadStart: function(){
		// summary:
		//		called before a load starts
		return this.loadingMessage;
	},

	onLoadError: function(/*Error*/ error){
		// summary:
		//		called when a load error occurs.
		return this.errorMessage;
	},

	onItems: function(){
		// summary:
		//		called after a fetch or load - at this point, this.items should be
		//  	set and loaded.  Override this function to "do your stuff"
		if(!this.onLoadDeferred){
			this.cancel();
			this.onLoadDeferred = new dojo.Deferred(dojo.hitch(this, "cancel"));
		}
		this._onLoadHandler();
	}

});

dojo.declare("dojox.widget._RollingListGroupPane",
	[dojox.widget._RollingListPane], {
	// summary:
	//		a pane that will handle groups (treats them as menu items)

	// templateString: string
	//		our template
	templateString: '

' +
					'
' +
						'

' +
					'

',

	// _menu: dijit.Menu
	//		The menu that we will call addChild() on for adding items
	_menu: null,

	_setContent: function(/*String|DomNode|Nodelist*/cont){
		if(!this._menu){
			// Only set the content if we don't already have a menu
			this.inherited(arguments);
		}
	},

	_onMinWidthChange: function(v){
		// override and resize the menu instead
		if(!this._menu){ return; }
		var dWidth = dojo.marginBox(this.domNode).w;
		var mWidth = dojo.marginBox(this._menu.domNode).w;
		this._updateNodeWidth(this._menu.domNode, v - (dWidth - mWidth));
	},

	onItems: function(){
		// summary:
		//		called after a fetch or load
		var selectItem, hadChildren = false;
		if(this._menu){
			selectItem = this._getSelected();
			this._menu.destroyRecursive();
		}
		this._menu = this._getMenu();
		var child, selectMenuItem;
		if(this.items.length){
			dojo.forEach(this.items, function(item){
				child = this.parentWidget._getMenuItemForItem(item, this);
				if(child){
					if(selectItem && this.parentWidget._itemsMatch(child.item, selectItem.item)){
						selectMenuItem = child;
					}
					this._menu.addChild(child);
				}
			}, this);
		}else{
			child = this.parentWidget._getMenuItemForItem(null, this);
			if(child){
				this._menu.addChild(child);
			}
		}
		if(selectMenuItem){
			this._setSelected(selectMenuItem);
			if((selectItem && !selectItem.children && selectMenuItem.children) ||
				(selectItem && selectItem.children && !selectMenuItem.children)){
				var itemPane = this.parentWidget._getPaneForItem(selectMenuItem.item, this, selectMenuItem.children);
				if(itemPane){
					this.parentWidget.addChild(itemPane, this.getIndexInParent() + 1);
				}else{
					this.parentWidget._removeAfter(this);
					this.parentWidget._onItemClick(null, this, selectMenuItem.item, selectMenuItem.children);
				}
			}
		}else if(selectItem){
			this.parentWidget._removeAfter(this);
		}
		this.containerNode.innerHTML = "";
		this.containerNode.appendChild(this._menu.domNode);
		this.parentWidget.scrollIntoView(this);
		this._checkScrollConnection(true);
		this.inherited(arguments);
		this._onMinWidthChange(this.minWidth);
	},

	_checkScrollConnection: function(doLoad){
		// summary:
		//		checks whether or not we need to connect to our onscroll
		//		function
		var store = this.store;
		if(this._scrollConn){
			this.disconnect(this._scrollConn);
		}
		delete this._scrollConn;
		if(!dojo.every(this.items, function(i){return store.isItemLoaded(i);})){
			if(doLoad){
				this._loadVisibleItems();
			}
			this._scrollConn = this.connect(this.domNode, "onscroll", "_onScrollPane");
		}
	},

	startup: function(){
		this.inherited(arguments);
		this.parentWidget._updateClass(this.domNode, "GroupPane");
	},

	focus: function(/*boolean*/force){
		// summary:
		//		sets the focus to this current widget
		if(this._menu){
			if(this._pendingFocus){
				this.disconnect(this._pendingFocus);
			}
			delete this._pendingFocus;

			// We focus the right widget - either the focusedChild, the
			// selected node, the first menu item, or the menu itself
			var focusWidget = this._menu.focusedChild;
			if(!focusWidget){
				var focusNode = dojo.query(".dojoxRollingListItemSelected", this.domNode)[0];
				if(focusNode){
					focusWidget = dijit.byNode(focusNode);
				}
			}
			if(!focusWidget){
				focusWidget = this._menu.getChildren()[0] || this._menu;
			}
			this._focusByNode = false;
			if(focusWidget.focusNode){
				if(!this.parentWidget._savedFocus || force){
					try{focusWidget.focusNode.focus();}catch(e){}
				}
				window.setTimeout(function(){
					try{
						dojo.window.scrollIntoView(focusWidget.focusNode);
					}catch(e){}
				}, 1);
			}else if(focusWidget.focus){
				if(!this.parentWidget._savedFocus || force){
					focusWidget.focus();
				}
			}else{
				this._focusByNode = true;
			}
			this.inherited(arguments);
		}else if(!this._pendingFocus){
			this._pendingFocus = this.connect(this, "onItems", "focus");
		}
	},

	_getMenu: function(){
		// summary:
		//		returns a widget to be used for the container widget.
		var self = this;
		var menu = new dijit.Menu({
			parentMenu: this.parentPane ? this.parentPane._menu : null,
			onCancel: function(/*Boolean*/ closeAll){
				if(self.parentPane){
					self.parentPane.focus(true);
				}
			},
			_moveToPopup: function(/*Event*/ evt){
				if(this.focusedChild && !this.focusedChild.disabled){
					this.onItemClick(this.focusedChild, evt);
				}
			}
		}, this.menuNode);
		this.connect(menu, "onItemClick", function(/*dijit.MenuItem*/ item, /*Event*/ evt){
			if(item.disabled){ return; }
			evt.alreadySelected = dojo.hasClass(item.domNode, "dojoxRollingListItemSelected");
			if(evt.alreadySelected &&
				((evt.type == "keypress" && evt.charOrCode != dojo.keys.ENTER) ||
				(evt.type == "internal"))){
				var p = this.parentWidget.getChildren()[this.getIndexInParent() + 1];
				if(p){
					p.focus(true);
					this.parentWidget.scrollIntoView(p);
				}
			}else{
				this._setSelected(item, menu);
				this.parentWidget._onItemClick(evt, this, item.item, item.children);
				if(evt.type == "keypress" && evt.charOrCode == dojo.keys.ENTER){
					this.parentWidget._onExecute();
				}
			}
		});
		if(!menu._started){
			menu.startup();
		}
		return menu;
	},

	_onScrollPane: function(){
		// summary:
		//		called when the pane has been scrolled - it sets a timeout
		//		so that we don't try and load our visible items too often during
		//		a scroll
		if(this._visibleLoadPending){
			window.clearTimeout(this._visibleLoadPending);
		}
		this._visibleLoadPending = window.setTimeout(dojo.hitch(this, "_loadVisibleItems"), 500);
	},

	_loadVisibleItems: function(){
		// summary:
		//		loads the items that are currently visible in the pane
		delete this._visibleLoadPending;
		var menu = this._menu;
		if(!menu){ return; }
		var children = menu.getChildren();
		if(!children || !children.length){ return; }
		var gpbme = function(n, m, pb){
			var s = dojo.getComputedStyle(n);
			var r = 0;
			if(m){ r += dojo._getMarginExtents(n, s).t; }
			if(pb){ r += dojo._getPadBorderExtents(n, s).t; }
			return r;
		};
		var topOffset = gpbme(this.domNode, false, true) +
						gpbme(this.containerNode, true, true) +
						gpbme(menu.domNode, true, true) +
						gpbme(children[0].domNode, true, false);
		var h = dojo.contentBox(this.domNode).h;
		var minOffset = this.domNode.scrollTop - topOffset - (h/2);
		var maxOffset = minOffset + (3*h/2);
		var menuItemsToLoad = dojo.filter(children, function(c){
			var cnt = c.domNode.offsetTop;
			var s = c.store;
			var i = c.item;
			return (cnt >= minOffset && cnt <= maxOffset && !s.isItemLoaded(i));
		})
		var itemsToLoad = dojo.map(menuItemsToLoad, function(c){
			return c.item;
		});
		var onItems = dojo.hitch(this, function(){
			var selectItem = this._getSelected();
			var selectMenuItem;
			dojo.forEach(itemsToLoad, function(item, idx){
				var newItem = this.parentWidget._getMenuItemForItem(item, this);
				var oItem = menuItemsToLoad[idx];
				var oIdx = oItem.getIndexInParent();
				menu.removeChild(oItem);
				if(newItem){
					if(selectItem && this.parentWidget._itemsMatch(newItem.item, selectItem.item)){
						selectMenuItem = newItem;
					}
					menu.addChild(newItem, oIdx);
					if(menu.focusedChild == oItem){
						menu.focusChild(newItem);
					}
				}
				oItem.destroy();
			}, this);
			this._checkScrollConnection(false);
		});
		this._doLoadItems(itemsToLoad, onItems);
	},

	_getSelected: function(/*dijit.Menu?*/ menu){
		// summary:
		//		returns the selected menu item - or null if none are selected
		if(!menu){ menu = this._menu; }
		if(menu){
			var children = this._menu.getChildren();
			for(var i = 0, item; (item = children[i]); i++){
				if(dojo.hasClass(item.domNode, "dojoxRollingListItemSelected")){
					return item;
				}
			}
		}
		return null;
	},

	_setSelected: function(/*dijit.MenuItem?*/ item, /*dijit.Menu?*/ menu){
		// summary:
		//		selects the given item in the given menu (defaults to pane's menu)
		if(!menu){ menu = this._menu;}
		if(menu){
			dojo.forEach(menu.getChildren(), function(i){
				this.parentWidget._updateClass(i.domNode, "Item", {"Selected": (item && (i == item && !i.disabled))});
			}, this);
		}
	}
});

dojo.declare("dojox.widget.RollingList",
	[dijit._Widget, dijit._Templated, dijit._Container], {
	// summary:
	//		a rolling list that can be tied to a data store with children

	// templateString: String
	//		The template to be used to construct the widget.
	templateString: dojo.cache("dojox.widget", "RollingList/RollingList.html", "

<button dojoType=\"dijit.form.Button\" dojoAttachPoint=\"okButton\"\n\t\t\t\tdojoAttachEvent=\"onClick:_onExecute\">${okButtonLabel}</button\n        ><button dojoType=\"dijit.form.Button\" dojoAttachPoint=\"cancelButton\"\n\t\t\t\tdojoAttachEvent=\"onClick:_onCancel\">${cancelButtonLabel}</button\n\t>

\n"),
	widgetsInTemplate: true,

	// className: string
	//		an additional class (or space-separated classes) to add for our widget
	className: "",

	// store: store
	//		the store we must use
	store: null,

	// query: object
	//		a query to pass to the datastore.  This is only used if items are null
	query: null,

	// queryOptions: object
	//		query options to be passed to the datastore
	queryOptions: null,

	// childrenAttrs: String[]
	//		one ore more attributes that holds children of a node
	childrenAttrs: ["children"],

	// parentAttr: string
	//		the attribute to read for finding our parent item (if any)
	parentAttr: "",

	// value: item
	//		The value that has been selected
	value: null,

	// executeOnDblClick: boolean
	//		Set to true if you want to call onExecute when an item is
	//		double-clicked, false if you want to call onExecute yourself. (mainly
	//		used for popups to control how they want to be handled)
	executeOnDblClick: true,

	// preloadItems: boolean or int
	//		if set to true, then onItems will be called only *after* all items have
	//		been loaded (ie store.isLoaded will return true for all of them).  If
	//		false, then no preloading will occur.  If set to an integer, preloading
	//		will occur if the number of items is less than or equal to the value
	//		of the integer.  The onItems function will need to be aware of handling
	//		items that may not be loaded
	preloadItems: false,

	// showButtons: boolean
	//		if set to true, then buttons for "OK" and "Cancel" will be provided
	showButtons: false,

	// okButtonLabel: string
	//		The string to use for the OK button - will use dijit's common "OK" string
	//		if not set
	okButtonLabel: "",

	// cancelButtonLabel: string
	//		The string to use for the Cancel button - will use dijit's common
	//		"Cancel" string if not set
	cancelButtonLabel: "",

	// minPaneWidth: integer
	//		the minimum pane width (in px) for all child panes.  If they are narrower,
	//		the width will be increased to this value.
	minPaneWidth: 0,

	postMixInProperties: function(){
		// summary:
		//		Mix in our labels, if they are not set
		this.inherited(arguments);
		var loc = dojo.i18n.getLocalization("dijit", "common");
		this.okButtonLabel = this.okButtonLabel || loc.buttonOk;
		this.cancelButtonLabel = this.cancelButtonLabel || loc.buttonCancel;
	},

	_setShowButtonsAttr: function(doShow){
		// summary:
		//		Sets the visibility of the buttons for the widget
		var needsLayout = false;
		if((this.showButtons != doShow && this._started) ||
			(this.showButtons == doShow && !this.started)){
			needsLayout = true;
		}
		dojo.toggleClass(this.domNode, "dojoxRollingListButtonsHidden", !doShow);
		this.showButtons = doShow;
		if(needsLayout){
			if(this._started){
				this.layout();
			}else{
				window.setTimeout(dojo.hitch(this, "layout"), 0);
			}
		}
	},

	_itemsMatch: function(/*item*/ item1, /*item*/ item2){
		// summary:
		//		returns whether or not the two items match - checks ID if
		//		they aren't the exact same object
		if(!item1 && !item2){
			return true;
		}else if(!item1 || !item2){
			return false;
		}
		return (item1 == item2 ||
			(this._isIdentity && this.store.getIdentity(item1) == this.store.getIdentity(item2)));
	},

	_removeAfter: function(/*Widget or int*/ idx){
		// summary:
		//		removes all widgets after the given widget (or index)
		if(typeof idx != "number"){
			idx = this.getIndexOfChild(idx);
		}
		if(idx >= 0){
			dojo.forEach(this.getChildren(), function(c, i){
				if(i > idx){
					this.removeChild(c);
					c.destroyRecursive();
				}
			}, this);
		}
		var children = this.getChildren(), child = children[children.length - 1];
		var selItem = null;
		while(child && !selItem){
			var val = child._getSelected ? child._getSelected() : null;
			if(val){
				selItem = val.item;
			}
			child = child.parentPane;
		}
		if(!this._setInProgress){
			this._setValue(selItem);
		}
	},

	addChild: function(/*dijit._Widget*/ widget, /*int?*/ insertIndex){
		// summary:
		//		adds a child to this rolling list - if passed an insertIndex,
		//		then all children from that index on will be removed and destroyed
		//		before adding the child.
		if(insertIndex > 0){
			this._removeAfter(insertIndex - 1);
		}
		this.inherited(arguments);
		if(!widget._started){
			widget.startup();
		}
		widget.attr("minWidth", this.minPaneWidth);
		this.layout();
		if(!this._savedFocus){
			widget.focus();
		}
	},

	_setMinPaneWidthAttr: function(value){
		// summary:
		//		Sets the min pane width of all children
		if(value !== this.minPaneWidth){
			this.minPaneWidth = value;
			dojo.forEach(this.getChildren(), function(c){
				c.attr("minWidth", value);
			});
		}
	},

	_updateClass: function(/* Node */ node, /* String */ type, /* Object? */ options){
		// summary:
		//		sets the state of the given node with the given type and options
		// options:
		//		an object with key-value-pairs.  The values are boolean, if true,
		//		the key is added as a class, if false, it is removed.
		if(!this._declaredClasses){
			this._declaredClasses = ("dojoxRollingList " + this.className).split(" ");
		}
		dojo.forEach(this._declaredClasses, function(c){
			if(c){
				dojo.addClass(node, c + type);
				for(var k in options||{}){
					dojo.toggleClass(node, c + type + k, options[k]);
				}
				dojo.toggleClass(node, c + type + "FocusSelected",
					(dojo.hasClass(node, c + type + "Focus") && dojo.hasClass(node, c + type + "Selected")));
				dojo.toggleClass(node, c + type + "HoverSelected",
					(dojo.hasClass(node, c + type + "Hover") && dojo.hasClass(node, c + type + "Selected")));
			}
		});
	},

	scrollIntoView: function(/*dijit._Widget*/ childWidget){
		// summary:
		//		scrolls the given widget into view
		if(this._scrollingTimeout){
			window.clearTimeout(this._scrollingTimeout);
		}
		delete this._scrollingTimeout;
		this._scrollingTimeout = window.setTimeout(dojo.hitch(this, function(){
			if(childWidget.domNode){
				dojo.window.scrollIntoView(childWidget.domNode);
			}
			delete this._scrollingTimeout;
			return;
		}), 1);
	},

	resize: function(args){
		dijit.layout._LayoutWidget.prototype.resize.call(this, args);
	},

	layout: function(){
		var children = this.getChildren();
		if(this._contentBox){
			var bn = this.buttonsNode;
			var height = this._contentBox.h - dojo.marginBox(bn).h -
								dojox.html.metrics.getScrollbar().h;
			dojo.forEach(children, function(c){
				dojo.marginBox(c.domNode, {h: height});
			});
		}
		if(this._focusedPane){
			var foc = this._focusedPane;
			delete this._focusedPane;
			if(!this._savedFocus){
				foc.focus();
			}
		}else if(children && children.length){
			if(!this._savedFocus){
				children[0].focus();
			}
		}
	},

	_onChange: function(/*item*/ value){
		this.onChange(value);
	},

	_setValue: function(/* item */ value){
		// summary:
		//		internally sets the value and fires onchange
		delete this._setInProgress;
		if(!this._itemsMatch(this.value, value)){
			this.value = value;
			this._onChange(value);
		}
	},

	_setValueAttr: function(/* item */ value){
		// summary:
		//		sets the value of this widget to the given store item
		if(this._itemsMatch(this.value, value) && !value){ return; }
		if(this._setInProgress && this._setInProgress === value){ return; }
		this._setInProgress = value;
		if(!value || !this.store.isItem(value)){
			var pane = this.getChildren()[0];
			pane._setSelected(null);
			this._onItemClick(null, pane, null, null);
			return;
		}

		var fetchParentItems = dojo.hitch(this, function(/*item*/ item, /*function*/callback){
			// summary:
			//		Fetches the parent items for the given item
			var store = this.store, id;
			if(this.parentAttr && store.getFeatures()["dojo.data.api.Identity"] &&
				((id = this.store.getValue(item, this.parentAttr)) || id === "")){
				// Fetch by parent attribute
				var cb = function(i){
					if(store.getIdentity(i) == store.getIdentity(item)){
						callback(null);
					}else{
						callback([i]);
					}
				};
				if(id === ""){
					callback(null);
				}else if(typeof id == "string"){
					store.fetchItemByIdentity({identity: id, onItem: cb});
				}else if(store.isItem(id)){
					cb(id);
				}
			}else{
				// Fetch by finding children
				var numCheck = this.childrenAttrs.length;
				var parents = [];
				dojo.forEach(this.childrenAttrs, function(attr){
					var q = {};
					q[attr] = item;
					store.fetch({query: q, scope: this,
						onComplete: function(items){
							if(this._setInProgress !== value){
								return;
							}
							parents = parents.concat(items);
							numCheck--;
							if(numCheck === 0){
								callback(parents);
							}
						}
					});
				}, this);
			}
		});

		var setFromChain = dojo.hitch(this, function(/*item[]*/itemChain, /*integer*/idx){
			// summary:
			//		Sets the value of the widget at the given index in the chain - onchanges are not
			//		fired here
			var set = itemChain[idx];
			var child = this.getChildren()[idx];
			var conn;
			if(set && child){
				var fx = dojo.hitch(this, function(){
					if(conn){
						this.disconnect(conn);
					}
					delete conn;
					if(this._setInProgress !== value){
						return;
					}
					var selOpt = dojo.filter(child._menu.getChildren(), function(i){
						return this._itemsMatch(i.item, set);
					}, this)[0];
					if(selOpt){
						idx++;
						child._menu.onItemClick(selOpt, {type: "internal",
													stopPropagation: function(){},
													preventDefault: function(){}});
						if(itemChain[idx]){
							setFromChain(itemChain, idx);
						}else{
							this._setValue(set);
							this.onItemClick(set, child, this.getChildItems(set));
						}
					}
				});
				if(!child.isLoaded){
					conn = this.connect(child, "onLoad", fx);
				}else{
					fx();
				}
			}else if(idx === 0){
				this.set("value", null);
			}
		});

		var parentChain = [];
		var onParents = dojo.hitch(this, function(/*item[]*/ parents){
			// summary:
			//		recursively grabs the parents - only the first one is followed
			if(parents && parents.length){
				parentChain.push(parents[0]);
				fetchParentItems(parents[0], onParents);
			}else{
				if(!parents){
					parentChain.pop();
				}
				parentChain.reverse();
				setFromChain(parentChain, 0);
			}
		});

		// Only set the value in display if we are shown - if we are in a dropdown,
		// and are hidden, don't actually do the scrolling in the display (it can
		// mess up layouts)
		var ns = this.domNode.style;
		if(ns.display == "none" || ns.visibility == "hidden"){
			this._setValue(value);
		}else if(!this._itemsMatch(value, this._visibleItem)){
			onParents([value]);
		}
	},

	_onItemClick: function(/* Event */ evt, /* dijit._Contained */ pane, /* item */ item, /* item[]? */ children){
		// summary:
		//		internally called when a widget should pop up its child

		if(evt){
			var itemPane = this._getPaneForItem(item, pane, children);
			var alreadySelected = (evt.type == "click" && evt.alreadySelected);

			if(alreadySelected && itemPane){
				this._removeAfter(pane.getIndexInParent() + 1);
				var next = pane.getNextSibling();
				if(next && next._setSelected){
					next._setSelected(null);
				}
				this.scrollIntoView(next);
			}else if(itemPane){
				this.addChild(itemPane, pane.getIndexInParent() + 1);
				if(this._savedFocus){
					itemPane.focus(true);
				}
			}else{
				this._removeAfter(pane);
				this.scrollIntoView(pane);
			}
		}else if(pane){
			this._removeAfter(pane);
			this.scrollIntoView(pane);
		}
		if(!evt || evt.type != "internal"){
			this._setValue(item);
			this.onItemClick(item, pane, children);
		}
		this._visibleItem = item;
	},

	_getPaneForItem: function(/* item? */ item, /* dijit._Contained? */ parentPane, /* item[]? */ children){
		// summary:
		//		gets the pane for the given item, and mixes in our needed parts
		//		Returns the pane for the given item (null if the root pane) - after mixing in
		//		its stuff.
		var ret = this.getPaneForItem(item, parentPane, children);
		ret.store = this.store;
		ret.parentWidget = this;
		ret.parentPane = parentPane||null;
		if(!item){
			ret.query = this.query;
			ret.queryOptions = this.queryOptions;
		}else if(children){
			ret.items = children;
		}else{
			ret.items = [item];
		}
		return ret;
	},

	_getMenuItemForItem: function(/*item*/ item, /* dijit._Contained */ parentPane){
		// summary:
		//		returns a widget for the given store item.  The returned
		//		item will be added to this widget's container widget.  null will
		//		be passed in for an "empty" item.
		var store = this.store;
		if(!item || !store || !store.isItem(item)){
			var i = new dijit.MenuItem({
				label: "---",
				disabled: true,
				iconClass: "dojoxEmpty",
				focus: function(){
					// Do nothing on focus of this guy...
				}
			});
			this._updateClass(i.domNode, "Item");
			return i;
		}else{
			var itemLoaded = store.isItemLoaded(item);
			var childItems = itemLoaded ? this.getChildItems(item) : undefined;
			var widgetItem;
			if(childItems){
				widgetItem = this.getMenuItemForItem(item, parentPane, childItems);
				widgetItem.children = childItems;
				this._updateClass(widgetItem.domNode, "Item", {"Expanding": true});
				if(!widgetItem._started){
					var c = widgetItem.connect(widgetItem, "startup", function(){
						this.disconnect(c);
						dojo.style(this.arrowWrapper, "visibility", "");
					});
				}else{
					dojo.style(widgetItem.arrowWrapper, "visibility", "");
				}
			}else{
				widgetItem = this.getMenuItemForItem(item, parentPane, null);
				if(itemLoaded){
					this._updateClass(widgetItem.domNode, "Item", {"Single": true});
				}else{
					this._updateClass(widgetItem.domNode, "Item", {"Unloaded": true});
					widgetItem.attr("disabled", true);
				}
			}
			widgetItem.store = this.store;
			widgetItem.item = item;
			if(!widgetItem.label){
				widgetItem.attr("label", this.store.getLabel(item).replace(/</,"<"));
			}
			if(widgetItem.focusNode){
				var self = this;
				widgetItem.focus = function(){
					// Don't set our class
					if(!this.disabled){try{this.focusNode.focus();}catch(e){}}
				};
				widgetItem.connect(widgetItem.focusNode, "onmouseenter", function(){
					if(!this.disabled){
						self._updateClass(this.domNode, "Item", {"Hover": true});
					}
				});
				widgetItem.connect(widgetItem.focusNode, "onmouseleave", function(){
					if(!this.disabled){
						self._updateClass(this.domNode, "Item", {"Hover": false});
					}
				});
				widgetItem.connect(widgetItem.focusNode, "blur", function(){
					self._updateClass(this.domNode, "Item", {"Focus": false, "Hover": false});
				});
				widgetItem.connect(widgetItem.focusNode, "focus", function(){
					self._updateClass(this.domNode, "Item", {"Focus": true});
					self._focusedPane = parentPane;
				});
				if(this.executeOnDblClick){
					widgetItem.connect(widgetItem.focusNode, "ondblclick", function(){
						self._onExecute();
					});
				}
			}
			return widgetItem;
		}
	},

	_setStore: function(/* dojo/data/api/Read */ store){
		// summary:
		//		sets the store for this widget */
		if(store === this.store && this._started){ return; }
		this.store = store;
		this._isIdentity = store.getFeatures()["dojo.data.api.Identity"];
		var rootPane = this._getPaneForItem();
		this.addChild(rootPane, 0);
	},

	_onKey: function(/*Event*/ e){
		// summary:
		//		called when a keypress event happens on this widget
		if(e.charOrCode == dojo.keys.BACKSPACE){
			dojo.stopEvent(e);
			return;
		}else if(e.charOrCode == dojo.keys.ESCAPE && this._savedFocus){
			try{dijit.focus(this._savedFocus);}catch(e){}
			dojo.stopEvent(e);
			return;
		}else if(e.charOrCode == dojo.keys.LEFT_ARROW ||
			e.charOrCode == dojo.keys.RIGHT_ARROW){
			dojo.stopEvent(e);
			return;
		}
	},

	_resetValue: function(){
		// summary:
		//		function called when the value is reset.
		this.set("value", this._lastExecutedValue);
	},

	_onCancel: function(){
		// summary:
		//		function called when the cancel button is clicked.  It
		//		resets its value to whatever was last executed and then cancels
		this._resetValue();
		this.onCancel();
	},

	_onExecute: function(){
		// summary:
		//		function called when the OK button is clicked or when an
		//		item is selected (double-clicked or "enter" pressed on it)
		this._lastExecutedValue = this.get("value");
		this.onExecute();
	},

	focus: function(){
		// summary:
		//		sets the focus state of this widget
		var wasSaved = this._savedFocus;
		this._savedFocus = dijit.getFocus(this);
		if(!this._savedFocus.node){
			delete this._savedFocus;
		}
		if(!this._focusedPane){
			var child = this.getChildren()[0];
			if(child && !wasSaved){
				child.focus(true);
			}
		}else{
			this._savedFocus = dijit.getFocus(this);
			var foc = this._focusedPane;
			delete this._focusedPane;
			if(!wasSaved){
				foc.focus(true);
			}
		}
	},

	handleKey:function(/*Event*/e){
		// summary:
		//		handle the key for the given event - called by dropdown
		//		widgets
		if(e.keyCode == dojo.keys.DOWN_ARROW){
			delete this._savedFocus;
			this.focus();
			return false;
		}else if(e.keyCode == dojo.keys.ESCAPE){
			this._onCancel();
			return false;
		}
		return true;
	},

	_updateChildClasses: function(){
		// summary:
		//		Called when a child is added or removed - so that we can
		//		update the classes for styling the "current" one differently than
		//		the others
		var children = this.getChildren();
		var length = children.length;
		dojo.forEach(children, function(c, idx){
			dojo.toggleClass(c.domNode, "dojoxRollingListPaneCurrentChild", (idx == (length - 1)));
			dojo.toggleClass(c.domNode, "dojoxRollingListPaneCurrentSelected", (idx == (length - 2)));
		});
	},

	startup: function(){
		if(this._started){ return; }
		if(!this.getParent || !this.getParent()){
			this.resize();
			this.connect(dojo.global, "onresize", "resize");
		}
		this.connect(this, "addChild", "_updateChildClasses");
		this.connect(this, "removeChild", "_updateChildClasses");
		this._setStore(this.store);
		this.set("showButtons", this.showButtons);
		this.inherited(arguments);
		this._lastExecutedValue = this.get("value");
	},

	getChildItems: function(/*item*/ item){
		// summary:
		//		Returns the child items for the given store item
		var childItems, store = this.store;
		dojo.forEach(this.childrenAttrs, function(attr){
			var vals = store.getValues(item, attr);
			if(vals && vals.length){
				childItems = (childItems||[]).concat(vals);
			}
		});
		return childItems;
	},

	getMenuItemForItem: function(/*item*/ item, /* dijit._Contained */ parentPane, /* item[]? */ children){
		// summary:
		//		user overridable function to return a widget for the given item
		//		and its children.
		return new dijit.MenuItem({});
	},

	getPaneForItem: function(/* item? */ item, /* dijit._Contained? */ parentPane, /* item[]? */ children){
		// summary:
		//		user-overridable function to return a pane that corresponds
		//		to the given item in the store.  It can return null to not add a new pane
		//		(ie, you are planning on doing something else with it in onItemClick)

		// Item is undefined for the root pane, children is undefined for non-group panes
		if(!item || children){
			return new dojox.widget._RollingListGroupPane({});
		}else{
			return null;
		}
	},

	onItemClick: function(/* item */ item, /* dijit._Contained */ pane, /* item[]? */ children){
		// summary:
		//		called when an item is clicked - it receives the store item
	},

	onExecute: function(){
		// summary:
		//		exists so that popups don't disappear too soon
	},

	onCancel: function(){
		// summary:
		//		exists so that we can close ourselves if we wish
	},

	onChange: function(/* item */ value){
		// summary:
		//		called when the value of this widget has changed
	}

});

});


text:
<configuration>
    <property name="LOG_DIR" value="/data/logs/java-web"/>
    <property name="LOG_FILE_NAME" value="java-web.log"/>

    <!-- Output to File and Rotate if it's necessary -->
    <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/${LOG_FILE_NAME}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_DIR}/${LOG_FILE_NAME}.%i</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>10</maxIndex>
        </rollingPolicy>

        <triggeringPolicy name="ROLLING" class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>50MB</maxFileSize>
        </triggeringPolicy>

        <encoder>
            <pattern>%date [%-5thread] %-5level [%-10logger] %-10msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.threathunter" level="INFO" additivity="false">
        <appender-ref ref="ROLLING"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="ROLLING"/>
    </root>
</configuration>

redpajama_set_name: RedPajamaGithub


text:
@interface LCHit (LCPrivate)
- (void) fetchTheHit;
@end

@implementation LCHit

- (id) init
{
	self = [super init];
	doc = nil;
	resolved = NO;
	hits = nil;
	return self;
}

- (id) initWithHits: (LCHits *) h index: (int) index
{
	self = [self init];
	ASSIGN(hits, h);
	hitNumber = index;
	return self;
}

- (void) dealloc
{
	DESTROY(hits);
	[super dealloc];
}

- (LCDocument *) document
{
	if (!resolved) [self fetchTheHit];
	return doc;
}

- (float) score
{
	return [hits score: hitNumber];
}

- (int) identifier
{
	return [hits identifier: hitNumber];
}

- (void) fetchTheHit
{
	doc = [hits document: hitNumber];
	resolved = YES;
}

- (float) boost
{
	return [[self document] boost];
}

- (NSString *) stringForField: (NSString *) name
{
	return [[self document] stringForField: name];
}

- (NSString *) description
{
	NSMutableString *buffer = [[NSMutableString alloc] init];
	[buffer appendFormat: @"Hit<%@ [%d] ", hits, hitNumber];
	if (resolved) {
		[buffer appendString: @"resolved>"];
	} else {
		[buffer appendString: @"unresolved>"];
	}
	return AUTORELEASE(buffer);
}

@end


text:
cask "menutube" do
  version "1.7.3"
  sha256 "2428a68c085c9a10407eca1d778c2d5b3d37e4d0dfadb12376b44eab2f9f43a1"

  # github.com/edanchenkov/MenuTube/ was verified as official when first introduced to the cask
  url "https://github.com/edanchenkov/MenuTube/releases/download/#{version}/MenuTube-#{version}.dmg"
  appcast "https://github.com/edanchenkov/MenuTube/releases.atom"
  name "MenuTube"
  homepage "https://edanchenkov.github.io/MenuTube/"

  app "MenuTube.app"
end


text:
require 'rails_helper'
require 'sidekiq/testing'

RSpec.describe 'Impressions', type: :request do
  let(:headers) { {} }
  let(:params)  { {} }
  let(:user)    { create :user }
  let(:positive_impression) { create(:impression, user: user, response: :positive) }
  let(:neutral_impression) { create(:impression, user: user, response: :neutral) }
  let(:json_body) do
    subject
    JSON.parse(response.body)
  end

  describe '*' do
    let(:url) { '/votes' } # as an example
    let(:request) { get url, params: params, headers: headers }
    context 'legacy user without auth0_uid or location' do
      before { user }
      let(:user) do
        User.skip_callback(:save, :after, :geocode_last_ip)
        user = create(:user, :without_geolocation, auth0_uid: nil)
        User.set_callback(:save, :after, :geocode_last_ip)
        user
      end

      context 'login the first time with AUTH0' do
        let(:headers) do
          user.auth0_uid = 'email|58d072bf0bdcab0a0ecee8ad'
          super().merge(authenticated_header(user))
        end

        describe 'updates the location of the user' do
          around(:each) do |example|
            VCR.use_cassette('auth0_access_token_and_geo_ip_lookup') do
              Sidekiq::Testing.inline! do
                example.run
              end
            end
          end

          specify { expect { request }.to change { User.first.location? }.from(false).to(true) }
          specify { expect { request }.to change { User.first.latitude }.from(nil).to(52.0903) }
          specify { expect { request }.to change { User.first.longitude }.from(nil).to(13.1677) }
        end
      end
    end
  end

  describe 'GET /votes' do
    let(:action) { get '/votes', params: params, headers: headers }
    let(:impressions) { [positive_impression, neutral_impression] }
    subject do
      impressions
      action
      response
    end

    it { is_expected.to have_http_status(:unauthorized) }

    context 'signed in' do
      let(:headers) { authenticated_header(user) }

      it { is_expected.to have_http_status(:ok) }
      it 'returns impressions of the current user' do
        expect(subject.body).to have_json_size(2).at_path('data')
        data = parse_json(subject.body, 'data').sort_by { |key| key['attributes']['response'] }
        expect(data.first['id']).to eq(neutral_impression.id.to_s)
        expect(data.first['attributes']).to include('response' => 'neutral')
        expect(data.second['id']).to eq(positive_impression.id.to_s)
        expect(data.second['attributes']).to include('response' => 'positive')
      end

      describe '?response=positive' do
        let(:params) { { filter: { response: 'positive' } } }

        it 'returns only impressions with a positive response' do
          expect(subject.body).to have_json_size(1).at_path('data')
          expect(parse_json(subject.body, 'data/0/attributes')).to include('response' => 'positive')
          expect(parse_json(subject.body, 'data/0/id')).to eq positive_impression.id.to_s
        end
      end
    end
  end

  describe 'GET /votes/:id' do
    let(:action) { get "/votes/#{impression.id}", params: params, headers: headers }
    let(:impression) { create(:impression, user: user) }

    subject do
      impression
      action
      response
    end

    it { is_expected.to have_http_status(:unauthorized) }

    context 'signed in' do
      let(:headers) { authenticated_header(user) }

      context 'access to own impression' do
        it { is_expected.to have_http_status(:ok) }

        it 'returns impression' do
          expect(json_body['data']['id']).to eq impression.id.to_s
        end
      end

      context 'access to impression of someone else' do
        let(:impression) { create(:impression) }
        it { is_expected.to have_http_status(:forbidden) }
      end
    end
  end

  describe 'POST /votes' do
    let(:action) { post '/votes', params: params, headers: headers }

    subject do
      action
      response
    end

    it { is_expected.to have_http_status(:unauthorized) }

    context 'signed in' do
      let(:headers) { authenticated_header(user) }

      context 'given a broadcast' do
        let(:broadcast) { create :broadcast }
        describe 'sending params[response,user_id,broadcast_id]' do
          let(:params) do
            {
              data: {
                type: 'impressions',
                attributes: {
                  response: :positive
                },
                relationships: {
                  broadcast: {
                    data: { id: broadcast.id, type: 'broadcasts' }
                  }
                }
              }
            }
          end

          it 'creates a impression' do
            expect { action }.to change { Impression.count }.from(0).to(1)
          end

          it 'user creates a impression, thus he wants to pay for the broadcast' do
            action
            user.reload
            expect(user.liked_broadcasts).to include(broadcast)
          end

          context 'given another user' do
            let(:other_user) { create :user }
            let(:params) do
              params = super()
              params[:data][:relationships][:user] = {
                data: {
                  id: other_user.id,
                  type: 'users'
                }
              }
              params
            end

            it 'cannot create a impression for another user' do
              action
              user.reload
              other_user.reload
              expect(other_user.liked_broadcasts).to be_empty
              expect(user.liked_broadcasts).to include(broadcast)
            end
          end
        end
      end
    end
  end
end


text:
```bash
docker service create \
	--name kafka_1 \
	--hostname=kafka_1 \
	--network swarm-net \
	--replicas 1 \
	--detach=true \
	--env BROKER_ID=1 \
	--env ZOOKEEPER_CONNECT=zookeeper_node1:2181,zookeeper_node2:2181,zookeeper_node3:2181 \
	--endpoint-mode dnsrr \
	newnius/kafka:2.1.1
```

## Configuration

### By environment variable

Currently, properties below are supported.

| env | file | property |
| --- | --- | --- |
| BROKER_ID | server.properties | broker.id |
| ZOOKEEPER_CONNECT | server.properties | zookeeper.connect |

### By configuration file

```bash
docker service create \
	--name kafka \
	--hostname=kafka \
	--network swarm-net \
	--detach=true \
	--replicas 1 \
	--endpoint-mode dnsrr \
	--mount type=bind,src=/data/kafka/,dst=/config/kafka/,readonly \
	newnius/kafka:2.1.1
```


text:
<?php

class OmniwebShowtimes_AdminPageFramework_FieldType_checkbox extends OmniwebShowtimes_AdminPageFramework_FieldType {
    public $aFieldTypeSlugs = array('checkbox');
    protected $aDefaultKeys = array('select_all_button' => false, 'select_none_button' => false,);
    protected function getScripts() {
        new OmniwebShowtimes_AdminPageFramework_Form_View___Script_CheckboxSelector;
        $_sClassSelectorSelectAll = $this->_getSelectButtonClassSelectors($this->aFieldTypeSlugs, 'select_all_button');
        $_sClassSelectorSelectNone = $this->_getSelectButtonClassSelectors($this->aFieldTypeSlugs, 'select_none_button');
        return <<<JAVASCRIPTS
jQuery( document ).ready( function(){
    // Add the buttons.
    jQuery( '{$_sClassSelectorSelectAll}' ).each( function(){
        jQuery( this ).before( '
' + jQuery( this ).data( 'select_all_button' ) + '
' );
    });
    jQuery( '{$_sClassSelectorSelectNone}' ).each( function(){
        jQuery( this ).before( '
' + jQuery( this ).data( 'select_none_button' ) + '
' );
    });
});
JAVASCRIPTS;

    }
    private function _getSelectButtonClassSelectors(array $aFieldTypeSlugs, $sDataAttribute = 'select_all_button') {
        $_aClassSelectors = array();
        foreach ($aFieldTypeSlugs as $_sSlug) {
            if (!is_scalar($_sSlug)) {
                continue;
            }
            $_aClassSelectors[] = '.omniweb-showtimes-checkbox-container-' . $_sSlug . "[data-{$sDataAttribute}]";
        }
        return implode(',', $_aClassSelectors);
    }
    protected function getStyles() {
        return ".select_all_button_container, .select_none_button_container{display: inline-block;margin-bottom: 0.4em;}.omniweb-showtimes-checkbox-label {margin-top: 0.1em;}.omniweb-showtimes-field input[type='checkbox' ] {margin-right: 0.5em;} .omniweb-showtimes-field-checkbox .omniweb-showtimes-input-label-container {padding-right: 1em;}.omniweb-showtimes-field-checkbox .omniweb-showtimes-input-label-string{display: inline; }";
    }
    protected $_sCheckboxClassSelector = 'apf_checkbox';
    protected function getField($aField) {
        $_aOutput = array();
        $_bIsMultiple = is_array($aField['label']);
        foreach ($this->getAsArray($aField['label'], true) as $_sKey => $_sLabel) {
            $_aOutput[] = $this->_getEachCheckboxOutput($aField, $_bIsMultiple ? $_sKey : '', $_sLabel);
        }
        return "
getAttributes($this->_getCheckboxContainerAttributes($aField)) . ">" . "

" . implode(PHP_EOL, $_aOutput) . "
";
    }
    protected function _getCheckboxContainerAttributes(array $aField) {
        return array('class' => 'omniweb-showtimes-checkbox-container-' . $aField['type'], 'data-select_all_button' => $aField['select_all_button'] ? (!is_string($aField['select_all_button']) ? $this->oMsg->get('select_all') : $aField['select_all_button']) : null, 'data-select_none_button' => $aField['select_none_button'] ? (!is_string($aField['select_none_button']) ? $this->oMsg->get('select_none') : $aField['select_none_button']) : null,);
    }
    private function _getEachCheckboxOutput(array $aField, $sKey, $sLabel) {
        $_oCheckbox = new OmniwebShowtimes_AdminPageFramework_Input_checkbox($aField['attributes']);
        $_oCheckbox->setAttributesByKey($sKey);
        $_oCheckbox->addClass($this->_sCheckboxClassSelector);
        return $this->getElementByLabel($aField['before_label'], $sKey, $aField['label']) . "
getLabelContainerAttributes($aField, 'omniweb-showtimes-input-label-container omniweb-showtimes-checkbox-label') . ">" . "getAttributes(array('for' => $_oCheckbox->getAttribute('id'), 'class' => $_oCheckbox->getAttribute('disabled') ? 'disabled' : null,)) . ">" . $this->getElementByLabel($aField['before_input'], $sKey, $aField['label']) . $_oCheckbox->get($sLabel) . $this->getElementByLabel($aField['after_input'], $sKey, $aField['label']) . "" . "
" . $this->getElementByLabel($aField['after_label'], $sKey, $aField['label']);
    }
}
class OmniwebShowtimes_AdminPageFramework_FieldType_posttype extends OmniwebShowtimes_AdminPageFramework_FieldType_checkbox {
    public $aFieldTypeSlugs = array('posttype',);
    protected $aDefaultKeys = array('slugs_to_remove' => null, 'query' => array(), 'operator' => 'and', 'attributes' => array('size' => 30, 'maxlength' => 400,), 'select_all_button' => true, 'select_none_button' => true,);
    protected $aDefaultRemovingPostTypeSlugs = array('revision', 'attachment', 'nav_menu_item',);
    protected function getStyles() {
        $_sParentStyles = parent::getStyles();
        return $_sParentStyles . ".omniweb-showtimes-field input[type='checkbox'] {margin-right: 0.5em;} .omniweb-showtimes-field-posttype .omniweb-showtimes-input-label-container {padding-right: 1em;}";
    }
    protected function getField($aField) {
        $this->_sCheckboxClassSelector = '';
        $aField['label'] = $this->_getPostTypeArrayForChecklist(isset($aField['slugs_to_remove']) ? $this->getAsArray($aField['slugs_to_remove']) : $this->aDefaultRemovingPostTypeSlugs, $aField['query'], $aField['operator']);
        return parent::getField($aField);
    }
    private function _getPostTypeArrayForChecklist($aSlugsToRemove, $asQueryArgs = array(), $sOperator = 'and') {
        $_aPostTypes = array();
        foreach (get_post_types($asQueryArgs, 'objects') as $_oPostType) {
            if (isset($_oPostType->name, $_oPostType->label)) {
                $_aPostTypes[$_oPostType->name] = $_oPostType->label;
            }
        }
        return array_diff_key($_aPostTypes, array_flip($aSlugsToRemove));
    }
}


text:
<?php

require_once '../../csrest_clients.php';

$auth = array(
    'access_token' => 'your access token',
    'refresh_token' => 'your refresh token');
$wrap = new CS_REST_Clients(
    'ClientID to get Lists for',
    $auth);

$email_address = 'your_email_address@example.com';

$result = $wrap->get_lists_for_email($email_address);

echo "Result of /api/v3.1/clients/{id}/listsforemail\n
";
if($result->was_successful()) {
    echo "Got lists to which email address ".$email_address." is subscribed\n

";
    var_dump($result->response);
} else {
    echo 'Failed with code '.$result->http_status_code."\n

";
    var_dump($result->response);
}
echo '
';


text:
require File.dirname(__FILE__) + '/../../spec_helper'

ruby_version_is "1.9" do

  describe "Hash.try_convert" do

    it "returns the argument if passed a Hash" do
      h = {:foo => :glark}
      Hash.try_convert(h).should == h
    end

    it "returns nil if the argument can't be coerced into a Hash" do
      Hash.try_convert(Object.new).should be_nil
    end

    it "coerces the argument with #to_hash" do
      obj = mock('hash')
      obj.should_receive(:to_hash).and_return({:foo => :bar})
      Hash.try_convert(obj).should == {:foo => :bar}
    end

  end
end


text:
<?php

namespace Troiswa\PublicBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Troiswa\PublicBundle\Entity\Film;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class FilmController extends Controller
{
    public function allFilmsAction()
    {

        $em = $this->getDoctrine()->getManager();
        $films = $em->getRepository('TroiswaPublicBundle:Film')->findAll();

        //return new Response('Hello Sexy films!');

        return $this->render('TroiswaPublicBundle:Films:films.html.twig',array('films' => $films));
    }

    public function addFilmAction(Request $request) {
        $film = new Film();
        $form = $this -> createFormBuilder($film)
            ->add('titre','text')
            ->add('description')
            ->add('dateCreation','date',array(
                'widget' => 'single_text',
                'format' => 'MM/dd/yyyy'))
            ->add('visible','choice',array(
                'choices' => array(0 => 'Non', 1 => 'Oui' ),
                'expanded' => true,
                'multiple' => false,
                'data' => 1,
            ))
            ->add('sauvegarder','submit')
            ->getForm();

        $form->handleRequest(($request));

        if ($form->isValid())
        {
            //$date = $request->request->get('form')['dateCreation'];

            //$tab = $request->request->get('form');
            //$dateCreation = $tab['dateCreation'];
            //$dateCreation = new \DateTime($dateCreation);
            //$film->setDateCreation($dateCreation);
            $em = $this->getDoctrine()->getManager();
            $em->persist($film);
            $em->flush();

            $request->getSession()->getFlashbag()->add('message','Votre film a bien été créé');

            return $this->redirect($this->generateUrl('troiswa_public_films'));
        }

        return $this->render('TroiswaPublicBundle:Films:addfilm.html.twig',array('formFilm'=>$form->createView()));
    }
}


text:
package openmarker.tea.compiler;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Arrays;

import openmarker.tea.parsetree.Template;
import openmarker.tea.parsetree.Variable;
import openmarker.trove.classfile.TypeDesc;
import openmarker.trove.io.DualOutput;
import openmarker.trove.io.SourceReader;
import openmarker.trove.util.ClassInjector;

/**
 * A compilation unit is a unit of compilation for a given template that
 * provides source details and outputs the compiled result to a given set of
 * output streams (class files, injectors, etc).  It works hand-in-hand with the
 * associated compiler during compilation.
 *
 * @author Brian S O'Neill
 */
public class CompilationUnit implements CompileListener {

    private String mName;
    private Compiler mCompiler;
    private Template mTree;
    private CompilationSource mSource;

    private int mErrorCount;
    private int mWarningCount;
    private File mDestDir;
    private File mDestFile;

    public CompilationUnit(String name, CompilationSource source,
                           Compiler compiler) {
        mName = name;
        mSource = source;
        mCompiler = compiler;

        initialize();
    }

    private void initialize() {
        String slashPath = mName.replace('.', '/');
        if (slashPath.endsWith("/")) {
            slashPath = slashPath.substring(0, slashPath.length() - 1);
        }

        File rootDestDir = mCompiler.getRootDestDir();
        if (rootDestDir != null) {
            if (slashPath.lastIndexOf('/') >= 0) {
                mDestDir = new File
                    (rootDestDir,
                     slashPath.substring(0,slashPath.lastIndexOf('/')));
            }
            else {
                mDestDir = rootDestDir;
            }

            mDestDir.mkdirs();
            mDestFile = new File(
                mDestDir,
                slashPath.substring(slashPath.lastIndexOf('/') + 1) +
                    ".class"
            );
        }
    }

    public String getName() {
        return mName;
    }

    public String getShortName() {
        String name = getName();
        int index = name.lastIndexOf('.');
        if (index >= 0) {
            return name.substring(index + 1);
        }

        return name;
    }

    public String getSourcePath() {
        return mSource == null ? null : mSource.getSourcePath();
    }

    /**
     * Get the associated compiler for this unit.
     *
     * @return The associated compiler for this compilation unit
     */
    protected Compiler getCompiler() {
        return mCompiler;
    }

    /**
     * The retrieves the runtime context.  The default behavior is to delegate
     * this call to the compiler.  This is overriden to implement compiled
     * templates.
     */
    public Class<?> getRuntimeContext() {
        return mCompiler.getRuntimeContext();
    }

    /**
     * Called when there is an error when compiling this CompilationUnit.
     */
    public void compileError(CompileEvent e) {
        mErrorCount++;
    }

    /**
     * Called when there is a warning when compiling this CompilationUnit.
     */
    public void compileWarning(CompileEvent e) {
        mWarningCount++;
    }

    /**
     * Returns the number of errors generated while compiling this
     * CompilationUnit.
     */
    public int getErrorCount() {
        return mErrorCount;
    }

    /**
     * Returns the number of warnings generated while compiling this
     * CompilationUnit.
     */
    public int getWarningCount() {
        return mWarningCount;
    }

    public Template getParseTree() {
        if (mTree == null && mCompiler != null) {
            return mCompiler.getParseTree(this);
        }
        return mTree;
    }

    public void setParseTree(Template tree) {
        mTree = tree;
    }

    /**
     * Current implementation returns only the same packages as the compiler.
     *
     * @see Compiler#getImportedPackages()
     */
    public final String[] getImportedPackages() {
        return mCompiler.getImportedPackages();
    }

    /**
     * Return the package name that this CompilationUnit should be compiled
     * into. Default implementation returns null, or no package.
     */
    public String getTargetPackage() {
        return mCompiler.getRootPackage();
    }

    public Reader getReader() throws IOException {
        Reader reader = null;
        InputStream in = getTemplateSource();
        String encoding = mCompiler.getEncoding();
        if (encoding == null) {
            reader = new InputStreamReader(in);
        }
        else {
            reader = new InputStreamReader(in, encoding);
        }

        return reader;
    }

    public void syncTimes() {
        if (mDestFile != null) {
            mDestFile.setLastModified(getLastModified());
        }
    }

    public boolean shouldCompile() {
        return getCompiler().isForceCompile() ||
               shouldCompile(getDestinationLastModified());
    }

    protected boolean shouldCompile(long timestamp) {
        if (mDestFile != null && !mDestFile.exists()) {
            return true;
        }

        long precompiledTolerance = mCompiler.getPrecompiledTolerance();
        long lastModified = getLastModified();
        if (timestamp > 0 && lastModified > 0 &&
            gteq(timestamp, lastModified, precompiledTolerance)) {

            return false;
        }

        return true;
    }

    public long getLastModified() {
        return mSource == null ? -1 : mSource.getLastModified();
    }

    protected long getDestinationLastModified() {
        if (mDestFile != null && mDestFile.exists()) {
            return mDestFile.lastModified();
        }

        return 0L;
    }

    /**
     * Returns the truth that a is greater than or equal to b assuming the given tolerance.
     *

     * ex. tolerance = 10, a = 1000 and b = 2000, returns false

     * ex. tolerance = 10, a = 1989 and b = 2000, returns false

     * ex. tolerance = 10, a = 1990 and b = 2000, returns true

     * ex. tolerance = 10, a = 2000 and b = 2000, returns true

     * ex. tolerance = 10, a = 3000 and b = 2000, returns true

     *

     *
     * @param a
     * @param b
     * @param tolerance
     * @return
     */
    private boolean gteq(long a, long b, long tolerance) {
        return a >= b - tolerance;
    }

    /**
     * @return the file that gets written by the compiler.
     */
    public File getDestinationFile() {
        return mDestFile;
    }

    public OutputStream getOutputStream() throws IOException {
        OutputStream out1 = null;
        OutputStream out2 = null;

        if (mDestDir != null) {
            if (!mDestDir.exists()) {
                mDestDir.mkdirs();
            }

            out1 = new FileOutputStream(mDestFile);
        }

        ClassInjector injector = mCompiler.getInjector();
        if (injector != null) {
            String className = getName();
            String pack = getTargetPackage();
            if (pack != null && pack.length() > 0) {
                className = pack + '.' + className;
            }
            out2 = injector.getStream(className);
        }

        OutputStream out;

        if (out1 != null) {
            if (out2 != null) {
                out = new DualOutput(out1, out2);
            }
            else {
                out = out1;
            }
        }
        else if (out2 != null) {
            out = out2;
        }
        else {
            out = new OutputStream() {
                public void write(int b) {}
                public void write(byte[] b, int off, int len) {}
            };
        }

        return new BufferedOutputStream(out);
    }

    public void resetOutputStream() {
        if (mDestFile != null) {
            mDestFile.delete();
        }

        ClassInjector injector = mCompiler.getInjector();
        if (injector != null) {
            injector.resetStream(getClassName());
        }
    }

    protected String getClassName() {
        return getClassName(null);
    }

    protected String getClassName(String innerClass) {
        String className = getName();
        String pack = getTargetPackage();
        if (pack != null && pack.length() > 0) {
            className = pack + '.' + className;
        }

        if (innerClass != null) {
            className = className + '$' + innerClass;
        }

        return className;
    }

    protected InputStream getTemplateSource()
        throws IOException {

        if (mSource == null) {
            throw new IOException("no source defined for " + mName);
        }

        return mSource.getSource();
    }

    public boolean signatureEquals(String templateName, TypeDesc[] params, TypeDesc returnType) throws IOException {
        if(!getName().equals(templateName)) {
            return false;
        }

        Reader r = new BufferedReader(getReader());
        SourceReader srcReader = new SourceReader(r, "<%", "%>");
        Template tree = null;
        try {
            Scanner s = new Scanner(srcReader, this);
            s.addCompileListener(this);
            Parser p = new Parser(s, this);
            p.addCompileListener(this);
            tree = p.parse();
            s.close();

        } finally {
            r.close();
        }

        // fill sourceParams
        Variable[] vars = tree.getParams();
        TypeDesc[] sourceParams = new TypeDesc[vars.length];

        for (int i = 0; i < vars.length; i++) {
            String type = classNameFromVariable(
                    vars[i].getTypeName().getName(), vars[i].getTypeName().getDimensions());
            sourceParams[i] = TypeDesc.forClass(type);
        }

        // strip off merged class since it may be different for remote compiler
        TypeDesc[] temp = new TypeDesc[params.length-1];
        System.arraycopy(params, 1, temp, 0, temp.length);

        // compare params
        if(! Arrays.equals(temp, sourceParams)) {
            return false;
        }

        // compare return types (null is default from Template.getReturnType())
        if(null!=tree.getReturnType()) {
            TypeDesc srcReturnType = TypeDesc.forClass(tree.getReturnType().getSimpleName());
            if(! returnType.equals(srcReturnType) ) {
                return false;
            }
        }

        return true;
    }

    private String classNameFromVariable(String type, int dimensions) {

        if("short".equals(type)
        || "long".equals(type)
        || "double".equals(type)) {
            type = type.substring(0, 1).toUpperCase()+ type.substring(1);
        }

        if("int".equals(type)) {
            type = "Integer";
        }

        if("Short".equals(type)
        || "Integer".equals(type)
        || "Long".equals(type)
        || "Double".equals(type)
        || "String".equals(type)) {
            type = "java.lang."+type;
        }

        for (int j = 0; j < dimensions; j++) {
            type = type + "[]";
        }
        return type;
    }
}


text:
require 'spec_helper'

describe Gitlab::BackgroundMigration::BackfillProjectRepositories do
  let(:group) { create(:group, name: 'foo', path: 'foo') }

  describe described_class::ShardFinder do
    let(:shard) { create(:shard, name: 'default') }

    describe '#find_shard_id' do
      it 'creates a new shard when it does not exist yet' do
        expect { subject.find_shard_id('other') }.to change(Shard, :count).by(1)
      end

      it 'returns the shard when it exists' do
        other_shard = create(:shard, name: 'other')

        shard_id = subject.find_shard_id('other')

        expect(shard_id).to eq(other_shard.id)
      end

      it 'only queries the database once to retrieve shards' do
        subject.find_shard_id('default')

        expect { subject.find_shard_id('default') }.not_to exceed_query_limit(0)
      end
    end
  end

  describe described_class::Project do
    let!(:project_hashed_storage_1) { create(:project, name: 'foo', path: 'foo', namespace: group, storage_version: 1) }
    let!(:project_hashed_storage_2) { create(:project, name: 'bar', path: 'bar', namespace: group, storage_version: 2) }
    let!(:project_legacy_storage_3) { create(:project, name: 'baz', path: 'baz', namespace: group, storage_version: 0) }
    let!(:project_legacy_storage_4) { create(:project, name: 'zoo', path: 'zoo', namespace: group, storage_version: nil) }

    describe '.on_hashed_storage' do
      it 'finds projects with repository on hashed storage' do
        projects = described_class.on_hashed_storage.pluck(:id)

        expect(projects).to match_array([project_hashed_storage_1.id, project_hashed_storage_2.id])
      end
    end

    describe '.on_legacy_storage' do
      it 'finds projects with repository on legacy storage' do
        projects = described_class.on_legacy_storage.pluck(:id)

        expect(projects).to match_array([project_legacy_storage_3.id, project_legacy_storage_4.id])
      end
    end

    describe '.without_project_repository' do
      it 'finds projects which do not have a projects_repositories entry' do
        create(:project_repository, project: project_hashed_storage_1)
        create(:project_repository, project: project_legacy_storage_3)

        projects = described_class.without_project_repository.pluck(:id)

        expect(projects).to contain_exactly(project_hashed_storage_2.id, project_legacy_storage_4.id)
      end
    end

    describe '#disk_path' do
      context 'for projects on hashed storage' do
        it 'returns the correct disk_path' do
          project = described_class.find(project_hashed_storage_1.id)

          expect(project.disk_path).to eq(project_hashed_storage_1.disk_path)
        end
      end

      context 'for projects on legacy storage' do
        it 'returns the correct disk_path' do
          project = described_class.find(project_legacy_storage_3.id)

          expect(project.disk_path).to eq(project_legacy_storage_3.disk_path)
        end

        it 'raises OrphanedNamespaceError when any parent namespace does not exist' do
          subgroup = create(:group, parent: group)
          project_orphaned_namespace = create(:project, name: 'baz', path: 'baz', namespace: subgroup, storage_version: nil)
          subgroup.update_column(:parent_id, Namespace.maximum(:id).succ)

          project = described_class.find(project_orphaned_namespace.id)

          expect { project.disk_path }
            .to raise_error(Gitlab::BackgroundMigration::BackfillProjectRepositories::OrphanedNamespaceError)
        end
      end
    end
  end
end


text:
from setuptools import setup, find_packages
import pyTGA

if __name__ == "__main__":
    setup(
        name="pyTGA",

        version=pyTGA.VERSION,

        description='A pure Python module to manage TGA images',
        long_description='A pure Python module to manage TGA images',

        # Author details
        author='Mirco Tracolli',
        author_email='mirco.theone@gmail.com',
        url='https://github.com/MircoT/pyTGA',
        download_url='https://github.com/MircoT/pyTGA/releases/latest',

        # Choose your license
        license='MIT',

        # https://pypi.python.org/pypi?%3Aaction=list_classifiers
        classifiers=[
            'Development Status :: 5 - Production/Stable',

            'Intended Audience :: Developers',
            'Intended Audience :: Education',
            'Intended Audience :: End Users/Desktop',

            'License :: OSI Approved :: MIT License',

            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.5',
        ],

        keywords='tga image development',

        packages=find_packages(exclude=['contrib', 'docs', 'tests']),

        install_requires=[],
        extras_require={},
        package_data={},
        data_files=[],
        entry_points={}
    )


text:
'use strict';

angular.module('core').controller('HomeController', ['$scope','uiGmapGoogleMapApi',
	function($scope, uiGmapGoogleMapApi) {
        $scope.map = { center: { latitude: 43.4500, longitude: -80.4833 }, zoom: 12,showKml: true };
        $scope.FusionTablesLayerOptions = {
            query: {
              select: 'geometry',
              from: '13UWrpziJArgWCQeZJSvpuwXpoVmCDKl2T_x96HQj'
            }
        };
         // uiGmapGoogleMapApi is a promise.
        // The "then" callback function provides the google.maps object.
        uiGmapGoogleMapApi.then(function(maps) {
        });
	}

]);


text:
#ifndef _HVSI_H
#define _HVSI_H

#define VS_DATA_PACKET_HEADER           0xff
#define VS_CONTROL_PACKET_HEADER        0xfe
#define VS_QUERY_PACKET_HEADER          0xfd
#define VS_QUERY_RESPONSE_PACKET_HEADER 0xfc

/* control verbs */
#define VSV_SET_MODEM_CTL    1 /* to service processor only */
#define VSV_MODEM_CTL_UPDATE 2 /* from service processor only */
#define VSV_CLOSE_PROTOCOL   3

/* query verbs */
#define VSV_SEND_VERSION_NUMBER 1
#define VSV_SEND_MODEM_CTL_STATUS 2

/* yes, these masks are not consecutive. */
#define HVSI_TSDTR 0x01
#define HVSI_TSCD  0x20

#define HVSI_MAX_OUTGOING_DATA 12
#define HVSI_VERSION 1

struct hvsi_header {
	uint8_t  type;
	uint8_t  len;
	uint16_t seqno;
} __attribute__((packed));

struct hvsi_data {
	struct hvsi_header hdr;
	uint8_t  data[HVSI_MAX_OUTGOING_DATA];
} __attribute__((packed));

struct hvsi_control {
	struct hvsi_header hdr;
	uint16_t verb;
	/* optional depending on verb: */
	uint32_t word;
	uint32_t mask;
} __attribute__((packed));

struct hvsi_query {
	struct hvsi_header hdr;
	uint16_t verb;
} __attribute__((packed));

struct hvsi_query_response {
	struct hvsi_header hdr;
	uint16_t verb;
	uint16_t query_seqno;
	union {
		uint8_t  version;
		uint32_t mctrl_word;
	} u;
} __attribute__((packed));

/* hvsi lib struct definitions */
#define HVSI_INBUF_SIZE		255
struct tty_struct;
struct hvsi_priv {
	unsigned int	inbuf_len;	/* data in input buffer */
	unsigned char	inbuf[HVSI_INBUF_SIZE];
	unsigned int	inbuf_cur;	/* Cursor in input buffer */
	unsigned int	inbuf_pktlen;	/* packet lenght from cursor */
	atomic_t	seqno;		/* packet sequence number */
	unsigned int	opened:1;	/* driver opened */
	unsigned int	established:1;	/* protocol established */
	unsigned int 	is_console:1;	/* used as a kernel console device */
	unsigned int	mctrl_update:1;	/* modem control updated */
	unsigned short	mctrl;		/* modem control */
	struct tty_struct *tty;		/* tty structure */
	int (*get_chars)(uint32_t termno, char *buf, int count);
	int (*put_chars)(uint32_t termno, const char *buf, int count);
	uint32_t	termno;
};

/* hvsi lib functions */
struct hvc_struct;
extern void hvsilib_init(struct hvsi_priv *pv,
			 int (*get_chars)(uint32_t termno, char *buf, int count),
			 int (*put_chars)(uint32_t termno, const char *buf,
					  int count),
			 int termno, int is_console);
extern int hvsilib_open(struct hvsi_priv *pv, struct hvc_struct *hp);
extern void hvsilib_close(struct hvsi_priv *pv, struct hvc_struct *hp);
extern int hvsilib_read_mctrl(struct hvsi_priv *pv);
extern int hvsilib_write_mctrl(struct hvsi_priv *pv, int dtr);
extern void hvsilib_establish(struct hvsi_priv *pv);
extern int hvsilib_get_chars(struct hvsi_priv *pv, char *buf, int count);
extern int hvsilib_put_chars(struct hvsi_priv *pv, const char *buf, int count);

#endif /* _HVSI_H */


text:
using UnityEngine;
using System.Collections;

public class OTEaseSineIn : OTEase
{
    private float _HALF_PI = Mathf.PI / 2;

    public override float ease(float t, float b, float c, float d)
    {
        return -c * Mathf.Cos(t / d * _HALF_PI) + c + b;
    }
}


text:
using namespace ikaros;

Module *
OutputRawImage::Create(Parameter * p)
{
    return new OutputRawImage(p);
}

OutputRawImage::OutputRawImage(Parameter * p):
        Module(p)
{
    scale	 	= GetFloatValue("scale");
    file_name	= GetValue("filename");
    supress 	= GetIntValue("supress");
    offset	 	= GetIntValue("offset");

    if (file_name == NULL)
    {
        Notify(msg_fatal_error, "No filename(s) supplied.\n");
        return;
    }

    cur_image = 0;

    AddInput("INPUT");
}

OutputRawImage::~OutputRawImage()
{
}

void
OutputRawImage::Init()
{
    image = GetInputArray("INPUT");
    size_x = GetInputSizeX("INPUT");
    size_y = GetInputSizeY("INPUT");
}

void
OutputRawImage::Tick()
{
    char fn[256];
    sprintf(fn, file_name, offset + cur_image);

    if (supress > cur_image)
    {
        Notify(msg_verbose, "Supressing write of \"%s\" (%dx%d)\n", fn, size_x, size_y);
        cur_image++;
        return;
    }

    file = fopen(fn, "wb");

    Notify(msg_verbose, "Writing \"%s\" (%dx%d)\n", fn, size_x, size_y);

    if (file == NULL)
    {
        Notify(msg_fatal_error, "Could not open image file \"%s\" \n", fn);
        return;
    }

    for (int i=0; i<size_x*size_y; i++)
        fputc(clip(scale*image[i], 0, 255), file);

    fclose(file);

    cur_image++;
}


text:
@implementation UIFont (Ledger)

+ (instancetype)ledgerRegularFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"Ledger-Regular"
                   fromBundle:@"Ledger"
                    onceToken:&onceToken];
  return [self fontWithName:@"Ledger-Regular" size:size];
}

@end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>edu.brown.cs.systems</groupId>
    <artifactId>xtrace-client</artifactId>
    <packaging>jar</packaging>

    <name>X-Trace - Client Library</name>

    <parent>
        <groupId>edu.brown.cs.systems</groupId>
        <artifactId>xtrace-project</artifactId>
        <version>4.0</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
        </dependency>
        <dependency>
            <groupId>edu.brown.cs.systems</groupId>
            <artifactId>pubsub</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>edu.brown.cs.systems</groupId>
            <artifactId>xtrace-common</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>edu.brown.cs.systems</groupId>
            <artifactId>tracingplane-client</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
</project>


text:
package com.alibaba.jstorm.schedule.default_assign;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.alibaba.jstorm.daemon.supervisor.SupervisorInfo;
import com.alibaba.jstorm.schedule.IToplogyScheduler;
import com.alibaba.jstorm.schedule.TopologyAssignContext;
import com.alibaba.jstorm.task.Assignment;
import com.alibaba.jstorm.utils.FailedAssignTopologyException;

public class DefaultTopologyScheduler implements IToplogyScheduler {
	private static final Logger LOG = Logger
			.getLogger(DefaultTopologyScheduler.class);

	private Map nimbusConf;

	@Override
	public void prepare(Map conf) {
		nimbusConf = conf;
	}

	/**
	 * @@@ Here maybe exist one problem, some dead slots have been free
	 *
	 * @param context
	 */
	protected void freeUsed(TopologyAssignContext context) {
		Set<Integer> canFree = new HashSet<Integer>();
		canFree.addAll(context.getAllTaskIds());
		canFree.removeAll(context.getUnstoppedTaskIds());

		Map<String, SupervisorInfo> cluster = context.getCluster();
		Assignment oldAssigns = context.getOldAssignment();
		for (Integer task : canFree) {
			ResourceWorkerSlot worker = oldAssigns.getWorkerByTaskId(task);
			if (worker == null) {
				LOG.warn("When free rebalance resource, no ResourceAssignment of task "
						+ task);
				continue;
			}

			SupervisorInfo supervisorInfo = cluster.get(worker.getNodeId());
			if (supervisorInfo == null) {
				continue;
			}
			supervisorInfo.getWorkerPorts().add(worker.getPort());
		}
	}

	private Set<Integer> getNeedAssignTasks(DefaultTopologyAssignContext context) {
		Set<Integer> needAssign = new HashSet<Integer>();

		int assignType = context.getAssignType();
		if (assignType == TopologyAssignContext.ASSIGN_TYPE_NEW) {
			needAssign.addAll(context.getAllTaskIds());
		} else if (assignType == TopologyAssignContext.ASSIGN_TYPE_REBALANCE) {
			needAssign.addAll(context.getAllTaskIds());
			needAssign.removeAll(context.getUnstoppedTaskIds());
		} else {
			// monitor
			needAssign.addAll(context.getDeadTaskIds());
		}

		return needAssign;
	}

	/**
	 * Get the task Map which the task is alive and will be kept Only when type
	 * is ASSIGN_TYPE_MONITOR, it is valid
	 *
	 * @param defaultContext
	 * @param needAssigns
	 * @return
	 */
	public Set<ResourceWorkerSlot> getKeepAssign(
			DefaultTopologyAssignContext defaultContext,
			Set<Integer> needAssigns) {

		Set<Integer> keepAssignIds = new HashSet<Integer>();
		keepAssignIds.addAll(defaultContext.getAllTaskIds());
		keepAssignIds.removeAll(defaultContext.getUnstoppedTaskIds());
		keepAssignIds.removeAll(needAssigns);
		Set<ResourceWorkerSlot> keeps = new HashSet<ResourceWorkerSlot>();
		if (keepAssignIds.isEmpty()) {
			return keeps;
		}

		Assignment oldAssignment = defaultContext.getOldAssignment();
		if (oldAssignment == null) {
			return keeps;
		}
		keeps.addAll(defaultContext.getOldWorkers());
		for (ResourceWorkerSlot worker : defaultContext.getOldWorkers()) {
			for (Integer task : worker.getTasks()) {
				if (!keepAssignIds.contains(task)) {
					keeps.remove(worker);
					break;
				}
			}
		}
		return keeps;
	}

	@Override
	public Set<ResourceWorkerSlot> assignTasks(TopologyAssignContext context)
			throws FailedAssignTopologyException {

		int assignType = context.getAssignType();
		if (TopologyAssignContext.isAssignTypeValid(assignType) == false) {
			throw new FailedAssignTopologyException("Invalide Assign Type "
					+ assignType);
		}

		DefaultTopologyAssignContext defaultContext = new DefaultTopologyAssignContext(
				context);
		if (assignType == TopologyAssignContext.ASSIGN_TYPE_REBALANCE) {
			freeUsed(defaultContext);
		}
		LOG.info("Dead tasks:" + defaultContext.getDeadTaskIds());
		LOG.info("Unstopped tasks:" + defaultContext.getUnstoppedTaskIds());

		Set<Integer> needAssignTasks = getNeedAssignTasks(defaultContext);

		Set<ResourceWorkerSlot> keepAssigns = getKeepAssign(defaultContext,
				needAssignTasks);

		// please use tree map to make task sequence
		Set<ResourceWorkerSlot> ret = new HashSet<ResourceWorkerSlot>();
		ret.addAll(keepAssigns);
		ret.addAll(defaultContext.getUnstoppedWorkers());

		int allocWorkerNum = defaultContext.getTotalWorkerNum()
				- defaultContext.getUnstoppedWorkerNum() - keepAssigns.size();

		if (allocWorkerNum <= 0) {
			LOG.warn("Don't need assign workers, all workers are fine "
					+ defaultContext.toDetailString());
			throw new FailedAssignTopologyException(
					"Don't need assign worker, all workers are fine ");
		}

		List<ResourceWorkerSlot> newAssignList = WorkerMaker.getInstance()
				.makeWorkers(defaultContext, needAssignTasks, allocWorkerNum);
		TaskGanker ganker = new TaskGanker(defaultContext, needAssignTasks,
				newAssignList);
		Set<ResourceWorkerSlot> newAssigns = new HashSet<ResourceWorkerSlot>(
				ganker.gankTask());
		ret.addAll(newAssigns);

		LOG.info("Keep Alive slots:" + keepAssigns);
		LOG.info("Unstopped slots:" + defaultContext.getUnstoppedWorkers());
		LOG.info("New assign slots:" + newAssigns);

		return ret;
	}

}


text:
if [[ -z $1 || -z $2 || -z $3 || -z $4 || -z $5 ]]; then
    >&2 cat <<USAGE
Usage:
  $0 <remote_host> <remote_port> <local_port> <ssh_user> <ssh_host>
This will map <remote_host>:<remote_port> to <local_port> by SSH over <ssh_host>,
then you can access the <remote_host>:<remote_port> through <localhost>:<local_port>
Please edit \`/etc/ssh/sshd_config\` on <ssh_host> and set \`GatewayPorts yes\`

Put this to crontab and run every minute to keep the tunnel active
USAGE
    exit
fi

REMOTE_HOST=$1
REMOTE_PORT=$2
LOCAL_PORT=$3
USER=$4
HOST=$5

CMD="ssh -NfL ${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT} ${USER}@${HOST}"
nc -zw3 127.0.0.1 ${LOCAL_PORT} && exit
echo Connection failed
PID=$(pgrep -f "${CMD}")
test $? = 0 && echo Killing old connection... && kill ${PID}
echo Reconnecting...
echo ${CMD}
${CMD}
echo Done


text:
<?php

/**
*
* Tests filters and plugins
*
* @version $Id: 5_filters.php,v 1.1 2004/10/04 01:52:24 pmjones Exp $
*
*/

error_reporting(E_ALL);

require_once 'Savant2.php';

$conf = array(
	'template_path' => 'templates',
	'resource_path' => 'resources'
);

$savant =& new Savant2($conf);

// set up filters
$savant->loadFilter('colorizeCode');
$savant->loadFilter('trimwhitespace');
$savant->loadFilter('fester', null, true);

// run through the template
$savant->display('filters.tpl.php');

// do it again to test object persistence
$savant->display('filters.tpl.php');

// do it again to test object persistence
$savant->display('filters.tpl.php');

echo "
\n";
echo "
";
print_r($savant);
echo "
";

?>


text:
<?php

require_once dirname(__FILE__) . '/interfaces/ICBHasFunctions.php';
require_once dirname(__FILE__) . '/interfaces/ICBHasParentScope.php';
require_once dirname(__FILE__) . '/interfaces/ICBNamedEntity.php';

require_once dirname(__FILE__) . '/_base/CBEntity.php';
require_once dirname(__FILE__) . '/_base/CBBuildableEntity.php';

require_once dirname(__FILE__) . '/CBFactory.php';
require_once dirname(__FILE__) . '/CBFileBuildContext.php';
require_once dirname(__FILE__) . '/CBFinal.php';
require_once dirname(__FILE__) . '/CBSettings.php';
require_once dirname(__FILE__) . '/CBUtil.php';
require_once dirname(__FILE__) . '/CBValueSource.php';

require_once dirname(__FILE__) . '/Backend/_base/CBBackend.php';
require_once dirname(__FILE__) . '/Backend/CBCBackend.php';
require_once dirname(__FILE__) . '/Backend/CBPhpBackend.php';

require_once dirname(__FILE__) . '/Scope/_base/CBScope.php';
require_once dirname(__FILE__) . '/Scope/CBClass.php';
require_once dirname(__FILE__) . '/Scope/Block/_base/CBBlock.php';
require_once dirname(__FILE__) . '/Scope/Block/CBEach.php';
require_once dirname(__FILE__) . '/Scope/Block/CBFile.php';
require_once dirname(__FILE__) . '/Scope/Block/CBFunction.php';
require_once dirname(__FILE__) . '/Scope/Block/CBListIterator.php';

require_once dirname(__FILE__) . '/Entity/Entity/CBClassRef.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBFunctionCallResult.php';

require_once dirname(__FILE__) . '/Entity/Entity/CBType/_base/CBType.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBType/CBTypeAtomic.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBType/CBTypeList.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBType/CBTypeObject.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBType/CBTypeStruct.php';
require_once dirname(__FILE__) . '/Entity/Entity/CBType/CBTypeUnknown.php';

require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBFunctionCall.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBFunctionCall.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBFunctionParameter.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBIf.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBMutVarAssignment.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/CBPredicate.php';

require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/factory/CBContainerValueFactory.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/factory/CBContainerValueListFactory.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/factory/CBContainerValueStructFactory.php';

require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/_base/CBValue.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/CBList.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/CBObject.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Value/CBStruct.php';

require_once dirname(__FILE__) . '/Entity/BuildableEntity/Variable/_base/CBBaseVariable.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Variable/CBVariable.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/Variable/CBMutVar.php';

require_once dirname(__FILE__) . '/Entity/BuildableEntity/VarPath/CBVarPath.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/VarPath/CBVarPathListIndex.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/VarPath/CBVarPathListItem.php';
require_once dirname(__FILE__) . '/Entity/BuildableEntity/VarPath/CBVarPathStructField.php';

require_once dirname(__FILE__) . '/hl/selector/CBSelector.php';
require_once dirname(__FILE__) . '/hl/selector/CBSelectorPathParser.php';
require_once dirname(__FILE__) . '/hl/selector/tokens/CBSelectorToken.php';
require_once dirname(__FILE__) . '/hl/selector/tokens/CBSelectorTokenField.php';
require_once dirname(__FILE__) . '/hl/selector/tokens/CBSelectorTokenList.php';


text:
using Serilog.Core;
using Serilog.Events;
using System.Collections.Generic;
using System.Linq;

namespace Serilog.Filters.Expressions.Tests.Support
{
    class CollectingSink : ILogEventSink
    {
        readonly List<LogEvent> _events = new List<LogEvent>();

        public List<LogEvent> Events { get { return _events; } }

        public LogEvent SingleEvent { get { return _events.Single(); } }

        public void Emit(LogEvent logEvent)
        {
            _events.Add(logEvent);
        }
    }
}


text:
package main

import (
	"context"

	"github.com/someone1/zfsbackup-go/cmd"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cmd.Execute(ctx)
}


text:
---
title : "Mermaid"
description : "Génération de diagrammes à partir de texte, dans le même style que Markdown"
---

[Mermaid](https://mermaidjs.github.io/) est une bibliothèque Javascript qui permet de générer des diagrammes (séquence, état, gantt, etc.) à partir de texte, dans le même style que Markdown.

Insérer votre code Mermaid dans un shortcode `mermaid` et c'est tout.

## Flowchart example
    {{</*mermaid align="left"*/>}}
    graph LR;
        A[Bords droits] -->|Lien texte| B(Bords arondis)
        B --> C{Décision}
        C -->|Un| D[Résultat un]
        C -->|Deux| E[Résultat deux]
    {{</* /mermaid */>}}

renders as

{{<mermaid align="left">}}
graph LR;
    A[Bords droits] -->|Lien texte| B(Bords arondis)
    B --> C{Décision}
    C -->|Un| D[Résultat un]
    C -->|Deux| E[Résultat deux]
{{< /mermaid >}}

## Sequence example

    {{</*mermaid*/>}}
    sequenceDiagram
        participant Alice
        participant Bob
        Alice->>John: Salut John, comment vas-tu?
        loop Vérification
            John->John: Se bat contre l'hyponcodrie.
        end
        Note right of John: Les pensées rationnelles
prédominent...
        John-->Alice: Super!
        John->Bob: Et toi?
        Bob-->John: Au top!
    {{</* /mermaid */>}}

renders as

{{<mermaid>}}
sequenceDiagram
    participant Alice
    participant Bob
    Alice->>John: Salut John, comment vas-tu?
    loop Vérification
        John->John: Se bat contre l'hyponcodrie.
    end
    Note right of John: Les pensées rationnelles
prédominent...
    John-->Alice: Super!
    John->Bob: Et toi?
    Bob-->John: Au top!
{{< /mermaid >}}

## GANTT Example

    {{</*mermaid*/>}}
    gantt
            dateFormat  YYYY-MM-DD
            title Ajout de la fonctionnalité de GANTT à Mermaid
            section Une section
            Tâche complétée            :done,    des1, 2014-01-06,2014-01-08
            Tâche en cours             :active,  des2, 2014-01-09, 3d
            Future tâche               :         des3, after des2, 5d
            Future tâche 2             :         des4, after des3, 5d
            section Tâches critiques
            Tâche complétée dans le chemin critique :crit, done, 2014-01-06,24h
            Implémenter le parser et jison          :crit, done, after des1, 2d
            Créer des tests pour le parser          :crit, active, 3d
            Future tâche dans le chemin critique    :crit, 5d
            Créer des tests pour le renderer        :2d
            Ajout à Mermaid                          :1d
    {{</* /mermaid */>}}

renders as

{{<mermaid>}}
gantt
        dateFormat  YYYY-MM-DD
        title Ajout de la fonctionnalité de GANTT à Mermaid
        section Une section
        Tâche complétée            :done,    des1, 2014-01-06,2014-01-08
        Tâche en cours             :active,  des2, 2014-01-09, 3d
        Future tâche               :         des3, after des2, 5d
        Future tâche 2             :         des4, after des3, 5d
        section Tâches critiques
        Tâche complétée dans le chemin critique :crit, done, 2014-01-06,24h
        Implémenter le parser et jison          :crit, done, after des1, 2d
        Créer des tests pour le parser             :crit, active, 3d
        Future tâche dans le chemin critique        :crit, 5d
        Créer des tests pour le renderer           :2d
        Ajout à Mermaid                      :1d
{{</mermaid>}}

### Class example

    {{/* mermaid */}}
    classDiagram
      Class01 <|-- AveryLongClass : Cool
      Class03 *-- Class04
      Class05 o-- Class06
      Class07 .. Class08
      Class09 --> C2 : Where am i?
      Class09 --* C3
      Class09 --|> Class07
      Class07 : equals()
      Class07 : Object[] elementData
      Class01 : size()
      Class01 : int chimp
      Class01 : int gorilla
      Class08 <--> C2: Cool label
    {{/* /mermaid */}}

renders as

{{< mermaid >}}
classDiagram
  Class01 <|-- AveryLongClass : Cool
  Class03 *-- Class04
  Class05 o-- Class06
  Class07 .. Class08
  Class09 --> C2 : Where am i?
  Class09 --* C3
  Class09 --|> Class07
  Class07 : equals()
  Class07 : Object[] elementData
  Class01 : size()
  Class01 : int chimp
  Class01 : int gorilla
  Class08 <--> C2: Cool label
{{< /mermaid >}}

### Git example

    {{</* mermaid */>}}
    gitGraph:
    options
    {
      "nodeSpacing": 150,
      "nodeRadius": 10
    }
    end
      commit
      branch newbranch
      checkout newbranch
      commit
      commit
      checkout master
      commit
      commit
      merge newbranch
    {{</* /mermaid */>}}

renders as

{{< mermaid >}}
gitGraph:
options
{
  "nodeSpacing": 150,
  "nodeRadius": 10
}
end
  commit
  branch newbranch
  checkout newbranch
  commit
  commit
  checkout master
  commit
  commit
  merge newbranch
{{< /mermaid >}}

### State Diagrams

    {{</* mermaid */>}}
    stateDiagram-v2
      ouvert: Ouvert
      clos: Clos
      fermé: Fermé
      ouvert --> clos
      clos   --> fermé: Lock
      fermé --> clos: Unlock
      clos --> ouvert: Open
    {{</* /mermaid */>}}

renders as

{{<mermaid>}}
stateDiagram-v2
  ouvert: Ouvert
  clos: Clos
  fermé: Fermé
  ouvert --> clos
  clos   --> fermé: Lock
  fermé --> clos: Unlock
  clos --> ouvert: Open
{{</mermaid>}}


text:
require File.expand_path("../../../../base", __FILE__)

describe "VagrantPlugins::CommandSSHConfig::Command" do
  include_context "unit"
  include_context "virtualbox"

  let(:described_class) { Vagrant.plugin("2").manager.commands[:"ssh-config"] }

  let(:argv)     { [] }
  let(:env)      { Vagrant::Environment.new }
  let(:machine)  { double("Vagrant::Machine", :name => nil) }
  let(:ssh_info) {{
    :host             => "testhost.vagrant.dev",
    :port             => 1234,
    :username         => "testuser",
    :private_key_path => [],
    :forward_agent    => false,
    :forward_x11      => false
  }}

  subject { described_class.new(argv, env) }

  before do
    subject.stub(:with_target_vms) { |&block| block.call machine }
  end

  describe "execute" do
    it "prints out the ssh config for the given machine" do
      machine.stub(:ssh_info) { ssh_info }
      subject.should_receive(:safe_puts).with(<<-SSHCONFIG)
Host vagrant
  HostName testhost.vagrant.dev
  User testuser
  Port 1234
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentitiesOnly yes
  LogLevel FATAL
      SSHCONFIG
      subject.execute
    end

    it "turns on agent forwarding when it is configured" do
      machine.stub(:ssh_info) { ssh_info.merge(:forward_agent => true) }
      subject.should_receive(:safe_puts).with { |ssh_config|
        ssh_config.should include("ForwardAgent yes")
      }
      subject.execute
    end

    it "turns on x11 forwarding when it is configured" do
      machine.stub(:ssh_info) { ssh_info.merge(:forward_x11 => true) }
      subject.should_receive(:safe_puts).with { |ssh_config|
        ssh_config.should include("ForwardX11 yes")
      }
      subject.execute
    end

    it "handles multiple private key paths" do
      machine.stub(:ssh_info) { ssh_info.merge(:private_key_path => ["foo", "bar"]) }
      subject.should_receive(:safe_puts).with { |ssh_config|
        ssh_config.should include("IdentityFile foo")
        ssh_config.should include("IdentityFile bar")
      }
      subject.execute
    end

    it "puts quotes around an identityfile path if it has a space" do
      machine.stub(:ssh_info) { ssh_info.merge(:private_key_path => ["with a space"]) }
      subject.should_receive(:safe_puts).with { |ssh_config|
        ssh_config.should include('IdentityFile "with a space"')
      }
      subject.execute
    end
  end
end