text:
#ifndef itkWindowedSincInterpolateImageFunction_h
#define itkWindowedSincInterpolateImageFunction_h

#include "itkConstNeighborhoodIterator.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itkInterpolateImageFunction.h"

namespace itk
{
namespace Function
{
/**
 * \class CosineWindowFunction
 * \brief Window function for sinc interpolation.
 * \f[ w(x) = cos(\frac{\pi x}{2 m} ) \f]
 * \sa WindowedSincInterpolateImageFunction
 * \ingroup ITKImageFunction
 */
template <unsigned int VRadius, typename TInput = double, typename TOutput = double>
class ITK_TEMPLATE_EXPORT CosineWindowFunction
{
public:
  inline TOutput
  operator()(const TInput & A) const
  {
    return static_cast<TOutput>(std::cos(A * m_Factor));
  }

private:
  /** Equal to \f$ \frac{\pi}{2 m} \f$ */
  static const double m_Factor;
};

/**
 * \class HammingWindowFunction
 * \brief Window function for sinc interpolation.
 * \f[ w(x) = 0.54 + 0.46 cos(\frac{\pi x}{m} ) \f]
 * \sa WindowedSincInterpolateImageFunction
 * \ingroup ITKImageFunction
 */
template <unsigned int VRadius, typename TInput = double, typename TOutput = double>
class ITK_TEMPLATE_EXPORT HammingWindowFunction
{
public:
  inline TOutput
  operator()(const TInput & A) const
  {
    return static_cast<TOutput>(0.54 + 0.46 * std::cos(A * m_Factor));
  }

private:
  /** Equal to \f$ \frac{\pi}{m} \f$ */
  static const double m_Factor;
};

/**
 * \class WelchWindowFunction
 * \brief Window function for sinc interpolation.
 * \f[ w(x) = 1 - ( \frac{x^2}{m^2} ) \f]
 * \sa WindowedSincInterpolateImageFunction
 * \ingroup ITKImageFunction
 */
template <unsigned int VRadius, typename TInput = double, typename TOutput = double>
class ITK_TEMPLATE_EXPORT WelchWindowFunction
{
public:
  inline TOutput
  operator()(const TInput & A) const
  {
    return static_cast<TOutput>(1.0 - A * m_Factor * A);
  }

private:
  /** Equal to \f$ \frac{1}{m^2} \f$ */
  static const double m_Factor;
};

/**
 * \class LanczosWindowFunction
 * \brief Window function for sinc interpolation.
 * \f[ w(x) = \textrm{sinc} ( \frac{x}{m} ) \f]
 * Note: Paper referenced in WindowedSincInterpolateImageFunction gives
 * an incorrect definition of this window function.
 * \sa WindowedSincInterpolateImageFunction
 * \ingroup ITKImageFunction
 */
template <unsigned int VRadius, typename TInput = double, typename TOutput = double>
class ITK_TEMPLATE_EXPORT LanczosWindowFunction
{
public:
  inline TOutput
  operator()(const TInput & A) const
  {
    if (A == 0.0)
    {
      return static_cast<TOutput>(1.0);
    }
    double z = m_Factor * A;
    return static_cast<TOutput>(std::sin(z) / z);
  }

private:
  /** Equal to \f$ \frac{\pi}{m} \f$ */
  static const double m_Factor;
};

/**
 * \class BlackmanWindowFunction
 * \brief Window function for sinc interpolation.
 * \f[ w(x) = 0.42 + 0.5 cos(\frac{\pi x}{m}) + 0.08 cos(\frac{2 \pi x}{m}) \f]
 * \sa WindowedSincInterpolateImageFunction
 * \ingroup ITKImageFunction
 */
template <unsigned int VRadius, typename TInput = double, typename TOutput = double>
class ITK_TEMPLATE_EXPORT BlackmanWindowFunction
{
public:
  inline TOutput
  operator()(const TInput & A) const
  {
    return static_cast<TOutput>(0.42 + 0.5 * std::cos(A * m_Factor1) + 0.08 * std::cos(A * m_Factor2));
  }

private:
  /** Equal to \f$ \frac{\pi}{m} \f$ */
  static const double m_Factor1;

  /** Equal to \f$ \frac{2 \pi}{m} \f$  */
  static const double m_Factor2;
};
} // namespace Function

/**
 * \class WindowedSincInterpolateImageFunction
 * \brief Use the windowed sinc function to interpolate
 * \author Paul A. Yushkevich
 *
 * \par THEORY
 *
 * This function is intended to provide an interpolation function that
 * has minimum aliasing artifacts, in contrast to linear interpolation.
 * According to sampling theory, the infinite-support sinc filter,
 * whose Fourier transform is the box filter, is optimal for resampling
 * a function. In practice, the infinite support sinc filter is
 * approximated using a limited support 'windowed' sinc filter.
 *
 * \par
 * This function is based on the following publication:
 *
 * \par
 * Erik H. W. Meijering, Wiro J. Niessen, Josien P. W. Pluim,
 * Max A. Viergever: Quantitative Comparison of Sinc-Approximating
 * Kernels for Medical Image Interpolation. MICCAI 1999, pp. 210-217
 *
 * \par
 * In this work, several 'windows' are estimated. In two dimensions, the
 * interpolation at a position (x,y) is given by the following
 * expression:
 *
 * \par
 * \f[
 *   I(x,y) =
 *     \sum_{i = \lfloor x \rfloor + 1 - m}^{\lfloor x \rfloor + m}
 *     \sum_{j = \lfloor y \rfloor + 1 - m}^{\lfloor y \rfloor + m}
 *     I_{i,j} K(x-i) K(y-j),
 * \f]
 *
 * \par
 * where m is the 'radius' of the window, (3,4 are reasonable numbers),
 * and K(t) is the kernel function, composed of the sinc function and
 * one of several possible window functions:
 *
 * \par
 * \f[
 *   K(t) = w(t) \textrm{sinc}(t) = w(t) \frac{\sin(\pi t)}{\pi t}
 * \f]
 *
 * \par
 * Several window functions are provided here in the itk::Function
 * namespace. The conclusions of the referenced paper suggest to use the
 * Welch, Cosine, Kaiser, and Lanczos windows for m = 4,5. These are based
 * on error in rotating medical images w.r.t. the linear interpolation
 * method. In some cases the results achieve a 20-fold improvement in
 * accuracy.
 *
 * \par USING THIS FILTER
 *
 * Use this filter the way you would use any ImageInterpolationFunction,
 * so for instance, you can plug it into the ResampleImageFilter class.
 * In order to initialize the filter you must choose several template
 * parameters.
 *
 * \par
 * The first (TInputImage) is the image type, that's standard.
 *
 * \par
 * The second (VRadius) is the radius of the kernel, i.e., the
 * \f$ m \f$ from the formula above.
 *
 * \par
 * The third (TWindowFunction) is the window function object, which you
 * can choose from about five different functions defined in this
 * header. The default is the Hamming window, which is commonly used
 * but not optimal according to the cited paper.
 *
 * \par
 * The fourth (TBoundaryCondition) is the boundary condition class used
 * to determine the values of pixels that fall off the image boundary.
 * This class has the same meaning here as in the NeighborhoodItetator
 * classes.
 *
 * \par
 * The fifth (TCoordRep) is again standard for interpolating functions,
 * and should be float or double.
 *
 * \par CAVEATS
 *
 * There are a few improvements that an enthusiastic ITK developer
 * could make to this filter. One issue is with the way that the kernel
 * is applied. The computational expense comes from two sources:
 * computing the kernel weights K(t) and multiplying the pixels in the
 * window by the kernel weights. The first is done more or less
 * efficiently in \f$ 2 m d \f$ operations (where d is the
 * dimensionality of the image). The second can be done
 * better. Presently, each pixel \f$ I(i,j,k) \f$ is multiplied by the
 * weights \f$ K(x-i), K(y-j), K(z-k) \f$ and added to the running
 * total. This results in \f$ d (2m)^d \f$ multiplication
 * operations. However, by keeping intermediate sums, it would be
 * possible to do the operation in \f$ O ( (2m)^d ) \f$
 * operations. This would require some creative coding. In addition, in
 * the case when one of the coordinates is integer, the computation
 * could be reduced by an order of magnitude.
 *
 * \sa LinearInterpolateImageFunction ResampleImageFilter
 * \sa Function::HammingWindowFunction
 * \sa Function::CosineWindowFunction
 * \sa Function::WelchWindowFunction
 * \sa Function::LanczosWindowFunction
 * \sa Function::BlackmanWindowFunction
 * \ingroup ImageFunctions ImageInterpolators
 * \ingroup ITKImageFunction
 */
template <typename TInputImage,
          unsigned int VRadius,
          typename TWindowFunction = Function::HammingWindowFunction<VRadius>,
          class TBoundaryCondition = ZeroFluxNeumannBoundaryCondition<TInputImage, TInputImage>,
          class TCoordRep = double>
class WindowedSincInterpolateImageFunction : public InterpolateImageFunction<TInputImage, TCoordRep>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(WindowedSincInterpolateImageFunction);

  /** Standard class type aliases. */
  using Self = WindowedSincInterpolateImageFunction;
  using Superclass = InterpolateImageFunction<TInputImage, TCoordRep>;

  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Run-time type information (and related methods). */
  itkTypeMacro(WindowedSincInterpolateImageFunction, InterpolateImageFunction);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** OutputType type alias support */
  using OutputType = typename Superclass::OutputType;

  /** InputImageType type alias support */
  using InputImageType = typename Superclass::InputImageType;

  /** RealType type alias support */
  using RealType = typename Superclass::RealType;

  /** Dimension underlying input image. */
  static constexpr unsigned int ImageDimension = Superclass::ImageDimension;

  /** Index type alias support */
  using IndexType = typename Superclass::IndexType;
  using IndexValueType = typename Superclass::IndexValueType;

  /** Size type alias support */
  using SizeType = typename Superclass::SizeType;

  /** Image type definition */
  using ImageType = TInputImage;

  /** ContinuousIndex type alias support */
  using ContinuousIndexType = typename Superclass::ContinuousIndexType;

  void
  SetInputImage(const ImageType * image) override;

  /** Evaluate the function at a ContinuousIndex position
   *
   * Returns the interpolated image intensity at a
   * specified point position.  Bounds checking is based on the
   * type of the TBoundaryCondition specified.
   */
  OutputType
  EvaluateAtContinuousIndex(const ContinuousIndexType & index) const override;

