text:
(function ($) {

	$.widget("thomaskahn.smoothDivScroll", {
		// Default options
		options: {
			// Classes for elements added by Smooth Div Scroll
			scrollingHotSpotLeftClass: "scrollingHotSpotLeft", // String
			scrollingHotSpotRightClass: "scrollingHotSpotRight", // String
			scrollableAreaClass: "scrollableArea", // String
			scrollWrapperClass: "scrollWrapper", // String

			// Misc settings
			hiddenOnStart: false, // Boolean
			ajaxContentURL: "", // String
			countOnlyClass: "", // String
			startAtElementId: "", // String

			// Hotspot scrolling
			hotSpotScrolling: true, // Boolean
			hotSpotScrollingStep: 15, // Pixels
			hotSpotScrollingInterval: 10, // Milliseconds
			hotSpotMouseDownSpeedBooster: 3, // Integer
			visibleHotSpotBackgrounds: "always", // always, onstart or empty (no visible hotspots)
			hotSpotsVisibleTime: 1000, // Milliseconds
			easingAfterHotSpotScrolling: true, // Boolean
			easingAfterHotSpotScrollingDistance: 15, // Pixels
			easingAfterHotSpotScrollingDuration: 100, // Milliseconds
			easingAfterHotSpotScrollingFunction: "easeInQuint", // String

			// Mousewheel scrolling
			mousewheelScrolling: false, // Boolean
			mousewheelScrollingStep: 70, // Pixels
			easingAfterMouseWheelScrolling: true, // Boolean
			easingAfterMouseWheelScrollingDuration: 300, // Milliseconds
			easingAfterMouseWheelScrollingFunction: "easeOutQuart", // String

			// Manual scrolling (hotspot and/or mousewheel scrolling)
			manualContinuousScrolling: false, // Boolean

			// Autoscrolling
			autoScrollingMode: "", // String
			autoScrollingDirection: "endlessloopright", // String
			autoScrollingStep: 1, // Pixels
			autoScrollingInterval: 50, // Milliseconds

			// Easing for when the scrollToElement method is used
			scrollToAnimationDuration: 1000, // Milliseconds
			scrollToEasingFunction: "easeOutQuart" // String
		},
		_create: function () {
			var self = this, o = this.options, el = this.element;

			// Create additional elements needed by the plugin
			// First the wrappers
			el.wrapInner("
").wrapInner("
");
			// Then the hot spots
			el.prepend("

");

			// Create variables in the element data storage
			el.data("scrollWrapper", el.find("." + o.scrollWrapperClass));
			el.data("scrollingHotSpotRight", el.find("." + o.scrollingHotSpotRightClass));
			el.data("scrollingHotSpotLeft", el.find("." + o.scrollingHotSpotLeftClass));
			el.data("scrollableArea", el.find("." + o.scrollableAreaClass));
			el.data("speedBooster", 1);
			el.data("scrollXPos", 0);
			el.data("hotSpotWidth", el.data("scrollingHotSpotLeft").innerWidth());
			el.data("scrollableAreaWidth", 0);
			el.data("startingPosition", 0);
			el.data("rightScrollingInterval", null);
			el.data("leftScrollingInterval", null);
			el.data("autoScrollingInterval", null);
			el.data("hideHotSpotBackgroundsInterval", null);
			el.data("previousScrollLeft", 0);
			el.data("pingPongDirection", "right");
			el.data("getNextElementWidth", true);
			el.data("swapAt", null);
			el.data("startAtElementHasNotPassed", true);
			el.data("swappedElement", null);
			el.data("originalElements", el.data("scrollableArea").children(o.countOnlyClass));
			el.data("visible", true);
			el.data("enabled", true);
			el.data("scrollableAreaHeight", el.data("scrollableArea").height());
			el.data("scrollerOffset", el.offset());
			el.data("initialAjaxContentLoaded", false);

			/*****************************************
			SET UP EVENTS FOR SCROLLING RIGHT
			*****************************************/
			// Check the mouse X position and calculate
			// the relative X position inside the right hotspot
			el.data("scrollingHotSpotRight").bind("mousemove", function (e) {
				var x = e.pageX - (this.offsetLeft + el.data("scrollerOffset").left);
				el.data("scrollXPos", Math.round((x / el.data("hotSpotWidth")) * o.hotSpotScrollingStep));
				if (el.data("scrollXPos") === Infinity) {
					el.data("scrollXPos", 0);
				}
			});

			// Mouseover right hotspot - scrolling
			el.data("scrollingHotSpotRight").bind("mouseover", function () {

				// Stop any ongoing animations
				el.data("scrollWrapper").stop(true, false);

				// Stop any ongoing autoscrolling
				self.stopAutoScrolling();

				// Start the scrolling interval
				el.data("rightScrollingInterval", setInterval(function () {
					if (el.data("scrollXPos") > 0 && el.data("enabled")) {
						el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + (el.data("scrollXPos") * el.data("speedBooster")));

						if (o.manualContinuousScrolling) {
							self._checkContinuousSwapRight();
						}

						self._showHideHotSpots();
					}
				}, o.hotSpotScrollingInterval));

				// Callback
				self._trigger("mouseOverRightHotSpot");

			});

			// Mouseout right hotspot - stop scrolling
			el.data("scrollingHotSpotRight").bind("mouseout", function () {
				clearInterval(el.data("rightScrollingInterval"));
				el.data("scrollXPos", 0);

				// Easing out after scrolling
				if (o.easingAfterHotSpotScrolling && el.data("enabled")) {
					el.data("scrollWrapper").animate({ scrollLeft: el.data("scrollWrapper").scrollLeft() + o.easingAfterHotSpotScrollingDistance }, { duration: o.easingAfterHotSpotScrollingDuration, easing: o.easingAfterHotSpotScrollingFunction });
				}
			});

			// mousedown right hotspot (add scrolling speed booster)
			el.data("scrollingHotSpotRight").bind("mousedown", function () {
				el.data("speedBooster", o.hotSpotMouseDownSpeedBooster);
			});

			// mouseup anywhere (stop boosting the scrolling speed)
			$("body").bind("mouseup", function () {
				el.data("speedBooster", 1);
			});

			/*****************************************
			SET UP EVENTS FOR SCROLLING LEFT
			*****************************************/
			// Check the mouse X position and calculate
			// the relative X position inside the left hotspot
			el.data("scrollingHotSpotLeft").bind("mousemove", function (e) {
				//var x = el.data("hotSpotWidth") - (e.pageX - el.data("scrollerOffset").left);
				var x = ((this.offsetLeft + el.data("scrollerOffset").left + el.data("hotSpotWidth")) - e.pageX);
				el.data("scrollXPos", Math.round((x / el.data("hotSpotWidth")) * o.hotSpotScrollingStep));

				if (el.data("scrollXPos") === Infinity) {
					el.data("scrollXPos", 0);
				}

			});

			// Mouseover left hotspot
			el.data("scrollingHotSpotLeft").bind("mouseover", function () {
				// Stop any ongoing animations
				el.data("scrollWrapper").stop(true, false);

				// Stop any ongoing autoscrolling
				self.stopAutoScrolling();

				el.data("leftScrollingInterval", setInterval(function () {
					if (el.data("scrollXPos") > 0 && el.data("enabled")) {
						el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() - (el.data("scrollXPos") * el.data("speedBooster")));

						if (o.manualContinuousScrolling) {
							self._checkContinuousSwapLeft();
						}

						self._showHideHotSpots();
					}
				}, o.hotSpotScrollingInterval));

				// Callback
				self._trigger("mouseOverLeftHotSpot");
			});

			// mouseout left hotspot
			el.data("scrollingHotSpotLeft").bind("mouseout", function () {
				clearInterval(el.data("leftScrollingInterval"));
				el.data("scrollXPos", 0);

				// Easing out after scrolling
				if (o.easingAfterHotSpotScrolling && el.data("enabled")) {
					el.data("scrollWrapper").animate({ scrollLeft: el.data("scrollWrapper").scrollLeft() - o.easingAfterHotSpotScrollingDistance }, { duration: o.easingAfterHotSpotScrollingDuration, easing: o.easingAfterHotSpotScrollingFunction });
				}

			});

			// mousedown left hotspot (add scrolling speed booster)
			el.data("scrollingHotSpotLeft").bind("mousedown", function () {
				el.data("speedBooster", o.hotSpotMouseDownSpeedBooster);
			});

			/*****************************************
			SET UP EVENT FOR MOUSEWHEEL SCROLLING
			*****************************************/
			el.data("scrollableArea").mousewheel(function (event, delta) {
				if (el.data("enabled") && o.mousewheelScrolling) {
					event.preventDefault();

					// Stop any ongoing autoscrolling if it's running
					self.stopAutoScrolling();

					// Can be either positive or negative
					var pixels = Math.round(o.mousewheelScrollingStep * delta);
					self.move(pixels);

				}
			});

			// Capture and disable mousewheel events when the pointer
			// is over any of the hotspots
			if (o.mousewheelScrolling) {
				el.data("scrollingHotSpotLeft").add(el.data("scrollingHotSpotRight")).mousewheel(function (event, delta) {
					event.preventDefault();
				});
			}

			/*****************************************
			SET UP EVENT FOR RESIZING THE BROWSER WINDOW
			*****************************************/
			$(window).bind("resize", function () {
				self._showHideHotSpots();
				self._trigger("windowResized");
			});

			/*****************************************
			FETCHING AJAX CONTENT ON INITIALIZATION
			*****************************************/
			// If there's an ajaxContentURL in the options,
			// fetch the content
			if (o.ajaxContentURL.length > 0) {
				self.changeContent(o.ajaxContentURL, "", "html", "replace");
			}

			// Should it be hidden on start?
			if (o.hiddenOnStart) {
				self.hide();
			}

			/*****************************************
			AUTOSCROLLING
			*****************************************/
			// The $(window).load event handler is used the width of the elements are not calculated
			// properly until then, at least not in Google Chrome. The start of the autoscrolling and the
			// setting of the hotspot backgrounds is started here as well for the same reason.
			// If the autoscrolling is not started in $(window).load, it won't start because it
			// will interpret the scrollable areas as too short.
			$(window).load(function () {

				// If scroller is not hidden, recalculate the scrollable area
				if (!(o.hiddenOnStart)) {
					self.recalculateScrollableArea();
				}

				// Autoscrolling is active
				if ((o.autoScrollingMode.length > 0) && !(o.hiddenOnStart)) {
					self.startAutoScrolling();
				}

				// If the user wants to have visible hotspot backgrounds,
				// here is where it's taken care of

				if (o.autoScrollingMode !== "always") {

					switch (o.visibleHotSpotBackgrounds) {
						case "always":
							self.showHotSpotBackgrounds();
							break;
						case "onstart":
							self.showHotSpotBackgrounds();
							el.data("hideHotSpotBackgroundsInterval", setTimeout(function () {
								self.hideHotSpotBackgrounds("slow");
							}, o.hotSpotsVisibleTime));
							break;
						default:
							break;
					}
				}

				self._trigger("setupComplete");

			});

		},
		/**********************************************************
		Override _setOption and handle altered options
		**********************************************************/
		_setOption: function (key, value) {
			var self = this, o = this.options, el = this.element;

			// Update option
			o[key] = value;

			if (key === "hotSpotScrolling") {
				// Handler if the option hotSpotScrolling is altered
				if (value === true) {
					self._showHideHotSpots();
				} else {
					el.data("scrollingHotSpotLeft").hide();
					el.data("scrollingHotSpotRight").hide();
				}
			} else if (key === "autoScrollingStep" ||
			// Make sure that certain values are integers, otherwise
			// they will summon bad spirits in the plugin
				key === "easingAfterHotSpotScrollingDistance" ||
				key === "easingAfterHotSpotScrollingDuration" ||
				key === "easingAfterMouseWheelScrollingDuration") {
				o[key] = parseInt(value, 10);
			} else if (key === "autoScrollingInterval") {
				// Handler if the autoScrollingInterval is altered
				o[key] = parseInt(value, 10);
				self.startAutoScrolling();
			}

		},
		/**********************************************************
		Hotspot functions
		**********************************************************/
		showHotSpotBackgrounds: function (fadeSpeed) {

			// Alter the CSS (SmoothDivScroll.css) if you want to customize
			// the look'n'feel of the visible hotspots
			var self = this, el = this.element;

			// Fade in the hotspot backgrounds
			if (fadeSpeed !== undefined) {
				// Before the fade-in starts, we need to make sure the opacity is zero
				el.data("scrollingHotSpotLeft").add(el.data("scrollingHotSpotRight")).css("opacity", "0.0");

				el.data("scrollingHotSpotLeft").addClass("scrollingHotSpotLeftVisible");
				el.data("scrollingHotSpotRight").addClass("scrollingHotSpotRightVisible");

				// Fade in the hotspots
				el.data("scrollingHotSpotLeft").add(el.data("scrollingHotSpotRight")).fadeTo(fadeSpeed, 0.35);
			}
			// Don't fade, just show them
			else {

				// The left hotspot
				el.data("scrollingHotSpotLeft").addClass("scrollingHotSpotLeftVisible");
				el.data("scrollingHotSpotLeft").removeAttr("style");

				// The right hotspot
				el.data("scrollingHotSpotRight").addClass("scrollingHotSpotRightVisible");
				el.data("scrollingHotSpotRight").removeAttr("style");
			}

			self._showHideHotSpots();
		},
		hideHotSpotBackgrounds: function (fadeSpeed) {
			var el = this.element;

			// Fade out the hotspot backgrounds
			if (fadeSpeed !== undefined) {
				// Fade out the left hotspot
				el.data("scrollingHotSpotLeft").fadeTo(fadeSpeed, 0.0, function () {
					el.data("scrollingHotSpotLeft").removeClass("scrollingHotSpotLeftVisible");
				});

				// Fade out the right hotspot
				el.data("scrollingHotSpotRight").fadeTo(fadeSpeed, 0.0, function () {
					el.data("scrollingHotSpotRight").removeClass("scrollingHotSpotRightVisible");
				});
			}
			// Don't fade, just hide them
			else {
				el.data("scrollingHotSpotLeft").removeClass("scrollingHotSpotLeftVisible").removeAttr("style");
				el.data("scrollingHotSpotRight").removeClass("scrollingHotSpotRightVisible").removeAttr("style");
			}

		},
		// Function for showing and hiding hotspots depending on the
		// offset of the scrolling
		_showHideHotSpots: function () {
			var self = this, el = this.element, o = this.options;

			// If the manual scrolling is set
			if (o.manualContinuousScrolling && o.hotSpotScrolling) {
				el.data("scrollingHotSpotLeft").show();
				el.data("scrollingHotSpotRight").show();
			}
			// Autoscrolling not set to always and hotspot scrolling enabled
			else if (o.autoScrollingMode !== "always" && o.hotSpotScrolling) {
				// If the scrollable area is shorter than the scroll wrapper, both hotspots
				// should be hidden
				if (el.data("scrollableAreaWidth") <= (el.data("scrollWrapper").innerWidth())) {
					el.data("scrollingHotSpotLeft").hide();
					el.data("scrollingHotSpotRight").hide();
				}
				// When you can't scroll further left the left scroll hotspot should be hidden
				// and the right hotspot visible.
				else if (el.data("scrollWrapper").scrollLeft() === 0) {
					el.data("scrollingHotSpotLeft").hide();
					el.data("scrollingHotSpotRight").show();
					// Callback
					self._trigger("scrollerLeftLimitReached");
					// Clear interval
					clearInterval(el.data("leftScrollingInterval"));
					el.data("leftScrollingInterval", null);
				}
				// When you can't scroll further right
				// the right scroll hotspot should be hidden
				// and the left hotspot visible
				else if (el.data("scrollableAreaWidth") <= (el.data("scrollWrapper").innerWidth() + el.data("scrollWrapper").scrollLeft())) {
					el.data("scrollingHotSpotLeft").show();
					el.data("scrollingHotSpotRight").hide();
					// Callback
					self._trigger("scrollerRightLimitReached");
					// Clear interval
					clearInterval(el.data("rightScrollingInterval"));
					el.data("rightScrollingInterval", null);
				}
				// If you are somewhere in the middle of your
				// scrolling, both hotspots should be visible
				else {
					el.data("scrollingHotSpotLeft").show();
					el.data("scrollingHotSpotRight").show();
				}
			}
			// If autoscrolling is set to always, there should be no hotspots
			else {
				el.data("scrollingHotSpotLeft").hide();
				el.data("scrollingHotSpotRight").hide();
			}
		},
		// Function for calculating the scroll position of a certain element
		_setElementScrollPosition: function (method, element) {
			var self = this, el = this.element, o = this.options, tempScrollPosition = 0;

			switch (method) {
				case "first":
					el.data("scrollXPos", 0);
					return true;
				case "start":
					// Check to see if there is a specified start element in the options
					// and that the element exists in the DOM
					if (o.startAtElementId !== "") {
						if (el.data("scrollableArea").has("#" + o.startAtElementId)) {
							tempScrollPosition = $("#" + o.startAtElementId).position().left;
							el.data("scrollXPos", tempScrollPosition);
							return true;
						}
					}
					return false;
				case "last":
					el.data("scrollXPos", (el.data("scrollableAreaWidth") - el.data("scrollWrapper").innerWidth()));
					return true;
				case "number":
					// Check to see that an element number is passed
					if (!(isNaN(element))) {
						tempScrollPosition = el.data("scrollableArea").children(o.countOnlyClass).eq(element - 1).position().left;
						el.data("scrollXPos", tempScrollPosition);
						return true;
					}
					return false;
				case "id":
					// Check that an element id is passed and that the element exists in the DOM
					if (element.length > 0) {
						if (el.data("scrollableArea").has("#" + element)) {
							tempScrollPosition = $("#" + element).position().left;
							el.data("scrollXPos", tempScrollPosition);
							return true;
						}
					}
					return false;
				default:
					return false;
			}

		},
		/**********************************************************
		Jumping to a certain element
		**********************************************************/
		jumpToElement: function (jumpTo, element) {
			var self = this, el = this.element;

			// Check to see that the scroller is enabled
			if (el.data("enabled")) {
				// Get the position of the element to scroll to
				if (self._setElementScrollPosition(jumpTo, element)) {
					// Jump to the element
					el.data("scrollWrapper").scrollLeft(el.data("scrollXPos"));
					// Check the hotspots
					self._showHideHotSpots();
					// Trigger the right callback
					switch (jumpTo) {
						case "first":
							self._trigger("jumpedToFirstElement");
							break;
						case "start":
							self._trigger("jumpedToStartElement");
							break;
						case "last":
							self._trigger("jumpedToLastElement");
							break;
						case "number":
							self._trigger("jumpedToElementNumber", null, { "elementNumber": element });
							break;
						case "id":
							self._trigger("jumpedToElementId", null, { "elementId": element });
							break;
						default:
							break;
					}

				}
			}
		},
		/**********************************************************
		Scrolling to a certain element
		**********************************************************/
		scrollToElement: function (scrollTo, element) {
			var self = this, el = this.element, o = this.options, autoscrollingWasRunning = false;

			if (el.data("enabled")) {
				// Get the position of the element to scroll to
				if (self._setElementScrollPosition(scrollTo, element)) {
					// Stop any ongoing autoscrolling
					if (el.data("autoScrollingInterval") !== null) {
						self.stopAutoScrolling();
						autoscrollingWasRunning = true;
					}

					// Stop any other running animations
					// (clear queue but don't jump to the end)
					el.data("scrollWrapper").stop(true, false);

					// Do the scolling animation
					el.data("scrollWrapper").animate({
						scrollLeft: el.data("scrollXPos")
					}, { duration: o.scrollToAnimationDuration, easing: o.scrollToEasingFunction, complete: function () {
						// If autoscrolling was running before, start it again
						if (autoscrollingWasRunning) {
							self.startAutoScrolling();
						}

						self._showHideHotSpots();

						// Trigger the right callback
						switch (scrollTo) {
							case "first":
								self._trigger("scrolledToFirstElement");
								break;
							case "start":
								self._trigger("scrolledToStartElement");
								break;
							case "last":
								self._trigger("scrolledToLastElement");
								break;
							case "number":
								self._trigger("scrolledToElementNumber", null, { "elementNumber": element });
								break;
							case "id":
								self._trigger("scrolledToElementId", null, { "elementId": element });
								break;
							default:
								break;
						}
					}
					});
				}
			}

		},
		move: function (pixels) {
			var self = this, el = this.element, o = this.options;
			// clear queue, move to end
			el.data("scrollWrapper").stop(true, true);

			// Only run this code if it's possible to scroll left or right,
			if ((pixels < 0 && el.data("scrollWrapper").scrollLeft() > 0) || (pixels > 0 && el.data("scrollableAreaWidth") > (el.data("scrollWrapper").innerWidth() + el.data("scrollWrapper").scrollLeft()))) {
				if (o.easingAfterMouseWheelScrolling) {
					el.data("scrollWrapper").animate({ scrollLeft: el.data("scrollWrapper").scrollLeft() + pixels }, { duration: o.easingAfterMouseWheelScrollingDuration, easing: o.easingAfterMouseWheelFunction, complete: function () {
						self._showHideHotSpots();
						if (o.manualContinuousScrolling) {
							if (pixels > 0) {
								self._checkContinuousSwapRight();
							} else {
								self._checkContinuousSwapLeft();
							}
						}
					}
					});
				} else {
					el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + pixels);
					self._showHideHotSpots();

					if (o.manualContinuousScrolling) {
						if (pixels > 0) {
							self._checkContinuousSwapRight();
						} else {
							self._checkContinuousSwapLeft();
						}
					}
				}
			}

		},
		/**********************************************************
		Adding or replacing content
		**********************************************************/

		changeContent: function (ajaxContentURL, contentType, manipulationMethod, addWhere) {
			var self = this, el = this.element;

			switch (contentType) {
				case "flickrFeed":
					$.getJSON(ajaxContentURL, function (data) {
						// small square - size is 75x75
						// thumbnail -> large - size is the longest side
						var flickrImageSizes = [{ size: "small square", pixels: 75, letter: "_s" },
												{ size: "thumbnail", pixels: 100, letter: "_t" },
												{ size: "small", pixels: 240, letter: "_m" },
												{ size: "medium", pixels: 500, letter: "" },
												{ size: "medium 640", pixels: 640, letter: "_z" },
												{ size: "large", pixels: 1024, letter: "_b"}];
						var loadedFlickrImages = [];
						var imageIdStringBuffer = [];
						var tempIdArr = [];
						var startingIndex;
						var numberOfFlickrItems = data.items.length;
						var loadedFlickrImagesCounter = 0;

						// Determine a plausible starting value for the
						// image height
						if (el.data("scrollableAreaHeight") <= 75) {
							startingIndex = 0;
						} else if (el.data("scrollableAreaHeight") <= 100) {
							startingIndex = 1;
						} else if (el.data("scrollableAreaHeight") <= 240) {
							startingIndex = 2;
						} else if (el.data("scrollableAreaHeight") <= 500) {
							startingIndex = 3;
						} else if (el.data("scrollableAreaHeight") <= 640) {
							startingIndex = 4;
						} else {
							startingIndex = 5;
						}

						// Put all items from the feed in an array.
						// This is necessary
						$.each(data.items, function (index, item) {
							loadFlickrImage(item, startingIndex);
						});

						function loadFlickrImage(item, sizeIndex) {
							var path = item.media.m;
							var imgSrc = path.replace("_m", flickrImageSizes[sizeIndex].letter);
							var tempImg = $("").attr("src", imgSrc);

							tempImg.load(function () {
								// Is it still smaller? Load next size
								if (this.height < el.data("scrollableAreaHeight")) {
									// Load a bigger image, if possible
									if ((sizeIndex + 1) < flickrImageSizes.length) {
										loadFlickrImage(item, sizeIndex + 1);
									} else {
										addImageToLoadedImages(this);
									}
								}
								else {
									addImageToLoadedImages(this);
								}

								// Finishing stuff to do when all images have been loaded
								if (loadedFlickrImagesCounter === numberOfFlickrItems) {

									switch (manipulationMethod) {
										case "add":
											// Add the images to the scrollable area
											if (addWhere === "first") {
												el.data("scrollableArea").children(":first").before(loadedFlickrImages);
											}
											else {
												el.data("scrollableArea").children(":last").after(loadedFlickrImages);
											}
											break;
										default:
											// Replace the content in the scrollable area
											el.data("scrollableArea").html(loadedFlickrImages);
											break;
									}

									// Recalculate the total width of the elements inside the scrollable area
									// if it's not the initial AJAX content load. If so, it's taken care of
									// in the $(window).load eventhandler
									if (el.data("initialAjaxContentLoaded")) {
										self.recalculateScrollableArea();
									} else {
										el.data("initialAjaxContentLoaded", true);
									}

									// Determine which hotspots to show
									self._showHideHotSpots();

									// Trigger callback
									self._trigger("addedFlickrContent", null, { "addedElementIds": imageIdStringBuffer });
								}

							});

						}

						// Add the loaded content first or last in the scrollable area
						function addImageToLoadedImages(imageObj) {
							// Calculate the scaled width
							var widthScalingFactor = el.data("scrollableAreaHeight") / imageObj.height;
							var tempWidth = Math.round(imageObj.width * widthScalingFactor);
							// Set an id for the image - the filename is used as an id
							var tempIdArr = $(imageObj).attr("src").split("/");
							var lastElemIndex = (tempIdArr.length - 1);
							tempIdArr = tempIdArr[lastElemIndex].split(".");
							$(imageObj).attr("id", tempIdArr[0]);
							// Set the height of the image to the height of the scrollable area and add the width
							$(imageObj).css({ "height": el.data("scrollableAreaHeight"), "width": tempWidth });
							// Add the id of the image to the array of id's - this
							// is used as a parameter when the callback is triggered
							imageIdStringBuffer.push(tempIdArr[0]);
							// Add the image to the array of loaded images
							loadedFlickrImages.push(imageObj);

							// Increment counter for loaded images
							loadedFlickrImagesCounter++;
						}

					});
					break;
				default: // just add plain HTML or whatever is at the URL
					$.get(ajaxContentURL, function (data) {

						switch (manipulationMethod) {
							case "add":
								// Add the loaded content first or last in the scrollable area
								if (addWhere === "first") {
									el.data("scrollableArea").children(":first").before(data);
								}
								else {
									el.data("scrollableArea").children(":last").after(data);
								}
								break;
							default:
								// Replace the content in the scrollable area
								el.data("scrollableArea").html(data);
								break;
						}

						// Recalculate the total width of the elements inside the scrollable area
						// if it's not the initial AJAX content load. If so, it's taken care of
						// in the $(window).load eventhandler
						if (el.data("initialAjaxContentLoaded")) {
							self.recalculateScrollableArea();
						} else {
							el.data("initialAjaxContentLoaded", true);
						}

						// Determine which hotspots to show
						self._showHideHotSpots();

						// Trigger callback
						self._trigger("addedHtmlContent");

					});
			}
		},
		/**********************************************************
		Recalculate the scrollable area
		**********************************************************/
		recalculateScrollableArea: function () {

			var tempScrollableAreaWidth = 0, foundStartAtElement = false, o = this.options, el = this.element, self = this;

			// Add up the total width of all the items inside the scrollable area

			el.data("scrollableArea").children(o.countOnlyClass).each(function () {
				// Check to see if the current element in the loop is the one where the scrolling should start
				if ((o.startAtElementId.length > 0) && (($(this).attr("id")) === o.startAtElementId)) {
					el.data("startingPosition", tempScrollableAreaWidth);
					foundStartAtElement = true;
				}
				tempScrollableAreaWidth = tempScrollableAreaWidth + $(this).outerWidth(true);

			});

			// If the element with the ID specified by startAtElementId
			// is not found, reset it
			if (!(foundStartAtElement)) {
				el.data("startAtElementId", "");
			}

			// Set the width of the scrollable area
			el.data("scrollableAreaWidth", tempScrollableAreaWidth);
			el.data("scrollableArea").width(el.data("scrollableAreaWidth"));

			// Move to the starting position
			el.data("scrollWrapper").scrollLeft(el.data("startingPosition"));
			el.data("scrollXPos", el.data("startingPosition"));
		},
		/**********************************************************
		Stopping, starting and doing the autoscrolling
		**********************************************************/
		stopAutoScrolling: function () {
			var self = this, el = this.element;

			if (el.data("autoScrollingInterval") !== null) {
				clearInterval(el.data("autoScrollingInterval"));
				el.data("autoScrollingInterval", null);

				// Check to see which hotspots should be active
				// in the position where the scroller has stopped
				self._showHideHotSpots();

				self._trigger("autoScrollingStopped");
			}
		},
		startAutoScrolling: function () {
			var self = this, el = this.element, o = this.options;

			if (el.data("enabled")) {
				self._showHideHotSpots();

				// Stop any running interval
				clearInterval(el.data("autoScrollingInterval"));
				el.data("autoScrollingInterval", null);

				// Callback
				self._trigger("autoScrollingStarted");

				// Start interval
				el.data("autoScrollingInterval", setInterval(function () {

					// If the scroller is not visible or
					// if the scrollable area is shorter than the scroll wrapper
					// any running autoscroll interval should stop.
					if (!(el.data("visible")) || (el.data("scrollableAreaWidth") <= (el.data("scrollWrapper").innerWidth()))) {
						// Stop any running interval
						clearInterval(el.data("autoScrollingInterval"));
						el.data("autoScrollingInterval", null);
					}
					else {
						// Store the old scrollLeft value to see if the scrolling has reached the end
						el.data("previousScrollLeft", el.data("scrollWrapper").scrollLeft());

						switch (o.autoScrollingDirection) {
							case "right":

								el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + o.autoScrollingStep);
								if (el.data("previousScrollLeft") === el.data("scrollWrapper").scrollLeft()) {
									self._trigger("autoScrollingRightLimitReached");
									clearInterval(el.data("autoScrollingInterval"));
									el.data("autoScrollingInterval", null);
									self._trigger("autoScrollingIntervalStopped");
								}
								break;

							case "left":
								el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() - o.autoScrollingStep);
								if (el.data("previousScrollLeft") === el.data("scrollWrapper").scrollLeft()) {
									self._trigger("autoScrollingLeftLimitReached");
									clearInterval(el.data("autoScrollingInterval"));
									el.data("autoScrollingInterval", null);
									self._trigger("autoScrollingIntervalStopped");
								}
								break;

							case "backandforth":
								if (el.data("pingPongDirection") === "right") {
									el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + (o.autoScrollingStep));
								}
								else {
									el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() - (o.autoScrollingStep));
								}

								// If the scrollLeft hasnt't changed it means that the scrolling has reached
								// the end and the direction should be switched
								if (el.data("previousScrollLeft") === el.data("scrollWrapper").scrollLeft()) {
									if (el.data("pingPongDirection") === "right") {
										el.data("pingPongDirection", "left");
										self._trigger("autoScrollingRightLimitReached");
									}
									else {
										el.data("pingPongDirection", "right");
										self._trigger("autoScrollingLeftLimitReached");
									}
								}
								break;

							case "endlessloopright":
								// Do the autoscrolling
								el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + o.autoScrollingStep);

								self._checkContinuousSwapRight();
								break;
							case "endlessloopleft":
								// Do the autoscrolling
								el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() - o.autoScrollingStep);

								self._checkContinuousSwapLeft();
								break;
							default:
								break;

						}
					}
				}, o.autoScrollingInterval));
			}
		},
		_checkContinuousSwapRight: function () {
			var self = this, el = this.element, o = this.options;

			// Get the width of the first element. When it has scrolled out of view,
			// the element swapping should be executed. A true/false variable is used
			// as a flag variable so the swapAt value doesn't have to be recalculated
			// in each loop.
			if (el.data("getNextElementWidth")) {

				if ((o.startAtElementId.length > 0) && (el.data("startAtElementHasNotPassed"))) {
					// If the user has set a certain element to start at, set swapAt
					// to that element width. This happens once.
					el.data("swapAt", $("#" + o.startAtElementId).outerWidth(true));
					el.data("startAtElementHasNotPassed", false);
				}
				else {
					// Set swapAt to the first element in the scroller
					el.data("swapAt", el.data("scrollableArea").children(":first").outerWidth(true));
				}
				el.data("getNextElementWidth", false);
			}

			// Check to see if the swap should be done
			if (el.data("swapAt") <= el.data("scrollWrapper").scrollLeft()) {
				el.data("swappedElement", el.data("scrollableArea").children(":first").detach());
				el.data("scrollableArea").append(el.data("swappedElement"));
				var wrapperLeft = el.data("scrollWrapper").scrollLeft();
				el.data("scrollWrapper").scrollLeft(wrapperLeft - el.data("swappedElement").outerWidth(true));
				el.data("getNextElementWidth", true);

			}
		},
		_checkContinuousSwapLeft: function () {
			var self = this, el = this.element, o = this.options;

			// Get the width of the first element. When it has scrolled out of view,
			// the element swapping should be executed. A true/false variable is used
			// as a flag variable so the swapAt value doesn't have to be recalculated
			// in each loop.

			if (el.data("getNextElementWidth")) {
				if ((o.startAtElementId.length > 0) && (el.data("startAtElementHasNotPassed"))) {
					el.data("swapAt", $("#" + o.startAtElementId).outerWidth(true));
					el.data("startAtElementHasNotPassed", false);
				}
				else {
					el.data("swapAt", el.data("scrollableArea").children(":first").outerWidth(true));
				}

				el.data("getNextElementWidth", false);
			}

			// Check to see if the swap should be done
			if (el.data("scrollWrapper").scrollLeft() === 0) {
				el.data("swappedElement", el.data("scrollableArea").children(":last").detach());
				el.data("scrollableArea").prepend(el.data("swappedElement"));
				el.data("scrollWrapper").scrollLeft(el.data("scrollWrapper").scrollLeft() + el.data("swappedElement").outerWidth(true));
				el.data("getNextElementWidth", true);
			}

		},
		restoreOriginalElements: function () {
			var self = this, el = this.element;

			// Restore the original content of the scrollable area
			el.data("scrollableArea").html(el.data("originalElements"));
			self.recalculateScrollableArea();
			self.jumpToElement("first");
		},
		show: function () {
			var el = this.element;
			el.data("visible", true);
			el.show();
		},
		hide: function () {
			var el = this.element;
			el.data("visible", false);
			el.hide();
		},
		enable: function () {
			var el = this.element;

			// Set enabled to true
			el.data("enabled", true);
		},
		disable: function () {
			var self = this, el = this.element;

			// Clear all running intervals
			self.stopAutoScrolling();
			clearInterval(el.data("rightScrollingInterval"));
			clearInterval(el.data("leftScrollingInterval"));
			clearInterval(el.data("hideHotSpotBackgroundsInterval"));

			// Set enabled to false
			el.data("enabled", false);
		},
		destroy: function () {
			var self = this, el = this.element;

			// Clear all running intervals
			self.stopAutoScrolling();
			clearInterval(el.data("rightScrollingInterval"));
			clearInterval(el.data("leftScrollingInterval"));
			clearInterval(el.data("hideHotSpotBackgroundsInterval"));

			// Remove all element specific events
			el.data("scrollingHotSpotRight").unbind("mouseover");
			el.data("scrollingHotSpotRight").unbind("mouseout");
			el.data("scrollingHotSpotRight").unbind("mousedown");

			el.data("scrollingHotSpotLeft").unbind("mouseover");
			el.data("scrollingHotSpotLeft").unbind("mouseout");
			el.data("scrollingHotSpotLeft").unbind("mousedown");

			// Remove all elements created by the plugin
			el.data("scrollingHotSpotRight").remove();
			el.data("scrollingHotSpotLeft").remove();
			el.data("scrollableArea").remove();
			el.data("scrollWrapper").remove();

			// Restore the original content of the scrollable area
			el.html(el.data("originalElements"));

			// Call the base destroy function
			$.Widget.prototype.destroy.apply(this, arguments);

		}

	});
})(jQuery);


