text:
//
//  GDIMath.h
//  GDI iOS Core
//
//  Created by Grant Davis on 1/30/12.
//  Copyright (c) 2012 Grant Davis Interactive, LLC. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in the
//  Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
//  AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "GDIMath.h"
#include "math.h"
#include "stdlib.h"

CGFloat distanceInMilesFromLatitude1(CGFloat lat1, CGFloat long1, CGFloat lat2, CGFloat long2)
{
    /*
     var R = 6371; // km
     var dLat = (lat2-lat1).toRad();
     var dLon = (lon2-lon1).toRad();
     var lat1 = lat1.toRad();
     var lat2 = lat2.toRad();

     var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
     Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
     var d = R * c;
     */

    CGFloat radiusOfEarth = 6371.0; // km
    CGFloat dLat = degreesToRadians(lat2-lat1);
    CGFloat dLon = degreesToRadians(long2-long1);
    CGFloat rLat1 = degreesToRadians(lat1);
    CGFloat rLat2 = degreesToRadians(lat2);

    CGFloat a = sinf(dLat/2.f) * sinf(dLat/2.f) + sinf(dLon/2.f) * sinf(dLon/2.f) * cosf(rLat1) * cosf(rLat2);
    CGFloat c = 2.f * atan2(sqrtf(a), sqrtf(1.f-a));
    CGFloat distanceInKilometers = radiusOfEarth * c;
    CGFloat distanceInMiles = kilometersToMiles(distanceInKilometers);

    return distanceInMiles;
}

CGFloat kilometersToMiles(CGFloat kilometers)
{
    return kilometers / KILOMETERS_PER_MILE;
}

CGFloat milesToKilometers(CGFloat miles)
{
    return miles * KILOMETERS_PER_MILE;
}

CGPoint cartesianCoordinateFromPolar(float radius, float radians)
{
    float x,y;

    x = radius * cosf(radians);
    y = radius * sinf(radians);

    return CGPointMake(x, y);
}

// 1 foot * 1 meter/3.280839895 feet => meter
float metersToFeet(float meters)
{
    return meters * FEET_PER_METERS;
}

// 1 meter * 3.280839895 feet => feet
float feetToMeters(float feet)
{
    return feet / FEET_PER_METERS;
}

float degreesToRadians(float degrees)
{
    return degrees * M_PI / 180;
}

float radiansToDegrees(float radians)
{
    return radians * 180 / M_PI;
}

float max(float a, float b)
{
	if( a>b) return a;
	return b;
}

float min(float a, float b)
{
	if( a<b) return a;
	return b;
}

float randRange(float low, float high)
{
	return ((float)arc4random() / ARC4RANDOM_MAX * (high-low))+low;
}

float distance(float x, float y, float x2, float y2)
{
	return sqrtf(powf(x2-x, 2)+powf(y2-y, 2));
}

// Interpolate between angles.  This function takes care of cases where its correct to go the "short way"  from say, 5 degrees to 359 degrees
float degreesInterp(float angle1, float angle2, float n)
{

	angle1=modulus(angle1,360);
    angle2= modulus(angle2,360);

    if(angle1<0) angle1=360+angle1;
    if(angle2<0) angle2=360+angle2;  //Make all angles positive, 0-360

    if(fabs(angle1-angle2)>180 && angle1<angle2) angle1+=360;
    else if(fabs(angle1-angle2)>180 && angle2<angle1) angle2+=360;

	return interp(angle1, angle2, n);
}

float modulus(float a, float b)
{
	int result = (int)( a / b );
	return a - (float)( result ) * b;
}

float knotsToMPH(float knots)
{
	return knots*1.15077945;
}

float knotsToKPH(float knots)
{
	return knots*1.852;
}

float inchesToCM(float in)
{
	return in*2.54;
}

float farenheitToCelsius(float f)
{
	return((f - 32.0) * (5./9.) );
}

float celsiusToFarenheit(float c)
{
	return (c * (9./5.)) + 32.;
}

float clamp(float input, float low, float high)
{
	if(input<low) input=low;
	else if(input>high) input=high;
	return input;
}

float interp(float low,float high, float n)
{
	return low+  ((high-low)*n);
}


text:
Type.registerNamespace("Ibn");

// ---------------------------------
// ------- TimePickerExtender ---------
// ---------------------------------

// TimePickerExtender Constructor
Ibn.TimePickerExtender = function(element)
{
    Ibn.TimePickerExtender.initializeBase(this, [element]);

    //internals
    this._element = element;
    this._timeValue = null;
    this._enabled = true;
    this._isAM = false;
    this._divCssClass = "";
    this._storeValue = null;

    this._isOpen = false;
    this._width = 95;
    this._height = 120;
    this._popupDiv = null;
    this._innerContainer = null;
    this._updateElement = null;

    this._calendar = null;
    this._calendarHandler = null;

    this._blur = new Ibn.DeferredOperation(((Sys.Browser.agent === Sys.Browser.Safari) ? 1000 : 100), this, this._onBlur);
    this._focus = new Ibn.DeferredOperation(((Sys.Browser.agent === Sys.Browser.Safari) ? 1000 : 100), this, this._onFocus);
    this._slowScroll = new Ibn.DeferredOperation(((Sys.Browser.agent == Sys.Browser.InternetExplorer) ? 100 : 1), this, this._setScroll);

    this._element$delegates = {
        focus : Function.createDelegate(this, this._element_onFocus),
        focusout : Function.createDelegate(this, this._element_onBlur),
        blur : Function.createDelegate(this, this._element_onBlur),
        keyup : Function.createDelegate(this, this._element_onkeyup)
    }

    this._cell$delegates = {
        mouseover : Function.createDelegate(this, this._cell_onmouseover),
        mouseout : Function.createDelegate(this, this._cell_onmouseout),
        click : Function.createDelegate(this, this._cell_onclick)
    }

    this._popup$delegates = {
		activate : Function.createDelegate(this, this._popup_onfocus),
        focus : Function.createDelegate(this, this._popup_onfocus),
        dragstart: Function.createDelegate(this, this._popup_ondragstart),
        select: Function.createDelegate(this, this._popup_onselect)
    }
}