  SizeType
  GetRadius() const override
  {
    SizeType radius;
    radius.Fill(VRadius);
    return radius;
  }

protected:
  WindowedSincInterpolateImageFunction();
  ~WindowedSincInterpolateImageFunction() override;
  void
  PrintSelf(std::ostream & os, Indent indent) const override;

private:
  // Internal type alias
  using IteratorType = ConstNeighborhoodIterator<ImageType, TBoundaryCondition>;

  // Constant to store twice the radius
  static const unsigned int m_WindowSize;

  /** The function object, used to compute window */
  TWindowFunction m_WindowFunction;

  /** The offset array, used to keep a list of relevant
   * offsets in the neihborhoodIterator */
  unsigned int * m_OffsetTable;

  /** Size of the offset table */
  unsigned int m_OffsetTableSize;

  /** Index into the weights array for each offset */
  unsigned int ** m_WeightOffsetTable;

  /** The sinc function */
  inline double
  Sinc(double x) const
  {
    const double px = itk::Math::pi * x;

    return (x == 0.0) ? 1.0 : std::sin(px) / px;
  }
};
} // namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkWindowedSincInterpolateImageFunction.hxx"
#endif

#endif // _itkWindowedSincInterpolateImageFunction_h


text:
// RUN: %ucc -S -o %t %s
//
// verify main is using callee save registers:
// RUN: awk '/main:/ { p = 1 } { if(p) print }' < %t > %t.maindisas
// RUN: grep 'mov.*%.bx' %t.maindisas >/dev/null
// RUN: rm -f %t.maindisas
//
// then run the test:
// RUN: %ocheck 0 %s
// RUN: %ocheck 0 %s -fstack-protector-all

long llabs(void)
{
	return 0;
}

void SNPRINTF(char *s, ...)
{
}

/* ---------------- original bug ---------------- */

int impl_val_str_r(void)
{
	long off = 0;
	SNPRINTF(0, 0, 0, 0, 0, 0, 0);
	SNPRINTF(0, off ? "-" : 0, llabs());
	return 1;
}
/*
 * stack:
 * 0-8: off
 * 8-16: %rbx AND stack-space for 7th arg AND saved space for 1st arg to 2nd SNPRINTF
 *
 * This bug is rare because it just so happens in this case that the stack is
 * perfectly filled by the call-space/spill values and the callee-save register stash.
 * Normally there would be 4-bytes or more, meaning the bug would go unnoticed.
 */

/* ---------------- attempt at causing fix to be buggy ---------------- */

int impl_val_str_r2(void)
{
	long off = 0;
	long off2 = 0; /* attempt to saturate the stack taking into account that it's now gone from 16-bytes to 32-bytes */
	SNPRINTF(0, 0, 0, 0, 0, 0, 0);
	SNPRINTF(0, off ? "-" : 0, llabs());
	return 1;
}

/* ---------------- harness for test below ---------------- */

void f(int g_, int i_, int h_)
{
	_Noreturn void abort(void);

	// this implicitly tests the callee save regs from main() weren't clobbered,
	// i.e. that impl_val_str_r() is able to save and restore them without them
	// being overwritten while on the stack
	if(g_ != -5) abort();
	if(h_ != -72) abort();

	if(i_ != 1) abort();
}

int g(void)
{
	return -5;
}

int h(void)
{
	return -72;
}

int main()
{
#include "../ocheck-init.c"
	// do something to cause us to require callee-save registers, so we can check
	// they're not clobbered by impl_val_str_r()'s save/restore of them
	f(g(), impl_val_str_r(), h());

	// check the second case
	f(g(), impl_val_str_r2(), h());

	// and again to try to aggravate
	f(g(), (impl_val_str_r2(), 1), h());
}

redpajama_set_name: RedPajamaGithub


text:
dojo.provide("dojo.io.iframe");

/*=====
dojo.declare("dojo.io.iframe.__ioArgs", dojo.__IoArgs, {
	constructor: function(){
		//	summary:
		//		All the properties described in the dojo.__ioArgs type, apply
		//		to this type. The following additional properties are allowed
		//		for dojo.io.iframe.send():
		//	method: String?
		//		The HTTP method to use. "GET" or "POST" are the only supported
		//		values.  It will try to read the value from the form node's
		//		method, then try this argument. If neither one exists, then it
		//		defaults to POST.
		//	handleAs: String?
		//		Specifies what format the result data should be given to the
		//		load/handle callback. Valid values are: text, html, xml, json,
		//		javascript. IMPORTANT: For all values EXCEPT html and xml, The
		//		server response should be an HTML file with a textarea element.
		//		The response data should be inside the textarea element. Using an
		//		HTML document the only reliable, cross-browser way this
		//		transport can know when the response has loaded. For the html
		//		handleAs value, just return a normal HTML document.  NOTE: xml
		//		is now supported with this transport (as of 1.1+); a known issue
		//		is if the XML document in question is malformed, Internet Explorer
		//		will throw an uncatchable error.
		//	content: Object?
		//		If "form" is one of the other args properties, then the content
		//		object properties become hidden form form elements. For
		//		instance, a content object of {name1 : "value1"} is converted
		//		to a hidden form element with a name of "name1" and a value of
		//		"value1". If there is not a "form" property, then the content
		//		object is converted into a name=value&name=value string, by
		//		using dojo.objectToQuery().
		this.method = method;
		this.handleAs = handleAs;
		this.content = content;
	}
});
=====*/