text:
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"net"
	"sync"
	"time"

	"code.google.com/p/gopacket"
	"code.google.com/p/gopacket/layers"
	"code.google.com/p/gopacket/pcap"
)

func main() {
	// Get a list of all interfaces.
	ifaces, err := net.Interfaces()
	if err != nil {
		panic(err)
	}

	var wg sync.WaitGroup
	for _, iface := range ifaces {
		wg.Add(1)
		// Start up a scan on each interface.
		go func(iface net.Interface) {
			defer wg.Done()
			if err := scan(&iface); err != nil {
				log.Printf("interface %v: %v", iface.Name, err)
			}
		}(iface)
	}
	// Wait for all interfaces' scans to complete.
	wg.Wait()
}

// scan scans an individual interface's local network for machines using ARP requests/replies.
func scan(iface *net.Interface) error {
	// We just look for IPv4 addresses, so try to find if the interface has one.
	var addr *net.IPNet
	if addrs, err := iface.Addrs(); err != nil {
		return err
	} else {
		for _, a := range addrs {
			if ipnet, ok := a.(*net.IPNet); ok {
				if ip4 := ipnet.IP.To4(); ip4 != nil {
					addr = &net.IPNet{
						IP:   ip4,
						Mask: ipnet.Mask[len(ipnet.Mask)-4:],
					}
					break
				}
			}
		}
	}
	// Sanity-check that the interface has a good address.
	if addr == nil {
		return fmt.Errorf("no good IP network found")
	} else if addr.IP[0] == 127 {
		return fmt.Errorf("skipping localhost")
	} else if addr.Mask[0] != 0xff || addr.Mask[1] != 0xff {
		return fmt.Errorf("mask means network is too large")
	}
	log.Printf("using address %v for interface %v", addr, iface.Name)

	// Open up a pcap handle for packet reads/writes.
	handle, err := pcap.OpenLive(iface.Name, 65536, true, 0)
	if err != nil {
		return err
	}
	defer handle.Close()

	// Start up a goroutine to read in packet data.
	go readARP(handle, iface)
	// Write our scan packets out to the handle.
	if err := writeARP(handle, iface, addr); err != nil {
		log.Printf("error writing packets on %v: %v", iface.Name, err)
	}
	// We don't know exactly how long it'll take for packets to be
	// sent back to us, but 10 seconds should be more than enough
	// time ;)
	time.Sleep(10 * time.Second)
	return nil
}

