text:
using System;
using System.Collections.Generic;

namespace Jurassic.Library
{
    /// <summary>
    /// Implements the array algorithms that are shared between arrays and typed arrays.
    /// </summary>
    internal abstract class ArrayAdapter<T>
    {
        private ObjectInstance wrappedInstance;
        private int length;

        /// <summary>
        /// Creates a new ArrayWrapper instance.
        /// </summary>
        /// <param name="wrappedInstance"> The array-like object that is being wrapped. </param>
        /// <param name="length"> The number of elements in the array. </param>
        protected ArrayAdapter(ObjectInstance wrappedInstance, int length)
        {
            this.wrappedInstance = wrappedInstance;
            this.length = length;
        }

        //     ABSTRACT OPERATIONS
        //_________________________________________________________________________________________

        /// <summary>
        /// The current scripting environment.
        /// </summary>
        public ScriptEngine Engine
        {
            get { return this.wrappedInstance.Engine; }
        }

        /// <summary>
        /// The array-like object that is being wrapped.
        /// </summary>
        public ObjectInstance WrappedInstance
        {
            get { return this.wrappedInstance; }
        }

        /// <summary>
        /// The number of elements in the array.
        /// </summary>
        public int Length
        {
            get { return this.length; }
        }

        /// <summary>
        /// Gets or sets an array element within the range 0 .. Length-1 (inclusive).
        /// </summary>
        /// <param name="index"> The index to get or set. </param>
        /// <returns> The value at the given index. </returns>
        public abstract T this[int index]
        {
            get;
            set;
        }

        /// <summary>
        /// Deletes the value at the given array index, throwing an exception on error.
        /// </summary>
        /// <param name="index"> The array index to delete. </param>
        public abstract void Delete(int index);

        /// <summary>
        /// Indicates whether the array index exists (has a value).
        /// </summary>
        /// <param name="index"> The index to check. </param>
        /// <returns> <c>true</c> if the index exists, <c>false</c> otherwise. </returns>
        public abstract bool HasProperty(int index);

        /// <summary>
        /// Creates a new array of the same type as this one.
        /// </summary>
        /// <param name="values"> The values in the new array. </param>
        /// <returns> A new array object. </returns>
        public abstract ObjectInstance ConstructArray(T[] values);

        /// <summary>
        /// Convert an untyped value to a typed value.
        /// </summary>
        /// <param name="value"> The value to convert. </param>
        /// <returns> The value converted to type <typeparamref name="T"/>. </returns>
        public abstract T ConvertValue(object value);

        //     JAVASCRIPT FUNCTIONS
        //_________________________________________________________________________________________

        /// <summary>
        /// Concatenates all the elements of the array, using the specified separator between each
        /// element.  If no separator is provided, a comma is used for this purpose.
        /// </summary>
        /// <param name="separator"> The string to use as a separator. </param>
        /// <returns> A string that consists of the element values separated by the separator string. </returns>
        public string Join(string separator)
        {
            var result = new System.Text.StringBuilder(Length * 2);
            for (int i = 0; i < Length; i++)
            {
                if (i > 0)
                    result.Append(separator);
                object element = this[i];
                if (element != null && element != Undefined.Value && element != Null.Value)
                    result.Append(TypeConverter.ToString(element));
            }
            return result.ToString();
        }

        /// <summary>
        /// Reverses the order of the elements in the array.
        /// </summary>
        /// <returns> The array that is being operated on. </returns>
        public ObjectInstance Reverse()
        {
            // Reverse each element.
            for (int lowIndex = 0; lowIndex < Length / 2; lowIndex++)
            {
                int highIndex = Length - lowIndex - 1;

                // Swap the two values.
                bool lowExists = HasProperty(lowIndex);
                T low = default;
                if (lowExists)
                    low = this[lowIndex];
                bool highExists = HasProperty(highIndex);
                T high = default;
                if (highExists)
                    high = this[highIndex];

                if (highExists)
                    this[lowIndex] = high;
                else
                    Delete(lowIndex);
                if (lowExists)
                    this[highIndex] = low;
                else
                    Delete(highIndex);
            }
            return WrappedInstance;
        }

        /// <summary>
        /// Returns a section of an array.
        /// </summary>
        /// <param name="start"> The index of the first element in the section.  If this value is
        /// negative it is treated as an offset from the end of the array. </param>
        /// <param name="end"> The index of the element just past the last element in the section.
        /// If this value is negative it is treated as an offset from the end of the array.  If
        /// <paramref name="end"/> is less than or equal to <paramref name="start"/> then an empty
        /// array is returned. </param>
        /// <returns> A section of an array. </returns>
        public ObjectInstance Slice(int start, int end)
        {
            // Fix the arguments so they are positive and within the bounds of the array.
            if (start < 0)
                start += Length;
            if (end < 0)
                end += Length;
            if (end <= start)
                return ConstructArray(new T[0]);
            start = Math.Min(Math.Max(start, 0), Length);
            end = Math.Min(Math.Max(end, 0), Length);

            // Populate a new array.
            var result = new T[end - start];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = this[start + i];
            }
            return ConstructArray(result);
        }

        /// <summary>
        /// Sorts the array.
        /// </summary>
        /// <param name="comparer"> A comparison function. </param>
        /// <returns> The array that was sorted. </returns>
        public ObjectInstance Sort(Comparison<T> comparer)
        {
            // An array of size 1 or less is already sorted.
            if (Length <= 1)
                return WrappedInstance;

            try
            {
                // Sort the array.
                QuickSort(comparer, 0, Length - 1);
            }
            catch (IndexOutOfRangeException)
            {
                throw new JavaScriptException(ErrorType.TypeError, "Invalid comparison function");
            }

            return WrappedInstance;
        }

        /// <summary>
        /// Returns a locale-specific string representing this object.
        /// </summary>
        /// <returns> A locale-specific string representing this object. </returns>
        public string ToLocaleString()
        {
            var result = new System.Text.StringBuilder(Length * 2);

            // Get the culture-specific list separator.
            var listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;

            try
            {

                for (int i = 0; i < Length; i++)
                {
                    // Append the localized list separator.
                    if (i > 0)
                        result.Append(listSeparator);

                    // Retrieve the array element.
                    object element = this[i];

                    // Convert the element to a string and append it to the result.
                    if (element != null && element != Undefined.Value && element != Null.Value)
                        result.Append(TypeConverter.ToObject(Engine, element).CallMemberFunction("toLocaleString"));
                }

            }
            catch (ArgumentOutOfRangeException)
            {
                throw new JavaScriptException(ErrorType.RangeError, "The array is too long");
            }

            return result.ToString();
        }

        /// <summary>
        /// Returns a string representing this object.
        /// </summary>
        /// <returns> A string representing this object. </returns>
        public override string ToString()
        {
            // Try calling WrappedInstance.join().
            object result;
            if (WrappedInstance.TryCallMemberFunction(out result, "join") == true)
                return TypeConverter.ToString(result);

            // Otherwise, use the default Object.prototype.toString() method.
            return ObjectInstance.ToStringJS(Engine, WrappedInstance);
        }

        //     JAVASCRIPT FUNCTIONS
        //_________________________________________________________________________________________

        /// <summary>
        /// Returns the index of the given search element in the array, starting from
        /// <paramref name="fromIndex"/>.
        /// </summary>
        /// <param name="searchElement"> The value to search for. </param>
        /// <param name="fromIndex"> The array index to start searching. </param>
        /// <returns> The index of the given search element in the array, or <c>-1</c> if the
        /// element wasn't found. </returns>
        public int IndexOf(object searchElement, int fromIndex)
        {
            // If fromIndex is less than zero, it is an offset from the end of the array.
            if (fromIndex < 0)
                fromIndex += Length;

            for (int i = Math.Max(fromIndex, 0); i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Compare the given search element with the array element.
                if (elementValue != null && TypeComparer.StrictEquals(searchElement, elementValue) == true)
                    return i;
            }

            // The search element wasn't found.
            return -1;
        }

        /// <summary>
        /// Returns the index of the given search element in the array, searching backwards from
        /// <paramref name="fromIndex"/>.
        /// </summary>
        /// <param name="searchElement"> The value to search for. </param>
        /// <param name="fromIndex"> The array index to start searching. </param>
        /// <returns> The index of the given search element in the array, or <c>-1</c> if the
        /// element wasn't found. </returns>
        public int LastIndexOf(object searchElement, int fromIndex)
        {
            // If fromIndex is less than zero, it is an offset from the end of the array.
            if (fromIndex < 0)
                fromIndex += Length;

            for (int i = Math.Min(Length - 1, fromIndex); i >= 0; i--)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Compare the given search element with the array element.
                if (elementValue != null && TypeComparer.StrictEquals(searchElement, elementValue) == true)
                    return i;
            }