dojo.io.iframe = {
	create: function(/*String*/fname, /*String*/onloadstr, /*String?*/uri){
		//	summary:
		//		Creates a hidden iframe in the page. Used mostly for IO
		//		transports.  You do not need to call this to start a
		//		dojo.io.iframe request. Just call send().
		//	fname: String
		//		The name of the iframe. Used for the name attribute on the
		//		iframe.
		//	onloadstr: String
		//		A string of JavaScript that will be executed when the content
		//		in the iframe loads.
		//	uri: String
		//		The value of the src attribute on the iframe element. If a
		//		value is not given, then dojo/resources/blank.html will be
		//		used.
		if(window[fname]){ return window[fname]; }
		if(window.frames[fname]){ return window.frames[fname]; }
		var cframe = null;
		var turi = uri;
		if(!turi){
			if(dojo.config["useXDomain"] && !dojo.config["dojoBlankHtmlUrl"]){
				console.warn("dojo.io.iframe.create: When using cross-domain Dojo builds,"
					+ " please save dojo/resources/blank.html to your domain and set djConfig.dojoBlankHtmlUrl"
					+ " to the path on your domain to blank.html");
			}
			turi = (dojo.config["dojoBlankHtmlUrl"]||dojo.moduleUrl("dojo", "resources/blank.html"));
		}
		var ifrstr = dojo.isIE ? '<iframe name="'+fname+'" src="'+turi+'" onload="'+onloadstr+'">' : 'iframe';
		cframe = dojo.doc.createElement(ifrstr);
		with(cframe){
			name = fname;
			setAttribute("name", fname);
			id = fname;
		}
		dojo.body().appendChild(cframe);
		window[fname] = cframe;

		with(cframe.style){
			if(!(dojo.isSafari < 3)){
				//We can't change the src in Safari 2.0.3 if absolute position. Bizarro.
				position = "absolute";
			}
			left = top = "1px";
			height = width = "1px";
			visibility = "hidden";
		}

		if(!dojo.isIE){
			this.setSrc(cframe, turi, true);
			cframe.onload = new Function(onloadstr);
		}

		return cframe;
	},

	setSrc: function(/*DOMNode*/iframe, /*String*/src, /*Boolean*/replace){
		//summary:
		//		Sets the URL that is loaded in an IFrame. The replace parameter
		//		indicates whether location.replace() should be used when
		//		changing the location of the iframe.
		try{
			if(!replace){
				if(dojo.isWebKit){
					iframe.location = src;
				}else{
					frames[iframe.name].location = src;
				}
			}else{
				// Fun with DOM 0 incompatibilities!
				var idoc;
				//WebKit > 521 corresponds with Safari 3, which started with 522 WebKit version.
				if(dojo.isIE || dojo.isWebKit > 521){
					idoc = iframe.contentWindow.document;
				}else if(dojo.isSafari){
					idoc = iframe.document;
				}else{ //  if(d.isMozilla){
					idoc = iframe.contentWindow;
				}

				//For Safari (at least 2.0.3) and Opera, if the iframe
				//has just been created but it doesn't have content
				//yet, then iframe.document may be null. In that case,
				//use iframe.location and return.
				if(!idoc){
					iframe.location = src;
					return;
				}else{
					idoc.location.replace(src);
				}
			}
		}catch(e){
			console.log("dojo.io.iframe.setSrc: ", e);
		}
	},

	doc: function(/*DOMNode*/iframeNode){
		//summary: Returns the document object associated with the iframe DOM Node argument.
		var doc = iframeNode.contentDocument || // W3
			(
				(
					(iframeNode.name) && (iframeNode.document) &&
					(document.getElementsByTagName("iframe")[iframeNode.name].contentWindow) &&
					(document.getElementsByTagName("iframe")[iframeNode.name].contentWindow.document)
				)
			) ||  // IE
			(
				(iframeNode.name)&&(document.frames[iframeNode.name])&&
				(document.frames[iframeNode.name].document)
			) || null;
		return doc;
	},

	send: function(/*dojo.io.iframe.__ioArgs*/args){
		//summary: function that sends the request to the server.
		//This transport can only process one send() request at a time, so if send() is called
		//multiple times, it will queue up the calls and only process one at a time.
		if(!this["_frame"]){
			this._frame = this.create(this._iframeName, dojo._scopeName + ".io.iframe._iframeOnload();");
		}

		//Set up the deferred.
		var dfd = dojo._ioSetArgs(
			args,
			function(/*Deferred*/dfd){
				//summary: canceller function for dojo._ioSetArgs call.
				dfd.canceled = true;
				dfd.ioArgs._callNext();
			},
			function(/*Deferred*/dfd){
				//summary: okHandler function for dojo._ioSetArgs call.
				var value = null;
				try{
					var ioArgs = dfd.ioArgs;
					var dii = dojo.io.iframe;
					var ifd = dii.doc(dii._frame);
					var handleAs = ioArgs.handleAs;

					//Assign correct value based on handleAs value.
					value = ifd; //html
					if(handleAs != "html"){
						if(handleAs == "xml"){
							//	FF, Saf 3+ and Opera all seem to be fine with ifd being xml.  We have to
							//	do it manually for IE.  Refs #6334.
							if(dojo.isIE){
								dojo.query("a", dii._frame.contentWindow.document.documentElement).orphan();
								var xmlText=(dii._frame.contentWindow.document).documentElement.innerText;
								xmlText=xmlText.replace(/>\s+</g, "><");
								xmlText=dojo.trim(xmlText);
								//Reusing some code in base dojo for handling XML content.  Simpler and keeps
								//Core from duplicating the effort needed to locate the XML Parser on IE.
								var fauxXhr = { responseText: xmlText };
								value = dojo._contentHandlers["xml"](fauxXhr); // DOMDocument
							}
						}else{
							value = ifd.getElementsByTagName("textarea")[0].value; //text
							if(handleAs == "json"){
								value = dojo.fromJson(value); //json
							}else if(handleAs == "javascript"){
								value = dojo.eval(value); //javascript
							}
						}
					}
				}catch(e){
					value = e;
				}finally{
					ioArgs._callNext();
				}
				return value;
			},
			function(/*Error*/error, /*Deferred*/dfd){
				//summary: errHandler function for dojo._ioSetArgs call.
				dfd.ioArgs._hasError = true;
				dfd.ioArgs._callNext();
				return error;
			}
		);

		//Set up a function that will fire the next iframe request. Make sure it only
		//happens once per deferred.
		dfd.ioArgs._callNext = function(){
			if(!this["_calledNext"]){
				this._calledNext = true;
				dojo.io.iframe._currentDfd = null;
				dojo.io.iframe._fireNextRequest();
			}
		}

		this._dfdQueue.push(dfd);
		this._fireNextRequest();

		//Add it the IO watch queue, to get things like timeout support.
		dojo._ioWatch(
			dfd,
			function(/*Deferred*/dfd){
				//validCheck
				return !dfd.ioArgs["_hasError"];
			},
			function(dfd){
				//ioCheck
				return (!!dfd.ioArgs["_finished"]);
			},
			function(dfd){
				//resHandle
				if(dfd.ioArgs._finished){
					dfd.callback(dfd);
				}else{
					dfd.errback(new Error("Invalid dojo.io.iframe request state"));
				}
			}
		);

		return dfd;
	},

	_currentDfd: null,
	_dfdQueue: [],
	_iframeName: dojo._scopeName + "IoIframe",

	_fireNextRequest: function(){
		//summary: Internal method used to fire the next request in the bind queue.
		try{
			if((this._currentDfd)||(this._dfdQueue.length == 0)){ return; }
			var dfd = this._currentDfd = this._dfdQueue.shift();
			var ioArgs = dfd.ioArgs;
			var args = ioArgs.args;

			ioArgs._contentToClean = [];
			var fn = dojo.byId(args["form"]);
			var content = args["content"] || {};
			if(fn){
				if(content){
					// if we have things in content, we need to add them to the form
					// before submission
					var pHandler = function(name, value) {
						var tn;
						if(dojo.isIE){
							tn = dojo.doc.createElement("<input type='hidden' name='"+name+"'>");
						}else{
							tn = dojo.doc.createElement("input");
							tn.type = "hidden";
							tn.name = name;
						}
						tn.value = value;
						fn.appendChild(tn);
						ioArgs._contentToClean.push(name);
					};
					for(var x in content){
						var val = content[x];
						if(dojo.isArray(val) && val.length > 1){
							var i;
							for (i = 0; i < val.length; i++) {
								pHandler(x,val[i]);
							}
						}else{
							if(!fn[x]){
								pHandler(x,val);
							}else{
								fn[x].value = val;
							}
						}
					}
				}
				//IE requires going through getAttributeNode instead of just getAttribute in some form cases,
				//so use it for all.  See #2844
				var actnNode = fn.getAttributeNode("action");
				var mthdNode = fn.getAttributeNode("method");
				var trgtNode = fn.getAttributeNode("target");
				if(args["url"]){
					ioArgs._originalAction = actnNode ? actnNode.value : null;
					if(actnNode){
						actnNode.value = args.url;
					}else{
						fn.setAttribute("action",args.url);
					}
				}
				if(!mthdNode || !mthdNode.value){
					if(mthdNode){
						mthdNode.value= (args["method"]) ? args["method"] : "post";
					}else{
						fn.setAttribute("method", (args["method"]) ? args["method"] : "post");
					}
				}
				ioArgs._originalTarget = trgtNode ? trgtNode.value: null;
				if(trgtNode){
					trgtNode.value = this._iframeName;
				}else{
					fn.setAttribute("target", this._iframeName);
				}
				fn.target = this._iframeName;
				fn.submit();
			}else{
				// otherwise we post a GET string by changing URL location for the
				// iframe
				var tmpUrl = args.url + (args.url.indexOf("?") > -1 ? "&" : "?") + ioArgs.query;
				this.setSrc(this._frame, tmpUrl, true);
			}
		}catch(e){
			dfd.errback(e);
		}
	},

	_iframeOnload: function(){
		var dfd = this._currentDfd;
		if(!dfd){
			this._fireNextRequest();
			return;
		}

		var ioArgs = dfd.ioArgs;
		var args = ioArgs.args;
		var fNode = dojo.byId(args.form);

		if(fNode){
			// remove all the hidden content inputs
			var toClean = ioArgs._contentToClean;
			for(var i = 0; i < toClean.length; i++) {
				var key = toClean[i];
				//Need to cycle over all nodes since we may have added
				//an array value which means that more than one node could
				//have the same .name value.
				for(var j = 0; j < fNode.childNodes.length; j++){
					var chNode = fNode.childNodes[j];
					if(chNode.name == key){
						dojo.destroy(chNode);
						break;
					}
				}
			}

			// restore original action + target
			if(ioArgs["_originalAction"]){
				fNode.setAttribute("action", ioArgs._originalAction);
			}
			if(ioArgs["_originalTarget"]){
				fNode.setAttribute("target", ioArgs._originalTarget);
				fNode.target = ioArgs._originalTarget;
			}
		}

		ioArgs._finished = true;
	}
}


text:
package models;

import lombok.Data;

/**
 * Created by nfischer on 2/29/2016.
 */
@Data
public class Location {
	private String city;
	private String state;
	private String country;
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;

namespace NuGet.Server.Core.Infrastructure
{
    public class PackageDerivedData
    {
        public PackageDerivedData()
        {
            PackageHashAlgorithm = Constants.HashAlgorithm;
        }

        public long PackageSize { get; set; }
        public string PackageHash { get; set; }
        public string PackageHashAlgorithm { get; set; }
        public DateTimeOffset LastUpdated { get; set; }
        public DateTimeOffset Created { get; set; }
        public string FullPath { get; set; }
    }
}


text:
using Newtonsoft.Json;
using SessionM.MMC.models.intefaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SessionM.MMC.models
{
    public class Offer : ISMModel
    {
        [JsonProperty("id")]
        public int id { get; set; }
        [DefaultValue(null)]
        [JsonProperty("name")]
        public string name { get; set; }
        [DefaultValue(null)]
        [JsonProperty("type")]
        public string type { get; set; }
        [DefaultValue(null)]
        [JsonProperty("description")]
        public string description { get; set; }
        [DefaultValue(0)]
        [JsonProperty("points")]
        public int points { get; set; }
        [DefaultValue(null)]
        [JsonProperty("tier")]
        public object tier { get; set; }
        [DefaultValue(null)]
        [JsonProperty("status")]
        public string status { get; set; }
        [DefaultValue(null)]
        [JsonProperty("logo")]
        public string logo { get; set; }

        [DefaultValue(null)]
        [JsonProperty("data")]
        public object data { get; set; }

        [DefaultValue(null)]
        [JsonProperty("options")]
        public IList<OfferOption> offerOptions { get; set; }

    }
}


text:
Booking

  <button type="button" class="btn btn-default" ng-click="saveData()">
     Save
  </button>

     Cancel

<form class="form-horizontal">

    Date From

                <input type="text" class="form-control" ng-model="model.DateFrom" data-date-time-input="YYYY-MM-DD HH:mm">

            <datetimepicker ng-model="model.DateFrom" data-datetimepicker-config="{ dropdownSelector: '#aDateFrom' }"/>

    Date To

                <input type="text" class="form-control" ng-model="model.DateTo" data-date-time-input="YYYY-MM-DD HH:mm">

            <datetimepicker ng-model="model.DateTo" data-datetimepicker-config="{ dropdownSelector: '#aDateTo' }"/>

    Car Type

      <select class="form-control" ng-model="model.CarTypeId" ng-options="type.Id as type.Name for type in carTypes"></select>

    Create new client?

      <input type="checkbox" ng-model="isNewClient">

        Full Name

          <input type="text" class="form-control" placeholder="Full Name" ng-model="model.Client.FullName">

        Phones

          <input type="text" class="form-control" placeholder="Phones" ng-model="model.Client.Phones">

        Insurance Number

          <input type="text" class="form-control" placeholder="Insurance Number" ng-model="model.Client.InsuranceNumber">

      <select class="form-control" ng-model="model.ClientId" ng-options="client.Id as client.FullName for client in clients"></select>

</form>

  <button type="button" class="btn btn-default" ng-click="saveData()">
     Save
  </button>

     Cancel


text:
from datetime import datetime

from celery import task
from statsd import statsd

@task()
def measure_queue_lag(queued_time):
    """A task that measures the time it was sitting in the queue.

    It saves the data to graphite via statsd.
    """
    lag = datetime.now() - queued_time
    lag = (lag.days * 3600 * 24) + lag.seconds
    statsd.gauge('rabbitmq.lag', max(lag, 0))


text:
package de.plushnikov.intellij.plugin.psi;

import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiTypeParameter;
import com.intellij.psi.PsiTypeParameterList;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.light.LightClass;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Arrays;

public class LombokLightClass extends LightClass {
  private String myQualifiedName;
  private PsiMethod[] myConstructors = new PsiMethod[0];
  private PsiField[] myFields = new PsiField[0];
  private PsiMethod[] myMethods = new PsiMethod[0];
  private LombokLightModifierList myModifierList;
  private PsiClass myContainingClass;
  private PsiTypeParameterList myTypeParameterList;
  private PsiTypeParameter[] myTypeParameters = new PsiTypeParameter[0];