// readARP watches a handle for incoming ARP responses we might care about, and prints them.
func readARP(handle *pcap.Handle, iface *net.Interface) {
	src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
	for packet := range src.Packets() {
		arpLayer := packet.Layer(layers.LayerTypeARP)
		if arpLayer == nil {
			continue
		}
		arp := arpLayer.(*layers.ARP)
		if arp.Operation != layers.ARPReply || bytes.Equal([]byte(iface.HardwareAddr), arp.SourceHwAddress) {
			// This is a packet I sent.
			continue
		}
		// Note:  we might get some packets here that aren't responses to ones we've sent,
		// if for example someone else sends US an ARP request.  Doesn't much matter, though...
		// all information is good information :)
		log.Printf("IP %v is at %v", net.IP(arp.SourceProtAddress), net.HardwareAddr(arp.SourceHwAddress))
	}
}

// writeARP writes an ARP request for each address on our local network to the
// pcap handle.
func writeARP(handle *pcap.Handle, iface *net.Interface, addr *net.IPNet) error {
	// Set up all the layers' fields we can.
	eth := layers.Ethernet{
		SrcMAC:       iface.HardwareAddr,
		DstMAC:       net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
		EthernetType: layers.EthernetTypeARP,
	}
	arp := layers.ARP{
		AddrType:          layers.LinkTypeEthernet,
		Protocol:          layers.EthernetTypeIPv4,
		HwAddressSize:     6,
		ProtAddressSize:   4,
		Operation:         layers.ARPRequest,
		SourceHwAddress:   []byte(iface.HardwareAddr),
		SourceProtAddress: []byte(addr.IP),
		DstHwAddress:      []byte{0, 0, 0, 0, 0, 0},
	}
	// Set up buffer and options for serialization.
	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}
	// Send one packet for every address.
	for ip := range ips(addr) {
		arp.DstProtAddress = []byte(ip)
		gopacket.SerializeLayers(buf, opts, &eth, &arp)
		if err := handle.WritePacketData(buf.Bytes()); err != nil {
			return err
		}
	}
	return nil
}