            // The search element wasn't found.
            return -1;
        }

        /// <summary>
        /// Determines if every element of the array matches criteria defined by the given user-
        /// defined function.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on.  The function should
        /// return <c>true</c> or <c>false</c>. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> <c>true</c> if every element of the array matches criteria defined by the
        /// given user-defined function; <c>false</c> otherwise. </returns>
        public bool Every(FunctionInstance callbackFunction, ObjectInstance context)
        {
            for (int i = 0; i < Length; i ++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    if (TypeConverter.ToBoolean(callbackFunction.CallFromNative("every", context, elementValue, i, WrappedInstance)) == false)
                        return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Determines if at least one element of the array matches criteria defined by the given
        /// user-defined function.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on.  The function should
        /// return <c>true</c> or <c>false</c>. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> <c>true</c> if at least one element of the array matches criteria defined by
        /// the given user-defined function; <c>false</c> otherwise. </returns>
        public bool Some(FunctionInstance callbackFunction, ObjectInstance context)
        {
            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    if (TypeConverter.ToBoolean(callbackFunction.CallFromNative("some", context, elementValue, i, WrappedInstance)) == true)
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Calls the given user-defined function once per element in the array.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        public void ForEach(FunctionInstance callbackFunction, ObjectInstance context)
        {
            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    callbackFunction.CallFromNative("forEach", context, elementValue, i, WrappedInstance);
                }
            }
        }

        /// <summary>
        /// Creates a new array with the results of calling the given function on every element in
        /// this array.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element
        /// in the array.  This function is called with three arguments: the value of the element,
        /// the index of the element, and the array that is being operated on.  The value that is
        /// returned from this function is stored in the resulting array. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> A new array with the results of calling the given function on every element
        /// in the array. </returns>
        public ObjectInstance Map(FunctionInstance callbackFunction, ObjectInstance context)
        {
            // Create a new array to hold the new values.
            // The length of the output array is always equal to the length of the input array.
            var resultArray = new T[Length];

            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    object result = callbackFunction.CallFromNative("map", context, elementValue, i, WrappedInstance);

                    // Store the result.
                    resultArray[i] = ConvertValue(result);
                }
            }

            return ConstructArray(resultArray);
        }

        /// <summary>
        /// Returns the first element in the given array that passes the test implemented by the
        /// given function.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on.  The function should
        /// return <c>true</c> or <c>false</c>. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> The first element that results in the callback returning <c>true</c>. </returns>
        public object Find(FunctionInstance callbackFunction, ObjectInstance context)
        {
            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    bool result = TypeConverter.ToBoolean(callbackFunction.CallFromNative("find", context, elementValue, i, WrappedInstance));

                    // Return if the result was true.
                    if (result == true)
                        return elementValue;
                }
            }

            // No matches, return undefined.
            return Undefined.Value;
        }

        /// <summary>
        /// Creates a new array with the elements from this array that pass the test implemented by
        /// the given function.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on.  The function should
        /// return <c>true</c> or <c>false</c>. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> A copy of this array but with only those elements which produce <c>true</c>
        /// when passed to the provided function. </returns>
        public ObjectInstance Filter(FunctionInstance callbackFunction, ObjectInstance context)
        {
            // Create a new array to hold the new values.
            var result = new List<T>(Length / 2);

            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                T elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    bool includeInArray = TypeConverter.ToBoolean(callbackFunction.CallFromNative("filter", context, elementValue, i, WrappedInstance));

                    // Store the result if the callback function returned true.
                    if (includeInArray == true)
                        result.Add(elementValue);
                }
            }
            return ConstructArray(result.ToArray());
        }

        /// <summary>
        /// Accumulates a single value by calling a user-defined function for each element.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element
        /// in the array.  This function is called with four arguments: the current accumulated
        /// value, the value of the element, the index of the element, and the array that is being
        /// operated on.  The return value for this function is the new accumulated value and is
        /// passed to the next invocation of the function. </param>
        /// <param name="initialValue"> The initial accumulated value. </param>
        /// <returns> The accumulated value returned from the last invocation of the callback
        /// function. </returns>
        public object Reduce(FunctionInstance callbackFunction, object initialValue)
        {
            // If an initial value is not provided, the initial value is the first (defined) element.
            int i = 0;
            object accumulatedValue = initialValue;
            if (accumulatedValue == null)
            {
                // Scan for a defined element.
                for (; i < Length; i++)
                {
                    if (this[i] != null)
                    {
                        accumulatedValue = this[i++];
                        break;
                    }
                }
                if (accumulatedValue == null)
                    throw new JavaScriptException(ErrorType.TypeError, "Reduce of empty array with no initial value");
            }

            // Scan from low to high.
            for (; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    accumulatedValue = callbackFunction.CallFromNative("reduce", Undefined.Value, accumulatedValue, elementValue, i, WrappedInstance);
                }
            }

            return accumulatedValue;
        }

        /// <summary>
        /// Accumulates a single value by calling a user-defined function for each element
        /// (starting with the last element in the array).
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element
        /// in the array.  This function is called with four arguments: the current accumulated
        /// value, the value of the element, the index of the element, and the array that is being
        /// operated on.  The return value for this function is the new accumulated value and is
        /// passed to the next invocation of the function. </param>
        /// <param name="initialValue"> The initial accumulated value. </param>
        /// <returns> The accumulated value returned from the last invocation of the callback
        /// function. </returns>
        public object ReduceRight(FunctionInstance callbackFunction, object initialValue)
        {
            // If an initial value is not provided, the initial value is the last (defined) element.
            int i = Length - 1;
            object accumulatedValue = initialValue;
            if (accumulatedValue == null)
            {
                // Scan for a defined element.
                for (; i >= 0; i--)
                {
                    if (this[i] != null)
                    {
                        accumulatedValue = this[i--];
                        break;
                    }
                }
                if (accumulatedValue == null)
                    throw new JavaScriptException(ErrorType.TypeError, "Reduce of empty array with no initial value");
            }

            // Scan from high to to low.
            for (; i >= 0; i--)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    accumulatedValue = callbackFunction.CallFromNative("reduceRight", Undefined.Value, accumulatedValue, elementValue, i, WrappedInstance);
                }
            }

            return accumulatedValue;
        }

        /// <summary>
        /// Copies the sequence of array elements within the array to the position starting at
        /// target. The copy is taken from the index positions of the second and third arguments
        /// start and end. The end argument is optional and defaults to the length of the array.
        /// This method has the same algorithm as Array.prototype.copyWithin.
        /// </summary>
        /// <param name="target"> Target start index position where to copy the elements to. </param>
        /// <param name="start"> Source start index position where to start copying elements from. </param>
        /// <param name="end"> Optional. Source end index position where to end copying elements from. </param>
        /// <returns> The array that is being operated on. </returns>
        public ObjectInstance CopyWithin(int target, int start, int end)
        {
            // Negative values represent offsets from the end of the array.
            target = target < 0 ? Math.Max(Length + target, 0) : Math.Min(target, Length);
            start = start < 0 ? Math.Max(Length + start, 0) : Math.Min(start, Length);
            end = end < 0 ? Math.Max(Length + end, 0) : Math.Min(end, Length);

            // Calculate the number of values to copy.
            int count = Math.Min(end - start, Length - target);

            // Check if we need to copy in reverse due to an overlap.
            int direction = 1;
            if (start < target && target < start + count)
            {
                direction = -1;
                start += count - 1;
                target += count - 1;
            }

            while (count > 0)
            {
                // Get the value of the array element.
                T elementValue = this[start];

                if (elementValue != null)
                {
                    // Copy the value to the new position.
                    this[target] = elementValue;
                }
                else
                {
                    // Delete the element at the new position.
                    Delete(target);
                }

                // Progress to the next element.
                start += direction;
                target += direction;
                count--;
            }

            return WrappedInstance;
        }

        /// <summary>
        /// Fills all the elements of a typed array from a start index to an end index with a
        /// static value.
        /// </summary>
        /// <param name="value"> The value to fill the typed array with. </param>
        /// <param name="start"> Optional. Start index. Defaults to 0. </param>
        /// <param name="end"> Optional. End index (exclusive). Defaults to the length of the array. </param>
        /// <returns> The array that is being operated on. </returns>
        public ObjectInstance Fill(T value, int start, int end)
        {
            // Negative values represent offsets from the end of the array.
            start = start < 0 ? Math.Max(Length + start, 0) : Math.Min(start, Length);
            end = end < 0 ? Math.Max(Length + end, 0) : Math.Min(end, Length);

            for (; start < end; start ++)
            {
                this[start] = value;
            }

            return WrappedInstance;
        }

        /// <summary>
        /// Returns an index in the typed array, if an element in the typed array satisfies the
        /// provided testing function. Otherwise -1 is returned.
        /// </summary>
        /// <param name="callbackFunction"> A user-defined function that is called for each element in the
        /// array.  This function is called with three arguments: the value of the element, the
        /// index of the element, and the array that is being operated on.  The function should
        /// return <c>true</c> or <c>false</c>. </param>
        /// <param name="context"> The value of <c>this</c> in the context of the callback function. </param>
        /// <returns> The first element that results in the callback returning <c>true</c>. </returns>
        public int FindIndex(FunctionInstance callbackFunction, ObjectInstance context)
        {
            for (int i = 0; i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Only call the callback function for array elements that exist in the array.
                if (elementValue != null)
                {
                    // Call the callback function.
                    bool result = TypeConverter.ToBoolean(callbackFunction.CallFromNative("findIndex", context, elementValue, i, WrappedInstance));

                    // Return if the result was true.
                    if (result == true)
                        return i;
                }
            }

            // No matches, return undefined.
            return -1;
        }

        /// <summary>
        /// Determines whether an array includes a certain value among its entries.
        /// </summary>
        /// <param name="searchElement"> The value to search for. </param>
        /// <param name="fromIndex"> The array index to start searching. </param>
        /// <returns> <c>true</c> given search element in the array, or <c>false</c> if the element
        /// wasn't found. </returns>
        public bool Includes(object searchElement, int fromIndex)
        {
            // If fromIndex is less than zero, it is an offset from the end of the array.
            if (fromIndex < 0)
                fromIndex += Length;

            for (int i = Math.Max(fromIndex, 0); i < Length; i++)
            {
                // Get the value of the array element.
                object elementValue = this[i];

                // Compare the given search element with the array element.
                if (TypeComparer.SameValueZero(searchElement, elementValue) == true)
                    return true;
            }

            // The search element wasn't found.
            return false;
        }

        //     PRIVATE IMPLEMENTATION METHODS
        //_________________________________________________________________________________________

        /// <summary>
        /// Sorts a array using the quicksort algorithm.
        /// </summary>
        /// <param name="comparer"> A comparison function. </param>
        /// <param name="start"> The first index in the range. </param>
        /// <param name="end"> The last index in the range. </param>
        private void QuickSort(Comparison<T> comparer, int start, int end)
        {
            if (end - start < 30)
            {
                // Insertion sort is faster than quick sort for small arrays.
                InsertionSort(comparer, start, end);
                return;
            }

            // Choose a random pivot.
            int pivotIndex = start + (int)(MathObject.Random() * (end - start));

            // Get the pivot value.
            T pivotValue = this[pivotIndex];

            // Send the pivot to the back.
            Swap(pivotIndex, end);

            // Sweep all the low values to the front of the array and the high values to the back
            // of the array.  This version of quicksort never gets into an infinite loop even if
            // the comparer function is not consistent.
            int newPivotIndex = start;
            for (int i = start; i < end; i++)
            {
                if (comparer(this[i], pivotValue) <= 0)
                {
                    Swap(i, newPivotIndex);
                    newPivotIndex++;
                }
            }

            // Swap the pivot back to where it belongs.
            Swap(end, newPivotIndex);

            // Quick sort the array to the left of the pivot.
            if (newPivotIndex > start)
                QuickSort(comparer, start, newPivotIndex - 1);

            // Quick sort the array to the right of the pivot.
            if (newPivotIndex < end)
                QuickSort(comparer, newPivotIndex + 1, end);
        }

        /// <summary>
        /// Sorts a array using the insertion sort algorithm.
        /// </summary>
        /// <param name="comparer"> A comparison function. </param>
        /// <param name="start"> The first index in the range. </param>
        /// <param name="end"> The last index in the range. </param>
        private void InsertionSort(Comparison<T> comparer, int start, int end)
        {
            for (int i = start + 1; i <= end; i++)
            {
                T value = this[i];
                int j;
                for (j = i - 1; j > start && comparer(this[j], value) > 0; j--)
                    this[j + 1] = this[j];

                // Normally the for loop above would continue until j < start but since we are
                // using uint it doesn't work when start == 0.  Therefore the for loop stops one
                // short of start then the extra loop iteration runs below.
                if (j == start && comparer(this[j], value) > 0)
                {
                    this[j + 1] = this[j];
                    j--;
                }

                this[j + 1] = value;
            }
        }

        /// <summary>
        /// Swaps the elements at two locations in the array.
        /// </summary>
        /// <param name="index1"> The location of the first element. </param>
        /// <param name="index2"> The location of the second element. </param>
        private void Swap(int index1, int index2)
        {
            T temp = this[index1];
            this[index1] = this[index2];
            this[index2] = temp;
        }
    }
}