  public LombokLightClass(@NotNull PsiClass delegate) {
    super(delegate);
    myModifierList = new LombokLightModifierList(delegate.getManager(), JavaLanguage.INSTANCE);
  }

  @Nullable
  @Override
  public String getQualifiedName() {
    return myQualifiedName;
  }

  public void setQualifiedName(@NotNull String qualifiedName) {
    myQualifiedName = qualifiedName;
  }

  @NotNull
  @Override
  public PsiMethod[] getConstructors() {
    return myConstructors;
  }

  public void setConstructors(@NotNull PsiMethod[] constructors) {
    myConstructors = constructors;
  }

  @Override
  @NotNull
  public PsiField[] getFields() {
    return myFields;
  }

  public void setFields(@NotNull PsiField[] fields) {
    myFields = fields;
  }

  @NotNull
  @Override
  public PsiMethod[] getMethods() {
    // http://stackoverflow.com/a/784842/411905
    PsiMethod[] result = Arrays.copyOf(myMethods, myMethods.length + myConstructors.length);
    System.arraycopy(myConstructors, 0, result, myMethods.length, myConstructors.length);
    return result;
  }

  public void setMethods(@NotNull PsiMethod[] methods) {
    myMethods = methods;
  }

  @NotNull
  @Override
  public LombokLightModifierList getModifierList() {
    return myModifierList;
  }

  @Override
  public boolean hasModifierProperty(@NonNls @NotNull String name) {
    return myModifierList.hasModifierProperty(name);
  }

  @Nullable
  @Override
  public PsiTypeParameterList getTypeParameterList() {
    return myTypeParameterList;
  }

  @NotNull
  @Override
  public PsiTypeParameter[] getTypeParameters() {
    return myTypeParameters;
  }

  public void setTypeParameterList(@Nullable PsiTypeParameterList list) {
    myTypeParameterList = list;
    if (null == myTypeParameterList) {
      myTypeParameters = PsiTypeParameter.EMPTY_ARRAY;
    } else {
      myTypeParameters = myTypeParameterList.getTypeParameters();
    }
  }

  @Nullable
  @Override
  public PsiClass getContainingClass() {
    return myContainingClass;
  }

  public void setContainingClass(@Nullable PsiClass containingClass) {
    myContainingClass = containingClass;
  }

  @Override
  public PsiElement getScope() {
    if (myContainingClass != null) {
      return myContainingClass.getScope();
    }
    return super.getScope();
  }

  @Override
  public PsiElement getParent() {
    if (myContainingClass != null) {
      return myContainingClass.getParent();
    }
    return super.getParent();
  }

  @Override
  public Icon getElementIcon(final int flags) {
    return PsiClassImplUtil.getClassIcon(flags, this);
  }

  @Override
  public TextRange getTextRange() {
    TextRange r = super.getTextRange();
    return r == null ? TextRange.EMPTY_RANGE : r;
  }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import tempfile

import six
import tensorflow as tf
from tensorflow.python.framework import test_util
from tensorflow.python.ops import math_ops
from tensorflow_estimator.python.estimator import estimator_lib
from tensorflow_estimator.python.estimator.canned.timeseries import ar_model
from tensorflow_estimator.python.estimator.canned.timeseries import estimators
from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys
from tensorflow_estimator.python.estimator.canned.timeseries import saved_model_utils

class _SeedRunConfig(estimator_lib.RunConfig):

  @property
  def tf_random_seed(self):
    return 3

def _generate_data():
  time = tf.range(20, dtype=tf.dtypes.int64)
  data = tf.reshape(tf.range(20, dtype=tf.dtypes.float32), (20, 1))
  exogenous = data
  return time, data, exogenous

def _build_input_fn_with_seed(seed):

  def map_to_dict(time, data, exogenous):
    return {
        feature_keys.TrainEvalFeatures.TIMES: time,
        feature_keys.TrainEvalFeatures.VALUES: data,
        "exogenous": exogenous
    }

  def batch_windows(time, data, exogenous):
    return tf.compat.v1.data.Dataset.zip((time, data, exogenous)).batch(
        16, drop_remainder=True)

  def input_fn():
    dataset = tf.compat.v1.data.Dataset.from_tensor_slices(_generate_data())
    dataset = dataset.window(16, shift=1, drop_remainder=True)
    dataset = dataset.shuffle(1000, seed=seed).repeat()
    dataset = dataset.flat_map(batch_windows).batch(16).map(map_to_dict)
    return dataset

  return input_fn

@test_util.run_v1_only("Currently incompatible with ResourceVariable")
class TimeSeriesRegressorTest(tf.test.TestCase):

  def _fit_restore_fit_test_template(self, estimator_fn, test_saved_model):
    """Tests restoring previously fit models."""
    temp_dir = self.get_temp_dir()
    model_dir = tempfile.mkdtemp(dir=temp_dir)
    exogenous_feature_columns = (tf.feature_column.numeric_column("exogenous"),)
    first_estimator = estimator_fn(model_dir, exogenous_feature_columns)
    train_input_fn = _build_input_fn_with_seed(2)
    eval_input_fn = _build_input_fn_with_seed(3)
    first_estimator.train(input_fn=train_input_fn, steps=1)
    first_evaluation = first_estimator.evaluate(input_fn=eval_input_fn, steps=1)
    first_loss_before_fit = first_evaluation["loss"]
    self.assertAllEqual(first_loss_before_fit, first_evaluation["average_loss"])
    self.assertAllEqual([], first_loss_before_fit.shape)
    first_estimator.train(input_fn=train_input_fn, steps=1)
    first_loss_after_fit = first_estimator.evaluate(
        input_fn=eval_input_fn, steps=1)["loss"]
    self.assertAllEqual([], first_loss_after_fit.shape)
    second_estimator = estimator_fn(model_dir, exogenous_feature_columns)
    second_estimator.train(input_fn=train_input_fn, steps=1)
    second_evaluation = second_estimator.evaluate(
        input_fn=eval_input_fn, steps=1)
    exogenous_values_ten_steps = {
        "exogenous": tf.range(10, dtype=tf.dtypes.float32)[None, :, None]
    }
    input_receiver_fn = first_estimator.build_raw_serving_input_receiver_fn()
    export_location = first_estimator.export_saved_model(
        temp_dir, input_receiver_fn)
    if not test_saved_model:
      return
    with tf.Graph().as_default():
      with tf.compat.v1.Session() as sess:
        signatures = tf.compat.v1.saved_model.load(sess,
                                                   [tf.saved_model.SERVING],
                                                   export_location)
        # Test that prediction and filtering can continue from evaluation output
        _ = saved_model_utils.predict_continuation(
            continue_from=second_evaluation,
            steps=10,
            exogenous_features=exogenous_values_ten_steps,
            signatures=signatures,
            session=sess)
        times, values, _ = _generate_data()
        first_filtering = saved_model_utils.filter_continuation(
            continue_from=second_evaluation,
            features={
                feature_keys.FilteringFeatures.TIMES: times[None, -1] + 2,
                feature_keys.FilteringFeatures.VALUES: values[None, -1] + 2.,
                "exogenous": values[None, -1, None] + 12.
            },
            signatures=signatures,
            session=sess)
        # Test that prediction and filtering can continue from filtering output
        second_saved_prediction = saved_model_utils.predict_continuation(
            continue_from=first_filtering,
            steps=1,
            exogenous_features={
                "exogenous": tf.range(1, dtype=tf.dtypes.float32)[None, :, None]
            },
            signatures=signatures,
            session=sess)
        self.assertEqual(
            times[-1] + 3,
            tf.compat.v1.squeeze(
                second_saved_prediction[feature_keys.PredictionResults.TIMES]))
        saved_model_utils.filter_continuation(
            continue_from=first_filtering,
            features={
                feature_keys.FilteringFeatures.TIMES: times[-1] + 3,
                feature_keys.FilteringFeatures.VALUES: values[-1] + 3.,
                "exogenous": values[-1, None] + 13.
            },
            signatures=signatures,
            session=sess)

        # Test cold starting
        six.assertCountEqual(
            self, [
                feature_keys.FilteringFeatures.TIMES,
                feature_keys.FilteringFeatures.VALUES, "exogenous"
            ], signatures.signature_def[
                feature_keys.SavedModelLabels.COLD_START_FILTER].inputs.keys())
        batched_times = tf.tile(
            tf.range(30, dtype=tf.dtypes.int64)[None, :], (10, 1))
        batched_values = tf.ones([10, 30, 1])
        state = saved_model_utils.cold_start_filter(
            signatures=signatures,
            session=sess,
            features={
                feature_keys.FilteringFeatures.TIMES: batched_times,
                feature_keys.FilteringFeatures.VALUES: batched_values,
                "exogenous": 10. + batched_values
            })
        predict_times = math_ops.tile(
            tf.range(30, 45, dtype=tf.dtypes.int64)[None, :], (10, 1))
        predictions = saved_model_utils.predict_continuation(
            continue_from=state,
            times=predict_times,
            exogenous_features={
                "exogenous":
                    math_ops.tile(tf.range(15, dtype=tf.dtypes.float32), (10,))
                    [None, :, None]
            },
            signatures=signatures,
            session=sess)
        self.assertAllEqual([10, 15, 1], predictions["mean"].shape)

  def disabled_test_time_series_regressor(self):

    def _estimator_fn(model_dir, exogenous_feature_columns):
      return estimators.TimeSeriesRegressor(
          model=ar_model.ARModel(
              periodicities=10,
              input_window_size=10,
              output_window_size=6,
              num_features=1,
              exogenous_feature_columns=exogenous_feature_columns,
              prediction_model_factory=functools.partial(
                  ar_model.LSTMPredictionModel, num_units=10)),
          config=_SeedRunConfig(),
          model_dir=model_dir)

    self._fit_restore_fit_test_template(_estimator_fn, test_saved_model=True)

  def test_ar_lstm_regressor(self):

    def _estimator_fn(model_dir, exogenous_feature_columns):
      return estimators.LSTMAutoRegressor(
          periodicities=10,
          input_window_size=10,
          output_window_size=6,
          model_dir=model_dir,
          num_features=1,
          extra_feature_columns=exogenous_feature_columns,
          num_units=10,
          config=_SeedRunConfig())