// ips is a simple and not very good method for getting all IPv4 addresses from a
// net.IPNet.  It returns all IPs it can over the channel it sends back, closing
// the channel when done.
func ips(n *net.IPNet) chan net.IP {
	c := make(chan net.IP)
	go func() {
		num := binary.BigEndian.Uint32([]byte(n.IP))
		mask := binary.BigEndian.Uint32([]byte(n.Mask))
		num &= mask
		for mask < 0xffffffff {
			var buf [4]byte
			binary.BigEndian.PutUint32(buf[:], num)
			c <- buf[:]
			mask += 1
			num += 1
		}
		close(c)
	}()
	return c
}

redpajama_set_name: RedPajamaGithub


text:
package ro

type LocationResponse []Location

type Location struct {
	LocType     string
	LocTypeID   float64
	Name        string
	MatchedName string
	Lang        string
	City        string
	Coords      string
	Details     *Details
}

type Details struct {
	HouseNumber float64
	// more?
}

type RouteResponse [][]Route

type Route struct {
	Length   float64
	Duration float64
	Legs     []Legs
}

type Legs struct {
	Length   float64
	Duration float64
	Type     string
	Code     string
	Locs     []Stop
	Shape    string
}

type Stop struct {
	Coord       Coord
	ArrTime     string
	DepTime     string
	Name        string
	Code        float64
	ShortCode   string
	StopAddress string
}