text:
(function( window, undefined ) {

// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
	navigator = window.navigator,
	location = window.location;
var jQuery = (function() {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// A central reference to the root jQuery(document)
	rootjQuery,

	// A simple way to check for HTML strings or ID strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

	// Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,

	// Used for trimming whitespace
	trimLeft = /^\s+/,
	trimRight = /\s+$/,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

	// Useragent RegExp
	rwebkit = /(webkit)[ \/]([\w.]+)/,
	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
	rmsie = /(msie) ([\w.]+)/,
	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,

	// Matches dashed string for camelizing
	rdashAlpha = /-([a-z]|[0-9])/ig,
	rmsPrefix = /^-ms-/,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return ( letter + "" ).toUpperCase();
	},

	// Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,

	// For matching the engine and version of the browser
	browserMatch,

	// The deferred used on DOM ready
	readyList,

	// The ready event handler
	DOMContentLoaded,

	// Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwn = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	trim = String.prototype.trim,
	indexOf = Array.prototype.indexOf,

	// [[Class]] -> type pairs
	class2type = {};

jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem, ret, doc;

		// Handle $(""), $(null), or $(undefined)
		if ( !selector ) {
			return this;
		}

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}

		// The body element only exists once, optimize finding it
		if ( selector === "body" && !context && document.body ) {
			this.context = document;
			this[0] = document.body;
			this.selector = selector;
			this.length = 1;
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = quickExpr.exec( selector );
			}

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;
					doc = ( context ? context.ownerDocument || context : document );

					// If a single string is passed in and it's a single tag
					// just do a createElement and skip the rest
					ret = rsingleTag.exec( selector );

					if ( ret ) {
						if ( jQuery.isPlainObject( context ) ) {
							selector = [ document.createElement( ret[1] ) ];
							jQuery.fn.attr.call( selector, context, true );

						} else {
							selector = [ doc.createElement( ret[1] ) ];
						}

					} else {
						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
						selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
					}

					return jQuery.merge( this, selector );

				// HANDLE: $("#id")
				} else {
					elem = document.getElementById( match[2] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || rootjQuery ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.7.1",

	// The default length of a jQuery object is 0
	length: 0,

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	toArray: function() {
		return slice.call( this, 0 );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = this.constructor();

		if ( jQuery.isArray( elems ) ) {
			push.apply( ret, elems );

		} else {
			jQuery.merge( ret, elems );
		}

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" ) {
			ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
		} else if ( name ) {
			ret.selector = this.selector + "." + name + "(" + selector + ")";
		}

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	ready: function( fn ) {
		// Attach the listeners
		jQuery.bindReady();

		// Add the callback
		readyList.add( fn );

		return this;
	},

	eq: function( i ) {
		i = +i;
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, i + 1 );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ),
			"slice", slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},

	end: function() {
		return this.prevObject || this.constructor(null);
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: [].sort,
	splice: [].splice
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function( deep ) {
		if ( window.$ === jQuery ) {
			window.$ = _$;
		}

		if ( deep && window.jQuery === jQuery ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {
		// Either a released hold or an DOMready/load event and not yet ready
		if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
			if ( !document.body ) {
				return setTimeout( jQuery.ready, 1 );
			}

			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If a normal DOM Ready event fired, decrement, and wait if need be
			if ( wait !== true && --jQuery.readyWait > 0 ) {
				return;
			}

			// If there are functions bound, to execute
			readyList.fireWith( document, [ jQuery ] );

			// Trigger any bound ready events
			if ( jQuery.fn.trigger ) {
				jQuery( document ).trigger( "ready" ).off( "ready" );
			}
		}
	},

	bindReady: function() {
		if ( readyList ) {
			return;
		}

		readyList = jQuery.Callbacks( "once memory" );

		// Catch cases where $(document).ready() is called after the
		// browser event has already occurred.
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			return setTimeout( jQuery.ready, 1 );
		}

		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );

		// If IE event model is used
		} else if ( document.attachEvent ) {
			// ensure firing before onload,
			// maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", DOMContentLoaded );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );

			// If IE and not a frame
			// continually check to see if the document is ready
			var toplevel = false;

			try {
				toplevel = window.frameElement == null;
			} catch(e) {}

			if ( document.documentElement.doScroll && toplevel ) {
				doScrollCheck();
			}
		}
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	// A crude way of determining if an object is a window
	isWindow: function( obj ) {
		return obj && typeof obj === "object" && "setInterval" in obj;
	},

	isNumeric: function( obj ) {
		return !isNaN( parseFloat(obj) ) && isFinite( obj );
	},

	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	},

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {
			// Not own constructor property must be Object
			if ( obj.constructor &&
				!hasOwn.call(obj, "constructor") &&
				!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
				return false;
			}
		} catch ( e ) {
			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.

		var key;
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		for ( var name in obj ) {
			return false;
		}
		return true;
	},

	error: function( msg ) {
		throw new Error( msg );
	},

	parseJSON: function( data ) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );

		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
			.replace( rvalidtokens, "]" )
			.replace( rvalidbraces, "")) ) {

			return ( new Function( "return " + data ) )();

		}
		jQuery.error( "Invalid JSON: " + data );
	},

	// Cross-browser xml parsing
	parseXML: function( data ) {
		var xml, tmp;
		try {
			if ( window.DOMParser ) { // Standard
				tmp = new DOMParser();
				xml = tmp.parseFromString( data , "text/xml" );
			} else { // IE
				xml = new ActiveXObject( "Microsoft.XMLDOM" );
				xml.async = "false";
				xml.loadXML( data );
			}
		} catch( e ) {
			xml = undefined;
		}
		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
			jQuery.error( "Invalid XML: " + data );
		}
		return xml;
	},

	noop: function() {},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && rnotwhite.test( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = length === undefined || jQuery.isFunction( object );

		if ( args ) {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.apply( object[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( object[ i++ ], args ) === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
						break;
					}
				}
			}
		}

		return object;
	},

	// Use native String.trim function wherever possible
	trim: trim ?
		function( text ) {
			return text == null ?
				"" :
				trim.call( text );
		} :

		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
		},

	// results is for internal usage only
	makeArray: function( array, results ) {
		var ret = results || [];

		if ( array != null ) {
			// The window, strings (and functions) also have 'length'
			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
			var type = jQuery.type( array );

			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
				push.call( ret, array );
			} else {
				jQuery.merge( ret, array );
			}
		}

		return ret;
	},

	inArray: function( elem, array, i ) {
		var len;

		if ( array ) {
			if ( indexOf ) {
				return indexOf.call( array, elem, i );
			}

			len = array.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {
				// Skip accessing in sparse arrays
				if ( i in array && array[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var i = first.length,
			j = 0;

		if ( typeof second.length === "number" ) {
			for ( var l = second.length; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}

		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, inv ) {
		var ret = [], retVal;
		inv = !!inv;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var value, key, ret = [],
			i = 0,
			length = elems.length,
			// jquery objects are treated as arrays
			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( key in elems ) {
				value = callback( elems[ key ], key, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		if ( typeof context === "string" ) {
			var tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		var args = slice.call( arguments, 2 ),
			proxy = function() {
				return fn.apply( context, args.concat( slice.call( arguments ) ) );
			};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

		return proxy;
	},

	// Mutifunctional method to get and set values to a collection
	// The value/s can optionally be executed if it's a function
	access: function( elems, key, value, exec, fn, pass ) {
		var length = elems.length;

		// Setting many attributes
		if ( typeof key === "object" ) {
			for ( var k in key ) {
				jQuery.access( elems, k, key[k], exec, fn, value );
			}
			return elems;
		}

		// Setting one attribute
		if ( value !== undefined ) {
			// Optionally, function values get executed if exec is true
			exec = !pass && exec && jQuery.isFunction(value);

			for ( var i = 0; i < length; i++ ) {
				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
			}

			return elems;
		}

		// Getting an attribute
		return length ? fn( elems[0], key ) : undefined;
	},

	now: function() {
		return ( new Date() ).getTime();
	},

	// Use of jQuery.browser is frowned upon.
	// More details: http://docs.jquery.com/Utilities/jQuery.browser
	uaMatch: function( ua ) {
		ua = ua.toLowerCase();

		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},

	sub: function() {
		function jQuerySub( selector, context ) {
			return new jQuerySub.fn.init( selector, context );
		}
		jQuery.extend( true, jQuerySub, this );
		jQuerySub.superclass = this;
		jQuerySub.fn = jQuerySub.prototype = this();
		jQuerySub.fn.constructor = jQuerySub;
		jQuerySub.sub = this.sub;
		jQuerySub.fn.init = function init( selector, context ) {
			if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
				context = jQuerySub( context );
			}

			return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
		};
		jQuerySub.fn.init.prototype = jQuerySub.fn;
		var rootjQuerySub = jQuerySub(document);
		return jQuerySub;
	},

	browser: {}
});

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
	jQuery.browser[ browserMatch.browser ] = true;
	jQuery.browser.version = browserMatch.version;
}

// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
	jQuery.browser.safari = true;
}

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
	trimLeft = /^[\s\xA0]+/;
	trimRight = /[\s\xA0]+$/;
}

// All jQuery objects should point back to these
rootjQuery = jQuery(document);

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		jQuery.ready();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	};
}

// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( jQuery.isReady ) {
		return;
	}

	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch(e) {
		setTimeout( doScrollCheck, 1 );
		return;
	}

	// and execute any waiting functions
	jQuery.ready();
}

return jQuery;

})();

// String to Object flags format cache
var flagsCache = {};

// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
	var object = flagsCache[ flags ] = {},
		i, length;
	flags = flags.split( /\s+/ );
	for ( i = 0, length = flags.length; i < length; i++ ) {
		object[ flags[i] ] = true;
	}
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	flags:	an optional list of space-separated flags that will change how
 *			the callback list behaves
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible flags:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( flags ) {

	// Convert flags from String-formatted to Object-formatted
	// (we check in cache first)
	flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};

	var // Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = [],
		// Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list is currently firing
		firing,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// Add one or several callbacks to the list
		add = function( args ) {
			var i,
				length,
				elem,
				type,
				actual;
			for ( i = 0, length = args.length; i < length; i++ ) {
				elem = args[ i ];
				type = jQuery.type( elem );
				if ( type === "array" ) {
					// Inspect recursively
					add( elem );
				} else if ( type === "function" ) {
					// Add if not in unique mode and callback is not in
					if ( !flags.unique || !self.has( elem ) ) {
						list.push( elem );
					}
				}
			}
		},
		// Fire callbacks
		fire = function( context, args ) {
			args = args || [];
			memory = !flags.memory || [ context, args ];
			firing = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
					memory = true; // Mark as halted
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( !flags.once ) {
					if ( stack && stack.length ) {
						memory = stack.shift();
						self.fireWith( memory[ 0 ], memory[ 1 ] );
					}
				} else if ( memory === true ) {
					self.disable();
				} else {
					list = [];
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					var length = list.len

redpajama_set_name: RedPajamaGithub


text:
KUBE_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${KUBE_ROOT}/hack/lib/init.sh"

focus=${FOCUS:-""}
skip=${SKIP:-""}
# The number of tests that can run in parallel depends on what tests
# are running and on the size of the node. Too many, and tests will
# fail due to resource contention. 8 is a reasonable default for a
# n1-standard-1 node.
# Currently, parallelism only affects when REMOTE=true. For local test,
# ginkgo default parallelism (cores - 1) is used.
parallelism=${PARALLELISM:-8}
report=${REPORT:-"/tmp/"}
artifacts=${ARTIFACTS:-"/tmp/_artifacts"}
remote=${REMOTE:-"false"}
images=${IMAGES:-""}
hosts=${HOSTS:-""}
metadata=${INSTANCE_METADATA:-""}
gubernator=${GUBERNATOR:-"false"}
if [[ $hosts == "" && $images == "" ]]; then
  gci_image=$(gcloud compute images list --project google-containers \
    --no-standard-images --regexp="gci-dev.*" --format="table[no-heading](name)")
  images=$gci_image
  metadata="user-data<${KUBE_ROOT}/test/e2e_node/jenkins/gci-init.yaml"
fi
image_project=${IMAGE_PROJECT:-"google-containers"}
instance_prefix=${INSTANCE_PREFIX:-"test"}
cleanup=${CLEANUP:-"true"}
delete_instances=${DELETE_INSTANCES:-"false"}
run_until_failure=${RUN_UNTIL_FAILURE:-"false"}
list_images=${LIST_IMAGES:-"false"}
test_args=${TEST_ARGS:-""}

if  [[ $list_images == "true" ]]; then
  gcloud compute images list --project="${image_project}" | grep "e2e-node"
  exit 0
fi

# Parse the flags to pass to ginkgo
ginkgoflags=""
if [[ $parallelism > 1 ]]; then
  ginkgoflags="$ginkgoflags -nodes=$parallelism "
fi

if [[ $focus != "" ]]; then
  ginkgoflags="$ginkgoflags -focus=$focus "
fi

if [[ $skip != "" ]]; then
  ginkgoflags="$ginkgoflags -skip=$skip "
fi

if [[ $run_until_failure != "" ]]; then
  ginkgoflags="$ginkgoflags -untilItFails=$run_until_failure "
fi

if [ $remote = true ] ; then
  # Setup the directory to copy test artifacts (logs, junit.xml, etc) from remote host to local host
  if [[ $gubernator = true && -d "${artifacts}" ]]; then
    echo "Removing artifacts directory at ${artifacts}"
    rm -r ${artifacts}
  fi

  if [ ! -d "${artifacts}" ]; then
    echo "Creating artifacts directory at ${artifacts}"
    mkdir -p ${artifacts}
  fi
  echo "Test artifacts will be written to ${artifacts}"

  # Get the compute zone
  zone=$(gcloud info --format='value(config.properties.compute.zone)')
  if [[ $zone == "" ]]; then
    echo "Could not find gcloud compute/zone when running:\ngcloud info --format='value(config.properties.compute.zone)'"
    exit 1
  fi

  # Get the compute project
  project=$(gcloud info --format='value(config.project)')
  if [[ $project == "" ]]; then
    echo "Could not find gcloud project when running:\ngcloud info --format='value(config.project)'"
    exit 1
  fi

  # Check if any of the images specified already have running instances.  If so reuse those instances
  # by moving the IMAGE to a HOST
  if [[ $images != "" ]]; then
  IFS=',' read -ra IM <<< "$images"
       images=""
       for i in "${IM[@]}"; do
         if [[ $(gcloud compute instances list "${instance_prefix}-$i" | grep $i) ]]; then
           if [[ $hosts != "" ]]; then
             hosts="$hosts,"
           fi
           echo "Reusing host ${instance_prefix}-$i"
           hosts="${hosts}${instance_prefix}-${i}"
         else
           if [[ $images != "" ]]; then
             images="$images,"
           fi
           images="$images$i"
         fi
       done
  fi

  # Output the configuration we will try to run
  echo "Running tests remotely using"
  echo "Project: $project"
  echo "Image Project: $image_project"
  echo "Compute/Zone: $zone"
  echo "Images: $images"
  echo "Hosts: $hosts"
  echo "Ginkgo Flags: $ginkgoflags"
  echo "Instance Metadata: $metadata"
  # Invoke the runner
  go run test/e2e_node/runner/remote/run_remote.go  --logtostderr --vmodule=*=4 --ssh-env="gce" \
    --zone="$zone" --project="$project" --gubernator="$gubernator" \
    --hosts="$hosts" --images="$images" --cleanup="$cleanup" \
    --results-dir="$artifacts" --ginkgo-flags="$ginkgoflags" \
    --image-project="$image_project" --instance-name-prefix="$instance_prefix" --setup-node="true" \
    --delete-instances="$delete_instances" --test_args="$test_args" --instance-metadata="$metadata" \
    2>&1 | tee "${artifacts}/build-log.txt"
  exit $?

else
  # Refresh sudo credentials if not running on GCE.
  if ! ping -c 1 -q metadata.google.internal &> /dev/null; then
    sudo -v || exit 1
  fi

  # If the flag --disable-kubenet is not set, set true by default.
  if ! [[ $test_args =~ "--disable-kubenet" ]]; then
    test_args="$test_args --disable-kubenet=true"
  fi

  # On selinux enabled systems, it might
  # require to relabel /var/lib/kubelet
  if which selinuxenabled &> /dev/null && \
     selinuxenabled && \
     which chcon > /dev/null ; then
     mkdir -p /var/lib/kubelet
     if [[ ! $(ls -Zd /var/lib/kubelet) =~ svirt_sandbox_file_t ]] ; then
        echo "Applying SELinux label to /var/lib/kubelet directory."
        if ! sudo chcon -Rt svirt_sandbox_file_t /var/lib/kubelet; then
           echo "Failed to apply selinux label to /var/lib/kubelet."
        fi
     fi
  fi

  # Test using the host the script was run on
  # Provided for backwards compatibility
  go run test/e2e_node/runner/local/run_local.go --ginkgo-flags="$ginkgoflags" \
    --test-flags="--alsologtostderr --v 2 --report-dir=${report} --node-name $(hostname) \
    --start-services=true --stop-services=true $test_args" --build-dependencies=true
  exit $?
fi


text:
@interface UIImage (RenderedImage)

+ (UIImage *)imageWithRenderColor:(UIColor *)color renderSize:(CGSize)size;
@end


text:
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
require 'net/http'
require 'socket'
require 'csv'
require 'uri'

class CheckHAProxy < Sensu::Plugin::Check::CLI
  option :stats_source,
         short: '-S HOSTNAME|SOCKETPATH',
         long: '--stats HOSTNAME|SOCKETPATH',
         description: 'HAproxy web stats hostname or path to stats socket',
         required: true
  option :port,
         short: '-P PORT',
         long: '--port PORT',
         description: 'HAproxy web stats port',
         default: '80'
  option :path,
         short: '-q STATUSPATH',
         long: '--statspath STATUSPATH',
         description: 'HAproxy web stats path',
         default: '/'
  option :username,
         short: '-u USERNAME',
         long: '--user USERNAME',
         description: 'HAproxy web stats username'
  option :password,
         short: '-p PASSWORD',
         long: '--pass PASSWORD',
         description: 'HAproxy web stats password'
  option :warn_percent,
         short: '-w PERCENT',
         boolean: true,
         default: 50,
         proc: proc(&:to_i),
         description: 'Warning Percent, default: 50'
  option :crit_percent,
         short: '-c PERCENT',
         boolean: true,
         default: 25,
         proc: proc(&:to_i),
         description: 'Critical Percent, default: 25'
  option :session_warn_percent,
         short: '-W PERCENT',
         boolean: true,
         default: 75,
         proc: proc(&:to_i),
         description: 'Session Limit Warning Percent, default: 75'
  option :session_crit_percent,
         short: '-C PERCENT',
         boolean: true,
         default: 90,
         proc: proc(&:to_i),
         description: 'Session Limit Critical Percent, default: 90'
  option :all_services,
         short: '-A',
         boolean: true,
         description: 'Check ALL Services, flag enables'
  option :missing_ok,
         short: '-m',
         boolean: true,
         description: 'Missing OK, flag enables'
  option :service,
         short: '-s SVC',
         description: 'Service Name to Check'
  option :exact_match,
         short: '-e',
         boolean: false,
         description: 'Whether service name specified with -s should be exact match or not'

  def run
    if config[:service] || config[:all_services]
      services = acquire_services
    else
      unknown 'No service specified'
    end

    if services.empty?
      message "No services matching /#{config[:service]}/"
      if config[:missing_ok]
        ok
      else
        warning
      end
    else
      percent_up = 100 * services.count { |svc| svc[:status] == 'UP' || svc[:status] == 'OPEN' } / services.size
      failed_names = services.reject { |svc| svc[:status] == 'UP' || svc[:status] == 'OPEN' }.map { |svc| svc[:svname] }
      critical_sessions = services.select { |svc| svc[:slim].to_i > 0 && (100 * svc[:scur].to_f / svc[:slim].to_f) > config[:session_crit_percent] }
      warning_sessions = services.select { |svc| svc[:slim].to_i > 0 && (100 * svc[:scur].to_f / svc[:slim].to_f) > config[:session_warn_percent] }

      status = "UP: #{percent_up}% of #{services.size} /#{config[:service]}/ services" + (failed_names.empty? ? '' : ", DOWN: #{failed_names.join(', ')}")
      if percent_up < config[:crit_percent]
        critical status
      elsif !critical_sessions.empty?
        critical status + '; Active sessions critical: ' + critical_sessions.map { |s| "#{s[:scur]} #{s[:pxname]}.#{s[:svname]}" }.join(', ')
      elsif percent_up < config[:warn_percent]
        warning status
      elsif !warning_sessions.empty?
        warning status + '; Active sessions warning: ' + warning_sessions.map { |s| "#{s[:scur]} #{s[:pxname]}.#{s[:svname]}" }.join(', ')
      else
        ok status
      end
    end
  end

  def acquire_services
    uri = URI.parse(config[:stats_source])

    if uri.is_a?(URI::Generic) && File.socket?(uri.path)
      srv = UNIXSocket.open(config[:stats_source])
      srv.write("show stat\n")
      out = srv.read
      srv.close
    else
      res = Net::HTTP.start(config[:stats_source], config[:port]) do |http|
        req = Net::HTTP::Get.new("/#{config[:path]};csv;norefresh")
        unless config[:username].nil?
          req.basic_auth config[:username], config[:password]
        end
        http.request(req)
      end
      unless res.code.to_i == 200
        unknown "Failed to fetch from #{config[:stats_source]}:#{config[:port]}/#{config[:path]}: #{res.code}"
      end

      out = res.body
    end

    parsed = CSV.parse(out, skip_blanks: true)
    keys = parsed.shift.reject(&:nil?).map { |k| k.match(/(\w+)/)[0].to_sym }
    haproxy_stats = parsed.map { |line| Hash[keys.zip(line)] }

    if config[:all_services]
      haproxy_stats
    else
      regexp = config[:exact_match] ? Regexp.new("^#{config[:service]}$") : Regexp.new(config[:service].to_s)
      haproxy_stats.select do |svc|
        svc[:pxname] =~ regexp
        # #YELLOW
      end.reject do |svc| # rubocop: disable MultilineBlockChain
        %w(FRONTEND BACKEND).include?(svc[:svname])
      end
    end
  end
end


text:
<?xml version="1.0"?>
<package>
  <name>ieee2016_controller</name>
  <version>0.0.0</version>
  <description>Controllers for Maverick</description>

  <maintainer email="lbassettaudain@ufl.edu">Lucas Bassett-Audain</maintainer>

  <license>GPLv2</license>
  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>rospy</build_depend>
  <build_depend>std_msgs</build_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>rospy</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>message_runtime</run_depend>
  <export>
  </export>
</package>


text:
title: Crate.IO Newsletter
description:  Subscribe to our monthly newsletter announcing new features, events, and Crate community news.

{% extends "base.html" %}

{% block header %}

Crate.IO Newsletter

Subscribe to our monthly newsletter announcing new features, events, and Crate community news.

{% endblock %}

{% block body %}

      {% include "mailchimp-large.html" %}

Recent Blog Posts

Read the latest news on our blog.

        {% for post in posts|slice:":3" %}

{{ post.title }}
{{ post.date|date }}

Read »

        {% endfor %}

{% endblock %}


text:
typedef int (*qu_var_resolver)(struct qu_var_frame *frame,
    const char *name, int nlen,
    const char **result, int *rlen);

struct qu_variable {
    struct qu_variable *left;
    struct qu_variable *right;
    char *name;
    int name_len;
    char *value;
    int value_len;
};

struct qu_var_frame {
    qu_var_resolver resolver;
    struct qu_var_frame *parent;
};

struct qu_var_frame_tree {
    struct qu_var_frame frame;
    struct qu_variable *vars;
};

struct qu_var_frame_anchors {
    struct qu_var_frame frame;
    struct qu_parser *ctx;
};

struct qu_var_frame_node {
    struct qu_var_frame frame;
    qu_ast_node *node;
};

static int qu_string_var(struct qu_var_frame *frame,
    const char *name, int name_len, const char **data, int *dlen);

static struct qu_variable **qu_var_find(struct qu_var_frame *frame,
    const char *name, int nlen)
{
    assert(frame->resolver == qu_string_var);
    struct qu_variable **node = &((struct qu_var_frame_tree *)frame)->vars;
    while(*node) {
        int cmp = memcmp((*node)->name, name, min((*node)->name_len, nlen));
        if(!cmp && (*node)->name_len != nlen)
            cmp = (*node)->name_len > nlen ? 1 : -1;
        if(!cmp)
            return node;
        if(cmp < 0)
            node = &(*node)->left;
        if(cmp > 0)
            node = &(*node)->right;
    }
    return node;
}

static int qu_string_var(struct qu_var_frame *frame,
    const char *name, int name_len, const char **data, int *dlen)
{
    struct qu_variable **ptr = qu_var_find(frame, name, name_len);
    if(*ptr) {
        *data = (*ptr)->value;
        *dlen = (*ptr)->value_len;
        return 1;
    }
    return 0;
}

void qu_var_set_string(struct obstack *buf, struct qu_var_frame *frame,
    const char *name, int nlen, const char *data, int dlen)
{
    struct qu_variable **var = qu_var_find(frame, name, nlen);
    struct qu_variable *v = *var;
    if(!v) {
        *var = v = obstack_alloc(buf, sizeof(struct qu_variable));
        v->left = NULL;
        v->right = NULL;
        v->name_len = nlen;
        v->name = obstack_copy0(buf, name, nlen);
    }
    v->value = obstack_copy0(buf, data, dlen);
    v->value_len = dlen;
}

static int qu_anchor_var(struct qu_var_frame *frame, const char *name, int nlen,
    const char **data, int *dlen)
{
    qu_ast_node *node = qu_find_anchor(
        ((struct qu_var_frame_anchors *)frame)->ctx, name, nlen);
    if(node) {
        *data = qu_node_content(node);
        if(*data) {
            *dlen = strlen(*data);
            return 1;
        }
    }
    return 0;
}

static int qu_node_var(struct qu_var_frame *frame, const char *name, int nlen,
    const char **data, int *dlen)
{
    qu_ast_node *node = qu_map_get_len(
        ((struct qu_var_frame_node *)frame)->node, name, nlen);
    if(node) {
        *data = qu_node_content(node);
        if(*data) {
            *dlen = strlen(*data);
            return 1;
        }
    }
    return 0;
}

struct qu_var_frame *qu_vars_frame(struct obstack *buf,
    struct qu_var_frame *parent)
{
    struct qu_var_frame_tree *self;
    self = obstack_alloc(buf, sizeof(struct qu_var_frame_tree));
    self->frame.resolver = qu_string_var;
    self->frame.parent = parent;
    self->vars = NULL;
    return (struct qu_var_frame *)self;
}

struct qu_var_frame *qu_anchors_frame(struct obstack *buf,
    struct qu_parser *ctx, struct qu_var_frame *parent)
{
    struct qu_var_frame_anchors *self;
    self = obstack_alloc(buf, sizeof(struct qu_var_frame_anchors));
    self->frame.resolver = qu_anchor_var;
    self->frame.parent = parent;
    self->ctx = ctx;
    return (struct qu_var_frame *)self;
}

struct qu_var_frame *qu_node_frame(struct obstack *buf,
    qu_ast_node *node, struct qu_var_frame *parent)
{
    struct qu_var_frame_node *self;
    self = obstack_alloc(buf, sizeof(struct qu_var_frame_node));
    self->frame.resolver = qu_node_var;
    self->frame.parent = parent;
    self->node = node;
    return (struct qu_var_frame *)self;
}

int qu_var_get_string(struct qu_var_frame *frame,
    const char *name, int name_len, const char **data, int *dlen) {
    while(frame) {
        if(frame->resolver(frame, name, name_len, data, dlen)) {
            return 1;
        }
        frame = frame->parent;
    }
    return 0;
}


text:
import React from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import * as mapActions from '../../actions/map';
import {DEFAULT_ZOOM} from '../../constants';

/** @module components/map/zoom-slider
 * @example
 * import SdkZoomSlider from '@boundlessgeo/sdk/components/map/zoom-slider';
 * import { Provider } from 'react-redux';
 * import SdkMap from '@boundlessgeo/sdk/components/map';
 * import ReactDOM from 'react-dom';
 *
 * ReactDOM.render(<Provider store={store}>
 *   <SdkMap>
 *     <SdkZoomSlider />
 *   </SdkMap>
 * </Provider>, document.getElementById('map'));
 *
 * @desc Provides a vertical slider to zoom the map.
 */
class ZoomSlider extends React.Component {
  render() {
    let className = 'sdk-slider-control';
    if (this.props.className) {
      className += ' ' + this.props.className;
    }
    return (
      <div style={this.props.style} className={className}>
        <input className='sdk-zoom-slider' min={this.props.minZoom} max={this.props.maxZoom} value={this.props.zoom} onChange={(evt) => {
          this.props.onChange(evt.target.value);
        }} type='range' />
      </div>
    );
  }
}

ZoomSlider.propTypes = {
  /**
   * Css className to use on the root div.
   */
  className: PropTypes.string,
  /**
   * Style config for the root div.
   */
  style: PropTypes.object,
  /**
   * Minimum zoom level value.
   */
  minZoom: PropTypes.number,
  /**
   * Maximum zoom level value.
   */
  maxZoom: PropTypes.number,
};

ZoomSlider.defaultProps = {
  minZoom: DEFAULT_ZOOM.MIN,
  maxZoom: DEFAULT_ZOOM.MAX,
};

function mapStateToProps(state) {
  return {
    zoom: state.map.zoom,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    onChange: (value) => {
      dispatch(mapActions.setZoom(value));
    },
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ZoomSlider);


text:
module Dapp
  module Dimg
    module Error
      class Rugged < Default; end
    end
  end
end


text:
<?
include("../admin/function/db.php");
include("payments_settings.php");

if($site_fortumo_account!="")
{

  function check_signature($params_array, $secret) {
    ksort($params_array);

    $str = '';
    foreach ($params_array as $k=>$v) {
      if($k != 'sig') {
        $str .= "$k=$v";
      }
    }
    $str .= $secret;
    $signature = md5($str);

    return ($params_array['sig'] == $signature);
  }

  // check that the request comes from Fortumo server
 if(!in_array($_SERVER['REMOTE_ADDR'],
    array('1.2.3.4', '2.3.4.5'))) {
    header("HTTP/1.0 403 Forbidden");
    die("Error: Unknown IP");
  }

  // check the signature
  $secret = $site_fortumo_password; // insert your secret between ''
  if(empty($secret) || !check_signature($_GET, $secret)) {
    header("HTTP/1.0 404 Not Found");
    die("Error: Invalid signature");
  }

  $sender = (int)$_GET['sender'];//phone num.
  $amount = (int)$_GET['amount'];//credit
  $cuid = (int)$_GET['cuid'];//resource i.e. user
  $payment_id = $_GET['payment_id'];//unique id

  //hint: find or create payment by payment_id
  //additional parameters: operator, price, user_share, country

  if(preg_match("/completed/i", $_GET['status'])) {
    // mark payment successful

    $sql="select login,name,lastname,address,city,zipcode,country from users where id_parent=".$cuid;
    $rs->open($sql);
    if(!$rs->eof)
    {
    	$sql="insert into credits_list (title,quantity,data,user,approved,payment,credits,expiration_date,subtotal,discount,taxes,total,billing_firstname,billing_lastname,billing_address,billing_city,billing_zip,billing_country) values ('".$amount." Credits','".$amount."',".mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y")).",'".$rs->row["login"]."',1,0,0,0,".(float)$_GET['price'].",0,0,".(float)$_GET['price'].",'".$rs->row["name"]."','".$rs->row["lastname"]."','".$rs->row["address"]."','".$rs->row["city"]."','".$rs->row["zipcode"]."','".$rs->row["country"]."')";
		$db->execute($sql);

		$sql="select id_parent from credits_list where user='".$rs->row["login"]."' order by id_parent desc";
		$ds->open($sql);
		$credits_id=$ds->row["id_parent"];
    	$transaction_id=transaction_add("fortumo",$payment_id,"credits",$credits_id);

		credits_approve($credits_id,$transaction_id);
		send_notification('credits_to_user',$credits_id);
		send_notification('credits_to_admin',$credits_id);
	}
  }

  // print out the reply
  echo('OK');

}
?>


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

<title>com.blockhaus2000.minecraft.util.command.event</title>
<meta name="date" content="2014-03-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV PACKAGE

NEXT PACKAGE

FRAMES

NO FRAMES

All Classes

Package com.blockhaus2000.minecraft.util.command.event

Class Summary

Class
Description

CommandEvent<T extends CommandInfo>

This is the main class for all CommandEvents.

CommandEventPackage

This Event is not a regular CommandEvent, because this will
 hold a bunch of CommandEvents that are fired within a command
 execution.

IllegalSyntaxCommandEvent

A CommandEvent that is fired if the syntax of a command is
 wrong/illegal.

NoPermissionCommandEvent

This CommandEvent will be fired if a command has been executed but
 the CommandSender does not have the required permission.

NotEnoughArgumentsCommandEvent

This CommandEvent will be fired if a command has been executed but
 the CommandSender does not have the required minimum arguments.

TooManyArgumentsCommandEvent

This CommandEvent will be fired if a command has been executed but
 the CommandSender does have too many arguments.

UnknownSecondLevelCommandEvent

This CommandEvent will be fired if a command has been executed but
 the second-level-command does not match.

Enum Summary

Enum
Description

IllegalSyntaxType

Specifies the illegal syntax type in the IllegalSyntaxCommandEvent.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV PACKAGE

NEXT PACKAGE

FRAMES

NO FRAMES

All Classes


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

src

WixExtensions

UserPrivilegesExtension

UserPrivilegesExtension Directory Reference

Directories

directory  	wixext

directory  	wixlib

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

  <link href="tabs.css" rel="stylesheet" type="text/css">


text:
package com.taobao.weex.devtools.dumpapp.plugins;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;

import com.taobao.weex.devtools.dumpapp.DumpUsageException;
import com.taobao.weex.devtools.dumpapp.DumperContext;
import com.taobao.weex.devtools.dumpapp.DumperPlugin;

import java.io.File;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class SharedPreferencesDumperPlugin implements DumperPlugin {

  private static final String XML_SUFFIX = ".xml";
  private static final String NAME = "prefs";
  private final Context mAppContext;

  public SharedPreferencesDumperPlugin(Context context) {
    mAppContext = context.getApplicationContext();
  }

  @Override
  public String getName() {
    return NAME;
  }

  @Override
  public void dump(DumperContext dumpContext) throws DumpUsageException {
    PrintStream writer = dumpContext.getStdout();
    List<String> args = dumpContext.getArgsAsList();

    String commandName = args.isEmpty() ? "" : args.remove(0);

    if (commandName.equals("print")) {
      doPrint(writer, args);
    } else if (commandName.equals("write")) {
      doWrite(args);
    } else {
      doUsage(writer);
    }
  }

  /**
   * Executes command to update one value in the shared preferences
   */
  private void doWrite(List<String> args) throws DumpUsageException {
    String usagePrefix = "Usage: prefs write <path> <key> <type> <value>, where type is one of: ";

    Iterator<String> argsIter = args.iterator();
    String path = nextArg(argsIter, "Expected <path>");
    String key = nextArg(argsIter, "Expected <key>");
    String typeName = nextArg(argsIter, "Expected <type>");

    Type type = Type.of(typeName);
    if (type == null) {
      throw new DumpUsageException(
          Type.appendNamesList(new StringBuilder(usagePrefix), ", ").toString());
    }

    SharedPreferences sharedPreferences = getSharedPreferences(path);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    switch (type) {
      case BOOLEAN:
        editor.putBoolean(key, Boolean.valueOf(nextArgValue(argsIter)));
        break;
      case INT:
        editor.putInt(key, Integer.valueOf(nextArgValue(argsIter)));
        break;
      case LONG:
        editor.putLong(key, Long.valueOf(nextArgValue(argsIter)));
        break;
      case FLOAT:
        editor.putFloat(key, Float.valueOf(nextArgValue(argsIter)));
        break;
      case STRING:
        editor.putString(key, nextArgValue(argsIter));
        break;
      case SET:
        putStringSet(editor, key, argsIter);
        break;
    }

    editor.commit();
  }

  @Nonnull
  private static String nextArg(Iterator<String> iter, String messageIfNotPresent)
      throws DumpUsageException {
    if (!iter.hasNext()) {
      throw new DumpUsageException(messageIfNotPresent);
    }
    return iter.next();
  }

  @Nonnull
  private static String nextArgValue(Iterator<String> iter) throws DumpUsageException {
    return nextArg(iter, "Expected <value>");
  }

  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  private static void putStringSet(
      SharedPreferences.Editor editor,
      String key,
      Iterator<String> remainingArgs) {
    HashSet<String> set = new HashSet<String>();
    while (remainingArgs.hasNext()) {
      set.add(remainingArgs.next());
    }
    editor.putStringSet(key, set);
  }

  /**
   * Execute command to print all keys and values stored in the shared preferences which match
   * the optional given prefix
   */
  private void doPrint(PrintStream writer, List<String> args) {
    String rootPath = mAppContext.getApplicationInfo().dataDir + "/shared_prefs";
    String offsetPrefix = args.isEmpty() ? "" : args.get(0);
    String keyPrefix = (args.size() > 1) ? args.get(1) : "";

    printRecursive(writer, rootPath, "", offsetPrefix, keyPrefix);
  }

  private void printRecursive(
      PrintStream writer,
      String rootPath,
      String offsetPath,
      String pathPrefix,
      String keyPrefix) {
    File file = new File(rootPath, offsetPath);
    if (file.isFile()) {
      if (offsetPath.endsWith(XML_SUFFIX)) {
        int suffixLength = XML_SUFFIX.length();
        String prefsName = offsetPath.substring(0, offsetPath.length() - suffixLength);
        printFile(writer, prefsName, keyPrefix);
      }
    } else if (file.isDirectory()) {
      String[] children = file.list();
      if (children != null) {
        for (int i = 0; i < children.length; i++) {
          String childOffsetPath = TextUtils.isEmpty(offsetPath)
              ? children[i]
              : (offsetPath + File.separator + children[i]);
          if (childOffsetPath.startsWith(pathPrefix)) {
            printRecursive(writer, rootPath, childOffsetPath, pathPrefix, keyPrefix);
          }
        }
      }
    }
  }

  private void printFile(PrintStream writer, String prefsName, String keyPrefix) {
    writer.println(prefsName + ":");
    SharedPreferences preferences = getSharedPreferences(prefsName);
    for (Map.Entry<String, ?> entry : preferences.getAll().entrySet()) {
      if (entry.getKey().startsWith(keyPrefix)) {
        writer.println("  " + entry.getKey() + " = " + entry.getValue());
      }
    }
  }

  private void doUsage(PrintStream writer) {
    final String cmdName = "dumpapp " + NAME;

    String usagePrefix = "Usage: " + cmdName + " ";
    String blankPrefix = "       " + cmdName + " ";
    writer.println(usagePrefix + "<command> [command-options]");
    writer.println(usagePrefix + "print [pathPrefix [keyPrefix]]");
    writer.println(
        Type.appendNamesList(
            new StringBuilder(blankPrefix).append("write <path> <key> <"),
            "|")
            .append("> <value>"));
    writer.println();
    writer.println(cmdName + " print: Print all matching values from the shared preferences");
    writer.println();
    writer.println(cmdName + " write: Writes a value to the shared preferences");
  }

  private SharedPreferences getSharedPreferences(String name) {
    return mAppContext.getSharedPreferences(name, Context.MODE_MULTI_PROCESS);
  }

  private enum Type {
    BOOLEAN("boolean"),
    INT("int"),
    LONG("long"),
    FLOAT("float"),
    STRING("string"),
    SET("set");

    private final String name;

    private Type(String name) {
      this.name = name;
    }

    public static @Nullable Type of(String name) {
      for (Type type : values()) {
        if (type.name.equals(name)) {
          return type;
        }
      }
      return null;
    }

    public static StringBuilder appendNamesList(StringBuilder builder, String separator) {
      boolean isFirst = true;
      for (Type type : values()) {
        if (isFirst) {
          isFirst = false;
        } else {
          builder.append(separator);
        }
        builder.append(type.name);
      }
      return builder;
    }
  }
}


text:
package org.sharedhealth.datasense.repository;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sharedhealth.datasense.helpers.DatabaseHelper;
import org.sharedhealth.datasense.helpers.TestConfig;
import org.sharedhealth.datasense.launch.DatabaseConfig;
import org.sharedhealth.datasense.model.tr.CodeableConcept;
import org.sharedhealth.datasense.model.tr.Coding;
import org.sharedhealth.datasense.model.tr.TrMedication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.ResultSet;
import java.sql.SQLException;

import static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource("/test-shr-datasense.properties")
@ContextConfiguration(classes = {DatabaseConfig.class, TestConfig.class})
public class DrugDaoIT {
    @Autowired
    private DrugDao drugDao;
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Test
    public void shouldInsertANewDrug() throws Exception {
        TrMedication drug = new TrMedication();
        drug.setUuid("drug-uuid");
        drug.setName("drug-name");
        drug.setCode(getCodeableConcept("reference-code", "concept-uuid"));

        drugDao.saveOrUpdate(drug);

        assertDrug(drug);

    }

    @Test
    public void shouldUpdateAnExistingDrug() throws Exception {
        TrMedication drug = new TrMedication();
        drug.setUuid("drug-uuid");
        drug.setName("drug-name");
        drug.setCode(getCodeableConcept("reference-code", "concept-uuid"));
        drugDao.saveOrUpdate(drug);

        //update drug
        drug.setName("Brand new Drug");
        drug.setCode(getCodeableConcept("reference-code-new", "new-concept-uuid"));

        drugDao.saveOrUpdate(drug);

        assertDrug(drug);
    }

    private void assertDrug(final TrMedication drug) {
        jdbcTemplate.query("select * from drug where drug_uuid='drug-uuid'", new RowMapper<ResultSet>() {
            @Override
            public ResultSet mapRow(ResultSet rs, int rowNum) throws SQLException {
                assertEquals(drug.getUuid(), rs.getString("drug_uuid"));
                assertEquals(drug.getName(), rs.getString("name"));
                assertEquals(drug.getReferenceTermId(), rs.getString("reference_term_uuid"));
                assertEquals(drug.getAssociatedConceptId(), rs.getString("concept_uuid"));
                return rs;
            }
        });
    }

    private CodeableConcept getCodeableConcept(String code, String conceptId) {
        CodeableConcept drugCode = new CodeableConcept();
        drugCode.addCoding(getCoding("http://tr.com/openmrs/ws/rest/v1/tr/referenceterms/" + code, code));
        drugCode.addCoding(getCoding("http://tr.com/openmrs/ws/rest/v1/tr/concepts/concept-uuid", conceptId));
        return drugCode;
    }

    private Coding getCoding(String system, String code) {
        Coding coding = new Coding();
        coding.setSystem(system);
        coding.setCode(code);
        return coding;
    }

    @After
    public void tearDown() throws Exception {
        DatabaseHelper.clearDatasenseTables(jdbcTemplate);
    }
}


text:
describe("Techniques.Controller.Test", function(){

});


text:
package service

import (
	"go-common/app/admin/ep/melloi/model"
	"go-common/library/log"
)

// AddReport add report
func (s *Service) AddReport(userName string, report *model.OrderReport) (err error) {
	var qor *model.QueryOrderResponse
	report.UpdateBy = userName
	report.Active = 1

	// 更新order report
	if report.ID != 0 {
		return s.UpdateReportByID(report)
	}

	// 新增order report
	order := model.Order{ID: report.OrderID}
	if qor, err = s.dao.QueryOrder(&order, 1, 1); err != nil {
		log.Error("order_report.service get order error (%v)", err)
		return err
	}
	report.Name = qor.Orders[0].Name
	return s.dao.AddReport(report)
}

//QueryReportByOrderID  query report
func (s *Service) QueryReportByOrderID(orderID int64) (*model.OrderReport, error) {
	return s.dao.QueryReportByOrderID(orderID)
}

//UpdateReportByID update report by order_id
func (s *Service) UpdateReportByID(report *model.OrderReport) (err error) {
	err = s.dao.UpdateReportByID(report)
	return
}