    # LSTMAutoRegressor uses OneShotPredictionHead which does not work with
    # saved models.
    self._fit_restore_fit_test_template(_estimator_fn, test_saved_model=False)

if __name__ == "__main__":
  tf.test.main()


text:
layout: post
date: 2017-12-06
title: "Stella York Princess Wedding Dresses
 Style 5859 Sleeveless Court Train Ballgown"
category: Stella York
tags: [Stella York,Ballgown,Sweetheart,Court Train,Sleeveless]
---
### Stella York Princess Wedding Dresses
 Style 5859
Just **$349.99**
###   Sleeveless Court Train Ballgown

BRANDS	Stella York

Silhouette	Ballgown

Neckline	Sweetheart

Hemline/Train	Court Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/stella-york/13532-stella-york-princess-wedding-dresses-style-5859.html](https://www.readybrides.com/en/stella-york/13532-stella-york-princess-wedding-dresses-style-5859.html)


text:
Core.Object.extend('Ui.Event', {
	type: undefined,
	bubbles: true,
	cancelable: true,
	target: undefined,
	cancelBubble: false,
	stop: false,

	constructor: function(config) {
	},

	stopPropagation: function() {
		this.cancelBubble = true;
	},

	stopImmediatePropagation: function() {
		this.stop = true;
	},

	getIsPropagationStopped: function() {
		return this.stop || this.cancelBubble;
	},

	setType: function(type) {
		this.type = type;
	},

	setBubbles: function(bubbles) {
		this.bubbles = bubbles;
	},

	dispatchEvent: function(target) {
		var i; var i2; var list;
		this.target = target;

		if(this.bubbles) {
			var stack = [];

			var current = this.target;
			while((current !== undefined) && (current !== null)) {
				stack.push(current);
				current = current.parent;
			}

			// mode capture
			for(i = stack.length - 1; (i >= 0) && (!this.cancelBubble) && (!this.stop); i--) {
				current = stack[i];
				var handlers = current.getEventHandlers(this.type);
				for(var i2 = 0; (i2 < handlers.length) && (!this.stop); i2++) {
					var handler = handlers[i2];
					if(handler.capture)
						handler.method.apply(handler.scope, [this]);
				}
			}

			// bubble mode
			for(i = 0; (i < stack.length) && (!this.cancelBubble) && (!this.stop); i++) {
				current = stack[i];
				var handlers = current.getEventHandlers(this.type);
				for(var i2 = 0; (i2 < handlers.length) && (!this.stop); i2++) {
					var handler = handlers[i2];
					if(!handler.capture)
						handler.method.apply(handler.scope, [this]);
				}
			}
		}
		else {
			// capture before
			var handlers = this.target.getEventHandlers(this.type);
			for(var i2 = 0; (i2 < handlers.length) && (!this.stop); i2++) {
				var handler = handlers[i2];
				if(handler.capture)
					handler.method.apply(handler.scope, [this]);
			}

			// normal mode
			for(var i2 = 0; (i2 < handlers.length) && (!this.stop); i2++) {
				var handler = handlers[i2];
				if(!handler.capture)
					handler.method.apply(handler.scope, [this]);
			}
		}
	}
});


text:
var FastMap = /*@__PURE__*/ (/*@__PURE__*/ function () {
    function FastMap() {
        this.values = {};
    }
    FastMap.prototype.delete = function (key) {
        this.values[key] = null;
        return true;
    };
    FastMap.prototype.set = function (key, value) {
        this.values[key] = value;
        return this;
    };
    FastMap.prototype.get = function (key) {
        return this.values[key];
    };
    FastMap.prototype.forEach = function (cb, thisArg) {
        var values = this.values;
        for (var key in values) {
            if (values.hasOwnProperty(key) && values[key] !== null) {
                cb.call(thisArg, values[key], key);
            }
        }
    };
    FastMap.prototype.clear = function () {
        this.values = {};
    };
    return FastMap;
}());
export { FastMap };
//# sourceMappingURL=FastMap.js.map


text:
package eu.socialsensor.documentpivot.utils;

import eu.socialsensor.documentpivot.LSH.HashTables;
import eu.socialsensor.documentpivot.model.VectorSpace;
import eu.socialsensor.documentpivot.model.Vocabulary;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.StallWarning;

public class LSHListener implements StatusListener {

	int c = 0;
	private Vocabulary vocabulary;
	private HashTables hashTables;

	public LSHListener(Vocabulary vocabulary, HashTables hashTable) {
		this.vocabulary = vocabulary;
		this.hashTables = hashTables;
	}
	@Override
	public void onStatus(Status status) {
		c++;
		VectorSpace vsm = new VectorSpace(Long.toString(status.getId()), status.getText());
		vocabulary.update(vsm.tokens());
		hashTables.add(vsm);

		if(c>10000) {
			VectorSpace[] nn = hashTables.get(vsm);
			System.out.println(nn.length);
		}
    }

	@Override
    public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
	@Override
	public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
    @Override
	public void onScrubGeo(long arg0, long arg1) {
	}
    @Override
    public void onException(Exception ex) {
        ex.printStackTrace();
    }

    @Override
    public void onStallWarning(StallWarning sw) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


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

<TITLE>
mlflex.evaluation Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2012-02-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Tree
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package mlflex.evaluation

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

mlflex.evaluation.ClassificationResultsFilePaths
mlflex.evaluation.ClassificationResultsSaver
weka.classifiers.Evaluation (implements weka.core.RevisionHandler, weka.core.Summarizable)

mlflex.evaluation.CustomWekaEvaluation

mlflex.evaluation.FeatureSelectionResultsSaver
mlflex.evaluation.HtmlReportGenerator
mlflex.evaluation.PredictionResults

mlflex.evaluation.DefaultInnerPredictionResults

      Overview
      Package
      Class
    Tree
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Thyridaria aurata Rehm, 1912

### Remarks
null


text:
package saltchannel.dev;

import java.util.ArrayList;
import java.util.List;
import saltchannel.ByteChannel;
import saltchannel.ComException;
import saltchannel.util.Hex;

/**
 * Decorator for ByteChannel, stores read and written packages.
 */
public class LoggingByteChannel implements ByteChannel {
    private ByteChannel inner;
    private ArrayList<LoggingByteChannel.Entry> log;

    public LoggingByteChannel(ByteChannel channel) {
        this.log = new ArrayList<LoggingByteChannel.Entry>();
        this.inner = channel;
    }

    public List<LoggingByteChannel.Entry> getLog() {
        return log;
    }

    public static enum ReadOrWrite {
        READ, WRITE, WRITE_WITH_PREVIOUS
    }

    public static class Entry {
        /** Time in nanos (from System.nanoTime()). */
        public long time;

        public LoggingByteChannel.ReadOrWrite type;

        public boolean isLast;

        public byte[] bytes;

        public String toString() {
            StringBuilder b = new StringBuilder();
            b.append(type.name() + ", " + time + "\n");
            b.append("    " + bytes.length + ", " + Hex.create(bytes));
            return b.toString();
        }
    }

    @Override
    public byte[] read() throws ComException {
        byte[] result = inner.read();

        LoggingByteChannel.Entry entry = new Entry();
        entry.time = System.nanoTime();
        entry.type = ReadOrWrite.READ;
        entry.bytes = result;
        log.add(entry);

        return result;
    }

    @Override
    public void write(byte[]... messages) throws ComException {
        write(false, messages);
    }

    @Override
    public void write(boolean isLast, byte[]... messages) throws ComException {
        inner.write(isLast, messages);

        long time = System.nanoTime();

        for (int i = 0; i < messages.length; i++) {
            LoggingByteChannel.Entry entry = new Entry();
            entry.time = time;
            entry.type = i == 0 ? ReadOrWrite.WRITE : ReadOrWrite.WRITE_WITH_PREVIOUS;
            entry.bytes = messages[i];
            entry.isLast = i == messages.length - 1 ? isLast : false;
            log.add(entry);
        }
    }
}


text:
// A path exclusive reservation system
// reserve([list, of, paths], fn)
// When the fn is first in line for all its paths, it
// is called with a cb that clears the reservation.
//
// Used by async unpack to avoid clobbering paths in use,
// while still allowing maximal safe parallelization.

const assert = require('assert')
const normalize = require('./normalize-unicode.js')
const stripSlashes = require('./strip-trailing-slashes.js')
const { join } = require('path')

const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform
const isWindows = platform === 'win32'

module.exports = () => {
  // path => [function or Set]
  // A Set object means a directory reservation
  // A fn is a direct reservation on that path
  const queues = new Map()

  // fn => {paths:[path,...], dirs:[path, ...]}
  const reservations = new Map()

  // return a set of parent dirs for a given path
  // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d']
  const getDirs = path => {
    const dirs = path.split('/').slice(0, -1).reduce((set, path) => {
      if (set.length)
        path = join(set[set.length - 1], path)
      set.push(path || '/')
      return set
    }, [])
    return dirs
  }

  // functions currently running
  const running = new Set()

  // return the queues for each path the function cares about
  // fn => {paths, dirs}
  const getQueues = fn => {
    const res = reservations.get(fn)
    /* istanbul ignore if - unpossible */
    if (!res)
      throw new Error('function does not have any path reservations')
    return {
      paths: res.paths.map(path => queues.get(path)),
      dirs: [...res.dirs].map(path => queues.get(path)),
    }
  }

  // check if fn is first in line for all its paths, and is
  // included in the first set for all its dir queues
  const check = fn => {
    const {paths, dirs} = getQueues(fn)
    return paths.every(q => q[0] === fn) &&
      dirs.every(q => q[0] instanceof Set && q[0].has(fn))
  }

  // run the function if it's first in line and not already running
  const run = fn => {
    if (running.has(fn) || !check(fn))
      return false
    running.add(fn)
    fn(() => clear(fn))
    return true
  }

  const clear = fn => {
    if (!running.has(fn))
      return false

    const { paths, dirs } = reservations.get(fn)
    const next = new Set()

    paths.forEach(path => {
      const q = queues.get(path)
      assert.equal(q[0], fn)
      if (q.length === 1)
        queues.delete(path)
      else {
        q.shift()
        if (typeof q[0] === 'function')
          next.add(q[0])
        else
          q[0].forEach(fn => next.add(fn))
      }
    })

    dirs.forEach(dir => {
      const q = queues.get(dir)
      assert(q[0] instanceof Set)
      if (q[0].size === 1 && q.length === 1)
        queues.delete(dir)
      else if (q[0].size === 1) {
        q.shift()

        // must be a function or else the Set would've been reused
        next.add(q[0])
      } else
        q[0].delete(fn)
    })
    running.delete(fn)

    next.forEach(fn => run(fn))
    return true
  }

  const reserve = (paths, fn) => {
    // collide on matches across case and unicode normalization
    // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally
    // impossible to determine whether two paths refer to the same thing on
    // disk, without asking the kernel for a shortname.
    // So, we just pretend that every path matches every other path here,
    // effectively removing all parallelization on windows.
    paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => {
      // don't need normPath, because we skip this entirely for windows
      return normalize(stripSlashes(join(p))).toLowerCase()
    })

    const dirs = new Set(
      paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b))
    )
    reservations.set(fn, {dirs, paths})
    paths.forEach(path => {
      const q = queues.get(path)
      if (!q)
        queues.set(path, [fn])
      else
        q.push(fn)
    })
    dirs.forEach(dir => {
      const q = queues.get(dir)
      if (!q)
        queues.set(dir, [new Set([fn])])
      else if (q[q.length - 1] instanceof Set)
        q[q.length - 1].add(fn)
      else
        q.push(new Set([fn]))
    })

    return run(fn)
  }