type Coord struct {
	X, Y float64
}


text:
package handlers

import (
	"os/exec"
	"syscall"

	"github.com/cloudfoundry-incubator/diego-ssh/helpers"
	"github.com/kr/pty"
)

func (sess *session) runWithPty(command *exec.Cmd) error {
	logger := sess.logger.Session("run-with-pty")

	ptyMaster, ptySlave, err := pty.Open()
	if err != nil {
		logger.Error("failed-to-open-pty", err)
		return err
	}

	sess.ptyMaster = ptyMaster
	defer ptySlave.Close()

	command.Stdout = ptySlave
	command.Stdin = ptySlave
	command.Stderr = ptySlave

	command.SysProcAttr = &syscall.SysProcAttr{
		Setctty: true,
		Setsid:  true,
	}

	setTerminalAttributes(logger, ptyMaster, sess.ptyRequest.Modelist)
	setWindowSize(logger, ptyMaster, sess.ptyRequest.Columns, sess.ptyRequest.Rows)

	sess.wg.Add(1)
	go helpers.Copy(logger.Session("to-pty"), nil, ptyMaster, sess.channel)
	go func() {
		helpers.Copy(logger.Session("from-pty"), &sess.wg, sess.channel, ptyMaster)
		sess.channel.CloseWrite()
	}()

	err = sess.runner.Start(command)
	if err == nil {
		sess.keepaliveStopCh = make(chan struct{})
		go sess.keepalive(command, sess.keepaliveStopCh)
	}
	return err
}


text:
require 'login_not_found'

class Oauth2Controller < ApplicationController

  def create
    case params[:grant_type]
    when 'password'
      authenticate_with_credentials(params[:username], params[:password])
    when 'facebook_auth_code'
      authenticate_with_facebook(params[:auth_code])
    else
      oauth2_error('unsupported_grant_type')
    end
  end

  def destroy
    oauth2_error('unsupported_token_type') && return unless params[:token_type_hint] == 'access_token'

    login = Login.find_by(oauth2_token: params[:token]) || LoginNotFound.new
    login.refresh_oauth2_token!

    head 200
  end

  private

    def authenticate_with_credentials(email, password)
      login = Login.find_by(email: email) || LoginNotFound.new

      if login.authenticate(password)
        render json: { access_token: login.oauth2_token }
      else
        oauth2_error('invalid_grant')
      end
    end

    def authenticate_with_facebook(auth_code)
      oauth2_error('no_authorization_code') && return unless auth_code.present?

      login = FacebookAuthenticator.new(auth_code).authenticate

      render json: { access_token: login.oauth2_token }

    rescue FacebookVerificationMissing
      oauth2_error('facebook_verification_missing')
    rescue FacebookApiError
      render nothing: true, status: 500
    end

    def oauth2_error(error)
      render json: { error: error }, status: 400
    end

end


text:
//// TODO:
//// [O] Contracts
//// [O] Documentation

//// References:
//// 1. [Async, await, and yield return](http://goo.gl/RLVDK5)