Ibn.TimePickerExtender.prototype =
{
	// -========= Properties =========-
	get_timeValue: function () {
		return this._timeValue;
	},
	set_timeValue: function (value) {
		this._timeValue = value;
	},

	get_enabled: function () {
		return this._enabled;
	},
	set_enabled: function (value) {
		this._enabled = value;
	},

	get_isAM: function () {
		return this._isAM;
	},
	set_isAM: function (value) {
		this._isAM = value;
	},

	get_divCssClass: function () {
		return this._divCssClass;
	},
	set_divCssClass: function (value) {
		this._divCssClass = value;
	},

	get_calendar: function () {
		return this._calendar;
	},
	set_calendar: function (value) {
		this._calendar = value;
	},

	get_storeValue: function () {
		return this._storeValue;
	},
	set_storeValue: function (value) {
		this._storeValue = value;
	},

	//added by DVS
	get_updateElement: function () {
		return this._updateElement;
	},
	set_updateElement: function (value) {
		this._updateElement = value;
	},
	// -========= Methods =========-
	// ctor()
	initialize : function()
	{
		Ibn.TimePickerExtender.callBaseMethod(this, 'initialize');

		if(this._element)
			$addHandlers(this._element, this._element$delegates);

		if (this._calendar) {
			this._calendarHandler = Function.createDelegate(this, this._onCalendarEditHandler);
			this._calendar.add_editValue(this._calendarHandler);
		}

		if(this._timeValue)
			this._element.value = this._timeValue;

		this._ensureTimeString();
		if(this._calendar)
			this._calendar._ensureDateString();
	},

	dispose: function() {
		if (this._calendar && this._calendarHandler) {
			this._calendar.remove_editValue(this._calendarHandler);
		}

		if (this._element) {
			$clearHandlers(this._element);
		}
		if(this._innerContainer)
			this._innerContainer = null;
		if(this._popupDiv)
			this._popupDiv = null;
		this._calendar = null;

		Ibn.TimePickerExtender.callBaseMethod(this, 'dispose');
	},

	_onCalendarEditHandler : function(obj, args) {
		if(!this._enabled)
			return;
		var elt = obj.get_element();
		if(elt && elt.value == "")
		{
			if(this._element.value != "")
				this._storeValue = this._element.value;
			this._element.value = "";
			this._element.disabled = true;
		}
		else
		{
			if (typeof(this._element) == 'undefined' && this._updateElement)
				this._element = $get(this._updateElement.replace(/\$/g,'_'));
			this._element.disabled = false;
			if(this._storeValue != null && this._element.value == "")
			{
				this._element.value = this._storeValue;
				this._ensureTimeString();
			}
		}
	},

	_onBlur : function() {
        this._focus.cancel();
        this._hide();
        this._ensureTimeString();
    },
    _onFocus : function() {
        this._blur.cancel();
        this._element.focus();
    },

	_element_onFocus : function(e) {
        if (this._enabled) {
            this._focus.cancel();
            this._blur.cancel();
            this._show();
        }
    },
    _element_onBlur : function(e) {
        if ((e.type == 'blur' && Sys.Browser.agent != Sys.Browser.InternetExplorer) ||
            (e.type == 'focusout' && Sys.Browser.agent == Sys.Browser.InternetExplorer)) {
                this._focus.cancel();
                this._blur.post();
        }
    },

    _element_onkeyup : function(e) {
        if (this._enabled) {
            this._focus.cancel();
            this._blur.cancel();

           var _keyCode = e.keyCode;
           if(_keyCode == 38)
           {
				//todo - move div up
           }
           else if(_keyCode == 40)
           {
				//todo - move div down
           }
        }
    },

	_show : function() {

		this._ensureTicks();

		if (!this._isOpen) {
			var t = this._getTotalOffset(this._element);
			if(t && t.Left)
				this._popupDiv.style.left = t.Left + "px";
			if(t && t.Top)
				this._popupDiv.style.top = t.Top + this._element.offsetHeight + 1 + "px";

			this._popupDiv.style.display = "";
			this._isOpen = true;
			this._ensureSelected();
		}
	},

	_getTotalOffset : function(eSrc) {
		var retVal = new Object();
		retVal.Top = 0;
		retVal.Left = 0;
		while (eSrc)
		{
			retVal.Top += eSrc.offsetTop;
			retVal.Left += eSrc.offsetLeft;
			eSrc = eSrc.offsetParent;
		}
		return retVal;
	},

	_hide : function() {
		if(this._popupDiv)
		{
			this._popupDiv.style.display = "none";
		}
		this._isOpen = false;
	},

	_ensureTicks : function() {
		if (!this._popupDiv) {
			this._buildPopup();
		}
    },

    _isNearest : function(elemValue) {
		var retVal = false;

		var sH = "";
		var sM = "";
		var sAM = "";

		if(this._element.value != "")
		{
			var str = this._element.value;
			var idouble = str.indexOf(":");
			if(idouble > 0)
			{
				sH = str.substring(0, idouble);
				sM = str.substr(idouble + 1, 2);
				if(this._isAM)
					sAM = str.substr(idouble + 3);
			}
		}

		var sElH = "";
		var sElM = "";
		var sElAM = "";

		if(elemValue != "")
		{
			var str = elemValue;
			var idouble = str.indexOf(":");
			if(idouble > 0)
			{
				sElH = str.substring(0, idouble);
				sElM = str.substr(idouble + 1, 2);
				if(this._isAM)
					sElAM = str.substr(idouble + 3);
			}
		}
		if(sElH == sH && sAM == sElAM)
		{
			var iM = parseInt(sM, 10);
			var iElM = parseInt(sElM, 10);
			if(iM - iElM >= 0 && iM - iElM < 30)
				retVal = true;
		}
		return retVal;
    },

    _ensureSelected : function() {
		var iSel = 0;
		var iOffHeight = 0;
		if(!this._innerContainer)
			return;
		var s = "";
		for (var i = 0; i < this._innerContainer.childNodes.length; i++) {
			var d0 = this._innerContainer.childNodes[i];
			if(this._isNearest(d0.innerHTML))
			{
				s = s + " " + i.toString();
				iSel = i;
				iOffHeight = d0.offsetHeight;
				d0.style.backgroundColor = "#0000ff";
				d0.style.color = "#ffffff";
			}
			else
			{
				d0.style.backgroundColor = "#ffffff";
				d0.style.color = "#000000";
			}
		}
		this._slowScroll.post(iSel, iOffHeight);

    },

    _setScroll : function (x,y){
		if(this._popupDiv)
			this._popupDiv.scrollTop = x*y;
    },

    _buildPopup : function() {
        /// <summary>
        /// Builds the calendar's layout
        /// </summary>

        this._popupDiv = this._createElementFromTemplate({
            nodeName : "div",
            events : this._popup$delegates,
            visible : true
        }, document.body);

        if(this._divCssClass != "")
			this._popupDiv.className = this._divCssClass;
        this._popupDiv.style.backgroundColor = "#ffffff";
        this._popupDiv.style.border = "1px solid";
        this._popupDiv.style.borderColor = "#000000";
        this._popupDiv.style.width = this._width + "px";
        this._popupDiv.style.height = this._height + "px";
        this._popupDiv.style.overflow = "auto";
        this._popupDiv.style.zIndex = "2";
        this._popupDiv.style.position = "absolute";
        this._popupDiv.style.left = "50px";
        this._popupDiv.style.top = "50px";

        this._innerContainer = this._createElementFromTemplate({
            nodeName : "div",
            events : null,
            visible : true
        }, this._popupDiv);

        for(var i=0;i<24;i++)
        {
			var d0 = this._createElementFromTemplate({
				nodeName : "div",
				events : this._cell$delegates,
				visible : true
			}, this._innerContainer);
			d0.innerHTML = this._getTimeString(i.toString(),"0");
			d0.style.cursor = "pointer";
			d0.style.padding = "2px";
			d0.style.backgroundColor = "#ffffff";
			d0.style.color = "#000000";

			var d30 = this._createElementFromTemplate({
				nodeName : "div",
				events : this._cell$delegates,
				visible : true
			}, this._innerContainer);
			d30.innerHTML = this._getTimeString(i.toString(),"30");
			d30.style.cursor = "pointer";
			d30.style.padding = "2px";
			d30.style.backgroundColor = "#ffffff";
			d30.style.color = "#000000";
        }

        this._popupDiv.style.display = "none";
    },

    _getTimeString : function(h,m) {
		var am = "";
		if(!this._isAM && parseInt(h, 10) < 10)
			h = "0" + h;
		else if(this._isAM)
		{
			if(parseInt(h, 10) == 0)
			{
				h = "12";
				am = "AM";
			}
			else if(parseInt(h, 10) < 12)
				am = "AM";
			else if(parseInt(h, 10) > 12)
			{
				h = (parseInt(h, 10) - 12).toString();
				am = "PM";
			}
			else
				am = "PM";
		}
		var retVal = h + ":";
		var sM = m;
		if(parseInt(m, 10)<10)
			sM = "0" + sM;
		retVal = retVal + sM;
		if(this._isAM)
			retVal = retVal + am;
		return retVal;
    },

    _ensureTimeString : function() {
		if(this._element.value == "")
			return;

		var str = this._element.value;

		var idouble = str.indexOf(":");
		if(idouble < 0)
		{
			this._element.value = "";
			return;
		}

		try {
			var sH = str.substring(0, idouble);
			if(sH == "")
				sH = "0";
			var sM = str.substr(idouble + 1, 2);
			if(sM == "")
				sM = "0";
			if(isNaN(parseInt(sM, 10)))
			{
				this._element.value = "";
				return;
			}
			if(parseInt(sH, 10) > 24 || parseInt(sH, 10)<0)
			{
				this._element.value = "";
				return;
			}
			if(parseInt(sM, 10)>59 || parseInt(sM, 10)<0)
			{
				this._element.value = "";
				return;
			}
			if(parseInt(sM, 10)<10)
				sM = "0" + parseInt(sM, 10).toString();

			var sAM = str.substr(idouble + 3);
			sAM = sAM.replace(" ", "");
			if(this._isAM)
			{
				if(parseInt(sH, 10) == 0)
				{
					sH = "12";
					sAM = "AM";
				}
				if(sAM == "")
				{
					if(parseInt(sH, 10) < 12)
						sAM = "AM";
					else
						sAM = "PM";
				}
				if(sAM.toLowerCase() == "am")
					sAM = "AM";
				else if(sAM.toLowerCase() == "pm")
					sAM = "PM";
				else
					sAM = "AM";

				if(parseInt(sH, 10)<10)
					sH = parseInt(sH, 10).toString();
				if(parseInt(sH, 10)>12)
				{
					sH = (parseInt(sH, 10) - 12).toString();
					sAM = "PM";
				}
			}

			if(!this._isAM)
			{
				if(sAM.toLowerCase() == "am")
				{
					if(parseInt(sH, 10) == 12)
						sH = "00";
				}
				if(sAM.toLowerCase() == "pm")
				{
					if(parseInt(sH, 10) < 12)
						sH = (parseInt(sH, 10) + 12).toString();
				}

				if(parseInt(sH, 10)<10)
					sH = "0" + parseInt(sH, 10).toString();

				sAM = "";
			}

			this._element.value = sH + ":" + sM + sAM.toUpperCase();
		}
		catch(e)
		{
			this._element.value = "";
			return;
		}
    },

    _cell_onmouseover : function(e) {
        for (var i = 0; i < this._innerContainer.childNodes.length; i++) {
			var d0 = this._innerContainer.childNodes[i];
			d0.style.backgroundColor = "#ffffff";
			d0.style.color = "#000000";
        }

        var target = e.target;

		target.style.backgroundColor = "#0000ff";
		target.style.color = "#ffffff";

        e.stopPropagation();
    },

    _cell_onmouseout : function(e) {
        var target = e.target;

		target.style.backgroundColor = "#ffffff";
		target.style.color = "#000000";

        e.stopPropagation();
    },

     _cell_onclick : function(e) {
		if ((Sys.Browser.agent === Sys.Browser.Safari) ||
            (Sys.Browser.agent === Sys.Browser.Opera)) {
            this._popup_onfocus(e);
        }

		var target = e.target;
		this._element.value = target.innerHTML;
		this._focus.cancel();
		this._blur.post();
		//this._hide();
		e.stopPropagation();
        e.preventDefault();

        if (this._updateElement)
        {
			__doPostBack(this._updateElement, '');
        }
     },

    _popup_onfocus : function(e) {
		if ((e.type == 'focus' && Sys.Browser.agent != Sys.Browser.InternetExplorer) ||
            (e.type == 'activate' && Sys.Browser.agent == Sys.Browser.InternetExplorer) ||
            (Sys.Browser.agent === Sys.Browser.Safari) ||
            (Sys.Browser.agent === Sys.Browser.Opera)) {
            if (this._isOpen) {
                this._blur.cancel();
                this._focus.post();
            }
        }
    },

    _popup_ondragstart : function(e) {
        e.stopPropagation();
        e.preventDefault();
    },
    _popup_onselect : function(e) {
        e.stopPropagation();
        e.preventDefault();
    },

    _createElementFromTemplate : function(template, appendToParent, nameTable) {
       // if we wish to override the name table we do so here
        if (typeof(template.nameTable)!='undefined') {
            var newNameTable = template.nameTable;
            if (String.isInstanceOfType(newNameTable)) {
                newNameTable = nameTable[newNameTable];
            }
            if (newNameTable != null) {
                nameTable = newNameTable;
            }
        }

        // get a name for the element in the nameTable
        var elementName = null;
        if (typeof(template.name)!=='undefined') {
            elementName = template.name;
        }

        // create or acquire the element
        var elt = document.createElement(template.nodeName);

        // if our element is named, add it to the name table
        if (typeof(template.name)!=='undefined' && nameTable) {
            nameTable[template.name] = elt;
        }

        // if we wish to supply a default parent we do so here
        if (typeof(template.parent)!=='undefined' && appendToParent == null) {
            var newParent = template.parent;
            if (String.isInstanceOfType(newParent)) {
                newParent = nameTable[newParent];
            }
            if (newParent != null) {
                appendToParent = newParent;
            }
        }

        // events are added to the dom element using $addHandlers
        if (typeof(template.events)!=='undefined' && template.events != null) {
            $addHandlers(elt, template.events);
        }

        // if the element is visible or not its visibility is set
        if (typeof(template.visible)!=='undefined' && template.visible != null) {
            if(template.visible)
				elt.style.display = "";
			else
				elt.style.display = "none";
        }

        // if we have an appendToParent we will now append to it
        if (appendToParent) {
            appendToParent.appendChild(elt);
        }

        // if we have child templates, process them
        if (typeof(template.children)!=='undefined' && template.children != null) {
            for (var i = 0; i < template.children.length; i++) {
                var subtemplate = template.children[i];
                createElementFromTemplate(subtemplate, elt, nameTable);
            }
        }

        // if we have a content presenter for the element get it (the element itself is the default presenter for content)
        var contentPresenter = elt;
        if (typeof(template.contentPresenter)!=='undefined' && template.contentPresenter != null) {
            contentPresenter = nameTable[contentPresenter];
        }

        // if we have content, add it
        if (typeof(template.content)!=='undefined' && template.content != null) {
            var content = template.content;
            if (String.isInstanceOfType(content)) {
                content = nameTable[content];
            }
            if (content.parentNode) {
                wrapElement(content, elt, contentPresenter);
            } else {
                contentPresenter.appendChild(content);
            }
        }

        // return the created element
        return elt;
    },

    wrapElement : function(innerElement, newOuterElement, newInnerParentElement) {
        var parent = innerElement.parentNode;
        parent.replaceChild(newOuterElement, innerElement);
        (newInnerParentElement || newOuterElement).appendChild(innerElement);
    }
}