  return { check, reserve }
}


text:
"""empty message

Revision ID: c25189ab2b31
Revises: d9e98cba5844
Create Date: 2016-01-14 20:30:10.723983

"""

# revision identifiers, used by Alembic.
revision = 'c25189ab2b31'
down_revision = 'd9e98cba5844'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('idols', sa.Column('prev_rank', sa.Integer(), server_default=u'0', nullable=False))
    op.add_column('idols', sa.Column('prev_vote_percentage', sa.Float(), server_default=u'0.0', nullable=False))
    op.add_column('idols', sa.Column('rank', sa.Integer(), server_default=u'0', nullable=False))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('idols', 'rank')
    op.drop_column('idols', 'prev_vote_percentage')
    op.drop_column('idols', 'prev_rank')
    ### end Alembic commands ###


text:
#------------------------------------------------------------------------------

require 'pdq'

#---- Define globals ----------------------------------------------------------

arrivRate    = 0.75
service_time = 1.0

#---- Initialize --------------------------------------------------------------

Pdq.Init("OpenCenter")
Pdq.SetComment("A simple M/M/1 queue")

#---- Define the workload and circuit type ------------------------------------

Pdq.streams = Pdq.CreateOpen("work", arrivRate)

Pdq.SetWUnit("Customers")
Pdq.SetTUnit("Seconds")

#---- Define the queueing center ----------------------------------------------

Pdq.nodes = Pdq.CreateNode("server", Pdq::CEN, Pdq::FCFS)
# Pdq.nodes = Pdq.CreateNode("server", 4, 8)

#---- Define service demand due to workload on the queueing center ------------

Pdq.SetDemand("server", "work", service_time)

#---- Solve the model ---------------------------------------------------------
#  Must use the CANONical method for an open circuit

Pdq.Solve(Pdq::CANON)

#---- Generate a report -------------------------------------------------------

Pdq.Report()

#------------------------------------------------------------------------------

comment = Pdq.GetComment()

puts 'Pdq.GetComment -> "%s"' % comment

#------------------------------------------------------------------------------


text:
nagios-mail_flow
================

Mail Flow Checker: A set of scripts to perform monitoring of a complete mail flow

See http://troels.arvin.dk/code/nagios/mail_flow/ for more on this.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gameshop.advance.model.transazione;

import gameshop.advance.exceptions.InvalidMoneyException;
import gameshop.advance.interfaces.ITransazione;
import gameshop.advance.interfaces.remote.sales.IRigaDiTransazioneRemote;
import gameshop.advance.interfaces.remote.sales.ITransazioneRemote;
import gameshop.advance.interfaces.remote.utility.IIteratorWrapperRemote;
import gameshop.advance.utility.IteratorWrapper;
import gameshop.advance.utility.Money;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.LinkedList;

/** Proxy di protezione della transazione
 *
 * @author Lorenzo Di Giuseppe <lorenzo.digiuseppe88@gmail.com>
 */
public class TransazioneRemoteProxy extends UnicastRemoteObject implements ITransazioneRemote {

    private final ITransazione protectedRemoteTransaction;

    public TransazioneRemoteProxy(ITransazione trans) throws RemoteException
    {
        this.protectedRemoteTransaction = trans;
    }

    @Override
    public Money getResto() throws InvalidMoneyException, RemoteException {
        return this.protectedRemoteTransaction.getResto();
    }

    @Override
    public Money getTotal() throws RemoteException {
        return this.protectedRemoteTransaction.getTotal();
    }

    @Override
    public Integer getId() throws RemoteException {
        return this.protectedRemoteTransaction.getId();
    }
    /**
     *
     * @return Le righe di vendita wrappate
     * @throws java.rmi.RemoteException
     */
    @Override
    public IIteratorWrapperRemote<IRigaDiTransazioneRemote> getRigheDiVendita() throws RemoteException {
        IIteratorWrapperRemote<IRigaDiTransazioneRemote> righeDiVendita = this.protectedRemoteTransaction.getRigheDiVendita();
        LinkedList<IRigaDiTransazioneRemote> righeProtette = new LinkedList<>();
        while(righeDiVendita.hasNext())
        {
            righeProtette.add(new RigaDiTransazioneRemoteProxy(righeDiVendita.next()));
        }

        return new IteratorWrapper<>(righeProtette.iterator());
    }

}


text:
<!DOCTYPE html>

{% load staticfiles %}
<title>Worldli</title>

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/index.css">
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/post.css">
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/textbox.css">
{% block header_file %}
{% endblock %}

{% block style%}
{% endblock %}

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Worldli

      {% block nav %}
      {% endblock %}
      {% if user and not user.is_anonymous %}

Hello {{ user.get_short_name }}

My Profile

My Posts

Logout

      {% endif %}

{% block script %}
{% endblock %}

{% block content %}
{% endblock %}


text:
"""
Generic data algorithms. This module is experimental at the moment and not
intended for public consumption
"""
from __future__ import division
from warnings import warn
import numpy as np

import pandas.core.common as com
import pandas.algos as algos
import pandas.hashtable as htable
from pandas.compat import string_types

def match(to_match, values, na_sentinel=-1):
    """
    Compute locations of to_match into values

    Parameters
    ----------
    to_match : array-like
        values to find positions of
    values : array-like
        Unique set of values
    na_sentinel : int, default -1
        Value to mark "not found"

    Examples
    --------

    Returns
    -------
    match : ndarray of integers
    """
    values = com._asarray_tuplesafe(values)
    if issubclass(values.dtype.type, string_types):
        values = np.array(values, dtype='O')

    f = lambda htype, caster: _match_generic(to_match, values, htype, caster)
    result = _hashtable_algo(f, values.dtype)

    if na_sentinel != -1:

        # replace but return a numpy array
        # use a Series because it handles dtype conversions properly
        from pandas.core.series import Series
        result = Series(result.ravel()).replace(-1,na_sentinel).values.reshape(result.shape)

    return result

def unique(values):
    """
    Compute unique values (not necessarily sorted) efficiently from input array
    of values

    Parameters
    ----------
    values : array-like

    Returns
    -------
    uniques
    """
    values = com._asarray_tuplesafe(values)
    f = lambda htype, caster: _unique_generic(values, htype, caster)
    return _hashtable_algo(f, values.dtype)

def _hashtable_algo(f, dtype):
    """
    f(HashTable, type_caster) -> result
    """
    if com.is_float_dtype(dtype):
        return f(htable.Float64HashTable, com._ensure_float64)
    elif com.is_integer_dtype(dtype):
        return f(htable.Int64HashTable, com._ensure_int64)
    else:
        return f(htable.PyObjectHashTable, com._ensure_object)

def _match_generic(values, index, table_type, type_caster):
    values = type_caster(values)
    index = type_caster(index)
    table = table_type(min(len(index), 1000000))
    table.map_locations(index)
    return table.lookup(values)

def _unique_generic(values, table_type, type_caster):
    values = type_caster(values)
    table = table_type(min(len(values), 1000000))
    uniques = table.unique(values)
    return type_caster(uniques)

def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None):
    """
    Encode input values as an enumerated type or categorical variable

    Parameters
    ----------
    values : ndarray (1-d)
        Sequence
    sort : boolean, default False
        Sort by values
    order : deprecated
    na_sentinel : int, default -1
        Value to mark "not found"
    size_hint : hint to the hashtable sizer

    Returns
    -------
    labels : the indexer to the original array
    uniques : ndarray (1-d) or Index
        the unique values. Index is returned when passed values is Index or Series

    note: an array of Periods will ignore sort as it returns an always sorted PeriodIndex
    """
    if order is not None:
        warn("order is deprecated."
             "See https://github.com/pydata/pandas/issues/6926", FutureWarning)

    from pandas.core.index import Index
    from pandas.core.series import Series
    vals = np.asarray(values)

    is_datetime = com.is_datetime64_dtype(vals)
    is_timedelta = com.is_timedelta64_dtype(vals)
    (hash_klass, vec_klass), vals = _get_data_algo(vals, _hashtables)

    table = hash_klass(size_hint or len(vals))
    uniques = vec_klass()
    labels = table.get_labels(vals, uniques, 0, na_sentinel)

    labels = com._ensure_platform_int(labels)

    uniques = uniques.to_array()

    if sort and len(uniques) > 0:
        try:
            sorter = uniques.argsort()
        except:
            # unorderable in py3 if mixed str/int
            t = hash_klass(len(uniques))
            t.map_locations(com._ensure_object(uniques))

            # order ints before strings
            ordered = np.concatenate([
                np.sort(np.array([ e for i, e in enumerate(uniques) if f(e) ],dtype=object)) for f in [ lambda x: not isinstance(x,string_types),
                                                                                lambda x: isinstance(x,string_types) ]
                ])
            sorter = com._ensure_platform_int(t.lookup(com._ensure_object(ordered)))

        reverse_indexer = np.empty(len(sorter), dtype=np.int_)
        reverse_indexer.put(sorter, np.arange(len(sorter)))

        mask = labels < 0
        labels = reverse_indexer.take(labels)
        np.putmask(labels, mask, -1)

        uniques = uniques.take(sorter)

    if is_datetime:
        uniques = uniques.astype('M8[ns]')
    elif is_timedelta:
        uniques = uniques.astype('m8[ns]')
    if isinstance(values, Index):
        uniques = values._shallow_copy(uniques, name=None)
    elif isinstance(values, Series):
        uniques = Index(uniques)
    return labels, uniques