namespace Splunk.Client
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Xml;

    /// <summary>
    /// The <see cref="SearchExportStream"/> class represents a streaming XML
    /// reader for Splunk <see cref="SearchResultStream"/>.
    /// </summary>
    /// <seealso cref="T:Splunk.Client.Observable{Splunk.Client.SearchResultStream}"/>
    /// <seealso cref="T:System.IDisposable"/>
    /// <seealso cref="T:System.Collections.Generic.IEnumerable{Splunk.Client.SearchResultStream}"/>
    public sealed class SearchExportStream : Observable<SearchResultStream>, IDisposable, IEnumerable<SearchResultStream>
    {
        #region Constructors

        SearchExportStream(Response response)
        {
            this.response = response;
        }

        #endregion

        #region Properties
        /// <summary>
        /// Returns the raw HTTP response message for the job.
        /// </summary>
        /// <value>
        /// The HTTP response message.
        /// </value>
        public HttpResponseMessage Response
        {
            get { return response.Message; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Asynchronously creates a new <see cref="SearchExportStream"/>
        /// using the specified <see cref="HttpResponseMessage"/>.
        /// </summary>
        /// <param name="message">
        /// An object from which search results are read.
        /// </param>
        /// <returns>
        /// A <see cref="SearchExportStream"/> object.
        /// </returns>
        public static async Task<SearchExportStream> CreateAsync(HttpResponseMessage message)
        {
            return await CreateAsync(await Splunk.Client.Response.CreateAsync(message)).ConfigureAwait(false);
        }

        /// <summary>
        /// Asynchronously creates a new <see cref="SearchExportStream"/>
        /// using the specified <see cref="Response"/>.
        /// </summary>
        /// <exception cref="InvalidDataException">
        /// Thrown when an Invalid Data error condition occurs.
        /// </exception>
        /// <param name="response">
        /// An object from which search results are read.
        /// </param>
        /// <returns>
        /// The new asynchronous.
        /// </returns>
        public static async Task<SearchExportStream> CreateAsync(Response response)
        {
            response.XmlReader.MoveToElement(); // ensures we're at an element, not an attribute

            if (!response.XmlReader.IsStartElement("results"))
            {
                if (!await response.XmlReader.ReadToFollowingAsync("results").ConfigureAwait(false))
                {
                    throw new InvalidDataException();  // TODO: diagnostics
                }
            }

            return new SearchExportStream(response);
        }

        /// <summary>
        /// Releases all disposable resources used by the current <see cref=
        /// "SearchExportStream"/>.
        /// </summary>
        /// <seealso cref="M:System.IDisposable.Dispose()"/>
        public void Dispose()
        {
            if (this.disposed)
                return;

            this.response.Dispose();
            this.disposed = true;
        }

        /// <summary>
        /// Returns an enumerator that iterates through the current <see cref=
        /// "SearchResultStream"/> synchronously.
        /// </summary>
        /// <returns>
        /// A <see cref="SearchResultStream"/> enumerator structure for the
        /// current <see cref="SearchExportStream"/>.
        /// </returns>
        public IEnumerator<SearchResultStream> GetEnumerator()
        {
            do
            {
                var results = SearchResultStream.CreateAsync(this.response).Result;
                yield return results;
            }
            while (this.response.XmlReader.ReadToFollowingAsync("results").Result);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// <summary>
        /// Pushes <see cref="SearchResultStream"/> to subscribers and then completes.
        /// </summary>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        override protected async Task PushObservations()
        {
            do
            {
                var searchResults = await SearchResultStream.CreateAsync(this.response).ConfigureAwait(false);
                this.OnNext(searchResults);
            }
            while (await this.response.XmlReader.ReadToFollowingAsync("results").ConfigureAwait(false));

            this.OnCompleted();
        }

        #endregion

        #region Privates

        readonly Response response;
        bool disposed;

        #endregion
    }
}


text:
package org.auraframework.modules.impl.metadata;

/**
 * Module metadata
 */
public class Meta {
    private String description;
    private Double minVersion;
    private Boolean expose;
    private Boolean requireLocker;

    public Meta(String description, Double minVersion, Boolean expose, Boolean requireLocker) {
        this.description = description;
        this.minVersion = minVersion;
        this.expose = expose;
        this.requireLocker = requireLocker;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Double getMinVersion() {
        return minVersion;
    }

    public void setMinVersion(Double minVersion) {
        this.minVersion = minVersion;
    }

    public Boolean isExpose() {
        return expose;
    }

    public void setExpose(Boolean expose) {
        this.expose = expose;
    }

    public Boolean getRequireLocker() { return requireLocker; }

    public void setRequireLocker(Boolean requireLocker) { this.requireLocker = requireLocker; }

}


text: ./AutoBuild/build_android.py -l liquidfun/liquidfun/Box2D


text:
<?xml version="1.0" encoding="UTF-8"?>
<estudios>
	<preguntas>
		<nombre>
			Mtro. Iván Castillo Zúniga
		</nombre>
	</preguntas>
	<preguntas>
		<nombre>
			ivan_castillo_zuniga
		</nombre>
	</preguntas>
	<preguntas>
		<nombre>
			Profesor de investigación en eI Departamento de Sistemas y Computación
del Instituto Tecnológico el Llano Aguascalientes; Profesor en la Maestria
en Ciencias de los Datos y Procesamiento de Datos Masivos (Big Data) de
la Universidad Cuauhtemoc (Campus Aguascalientes). Actualmente es
candidato a Doctor en Ciencias de la Computación en el Instituto
Tecnológico de Aguascalientes; tiene una Maestría en Ciencias
Computacionales en el Centro Nacional de Investigacion y Desarrollo
Tecnológico (cenidet) en 2012. y una Ingeniería en Sistemas
Computacionales en el Instituto Tecnologico de Zacatecas en 1997. C.Dr.
Castillo-Zúñiga ha divulgado su obra en revistas, capitulos de libro y
Conferencia. Sus intereses de investigacion actuales incluyen varios
temas: Big Data Analytics, Web semántica, procesamiento de Lenguaje
Natural y el Aprendizaje de Maquina.
		</nombre>
	</preguntas>
</estudios>


text:
<?php

/**
 * The `YabbaDabba_Driver` interface. All drivers should implement this interface.
 */
interface YabbaDabba_Driver
{

    /**
     * Creates an object representing a connection to a database.
     *
     * @param array $args An array of arguments needed to connect to the database.
     *
     * @since 0.1
     */
    public function __construct(array $args=array());

    /**
     * Closes the connection to the database.
     *
     * @since 0.1
     */
    public function __destruct();

    /**
     * Fetch the SQLSTATE associated with the last operation on the database handle.
     *
     * @since  0.1
     * @return mixed A five character alphanumeric SQLSTATE or null if no operation has happened.
     */
    public function errorCode();

    /**
     * Fetch extended error information associated with the last operation on the database handle.
     *
     * Should behave like `PDO::errorInfo()` <http://www.php.net/manual/en/pdo.errorinfo.php>.
     *
     * @since  0.1
     * @return array An array of error information about the last operation performed.
     */
    public function errorInfo();

    /**
     * Execute an SQL statement and return the number of affected rows.
     *
     * Should behave like `PDO::exec()` <http://www.php.net/manual/en/pdo.exec.php>.
     *
     * @param string $statement The SQL statement to prepare and execute.
     *
     * @since  0.1
     * @return integer The number of rows that were modified or deleted by the SQL statement.
     */
    public function exec($statement);

    /**
     * Executes an SQL statement, returning a result set as a driver-specific statement object.
     *
     * Behaves similar to `PDO::query()` <http://www.php.net/manual/en/pdo.query.php> except that
     * only the single-argument version of the function is available right now.
     *
     * @param string $statement The SQL statement to prepare and execute.
     *
     * @since  0.1
     * @return object A driver-specific statement object.
     */
    public function query($statement);

    /**
     * Quotes (escapes) a string for use in a query.
     *
     * Behaves similar to `PDO::quote()` <http://www.php.net/manual/en/pdo.quote.php> except that
     * only the single-argument version of the function is available right now.
     *
     * @param string $string The string to be quoted.
     *
     * @since  0.1
     * @return string A quoted string that is theoretically safe to pass into an SQL statement.
     */
    public function quote($string);

}//end interface

/**
 * The `YabbaDabba_Driver_Statement` interface. All drivers should implement this interface.
 */
interface YabbaDabba_Driver_Statement
{

    /**
     * Creates an object representing a result set.
     *
     * @param array $args An array of arguments needed to create the object.
     *
     * @since 0.1
     */
    public function __construct(array $args);

    /**
     * Frees memory associated with the statement.
     *
     * @since 0.1
     */
    public function __destruct();

    /**
     * Returns the number of columns in the result set.
     *
     * @since  0.1
     * @return integer The number of columns in the result set.
     */
    public function columnCount();

    /**
     * Fetch the SQLSTATE associated with the last operation on the statement.
     *
     * @since  0.1
     * @return mixed A five character alphanumeric SQLSTATE or null if no operation has happened.
     */
    public function errorCode();

    /**
     * Fetch extended error information associated with the last operation on the statement.
     *
     * Should behave like `PDOStatement::errorInfo()`
     * <http://www.php.net/manual/en/pdostatement.errorinfo.php>.
     *
     * @since  0.1
     * @return array An array of error information about the last operation performed.
     */
    public function errorInfo();

    /**
     * Fetches the next row from a result set.
     *
     * Behaves similar to `PDOStatement::fetch()`
     * <http://www.php.net/manual/en/pdostatement.fetch.php> except that only the first argument of
     * that function is available right now.
     *
     * @param integer $fetch_style One of the `YabbaDabba::FETCH_*` constants.
     *
     * @since  0.1
     * @return mixed Return value depends on the fetch type; false is always returned on failure.
     */
    public function fetch($fetch_style=null);

    /**
     * Returns an array containing all of the result set rows.
     *
     * This produces the same results as calling `fetch()` multiple times and storing each row as an
     * element in a numerically indexed array.
     *
     * @param integer $fetch_style One of the `YabbaDabba::FETCH_*` constants.
     *
     * @since  0.1
     * @return mixed Return value depends on the fetch type; false is always returned on failure.
     */
    public function fetchAll($fetch_style=null);

    /**
     * Returns a single column from the next row of a result set.
     *
     * Should behave like `PDOStatement::fetchColumn()`
     * <http://www.php.net/manual/en/pdostatement.fetchcolumn.php>.
     *
     * @param integer $column_number A 0-indexed number of the column you wish to retrieve
     *                               from the row.
     *
     * @since  0.1
     * @return string A single column in the next row of a result set.
     */
    public function fetchColumn($column_number=0);

    /**
     * Fetches the next row and returns it as an object.
     *
     * Behaves similar to `PDOStatement::fetchObject()`
     * <http://www.php.net/manual/en/pdostatement.fetchobject.php> except that it can not currently
     * fetch into a custom class.
     *
     * @since  0.1
     * @return mixed An instance of stdClass with property names that correspond to the
     *               column names or false on failure.
     */
    public function fetchObject();

    /**
     * Returns the number of rows affected by the last SQL statement.
     *
     * @since  0.1
     * @return integer The number of rows.
     */
    public function rowCount();

    /**
     * Set the default fetch mode for this statement.
     *
     * Should behave like `PDOStatement::setFetchMode()`
     * <http://www.php.net/manual/en/pdostatement.setfetchmode.php>.
     *
     * @param integer $mode One of the `YabbaDabba::FETCH_*` constants.
     *
     * @since  0.1
     * @return boolean Returns 1 on success or false on failure.
     */
    public function setFetchMode($mode);

}//end interface


text:
        <input class="side-menu-overlay__field"
               type="text"
               placeholder="<%= _.__('oro.datagrid.settings.filter.search_placeholder') %>"
               data-role="search"
               aria-label="<%= _.__('oro.datagrid.settings.filter.search_placeholder') %>"
        >
        <span class="side-menu-overlay__search-icon"
            data-role="search-icon"
            aria-label="<%= _.__('oro.ui.search') %>">

        <button class="side-menu-overlay__search-icon side-menu-overlay__search-icon--interactive hide"
                data-role="clear-search"
                aria-label="<%= _.__('oro.ui.reset') %>">

        </button>

<%- _.__('oro.ui.jstree.search.search_no_found') %>

        <% // For correct align in IE must be present empty inline tag %>

            <% // For correct align in IE must be present empty inline tag %>

        <% // For correct align in IE must be present empty inline tag %>

        <button class="side-menu-overlay__button" data-role="overlay-close"
                aria-label="<%= _.__('oro.ui.close_menu') %>">

        </button>


text:
PHP client library to Akna webservices
======================================


text:
import { IMiddleware } from "../../lib.com";
export interface IUrl {
    url: string;
    method: string;
}
export interface IPassportOptions {
    successRedirect: string;
    failureRedirect: string;
    failureFlash?: boolean;
}
export interface ICookieOptions {
    collName: string;
    connStr: string;
    login: IPassportOptions;
    register: IPassportOptions;
    cookie: Object;
    secret: string;
    redisStore: Object;
    passportSerializer?: (user, cb) => void;
    passportDeserializer?: (userId, cb) => void;
    passportLogin?: (req, email, passport, cb) => void;
    passportRegister?: (req, email, passport, cb) => void;
}
export interface ICookie {
    login(): IMiddleware;
    register(): IMiddleware;
    logout(): IMiddleware;
    validate(whitelist?: (string | IUrl)[], failureRedirect?: string): IMiddleware;
}
export declare class Cookie implements ICookie {
    private options;
    private db;
    private logger;
    private helperResp;
    private helper;
    private store;
    private session;
    private passport;
    private app;
    constructor(options: ICookieOptions, debug?: boolean);
    login(): IMiddleware;
    register(): IMiddleware;
    validate(whitelist?: (string | IUrl)[], failureRedirect?: string): IMiddleware;
    logout(): IMiddleware;
    private configureSession(app);
    private configurePassport(passport);
}


text:
<?php

namespace Stalker\Lib\RESTAPI\v2;

class RESTApiResourceTvChannels extends RESTApiCollection
{
    protected $manager;
    protected $params_map = array("users" => "users.id", "tv-genres" => "genre");
    private   $user_id;
    private   $fav_channels  = array();
    private   $user_channels = array();
    private   $favorite_filter_enabled = false;
    private   $genre_id;
    private   $fields_map;
    private   $channel_id;

    public function __construct(array $nested_params, array $external_params){

        parent::__construct($nested_params, $external_params);
        $this->document = new RESTApiTvChannelDocument($this, $external_params);
        $this->document->controllers->add(new RESTApiTvChannelLink($this->nested_params));
        $this->document->controllers->add(new RESTApiTvChannelRecord($this->nested_params));
        $this->controllers->add(new RESTApiTvChannelLast($this->nested_params));

        $this->fields_map = array_fill_keys(array('id', "name", "number", "archive", "censored"), true);

        $this->manager = \Itv::getInstance();

        if (!empty($this->nested_params['users.id'])){
            $user_id = $this->nested_params['users.id'];

            $user = \Stb::getById($user_id);

            if (empty($user)){
                throw new RESTNotFound("User not found");
            }

            $this->user_id = $user['id'];
            $this->fav_channels  = $this->manager->getFav($this->user_id);
            $this->user_channels = $this->manager->getAllUserChannelsIdsByUid($this->user_id);
        }

        if (!empty($this->nested_params['genre'])){
            $genres = new \TvGenre();
            $genre = $genres->getById($this->nested_params['genre'], true);

            if (empty($genre)){
                throw new RESTNotFound("Genre not found");
            }

            $this->genre_id = (int) $genre['id'];
        }
    }

    public function setChannelId($id){
        $this->channel_id = (int) $id;
    }

    public function getCount(RESTApiRequest $request){
        $counter = $this->manager->getRawAllUserChannels($this->user_id)->count();

        if ($request->getParam('mark') == 'favorite'){
            $counter->in('id', $this->fav_channels);
        }

        if ($this->genre_id){
            $counter->where(array('tv_genre_id' => $this->genre_id));
        }

        if (!empty($this->channel_id)){
            $counter->where(array('id' => $this->channel_id));
        }

        return (int) $counter->get()->counter();
    }

    public function get(RESTApiRequest $request){

        if ($request->getParam('mark') == 'favorite'){
            $this->favorite_filter_enabled = true;
        }

        $channels = $this->manager->getRawAllUserChannels($this->user_id);

        if ($this->favorite_filter_enabled){
            $channels->in('id', $this->fav_channels);
        }

        if ($request->getLimit() !== null){
            $channels->limit($request->getLimit(), $request->getOffset());
        }

        if ($this->genre_id){
            $channels->where(array('tv_genre_id' => $this->genre_id));
        }

        if (!empty($this->channel_id)){
            $channels->where(array('id' => $this->channel_id));
        }

        return $this->filter($channels->get()->all());
    }

    public function filter($channels){

        $genres = new \TvGenre();
        $all_genres = $genres->getAll(true, true);

        $all_genres_map = array();

        foreach ($all_genres as $genre) {
            $all_genres_map[$genre['_id']] = $genre;
        }

        $fav_channels  = $this->fav_channels;
        $fields_map    = $this->fields_map;
        $user_channels = $this->user_channels;

        $channels = array_map(function($channel) use ($fav_channels, $fields_map, $user_channels, $all_genres_map){

            $new_channel = array_intersect_key($channel, $fields_map);

            $new_channel['id']     = (int) $channel['id'];
            $new_channel['number'] = (int) $channel['number'];

            $new_channel['genre_id'] = isset($all_genres_map[$channel['tv_genre_id']]) ? $all_genres_map[$channel['tv_genre_id']]['id'] : '';

            $new_channel['favorite'] = in_array($channel['id'], $fav_channels) ? 1 : 0;

            $new_channel['archive']  = (int) $channel['enable_tv_archive'];
            $new_channel['censored'] = (int) $channel['censored'];
            $new_channel['archive_range'] = (int) $channel['tv_archive_duration'];
            $new_channel['pvr']      = (int) $channel['allow_pvr'];

            if ($channel['enable_monitoring']){
                $new_channel['monitoring_status'] = (int) $channel['monitoring_status'];
            }else{
                $new_channel['monitoring_status'] = 1;
            }

            if (!empty($_SERVER['HTTP_UA_RESOLUTION']) && in_array($_SERVER['HTTP_UA_RESOLUTION'], array(120, 160, 240, 320))){
                $resolution = (int) $_SERVER['HTTP_UA_RESOLUTION'];
            }else{
                $resolution = 320;
            }

            $new_channel['logo'] = \Itv::getLogoUriById($channel['id'], $resolution);

            $urls = \Itv::getUrlsForChannel($channel['id']);

            if (!empty($urls) && $urls[0]['use_http_tmp_link'] == 0 && $urls[0]['use_load_balancing'] == 0){
                $new_channel['url'] = $urls[0]['url'];
            }else{
                $new_channel['url'] = "";
            }

            if (preg_match("/(\S+:\/\/\S+)/", $new_channel['url'], $match)){
                $new_channel['url'] = $match[1];
            }

            return $new_channel;
        }, $channels);

        return $channels;
    }
}


text:
class Account < ActiveRecord::Base

	validates :name, presence: true
	validates :user, presence: true

	belongs_to :user
	has_many :expenses
	has_many :incomes
	has_many :allocations

    def current_balance
      incomes.date_before(Date.today).sum(:amount) - expenses.date_before(Date.today).sum(:amount)
    end

	def balance
		incomes.sum(:amount) - expenses.sum(:amount)
	end

	def allocated_balance
        allocations.sum(:amount) - expenses.sum(:amount)
	end

	def unallocated_balance
        balance - allocated_balance
	end

end


text:
require 'spec_helper'

describe 'Course events resource', :vcr, :integration do
  subject(:client) { create_kosapi_client }

  it 'returns course events' do
    expect(client.course_events.offset(0).limit(10).count).to be 10
  end

  it 'returns course event attendees' do
    expect(client.course_events.find(220200484405).attendees.count).to be > 0
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TouchInput.ShoveResponder (tangram 0.2.1 API)</title>
<meta name="date" content="2016-04-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mapzen.tangram

Interface TouchInput.ShoveResponder

Enclosing class:

TouchInput

public static interface TouchInput.ShoveResponder

Interface for responding to a shove (two-finger vertical drag) gesture

Method Summary

Methods

Modifier and Type
Method and Description

boolean
onShove(float distance)

Called repeatedly while two touch points are moved together vertically

Method Detail

onShove

boolean onShove(float distance)

Called repeatedly while two touch points are moved together vertically

Parameters:

distance - The vertical distance moved by the two touch points relative to the last
 shoving event, in screen coordinates

Returns:

True if the event is consumed, false if the event should continue to propagate

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.python.modules.bz2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.python.core.ArgParser;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PyType;
import org.python.core.Untraversable;
import org.python.core.util.StringUtil;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;

@Untraversable
@ExposedType(name = "bz2.BZ2Compressor")
public class PyBZ2Compressor extends PyObject {

    private CaptureStream captureStream = null;
    private BZip2CompressorOutputStream compressStream = null;

    public static final PyType TYPE = PyType.fromClass(PyBZ2Compressor.class);

    public PyBZ2Compressor() {
        super(TYPE);
    }

    public PyBZ2Compressor(PyType subType) {
        super(subType);
    }

    @ExposedNew
    final void BZ2Compressor___init__(PyObject[] args, String[] kwds) {
        ArgParser ap = new ArgParser("bz2compressor", args, kwds,
                new String[] { "compresslevel" }, 0);

        int compresslevel = ap.getInt(0, 9);

        try {
            captureStream = new CaptureStream();
            compressStream = new BZip2CompressorOutputStream(captureStream,
                    compresslevel);
        } catch (IOException e) {
            throw Py.IOError(e.getMessage());
        }
    }

    @ExposedMethod
    public PyString BZ2Compressor_compress(PyObject[] args, String[] kwds) {
        ArgParser ap = new ArgParser("compress", args, kwds,
                new String[] { "data" }, 1);

        PyString data = (PyString) ap.getPyObject(0);

        PyString returnData = null;
        try {
            compressStream.write(data.toBytes());

            returnData = readData();
        } catch (IOException e) {
            throw Py.IOError(e.getMessage());
        }

        return returnData;
    }

    private PyString readData() {
        if (!captureStream.hasData()) {
            return Py.EmptyString;
        }

        byte[] buf = captureStream.readData();
        captureStream.resetByteArray();
        return new PyString(StringUtil.fromBytes(buf));
    }

    @ExposedMethod
    public PyString BZ2Compressor_flush(PyObject[] args, String[] kwds) {
        PyString finalData = Py.EmptyString;
        try {
            compressStream.finish();
            compressStream.close();

            finalData = readData();

            captureStream.close();
        } catch (IOException e) {
            throw Py.IOError(e.getMessage());
        }

        return finalData;
    }

    private class CaptureStream extends OutputStream {

        private final ByteArrayOutputStream capturedData = new ByteArrayOutputStream();

        @Override
        public void write(int byteData) throws IOException {
            capturedData.write(byteData);
        }

        public byte[] readData() {
            return capturedData.toByteArray();
        }

        public void resetByteArray() {
            capturedData.reset();
        }

        public boolean hasData() {
            return capturedData.size() > 0;
        }

    }
}


text:
  display: table;
  width: 100%; }
  #mvunit_container .mvunit-middle-col {
    width: 30%;
    margin: 50px auto 0 auto;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px; }
  #mvunit_container .mvunit-field label {
    display: block; }
  #mvunit_container h2 {
    margin-top: 0; }
  #mvunit_container #mvunit_results {
    margin-top: 20px; }
  #mvunit_container .mvunit-fails, #mvunit_container .mvunit-success {
    font-weight: bold; }
  #mvunit_container .mvunit-fails {
    color: red; }
  #mvunit_container .mvunit-success {
    color: green; }
  #mvunit_container #mnunit_output {
    margin-top: 20px; }
  #mvunit_container textarea#mvunit_output_text {
    width: 97%;
    height: 200px;
    border-radius: 5px;
    padding: 5px;
    overflow-y: scroll;
    overflow-x: hidden;
    outline: none; }