Ibn.TimePickerExtender.registerClass("Ibn.TimePickerExtender", Sys.UI.Control);

//Threading
Ibn.DeferredOperation = function(delay, context, callback) {
    this._delay = delay;
    this._context = context;
    this._callback = callback;
    this._completeCallback = null;
    this._errorCallback = null;
    this._timer = null;
    this._callArgs = null;
    this._isComplete = false;
    this._completedSynchronously = false;
    this._asyncResult = null;
    this._exception = null;
    this._throwExceptions = true;
    this._oncomplete$delegate = Function.createDelegate(this, this._oncomplete);

    // post to ensure that attaching it always gets the port as its context
    this.post = Function.createDelegate(this, this.post);
}
Ibn.DeferredOperation.prototype = {

    get_isPending : function() {
        /// <summary>
        /// Gets whether there is an asynchronous operation pending
        /// </summary>
        /// <returns type="Boolean" />

        return (this._timer != null);
    },

    get_isComplete : function() {
        /// <summary>
        /// Gets whether the asynchronous operation has completed
        /// </summary>
        /// <returns type="Boolean" />

        return this._isComplete;
    },

    get_completedSynchronously : function() {
        /// <summary>
        /// Gets whether the operation completed synchronously
        /// </summary>
        /// <returns type="Boolean" />

        return this._completedSynchronously;
    },

    get_exception : function() {
        /// <summary>
        /// Gets the current exception if there is one
        /// </summary>
        /// <returns type="Error" />

        return this._exception;
    },

    get_throwExceptions : function() {
        /// <summary>
        /// Gets whether to throw exceptions
        /// </summary>
        /// <returns type="Boolean" />

        return this._throwExceptions;
    },
    set_throwExceptions : function(value) {
        /// <summary>
        /// Sets whether to throw exceptions
        /// </summary>
        /// <param name="value" type="Boolean">True if exceptions should be thrown, otherwise false</param>

        this._throwExceptions = value;
    },

    get_delay : function() {
        /// <summary>
        /// Gets the current delay in milliseconds
        /// </summary>
        /// <returns type="Number" integer="true" />

        return this._delay;
    },
    set_delay : function(value) {
        /// <summary>
        /// Sets the current delay in milliseconds
        /// </summary>
        /// <param name="value" type="Number" integer="true">The delay in milliseconds</param>

        this._delay = value;
    },

    post : function(args) {
        /// <summary>
        /// A method that can be directly attached to a delegate
        /// </summary>
        /// <param name="args" type="Object" parameterArray="true">The arguments to the method</param>

        var ar = [];
        for (var i = 0; i < arguments.length; i++) {
            ar[i] = arguments[i];
        }
        this.beginPost(ar, null, null);
    },

    beginPost : function(args, completeCallback, errorCallback) {
        /// <summary>
        /// Posts a call to an async operation on this port
        /// </summary>
        /// <param name="args" type="Array">An array of arguments to the method</param>
        /// <param name="completeCallback" type="Function" optional="true" mayBeNull="true">The callback to execute after the delayed function completes</param>
        /// <param name="errorCallback" type="Function" optional="true" mayBeNull="true">The callback to execute in the event of an exception in the delayed function</param>

        // cancel any pending post
        this.cancel();

        // cache the call arguments
        this._callArgs = Array.clone(args || []);
        this._completeCallback = completeCallback;
        this._errorCallback = errorCallback;

        if (this._delay == -1) {
            // if there is no delay (-1), complete synchronously
            this._oncomplete();
            this._completedSynchronously = true;
        } else {
            // complete the post on a seperate call after a delay
            this._timer = setTimeout(this._oncomplete$delegate, this._delay);
        }
    },

    cancel : function() {
        /// <summary>
        /// Cancels a pending post
        /// </summary>

        if (this._timer) {
            clearTimeout(this._timer);
            this._timer = null;
        }
        this._callArgs = null;
        this._isComplete = false;
        this._asyncResult = null;
        this._completeCallback = null;
        this._errorCallback = null;
        this._exception = null;
        this._completedSynchronously = false;
    },

    complete : function() {
        /// <summary>
        /// Completes a pending post synchronously
        /// </summary>

        if (this._timer) {
            try {
                this._oncomplete();
            } finally {
                this._completedSynchronously = true;
            }
            return this._asyncResult;
        } else if (this._isComplete) {
            return this._asyncResult;
        }
    },

    _oncomplete : function() {
        /// <summary>
        /// Completes a pending post asynchronously
        /// </summary>

        var args = this._callArgs;
        var completeCallback = this._completeCallback;
        var errorCallback = this._errorCallback;

        // clear the post state
        this.cancel();
        try {
            // call the post callback
            if (args) {
                this._asyncResult = this._callback.apply(this._context, args);
            } else {
                this._asyncResult = this._callback.call(this._context);
            }
            this._isComplete = true;
            this._completedSynchronously = false;
            if (completeCallback) {
                completeCallback(this);
            }
        } catch (e) {
            this._isComplete = true;
            this._completedSynchronously = false;
            this._exception = e;
            if (errorCallback) {
                if (errorCallback(this)) {
                    return;
                }
            }
            if (this._throwExceptions) {
                throw e;
            }
        }
    }
}
Ibn.DeferredOperation.registerClass("Ibn.DeferredOperation");

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0005_auto_20170607_1251'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='item_image',
            name='item_variation',
        ),
        migrations.AddField(
            model_name='item_image',
            name='item',
            field=models.ForeignKey(blank=True, default='1', on_delete=django.db.models.deletion.CASCADE, to='shop.Item'),
        ),
    ]