def value_counts(values, sort=True, ascending=False, normalize=False,
                 bins=None, dropna=True):
    """
    Compute a histogram of the counts of non-null values.

    Parameters
    ----------
    values : ndarray (1-d)
    sort : boolean, default True
        Sort by values
    ascending : boolean, default False
        Sort in ascending order
    normalize: boolean, default False
        If True then compute a relative histogram
    bins : integer, optional
        Rather than count values, group them into half-open bins,
        convenience for pd.cut, only works with numeric data
    dropna : boolean, default True
        Don't include counts of NaN

    Returns
    -------
    value_counts : Series

    """
    from pandas.core.series import Series
    from pandas.tools.tile import cut
    from pandas.tseries.period import PeriodIndex

    values = Series(values).values

    if bins is not None:
        try:
            cat, bins = cut(values, bins, retbins=True)
        except TypeError:
            raise TypeError("bins argument only works with numeric data.")
        values = cat.codes

    if com.is_categorical_dtype(values.dtype):
        result = values.value_counts(dropna)

    else:

        dtype = values.dtype
        is_period = com.is_period_arraylike(values)

        if com.is_datetime_or_timedelta_dtype(dtype) or is_period:

            if is_period:
                values = PeriodIndex(values)

            values = values.view(np.int64)
            keys, counts = htable.value_count_int64(values)

            if dropna:
                from pandas.tslib import iNaT
                msk = keys != iNaT
                keys, counts = keys[msk], counts[msk]

            # convert the keys back to the dtype we came in
            keys = keys.astype(dtype)

        elif com.is_integer_dtype(dtype):
            values = com._ensure_int64(values)
            keys, counts = htable.value_count_int64(values)

        else:
            values = com._ensure_object(values)
            mask = com.isnull(values)
            keys, counts = htable.value_count_object(values, mask)
            if not dropna and mask.any():
                keys = np.insert(keys, 0, np.NaN)
                counts = np.insert(counts, 0, mask.sum())

        result = Series(counts, index=com._values_from_object(keys))

        if bins is not None:
            # TODO: This next line should be more efficient
            result = result.reindex(np.arange(len(cat.categories)), fill_value=0)
            result.index = bins[:-1]

    if sort:
        result.sort()
        if not ascending:
            result = result[::-1]

    if normalize:
        result = result / float(values.size)

    return result

def mode(values):
    """Returns the mode or mode(s) of the passed Series or ndarray (sorted)"""
    # must sort because hash order isn't necessarily defined.
    from pandas.core.series import Series

    if isinstance(values, Series):
        constructor = values._constructor
        values = values.values
    else:
        values = np.asanyarray(values)
        constructor = Series

    dtype = values.dtype
    if com.is_integer_dtype(values):
        values = com._ensure_int64(values)
        result = constructor(sorted(htable.mode_int64(values)), dtype=dtype)

    elif issubclass(values.dtype.type, (np.datetime64, np.timedelta64)):
        dtype = values.dtype
        values = values.view(np.int64)
        result = constructor(sorted(htable.mode_int64(values)), dtype=dtype)

    elif com.is_categorical_dtype(values):
        result = constructor(values.mode())
    else:
        mask = com.isnull(values)
        values = com._ensure_object(values)
        res = htable.mode_object(values, mask)
        try:
            res = sorted(res)
        except TypeError as e:
            warn("Unable to sort modes: %s" % e)
        result = constructor(res, dtype=dtype)

    return result

def rank(values, axis=0, method='average', na_option='keep',
         ascending=True, pct=False):
    """

    """
    if values.ndim == 1:
        f, values = _get_data_algo(values, _rank1d_functions)
        ranks = f(values, ties_method=method, ascending=ascending,
                  na_option=na_option, pct=pct)
    elif values.ndim == 2:
        f, values = _get_data_algo(values, _rank2d_functions)
        ranks = f(values, axis=axis, ties_method=method,
                  ascending=ascending, na_option=na_option, pct=pct)

    return ranks

def quantile(x, q, interpolation_method='fraction'):
    """
    Compute sample quantile or quantiles of the input array. For example, q=0.5
    computes the median.

    The `interpolation_method` parameter supports three values, namely
    `fraction` (default), `lower` and `higher`. Interpolation is done only,
    if the desired quantile lies between two data points `i` and `j`. For
    `fraction`, the result is an interpolated value between `i` and `j`;
    for `lower`, the result is `i`, for `higher` the result is `j`.

    Parameters
    ----------
    x : ndarray
        Values from which to extract score.
    q : scalar or array
        Percentile at which to extract score.
    interpolation_method : {'fraction', 'lower', 'higher'}, optional
        This optional parameter specifies the interpolation method to use,
        when the desired quantile lies between two data points `i` and `j`:

        - fraction: `i + (j - i)*fraction`, where `fraction` is the
                    fractional part of the index surrounded by `i` and `j`.
        -lower: `i`.
        - higher: `j`.

    Returns
    -------
    score : float
        Score at percentile.

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.arange(100)
    >>> stats.scoreatpercentile(a, 50)
    49.5

    """
    x = np.asarray(x)
    mask = com.isnull(x)

    x = x[~mask]

    values = np.sort(x)

    def _get_score(at):
        if len(values) == 0:
            return np.nan

        idx = at * (len(values) - 1)
        if idx % 1 == 0:
            score = values[int(idx)]
        else:
            if interpolation_method == 'fraction':
                score = _interpolate(values[int(idx)], values[int(idx) + 1],
                                     idx % 1)
            elif interpolation_method == 'lower':
                score = values[np.floor(idx)]
            elif interpolation_method == 'higher':
                score = values[np.ceil(idx)]
            else:
                raise ValueError("interpolation_method can only be 'fraction' "
                                 ", 'lower' or 'higher'")

        return score

    if np.isscalar(q):
        return _get_score(q)
    else:
        q = np.asarray(q, np.float64)
        return algos.arrmap_float64(q, _get_score)

def _interpolate(a, b, fraction):
    """Returns the point at the given fraction between a and b, where
    'fraction' must be between 0 and 1.
    """
    return a + (b - a) * fraction

def _get_data_algo(values, func_map):
    mask = None
    if com.is_float_dtype(values):
        f = func_map['float64']
        values = com._ensure_float64(values)

    elif com.needs_i8_conversion(values):

        # if we have NaT, punt to object dtype
        mask = com.isnull(values)
        if mask.ravel().any():
            f = func_map['generic']
            values = com._ensure_object(values)
            values[mask] = np.nan
        else:
            f = func_map['int64']
            values = values.view('i8')

    elif com.is_integer_dtype(values):
        f = func_map['int64']
        values = com._ensure_int64(values)
    else:
        f = func_map['generic']
        values = com._ensure_object(values)
    return f, values

def group_position(*args):
    """
    Get group position
    """
    from collections import defaultdict
    table = defaultdict(int)

    result = []
    for tup in zip(*args):
        result.append(table[tup])
        table[tup] += 1

    return result

_dtype_map = {'datetime64[ns]': 'int64', 'timedelta64[ns]': 'int64'}

def _finalize_nsmallest(arr, kth_val, n, take_last, narr):
    ns, = np.nonzero(arr <= kth_val)
    inds = ns[arr[ns].argsort(kind='mergesort')][:n]

    if take_last:
        # reverse indices
        return narr - 1 - inds
    return inds

def nsmallest(arr, n, take_last=False):
    '''
    Find the indices of the n smallest values of a numpy array.

    Note: Fails silently with NaN.

    '''
    if take_last:
        arr = arr[::-1]

    narr = len(arr)
    n = min(n, narr)

    sdtype = str(arr.dtype)
    arr = arr.view(_dtype_map.get(sdtype, sdtype))

    kth_val = algos.kth_smallest(arr.copy(), n - 1)
    return _finalize_nsmallest(arr, kth_val, n, take_last, narr)

def nlargest(arr, n, take_last=False):
    """
    Find the indices of the n largest values of a numpy array.

    Note: Fails silently with NaN.
    """
    sdtype = str(arr.dtype)
    arr = arr.view(_dtype_map.get(sdtype, sdtype))
    return nsmallest(-arr, n, take_last=take_last)

def select_n_slow(dropped, n, take_last, method):
    reverse_it = take_last or method == 'nlargest'
    ascending = method == 'nsmallest'
    slc = np.s_[::-1] if reverse_it else np.s_[:]
    return dropped[slc].order(ascending=ascending).head(n)

_select_methods = {'nsmallest': nsmallest, 'nlargest': nlargest}

def select_n(series, n, take_last, method):
    """Implement n largest/smallest.

    Parameters
    ----------
    n : int
    take_last : bool
    method : str, {'nlargest', 'nsmallest'}

    Returns
    -------
    nordered : Series
    """
    dtype = series.dtype
    if not issubclass(dtype.type, (np.integer, np.floating, np.datetime64,
                                   np.timedelta64)):
        raise TypeError("Cannot use method %r with dtype %s" % (method, dtype))

    if n <= 0:
        return series[[]]

    dropped = series.dropna()

    if n >= len(series):
        return select_n_slow(dropped, n, take_last, method)

    inds = _select_methods[method](dropped.values, n, take_last)
    return dropped.iloc[inds]

_rank1d_functions = {
    'float64': algos.rank_1d_float64,
    'int64': algos.rank_1d_int64,
    'generic': algos.rank_1d_generic
}

_rank2d_functions = {
    'float64': algos.rank_2d_float64,
    'int64': algos.rank_2d_int64,
    'generic': algos.rank_2d_generic
}

_hashtables = {
    'float64': (htable.Float64HashTable, htable.Float64Vector),
    'int64': (htable.Int64HashTable, htable.Int64Vector),
    'generic': (htable.PyObjectHashTable, htable.ObjectVector)
}


text:
#ifndef RANDOM_WITH_REPLACEMENT_SELECTION_H
#define RANDOM_WITH_REPLACEMENT_SELECTION_H

#include "Selection.h"

#ifdef seed
#undef seed
#endif

#include <boost/random/mersenne_twister.hpp>

BEGIN_NAMESPACE_MW

typedef	boost::mt19937	random_generator;

class RandomWithReplacementSelection : public Selection {

protected:

	random_generator rng;

public:
	RandomWithReplacementSelection(int _n_draws, bool _autoreset = false);

	virtual ~RandomWithReplacementSelection();
	virtual shared_ptr<Selection> clone();