table.mvunit-table {
  width: 100%;
  font-size: 14px;
  text-align: left;
  border-spacing: 0;
  border-collapse: collapse; }
  table.mvunit-table thead > tr > td, table.mvunit-table thead > tr > th, table.mvunit-table tbody > tr > td, table.mvunit-table tbody > tr > th, table.mvunit-table tfoot > tr > td, table.mvunit-table tfoot > tr > th {
    padding: 8px;
    border-top: 1px solid #ddd; }
  table.mvunit-table thead > tr:nth-of-type(odd) {
    background-color: #f9f9f9; }
  table.mvunit-table thead > tr > th {
    border-bottom: 2px solid #ddd; }


text:
using System;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using CQRSPipeline.Framework;

namespace CQRSPipeline.DemoAPI.Data
{
    public class CommandTransactionBehavior : PipelinedBehavior
    {

        public override void Invoke(CommandContext context, Action<CommandContext> next)
        {
            using (var dbContext = context.SingleInstanceFactory(typeof(DbContext)) as DbContext)
            {
                // commands, by default, will be RepeatableRead
                using (var transaction = dbContext.Database.BeginTransaction(IsolationLevel.RepeatableRead))
                {
                    next(context);
                    dbContext.SaveChanges();
                    transaction.Commit();
                }
            }
        }
    }
}


text:
<?php

$id = $_GET['id'];

$link = mysqli_connect("localhost",
    "root",
    "mysql123",
    "ftfl_training");

$query = "select * from empolyment_ftfl  WHERE id = $id";

$result = mysqli_query($link, $query);

$row = mysqli_fetch_assoc($result);

print_r($row);
?>

Go to Home


text:
#ifndef LLGL_D3D11_STATE_MANAGER_H
#define LLGL_D3D11_STATE_MANAGER_H

#include "../../DXCommon/ComPtr.h"
#include "../Shader/D3D11BuiltinShaderFactory.h"
#include "../Buffer/D3D11IntermediateBufferPool.h"
#include <LLGL/PipelineStateFlags.h>
#include <vector>
#include <cstdint>
#include "../Direct3D11.h"

namespace LLGL
{

class D3D11StateManager
{

    public:

        D3D11StateManager(
            ID3D11Device*                       device,
            const ComPtr<ID3D11DeviceContext>&  context,
            ID3D11DeviceContext*                cbufferPoolDeviceContext = nullptr
        );

        void SetViewports(std::uint32_t numViewports, const Viewport* viewportArray);
        void SetScissors(std::uint32_t numScissors, const Scissor* scissorArray);

        void SetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY primitiveTopology);
        void SetInputLayout(ID3D11InputLayout* inputLayout);

        void SetVertexShader(ID3D11VertexShader* shader);
        void SetHullShader(ID3D11HullShader* shader);
        void SetDomainShader(ID3D11DomainShader* shader);
        void SetGeometryShader(ID3D11GeometryShader* shader);
        void SetPixelShader(ID3D11PixelShader* shader);
        void SetComputeShader(ID3D11ComputeShader* shader);

        void SetRasterizerState(ID3D11RasterizerState* rasterizerState);

        void SetDepthStencilState(ID3D11DepthStencilState* depthStencilState);
        void SetDepthStencilState(ID3D11DepthStencilState* depthStencilState, UINT stencilRef);
        void SetStencilRef(UINT stencilRef);

        void SetBlendState(ID3D11BlendState* blendState, UINT sampleMask);
        void SetBlendState(ID3D11BlendState* blendState, const FLOAT* blendFactor, UINT sampleMask);
        void SetBlendFactor(const FLOAT* blendFactor);

        void SetConstantBuffers(
            UINT                    startSlot,
            UINT                    count,
            ID3D11Buffer* const*    buffers,
            long                    stageFlags
        );

        void SetConstantBuffersRange(
            UINT                    startSlot,
            UINT                    count,
            ID3D11Buffer* const*    buffers,
            const UINT*             firstConstants,
            const UINT*             numConstants,
            long                    stageFlags
        );

        void SetShaderResources(
            UINT                                startSlot,
            UINT                                count,
            ID3D11ShaderResourceView* const*    views,
            long                                stageFlags
        );

        void SetSamplers(
            UINT                        startSlot,
            UINT                        count,
            ID3D11SamplerState* const*  samplers,
            long                        stageFlags
        );

        void SetUnorderedAccessViews(
            UINT                                startSlot,
            UINT                                count,
            ID3D11UnorderedAccessView* const*   views,
            const UINT*                         initialCounts,
            long                                stageFlags
        );

        // Binds an intermediate constant buffer and updates its content with the specified data.
        void SetConstants(std::uint32_t slot, const void* data, std::uint16_t dataSize, long stageFlags);

        // Executes the specified builtin compute shader.
        void DispatchBuiltin(const D3D11BuiltinShader builtinShader, UINT numWorkGroupsX, UINT numWorkGroupsY, UINT numWorkGroupsZ);

        // Must be called in D3D11CommandBuffer::Begin
        void ResetIntermediateBufferPools();

        // Returns the ID3D11DeviceContext that this state manager is associated with.
        inline ID3D11DeviceContext* GetContext() const
        {
            return context_.Get();
        }

    private:

        struct D3DInputAssemblyState
        {
            D3D11_PRIMITIVE_TOPOLOGY    primitiveTopology   = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED;
            ID3D11InputLayout*          inputLayout         = nullptr;
        };

        struct D3DShaderState
        {
            ID3D11VertexShader*     vs = nullptr;
            ID3D11HullShader*       hs = nullptr;
            ID3D11DomainShader*     ds = nullptr;
            ID3D11GeometryShader*   gs = nullptr;
            ID3D11PixelShader*      ps = nullptr;
            ID3D11ComputeShader*    cs = nullptr;
        };

        struct D3DRenderState
        {
            ID3D11RasterizerState*      rasterizerState     = nullptr;
            ID3D11DepthStencilState*    depthStencilState   = nullptr;
            UINT                        stencilRef          = 0;
            ID3D11BlendState*           blendState          = nullptr;
            FLOAT                       blendFactor[4]      = { -1.0f, -1.0f, -1.0f, -1.0f };
            UINT                        sampleMask          = 0xffffffff;
        };

    private:

        ComPtr<ID3D11DeviceContext>     context_;

        #if LLGL_D3D11_ENABLE_FEATURELEVEL >= 1
        ComPtr<ID3D11DeviceContext1>    context1_;
        #endif

        D3D11IntermediateBufferPool     intermediateCbufferPool_;

        D3DInputAssemblyState           inputAssemblyState_;
        D3DShaderState                  shaderState_;
        D3DRenderState                  renderState_;

};

} // /namespace LLGL

#endif

// ================================================================================


text:
package com.aspectran.core.context.rule.parser.xml;

import com.aspectran.core.context.rule.BeanRule;
import com.aspectran.core.context.rule.DescriptionRule;
import com.aspectran.core.context.rule.ItemRuleMap;
import com.aspectran.core.context.rule.assistant.ActivityRuleAssistant;
import com.aspectran.core.context.rule.params.FilterParameters;
import com.aspectran.core.util.BooleanUtils;
import com.aspectran.core.util.StringUtils;
import com.aspectran.core.util.nodelet.NodeletAdder;
import com.aspectran.core.util.nodelet.NodeletParser;

/**
 * The Class BeanInnerNodeletAdder.
 *
 *
Created: 2008. 06. 14 AM 6:56:29

 */
class BeanNodeletAdder implements NodeletAdder {

    @Override
    public void add(String xpath, NodeletParser parser) {
        AspectranNodeParser nodeParser = parser.getNodeParser();
        ActivityRuleAssistant assistant = nodeParser.getAssistant();

        parser.setXpath(xpath + "/bean");
        parser.addNodelet(attrs -> {
            String id = StringUtils.emptyToNull(attrs.get("id"));
            String className = StringUtils.emptyToNull(assistant.resolveAliasType(attrs.get("class")));
            String factoryBean = StringUtils.emptyToNull(attrs.get("factoryBean"));
            String factoryMethod = StringUtils.emptyToNull(attrs.get("factoryMethod"));
            String scan = attrs.get("scan");
            String mask = attrs.get("mask");
            String initMethod = StringUtils.emptyToNull(attrs.get("initMethod"));
            String destroyMethod = StringUtils.emptyToNull(attrs.get("destroyMethod"));
            String scope = attrs.get("scope");
            Boolean singleton = BooleanUtils.toNullableBooleanObject(attrs.get("singleton"));
            Boolean lazyInit = BooleanUtils.toNullableBooleanObject(attrs.get("lazyInit"));
            Boolean lazyDestroy = BooleanUtils.toNullableBooleanObject(attrs.get("lazyDestroy"));
            Boolean important = BooleanUtils.toNullableBooleanObject(attrs.get("important"));

            BeanRule beanRule;
            if (className == null && scan == null && factoryBean != null) {
                beanRule = BeanRule.newOfferedFactoryBeanInstance(id, factoryBean, factoryMethod,
                        initMethod, destroyMethod, scope, singleton, lazyInit, lazyDestroy, important);
            } else {
                beanRule = BeanRule.newInstance(id, className, scan, mask, initMethod, destroyMethod,
                        factoryMethod, scope, singleton, lazyInit, lazyDestroy, important);
            }

            parser.pushObject(beanRule);
        });
        parser.addNodeEndlet(text -> {
            BeanRule beanRule = parser.popObject();
            assistant.resolveBeanClass(beanRule);
            assistant.resolveFactoryBeanClass(beanRule);
            assistant.addBeanRule(beanRule);
        });
        parser.setXpath(xpath + "/bean/description");
        parser.addNodelet(attrs -> {
            String profile = attrs.get("profile");
            String style = attrs.get("style");

            DescriptionRule descriptionRule = DescriptionRule.newInstance(profile, style);
            parser.pushObject(descriptionRule);
        });
        parser.addNodeEndlet(text -> {
            DescriptionRule descriptionRule = parser.popObject();
            BeanRule beanRule = parser.peekObject();

            descriptionRule.setContent(text);
            descriptionRule = assistant.profiling(descriptionRule, beanRule.getDescriptionRule());
            beanRule.setDescriptionRule(descriptionRule);
        });
        parser.setXpath(xpath + "/bean/filter");
        parser.addNodelet(attrs -> {
            String classScanFilterClassName = attrs.get("class");
            FilterParameters filterParameters = new FilterParameters();
            if (StringUtils.hasText(classScanFilterClassName)) {
                filterParameters.putValue(FilterParameters.filterClass, classScanFilterClassName);
            }
            parser.pushObject(filterParameters);
        });
        parser.addNodeEndlet(text -> {
            FilterParameters filterParameters = parser.popObject();
            if (StringUtils.hasText(text)) {
                filterParameters = new FilterParameters();
                filterParameters.readFrom(text);
            }
            if (filterParameters.hasValue(FilterParameters.filterClass) ||
                    filterParameters.hasValue(FilterParameters.exclude)) {
                BeanRule beanRule = parser.peekObject();
                beanRule.setFilterParameters(filterParameters);
            }
        });
        parser.setXpath(xpath + "/bean/arguments");
        parser.addNodelet(attrs -> {
            ItemRuleMap irm = new ItemRuleMap();
            irm.setProfile(StringUtils.emptyToNull(attrs.get("profile")));
            parser.pushObject(irm);
        });
        nodeParser.addItemNodelets();
        parser.addNodeEndlet(text -> {
            ItemRuleMap irm = parser.popObject();
            BeanRule beanRule = parser.peekObject();
            irm = assistant.profiling(irm, beanRule.getConstructorArgumentItemRuleMap());
            beanRule.setConstructorArgumentItemRuleMap(irm);
        });
        parser.setXpath(xpath + "/bean/properties");
        parser.addNodelet(attrs -> {
            ItemRuleMap irm = new ItemRuleMap();
            irm.setProfile(StringUtils.emptyToNull(attrs.get("profile")));
            parser.pushObject(irm);
        });
        nodeParser.addItemNodelets();
        parser.addNodeEndlet(text -> {
            ItemRuleMap irm = parser.popObject();
            BeanRule beanRule = parser.peekObject();
            irm = assistant.profiling(irm, beanRule.getPropertyItemRuleMap());
            beanRule.setPropertyItemRuleMap(irm);
        });
    }

}