text:
[![GoDoc](https://godoc.org/github.com/shekhei/go-engine.io-client?status.svg)](https://godoc.org/github.com/shekhei/go-engine.io-client)

# go-engine.io-client(works, but still very early stage)
golang engine.io-client

Have yet to implement the pingInterval thing, and given this is my first attempt, it might not be perfect

Please do try it out and contribute if anybody likes this :D


text:
package com.spotify.flo.contrib.styx;

import com.spotify.flo.context.TerminationHook;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TerminationLogging implements TerminationHook {

  private static final Logger LOG = LoggerFactory.getLogger(TerminationLogging.class);

  @Override
  public void accept(Integer exitCode) {
    final Map<String, String> env = System.getenv();

    final String terminationLog = env.get("STYX_TERMINATION_LOG");

    // make termination logging optional
    if (terminationLog == null) {
      return;
    }

    final String content = String.format("{\"component_id\": \"%s\","
                                         + "\"workflow_id\": \"%s\","
                                         + "\"parameter\": \"%s\","
                                         + "\"execution_id\": \"%s\","
                                         + "\"event\": \"exited\","
                                         + "\"exit_code\": %d}",
        env.getOrDefault("STYX_COMPONENT_ID", "UNKNOWN_COMPONENT_ID"),
        env.getOrDefault("STYX_WORKFLOW_ID", "UNKNOWN_WORKFLOW_ID"),
        env.getOrDefault("STYX_PARAMETER", "UNKNOWN_PARAMETER"),
        env.getOrDefault("STYX_EXECUTION_ID", "UNKNOWN_EXECUTION_ID"),
        exitCode);
    final Path path = Paths.get(terminationLog);

    try {
      Files.write(path, content.getBytes(),
          StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
      LOG.error("Could not write termination log to {}.", path, e);
      throw new RuntimeException(e);
    }
  }
}


text:
title: "data.table: Data analysis like a boss"
author: Alexey Shiklomanov
date: 2016-02-28
layout: post
comments: true
---

# Introduction: All your base are annoying, slow, and large

Compared to other languages, R has good utilities for managing data. Most
prominent among these utilities is R's `data.frame` class, which gives you all
the basic features you'd want in a data soring class (e.g. row and column
names, mixed data types).

That being said, `data.frame`s are not without their problems, of which I
highlight two (spoiler alert: `data.table` addresses both):

1. **The syntax is cumbersome**. At its core, a `data.frame` is just a list
   named list of columns where all of the columns happen to be the same length.
   This means that common data operations like subsetting can have
   annoyingly redundant syntax.

2. **Operations are slow**. As a list of lists, `data.frame` doesn't do
   anything to make your data more compact or organized. On the contrary, this
   means that accessing data stored in a `data.frame` is inefficient because it
   requires multiple searches through individual lists.

# data.table syntax

For demosntration purposes, let's load R's built in `iris` database. By
default, it's a `data.frame`, so we'll create a copy that's a `data.table`.

```r
library(data.table)
data(iris)
iris.dt <- data.table(iris)
dim(iris.dt)
```

```
## [1] 150   5
```

```r
class(iris.dt)
```

```
## [1] "data.table" "data.frame"
```

```r
names(iris.dt)
```

```
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"
## [5] "Species"
```

## Implict environment scoping

The first thing to understand about `data.table` syntax is that everything
inside brackets is scoped to the `data.table` in question. If you've ever used
R's `with` function, it's exactly the same idea.  For instance, to access a
column, by default, you do not use quotes because the variable `Sepal.Length`
is in the local `data.table` environment.

```r
head(iris.dt[,Sepal.Length])
```

```
## [1] 5.1 4.9 4.7 4.6 5.0 5.4
```

In fact, if you try to access the variable with quotes or by index, you'll get
a strange result:

```r
iris.dt[, "Sepal.Length"]
```

```
## [1] "Sepal.Length"
```

```r
iris.dt[, 3]
```

```
## [1] 3
```

If you do want to use strings or column indices instead of environment
variables (for instance, if you're passing column names from a variable), you
can disable the `with` syntax by just adding a `with=FALSE` inside the
brackets.

```r
cols <- c("Sepal.Length", "Sepal.Width")
head(iris.dt[, cols, with=FALSE])
```

```
##    Sepal.Length Sepal.Width
## 1:          5.1         3.5
## 2:          4.9         3.0
## 3:          4.7         3.2
## 4:          4.6         3.1
## 5:          5.0         3.6
## 6:          5.4         3.9
```

```r
head(iris.dt[, c(2,4), with=FALSE])
```

```
##    Sepal.Width Petal.Width
## 1:         3.5         0.2
## 2:         3.0         0.2
## 3:         3.2         0.2
## 4:         3.1         0.2
## 5:         3.6         0.2
## 6:         3.9         0.4
```

You CAN however, access rows by index without any additional syntax.

```r
iris.dt[2:4]    # Note that the comma is optional
```

```
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1:          4.9         3.0          1.4         0.2  setosa
## 2:          4.7         3.2          1.3         0.2  setosa
## 3:          4.6         3.1          1.5         0.2  setosa
```

Notice that for a single column, this operation returns a vector, but for
multiple columns, it returns a `data.table`.

Granted, this is barely an improvement over `data.frame`, where the same
operation is just `iris[, "Sepal.Length"]`. However, where this starts to shine
is in subsetting operations. For instance, in base R, if you wanted just the
rows with Sepal.Length < 5, you would have to do something like:

```r
slt5 <- iris[iris$Sepal.Length < 5,]
head(slt5)
```

```
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 2           4.9         3.0          1.4         0.2  setosa
## 3           4.7         3.2          1.3         0.2  setosa
## 4           4.6         3.1          1.5         0.2  setosa
## 7           4.6         3.4          1.4         0.3  setosa
## 9           4.4         2.9          1.4         0.2  setosa
## 10          4.9         3.1          1.5         0.1  setosa
```

By contrast, the same operation in `data.table` is:

```r
slt5 <- iris.dt[Sepal.Length < 5]  # The comma is optional
```

## Operating on columns

Another cool feature is that you can call functions directly on columns within
the `data.table`. For instance, if I wanted to get the mean sepal width for
only plants with sepal length < 5, I could do:

```r
iris.dt[Sepal.Length < 5, mean(Sepal.Width)]
```

```
## [1] 3.077273
```

```r
head(iris.dt[, Sepal.Width * Sepal.Length])
```

```
## [1] 17.85 14.70 15.04 14.26 18.00 21.06
```

It gets better. Built into `data.table` is a `by` option that lets you perform
aggregation functions by subsets based on columns. For example:

```r
iris.dt[ ,mean(Sepal.Width), by=Species]
```

```
##       Species    V1
## 1:     setosa 3.428
## 2: versicolor 2.770
## 3:  virginica 2.974
```

```r
iris.dt[ ,mean(Sepal.Width), by=list(Species, Sepal.Length < 5)]
```

```
##       Species Sepal.Length       V1
## 1:     setosa        FALSE 3.620000
## 2:     setosa         TRUE 3.140000
## 3: versicolor        FALSE 2.777551
## 4: versicolor         TRUE 2.400000
## 5:  virginica        FALSE 2.983673
## 6:  virginica         TRUE 2.500000
```

Note that I used a `list` in the `by` statement to select multiple columns. A
common mistake is to use the `c` function instead (i.e.
`by=c(column1,column2)`), but that won't work UNLESS you have the `with=FALSE`
flag.

## Unique operations

Similar to this is a very useful function in `data.table` -- `.N`, which counts
the numbers of each element.

```r
iris.dt[, .N, by=list(Species, Sepal.Length < 5)]
```

```
##       Species Sepal.Length  N
## 1:     setosa        FALSE 30
## 2:     setosa         TRUE 20
## 3: versicolor        FALSE 49
## 4: versicolor         TRUE  1
## 5:  virginica        FALSE 49
## 6:  virginica         TRUE  1
```

Notice that each of these returns a `data.table` that you can save and
manipulate however you want.

Yet another construct is `.SD`, which refers by default to all of the columns
in the `data.table` not referenced by the subset command or a subset of columns
specified by the user.  This is very handy if you have a lot of columns and
want to calculate some conditional statistic for each. The trick is to
recognize that a `data.table` is still a `list` of columns and therefore can be
worked on by the `lapply` function:

```r
iris.dt[, lapply(.SD, mean), by=list(Species, Sepal.Length < 5)]
```

```
##       Species Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1:     setosa        FALSE    3.620000     1.493333    0.280000
## 2:     setosa         TRUE    3.140000     1.415000    0.195000
## 3: versicolor        FALSE    2.777551     4.279592    1.332653
## 4: versicolor         TRUE    2.400000     3.300000    1.000000
## 5:  virginica        FALSE    2.983673     5.573469    2.032653
## 6:  virginica         TRUE    2.500000     4.500000    1.700000
```

Notice that the mean sepal lengths were not calculated because it was used as a
criterion for subsetting. Also, `data.table` is not smart enough to selectively
apply functions to only numeric columns, so you may get unexpected results if
you have numeric functions applied to non-numeric columns.

```r
iris.dt[, lapply(.SD, mean), by=Sepal.Length < 5]
```

```
##    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 1:        FALSE    3.053906     4.121875    1.353906 versicolor
## 2:         TRUE    3.077273     1.640909    0.300000     setosa
```

To specify columns, add the `.SDcols` argument. Note that `.SDcols` are given
as a character vector, NOT as a list.

```r
iris.dt[, lapply(.SD, mean), by=Species, .SDcols=c("Sepal.Width", "Sepal.Length")]
```

```
##       Species Sepal.Width Sepal.Length
## 1:     setosa       3.428        5.006
## 2: versicolor       2.770        5.936
## 3:  virginica       2.974        6.588
```

## Adding columns

Adding a new column to a `data.table` can be accomplished by using standard,
`data.frame` syntax...

```r
iris.dt$random.index <- sample(nrow(iris.dt))
```

...but there is also a way that lets you more conveniently leverage the
`data.table` subsetting syntax.

```r
iris.dt[, longer.than.five := FALSE][Sepal.Length > 5, longer.than.five := TRUE]
iris.dt[, .N, by=longer.than.five]
```

```
##    longer.than.five   N
## 1:             TRUE 118
## 2:            FALSE  32
```

A few points about that last bit. First, notice the `:=` internal assignment
operator. When you perform `data.table` assignments in this way, nothing is
returned because the `data.table` is modified in place.

Second, notice that `data.table` lets you chain commands by simply stacking
brackets back-to-back. The commands are executed sequentially -- first, a
column of all `FALSE` values was added to `iris.dt`, and then some of the
values in this `data.table` were changed to TRUE.

## Renaming columns

One major difference between `data.table` and `data.frame` operations is that
the former generally modify the object in place while the latter make lots of
copies. This is a core aspect of what makes `data.table` so fast and effective
for working with large data, but it does mean that certain `data.frame`
functions don't work for `data.table`. Instead, they are replaced by `set`
functions, such as the `setnames` function.

`setnames` is very intuitive. It takes 2-3 arguments: the name of the
`data.table`, [optionally] a vector of old names that you're changing, and a
vector of new names that map to the old ones (or all the columns by default).

```r
names(iris.dt)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five"
```

```r
setnames(iris.dt, c("Sepal.Length", "Sepal.Width"), c("sl", "sw"))
names(iris.dt)
```

```
## [1] "sl"               "sw"               "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five"
```

```r
setnames(iris.dt, c("sl", "sw"), c("Sepal.Length", "Sepal.Width"))
```

A similar function is the `setcolorder` function for--you guessed
it--reordering columns.

## Keys: Faster and more convenient searches

I hinted earlier that searching operations in `data.frame` are very
inefficient, and are much faster in `data.table`. But if you're working with
really big data, you'll want to squeeze even more speed out, which you can do
by telling `data.table` more about how your data is organized and letting it
optimize its memory to access it as fast as possible. The operation for doing
this is the `setkey` operation.

Say I'm going to be doing a lot of calculations in the `iris` database by
species. Before doing everything, I'll run:

```r
setkey(iris.dt, Species)
print(iris.dt)
```

```
##      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
##   1:          5.1         3.5          1.4         0.2    setosa
##   2:          4.9         3.0          1.4         0.2    setosa
##   3:          4.7         3.2          1.3         0.2    setosa
##   4:          4.6         3.1          1.5         0.2    setosa
##   5:          5.0         3.6          1.4         0.2    setosa
##  ---
## 146:          6.7         3.0          5.2         2.3 virginica
## 147:          6.3         2.5          5.0         1.9 virginica
## 148:          6.5         3.0          5.2         2.0 virginica
## 149:          6.2         3.4          5.4         2.3 virginica
## 150:          5.9         3.0          5.1         1.8 virginica
##      random.index longer.than.five
##   1:            5             TRUE
##   2:           44            FALSE
##   3:           68            FALSE
##   4:           48            FALSE
##   5:          137            FALSE
##  ---
## 146:           75             TRUE
## 147:          132             TRUE
## 148:           73             TRUE
## 149:           10             TRUE
## 150:           51             TRUE
```

You may have noticed that the `data.table` is now sorted alphabetically by
species. This isn't just eye candy -- it has major performance implications,
since it's much easier to perform operations on contiguous data that to search
for each case.

Another effect of setting a key is that I can now subset based on the key
without actually saying what I'm searching for. For instance:

```r
head(iris.dt["setosa"])
```

```
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species random.index
## 1:          5.1         3.5          1.4         0.2  setosa            5
## 2:          4.9         3.0          1.4         0.2  setosa           44
## 3:          4.7         3.2          1.3         0.2  setosa           68
## 4:          4.6         3.1          1.5         0.2  setosa           48
## 5:          5.0         3.6          1.4         0.2  setosa          137
## 6:          5.4         3.9          1.7         0.4  setosa          145
##    longer.than.five
## 1:             TRUE
## 2:            FALSE
## 3:            FALSE
## 4:            FALSE
## 5:            FALSE
## 6:             TRUE
```

```r
iris.dt[c("setosa", "virginica"), .N, by=Species]
```

```
##      Species  N
## 1:    setosa 50
## 2: virginica 50
```

You can set and reset keys as many times as you'd like, and you can even set
multiple keys, although you need the `setkeyv` function for that. (The
difference is that `setkey` takes columns as they are--no quotes--while
`setkeyv` interprets column names from strings. This also means you can pass it
a preset vector of column names for keying, which you can't do with `setkey`).

```r
keys <- c("Species", "longer.than.five")
setkeyv(iris.dt, keys)
iris.dt
```

```
##      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
##   1:          4.9         3.0          1.4         0.2    setosa
##   2:          4.7         3.2          1.3         0.2    setosa
##   3:          4.6         3.1          1.5         0.2    setosa
##   4:          5.0         3.6          1.4         0.2    setosa
##   5:          4.6         3.4          1.4         0.3    setosa
##  ---
## 146:          6.7         3.0          5.2         2.3 virginica
## 147:          6.3         2.5          5.0         1.9 virginica
## 148:          6.5         3.0          5.2         2.0 virginica
## 149:          6.2         3.4          5.4         2.3 virginica
## 150:          5.9         3.0          5.1         1.8 virginica
##      random.index longer.than.five
##   1:           44            FALSE
##   2:           68            FALSE
##   3:           48            FALSE
##   4:          137            FALSE
##   5:           30            FALSE
##  ---
## 146:           75             TRUE
## 147:          132             TRUE
## 148:           73             TRUE
## 149:           10             TRUE
## 150:           51             TRUE
```

## Merging data tables

First, let's create data to merge in.

```r
iris.supp <- data.table(species_name = c("setosa","versicolor", "virginica"),
                        testcode = c("SET", "VER", "VGA"))
```

The basic `data.frame` merge syntax will work.

```r
iris.merge <- merge(iris.dt, iris.supp, by.x = "Species", by.y="species_name")
```

That said, a much faster merge can be done using custom `data.table` syntax
that harnesses the power of keys.

```r
setkey(iris.dt, Species)
setkey(iris.supp, species_name)
iris.merge <- iris.dt[iris.supp]
```

Note that this is only a partial join -- i.e. `iris.dt` will only take values
from `iris.supp` that are in `iris.dt`, and any values in `iris.supp` that are
not in `iris.dt` will not be added. For full joins, use the `merge` function
with the `all=TRUE` argument.

# Performance -- speed and size

Whether or not `data.table` syntax is better than `data.frame` is a subjective
quesiton. However, the speed of `data.table` is unquestionable.  To do this,
let's simulate a large dataset. (Feel free to change the value of `nvals` and
`nvals.write` to see how `data.table` speeds scale, or to accomodate slower
PC's with less memory).

```r
nvals <- 1e7
col1 <- sample(letters[1:5], nvals, replace=TRUE)
col2 <- rnorm(nvals)
system.time(dat.df <- data.frame(col1, col2))
```

```
##    user  system elapsed
##   0.304   0.032   0.336
```

```r
system.time(dat.dt <- data.table(col1, col2))
```

```
##    user  system elapsed
##   0.092   0.016   0.107
```

Note the almost twofold increase in speed in creating a `data.frame` compared
to a `data.table`. Now, let's compare the calculation of an average.

```r
system.time(with(dat.df, tapply(col2, col1, mean)))
```

```
##    user  system elapsed
##   0.596   0.052   0.648
```

```r
system.time(dat.dt[, mean(col2), by=col1])
```

```
##    user  system elapsed
##   0.112   0.016   0.127
```

```r
setkey(dat.dt, col1)
system.time(dat.dt[, mean(col2), by=col1])
```

```
##    user  system elapsed
##   0.108   0.000   0.109
```

Without keys, `data.table` is approximately 5 times faster on my machine. With
keys, it's close to 30 times faster. Hard to argue with that.

On a similar note, the `data.table` function `fread` is dramatically faster at
reading in large files than base R's `read.table` (or its derivatives like
`read.csv`).

```r
nvals.write <- 1e6
write.table(dat.dt[1:nvals.write], file="testfile.dat", row.names=FALSE)
system.time(test.df <- read.table("testfile.dat"))
```

```
##    user  system elapsed
##  10.244   0.036  10.371
```

```r
system.time(test.dt <- fread("testfile.dat", header=TRUE))
```

```
##    user  system elapsed
##   0.260   0.004   0.267
```

Not only is `fread` dramatically faster, but, if the process takes more than a
second or two, it helpfully prints information on its progress, including the
size of the file and the percentage read so far.

That speed isn't completely free though -- `fread` achieves its speed by
quickly determining features of the file and assuming they are constant
throughout. I've run into situations where weird line endings or similar things
can cause `fread` to fail in situations where `read.table` worked just fine.
But, `fread` does have the advantage that you can fine-tune exactly what it
reads in to speed it up even more. For example, you can tell it to ignore the
first *n* lines of a file (useful for reading in instrument data that has long
headers), to only read in specific rows or columns (allowing you to subset data
before even reading it in to save memory and time), or to assume columns have a
specific class (rather than making it try to figure it out independently).

# Common `data.table` mistakes

Below are some important examples of counterintuitive behavior by `data.table`
that have tripped me up in the past. This is an evolving list that I'll update
as I get tripped up by other things.

## Shallow vs. true copying

Because `data.table` is optimized for working with very large datasets, it
doesn't treat variables the way you expect. Specifically, when you reassign a
`data.table` to a new variable name, both the old and new variable names
**point to the same object**, meaning that any changes you make to one are
**applied to both**. Case in point:

```r
names(iris.dt)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five"
```

```r
iris.dt2 <- iris.dt
iris.dt2[, random.index.2 := sample(letters, nrow(iris.dt2), replace=TRUE)]
names(iris.dt2)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five" "random.index.2"
```

```r
names(iris.dt)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five" "random.index.2"
```

The way to do a full object copy is simple, through the aptly named `copy`
command.  You just have to remember to do it!

```r
iris.dt[, random.index.2 := NULL]
iris.dt2 <- copy(iris.dt)
iris.dt2[, random.index.2 := sample(letters, nrow(iris.dt2), replace=TRUE)]
names(iris.dt2)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five" "random.index.2"
```

```r
names(iris.dt)
```

```
## [1] "Sepal.Length"     "Sepal.Width"      "Petal.Length"
## [4] "Petal.Width"      "Species"          "random.index"
## [7] "longer.than.five"
```


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

<TITLE>
StandardWatchEventKind
</TITLE>

<META NAME="date" CONTENT="2009-09-18">

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

      Overview
      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.newatlanta.nio.file

Class StandardWatchEventKind

java.lang.Object
  com.newatlanta.nio.file.StandardWatchEventKind

public final class StandardWatchEventKind
extends java.lang.Object

Defines the standard event kinds.

Since:

1.7

Field Summary

static WatchEvent.Kind<Path>
ENTRY_CREATE

          Directory entry created.

static WatchEvent.Kind<Path>
ENTRY_DELETE

          Directory entry deleted.

static WatchEvent.Kind<Path>
ENTRY_MODIFY

          Directory entry modified.

static WatchEvent.Kind<java.lang.Void>
OVERFLOW

          A special event to indicate that events may have been lost or
 discarded.

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

OVERFLOW

public static final WatchEvent.Kind<java.lang.Void> OVERFLOW

A special event to indicate that events may have been lost or
 discarded.

 The context for this event is
 implementation specific and may be null. The event count may be greater than 1.

See Also:
WatchService

ENTRY_CREATE

public static final WatchEvent.Kind<Path> ENTRY_CREATE

Directory entry created.

 When a directory is registered for this event then the WatchKey
 is queued when it is observed that an entry is created in the directory
 or renamed into the directory. The event count
 for this event is always 1.

ENTRY_DELETE

public static final WatchEvent.Kind<Path> ENTRY_DELETE

Directory entry deleted.

 When a directory is registered for this event then the WatchKey
 is queued when it is observed that an entry is deleted or renamed out of
 the directory. The event count for this event
 is always 1.

ENTRY_MODIFY

public static final WatchEvent.Kind<Path> ENTRY_MODIFY

Directory entry modified.

 When a directory is registered for this event then the WatchKey
 is queued when it is observed that an entry in the directory has been
 modified. The event count for this event is
 1 or greater.

      Overview
      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:
multiset-large
==============


text:
This example illustrates a hello world node.js server

Start the server with

    node server.js

Then open your browser at [http://127.0.0.1:3000][1]

[1]: http://127.0.0.1:3000


text:
package com.ycsoft.beans.core.acct;

/**
 * CAcctPreFee.java	2011/03/25
 */

import java.io.Serializable ;
import java.util.Date ;
import com.ycsoft.daos.config.POJO ;

/**
 * CAcctPreFee -> C_ACCT_PRE_FEE mapping
 */
@POJO(
	tn="C_ACCT_PRE_FEE",
	sn="",
	pk="done_code")
public class CAcctPreFee implements Serializable {

	// CAcctPreFee all properties

	private Integer done_code ;
	private String cust_id ;
	private String user_id ;
	private String acct_id ;
	private String acctitem_id ;
	private String prod_id ;
	private Integer fee ;
	private Date fee_time ;
	private String area_id ;
	private String county_id ;
	private String prog_name ;
	private String trans_id ;
	private Integer dealtype ;
	private String detailparams ;
	private Date deal_time ;
	private String status ;
	private Date cancel_time ;
	private Integer process_flag ;
	private Integer ticket_sn ;
	private String original_sn ;
	private String prog_id ;
	private String is_valid;

	/**
	 * default empty constructor
	 */
	public CAcctPreFee() {}

	public CAcctPreFee(Integer done_code,String cust_id,String user_id,
			String acct_id,String acctitem_id,String prod_id, Integer fee,Date fee_time,
			String area_id ,String county_id,String prog_name,String trans_id,String detailparams,
			Date deal_time,String status,String prog_id){
		this.done_code = done_code;
		this.cust_id = cust_id;
		this.user_id = user_id;
		this.acct_id = acct_id;
		this.acctitem_id = acctitem_id;
		this.prod_id = prod_id;
		this.fee = fee;
		this.fee_time = fee_time;
		this.area_id = area_id;
		this.county_id = county_id;
		this.prog_name = prog_name;
		this.trans_id = trans_id;
		this.detailparams = detailparams;
		this.deal_time = deal_time;
		this.status = status;
		this.prog_id = prog_id;
	}

	// done_code getter and setter
	public Integer getDone_code(){
		return this.done_code ;
	}

	public void setDone_code(Integer done_code){
		this.done_code = done_code ;
	}

	// cust_id getter and setter
	public String getCust_id(){
		return this.cust_id ;
	}

	public void setCust_id(String cust_id){
		this.cust_id = cust_id ;
	}

	// user_id getter and setter
	public String getUser_id(){
		return this.user_id ;
	}

	public void setUser_id(String user_id){
		this.user_id = user_id ;
	}

	// acct_id getter and setter
	public String getAcct_id(){
		return this.acct_id ;
	}

	public void setAcct_id(String acct_id){
		this.acct_id = acct_id ;
	}

	// acctitem_id getter and setter
	public String getAcctitem_id(){
		return this.acctitem_id ;
	}

	public void setAcctitem_id(String acctitem_id){
		this.acctitem_id = acctitem_id ;
	}

	// prod_id getter and setter
	public String getProd_id(){
		return this.prod_id ;
	}

	public void setProd_id(String prod_id){
		this.prod_id = prod_id ;
	}

	// fee getter and setter
	public Integer getFee(){
		return this.fee ;
	}

	public void setFee(Integer fee){
		this.fee = fee ;
	}

	// fee_time getter and setter
	public Date getFee_time(){
		return this.fee_time ;
	}

	public void setFee_time(Date fee_time){
		this.fee_time = fee_time ;
	}

	// area_id getter and setter
	public String getArea_id(){
		return this.area_id ;
	}

	public void setArea_id(String area_id){
		this.area_id = area_id ;
	}

	// county_id getter and setter
	public String getCounty_id(){
		return this.county_id ;
	}

	public void setCounty_id(String county_id){
		this.county_id = county_id ;
	}

	// prog_name getter and setter
	public String getProg_name(){
		return this.prog_name ;
	}

	public void setProg_name(String prog_name){
		this.prog_name = prog_name ;
	}

	// trans_id getter and setter
	public String getTrans_id(){
		return this.trans_id ;
	}

	public void setTrans_id(String trans_id){
		this.trans_id = trans_id ;
	}

	// dealtype getter and setter
	public Integer getDealtype(){
		return this.dealtype ;
	}

	public void setDealtype(Integer dealtype){
		this.dealtype = dealtype ;
	}

	// detailparams getter and setter
	public String getDetailparams(){
		return this.detailparams ;
	}

	public void setDetailparams(String detailparams){
		this.detailparams = detailparams ;
	}

	// deal_time getter and setter
	public Date getDeal_time(){
		return this.deal_time ;
	}

	public void setDeal_time(Date deal_time){
		this.deal_time = deal_time ;
	}

	// status getter and setter
	public String getStatus(){
		return this.status ;
	}

	public void setStatus(String status){
		this.status = status ;
	}

	// cancel_time getter and setter
	public Date getCancel_time(){
		return this.cancel_time ;
	}

	public void setCancel_time(Date cancel_time){
		this.cancel_time = cancel_time ;
	}

	// process_flag getter and setter
	public Integer getProcess_flag(){
		return this.process_flag ;
	}

	public void setProcess_flag(Integer process_flag){
		this.process_flag = process_flag ;
	}

	// ticket_sn getter and setter
	public Integer getTicket_sn(){
		return this.ticket_sn ;
	}

	public void setTicket_sn(Integer ticket_sn){
		this.ticket_sn = ticket_sn ;
	}

	// original_sn getter and setter
	public String getOriginal_sn(){
		return this.original_sn ;
	}

	public void setOriginal_sn(String original_sn){
		this.original_sn = original_sn ;
	}

	// prog_id getter and setter
	public String getProg_id(){
		return this.prog_id ;
	}

	public void setProg_id(String prog_id){
		this.prog_id = prog_id ;
	}

	public String getIs_valid() {
		return is_valid;
	}

	public void setIs_valid(String is_valid) {
		this.is_valid = is_valid;
	}

}


text:
namespace blink {

class DOMTimer;
class ExecutionContext;
class ScheduledAction;

// Maintains a set of DOMTimers for a given page or
// worker. DOMTimerCoordinator assigns IDs to timers; these IDs are
// the ones returned to web authors from setTimeout or setInterval. It
// also tracks recursive creation or iterative scheduling of timers,
// which is used as a signal for throttling repetitive timers.
class DOMTimerCoordinator {
  DISALLOW_NEW();

 public:
  DOMTimerCoordinator() = default;
  DOMTimerCoordinator(const DOMTimerCoordinator&) = delete;
  DOMTimerCoordinator& operator=(const DOMTimerCoordinator&) = delete;

  // Creates and installs a new timer. Returns the assigned ID.
  int InstallNewTimeout(ExecutionContext*,
                        ScheduledAction*,
                        base::TimeDelta timeout,
                        bool single_shot);

  // Removes and disposes the timer with the specified ID, if any. This may
  // destroy the timer.
  DOMTimer* RemoveTimeoutByID(int id);

  // Timers created during the execution of other timers, and
  // repeating timers, are throttled. Timer nesting level tracks the
  // number of linked timers or repetitions of a timer. See
  // https://html.spec.whatwg.org/C/#timers
  int TimerNestingLevel() { return timer_nesting_level_; }

  // Sets the timer nesting level. Set when a timer executes so that
  // any timers created while the timer is executing will incur a
  // deeper timer nesting level, see DOMTimer::DOMTimer.
  void SetTimerNestingLevel(int level) { timer_nesting_level_ = level; }

  void Trace(Visitor*) const;  // Oilpan.

 private:
  int NextID();

  using TimeoutMap = HeapHashMap<int, Member<DOMTimer>>;
  TimeoutMap timers_;

  int circular_sequential_id_ = 0;
  int timer_nesting_level_ = 0;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_TIMER_COORDINATOR_H_


text:
import { FETCH_WORD_SAMPLE_SENTENCES } from '../../../../actions/topicActions';
import { createAsyncReducer } from '../../../../lib/reduxHelpers';

const sampleSentences = createAsyncReducer({
  initialState: {
    sentences: [],
  },
  action: FETCH_WORD_SAMPLE_SENTENCES,
});

export default sampleSentences;