	virtual int draw();
	virtual void reset(){  Selection::reset(); }

	virtual void rejectSelections();
};

END_NAMESPACE_MW

#endif


text:
package jenkins.model;

import hudson.Extension;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import net.sf.json.JSONObject;

import org.kohsuke.stapler.StaplerRequest;

/**
 * Configures the project naming strategy.
 *
 * @author Dominik Bartholdi (imod)
 */
@Extension(ordinal = 250)
public class GlobalProjectNamingStrategyConfiguration extends GlobalConfiguration {

    @Override
    public boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException {
        // for compatibility reasons, the actual value is stored in Jenkins
        Jenkins j = Jenkins.getInstance();
        final JSONObject optJSONObject = json.optJSONObject("useProjectNamingStrategy");
        if (optJSONObject != null) {
            final JSONObject strategyObject = optJSONObject.getJSONObject("namingStrategy");
            final String className = strategyObject.getString("stapler-class");
            try {
                Class clazz = Class.forName(className);
                final ProjectNamingStrategy strategy = (ProjectNamingStrategy) req.bindJSON(clazz, strategyObject);
                j.setProjectNamingStrategy(strategy);
            } catch (ClassNotFoundException e) {
                throw new FormException(e, "namingStrategy");
            }
        }
        if (j.getProjectNamingStrategy() == null) {
            j.setProjectNamingStrategy(DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY);
        }
        return true;
    }
}


text:
from msrest.paging import Paged

class EndpointServiceResultPaged(Paged):
    """
    A paging container for iterating over a list of :class:`EndpointServiceResult <azure.mgmt.network.v2017_11_01.models.EndpointServiceResult>` object
    """

    _attribute_map = {
        'next_link': {'key': 'nextLink', 'type': 'str'},
        'current_page': {'key': 'value', 'type': '[EndpointServiceResult]'}
    }

    def __init__(self, *args, **kwargs):

        super(EndpointServiceResultPaged, self).__init__(*args, **kwargs)


text:
var loadScript = require("./loadScript");
var consts = require("./constants");
var fhparams = require("./fhparams");
var ajax = require("./ajax");
var handleError = require("./handleError");
var logger = require("./logger");
var hashFunc = require("./security/hash");
var appProps = require("./appProps");
var constants = require("./constants");
var events = require("./events");
var data = require('./data');

var init = function(cb) {
  appProps.load(function(err, data) {
    if (err) {
      return cb(err);
    }
    // Emit internal config loaded event - SDK will now set appprops
    events.emit(constants.INTERNAL_CONFIG_LOADED_EVENT, null, data);
    return loadCloudProps(data, cb);
  });
};

var loadCloudProps = function(app_props, callback) {
  if (app_props.loglevel) {
    logger.setLevel(app_props.loglevel);
  }
  // If local - shortcircuit the init - just return the host
  if (app_props.local) {
    var res = {
      "domain": "local",
      "firstTime": false,
      "hosts": {
        "debugCloudType": "node",
        "debugCloudUrl": app_props.host,
        "releaseCloudType": "node",
        "releaseCloudUrl": app_props.host,
        "type": "cloud_nodejs",
        "url": app_props.host
      },
      "init": {
        "trackId": "000000000000000000000000"
      },
      "status": "ok"
    };

    return callback(null, {
      cloud: res
    });
  }

  //now we have app props, add the fileStorageAdapter
  data.addFileStorageAdapter(app_props, hashFunc);
  var doInit = function(path, appProps, savedHost, storage) {
    var data = fhparams.buildFHParams();

    ajax({
      "url": path,
      "type": "POST",
      "tryJSONP": true,
      "dataType": "json",
      "contentType": "application/json",
      "data": JSON.stringify(data),
      "timeout": appProps.timeout,
      "success": function(initRes) {
        if (storage) {
          storage.save({
            key: "fh_init",
            value: initRes
          }, function() {});
        }
        if (callback) {
          callback(null, {
            cloud: initRes
          });
        }
      },
      "error": function(req, statusText, error) {
        var errormsg = "unknown";
        if (req) {
          errormsg = req.status + " - " + req.responseText;
        }
        logger.error("App init returned error : " + errormsg);
        //use the cached host if we have a copy
        if (savedHost) {
          logger.info("Using cached host: " + JSON.stringify(savedHost));
          if (callback) {
            callback(null, {
              cloud: savedHost
            });
          }
        } else {
          logger.error("No cached host found. Init failed.");
          handleError(function(msg, err) {
            if (callback) {
              callback({
                error: err,
                message: msg
              });
            }
          }, req, statusText, error);
        }
      }
    });
  };

  var storage = null;
  var path = app_props.host + consts.boxprefix + "app/init";
  try {
    storage = data.getStorage("fh_init_storage", typeof Titanium !== "undefined"?['titanium']:null);
    storage.get('fh_init', function(storage_res) {
      var savedHost = null;
      if (storage_res && storage_res.value !== null && typeof(storage_res.value) !== "undefined" && storage_res !== "") {
        storage_res = typeof(storage_res) === "string" ? JSON.parse(storage_res) : storage_res;
        storage_res.value = typeof(storage_res.value) === "string" ? JSON.parse(storage_res.value) : storage_res.value;
        if (storage_res.value.init) {
          app_props.init = storage_res.value.init;
        } else {
          //keep it backward compatible.
          app_props.init = typeof(storage_res.value) === "string" ? JSON.parse(storage_res.value) : storage_res.value;
        }
        if (storage_res.value.hosts) {
          savedHost = storage_res.value;
        }
      }

      doInit(path, app_props, savedHost, storage);
    });
  } catch (e) {
    //for whatever reason (e.g. localStorage is disabled) Lawnchair is failed to init, just do the init
    doInit(path, app_props, null, null);
  }
};

module.exports = {
  "init": init,
  "loadCloudProps": loadCloudProps
};


text:
using System;
using Android.OS;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using IoTMonitor.ViewModel;
using Android.Support.V4.Widget;
using Android.App;
using Android.Content;
using IoTMonitor.Helpers;
using IoTMonitor.Services;
using System.Threading.Tasks;
using IoTMonitor.Model;

namespace IoTMonitor.Droid
{
    public class BrowseFragment : Android.Support.V4.App.Fragment, IFragmentVisible
    {

        public static BrowseFragment NewInstance() =>
            new BrowseFragment { Arguments = new Bundle() };

        BrowseItemsAdapter adapter;
        SwipeRefreshLayout refresher;
        Task loadItems;

        ProgressBar progress;
        public ItemsViewModel ViewModel
        {
            get;
            set;
        }

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            ServiceLocator.Instance.Register<MockDataStore, MockDataStore>();

            ViewModel = new ItemsViewModel();
            loadItems = ViewModel.ExecuteLoadItemsCommand();

            MessagingCenter.Subscribe<AddItemActivity, Item>(this, "AddItem", async (obj, item) =>
            {
                var _item = item as Item;
                await ViewModel.AddItem(_item);
            });
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.fragment_browse, container, false);
            var recyclerView =
                view.FindViewById<RecyclerView>(Resource.Id.recyclerView);

            recyclerView.HasFixedSize = true;
            recyclerView.SetAdapter(adapter = new BrowseItemsAdapter(Activity, ViewModel));

            refresher = view.FindViewById<SwipeRefreshLayout>(Resource.Id.refresher);

            refresher.SetColorSchemeColors(Resource.Color.accent);

            progress = view.FindViewById<ProgressBar>(Resource.Id.progressbar_loading);
            progress.Visibility = ViewStates.Gone;

            return view;
        }

        public override void OnStart()
        {
            base.OnStart();

            refresher.Refresh += Refresher_Refresh;
            adapter.ItemClick += Adapter_ItemClick;

            if (ViewModel.Items.Count == 0)
                loadItems.Wait();
        }

        public override void OnStop()
        {
            base.OnStop();
            refresher.Refresh -= Refresher_Refresh;
            adapter.ItemClick -= Adapter_ItemClick;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            MessagingCenter.Unsubscribe<AddItemActivity>(this, "AddItem");
        }

        private void Adapter_ItemClick(object sender, RecyclerClickEventArgs e)
        {
            var item = ViewModel.Items[e.Position];
            var intent = new Intent(Activity, typeof(BrowseItemDetailActivity));

            intent.PutExtra("data", Newtonsoft.Json.JsonConvert.SerializeObject(item));
            Activity.StartActivity(intent);
        }

        private async void Refresher_Refresh(object sender, EventArgs e)
        {
            await ViewModel.ExecuteLoadItemsCommand();
            refresher.Refreshing = false;
        }

        public void BecameVisible()
        {
        }
    }

    class BrowseItemsAdapter : BaseRecycleViewAdapter
    {

        ItemsViewModel viewModel;
        Activity activity;

        public BrowseItemsAdapter(Activity activity, ItemsViewModel viewModel)
        {
            this.viewModel = viewModel;
            this.activity = activity;

            this.viewModel.Items.CollectionChanged += (sender, args) =>
            {
                this.activity.RunOnUiThread(NotifyDataSetChanged);
            };
        }

        // Create new views (invoked by the layout manager)
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            //Setup your layout here
            View itemView = null;
            var id = Resource.Layout.item_browse;
            itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false);

            var vh = new MyViewHolder(itemView, OnClick, OnLongClick);
            return vh;
        }

        // Replace the contents of a view (invoked by the layout manager)
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var item = viewModel.Items[position];

            // Replace the contents of the view with that element
            var myHolder = holder as MyViewHolder;
            myHolder.TextView.Text = item.Text;
            myHolder.DetailTextView.Text = item.Description;
        }

        public override int ItemCount => viewModel.Items.Count;

    }

    public class MyViewHolder : RecyclerView.ViewHolder
    {
        public TextView TextView { get; set; }
        public TextView DetailTextView { get; set; }

        public MyViewHolder(View itemView, Action<RecyclerClickEventArgs> clickListener,
                            Action<RecyclerClickEventArgs> longClickListener) : base(itemView)
        {
            TextView = itemView.FindViewById<TextView>(Android.Resource.Id.Text1);
            DetailTextView = itemView.FindViewById<TextView>(Android.Resource.Id.Text2);
            itemView.Click += (sender, e) => clickListener(new RecyclerClickEventArgs { View = itemView, Position = AdapterPosition });
            itemView.LongClick += (sender, e) => longClickListener(new RecyclerClickEventArgs { View = itemView, Position = AdapterPosition });
        }
    }

}