text:
//---------------------------------------------------------------------
// <copyright file="ClrQueryEvaluationStrategy.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Query
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.Contracts.EntityModel;
    using Microsoft.Test.Taupo.Contracts.Spatial;
    using Microsoft.Test.Taupo.Query.Contracts;
    using Microsoft.Test.Taupo.Query.Linq;

    /// <summary>
    /// Implementation of <see cref="IQueryEvaluationStrategy"/> that uses CLR/LINQ semantics.
    /// </summary>
    public class ClrQueryEvaluationStrategy : IQueryEvaluationStrategy
    {
        /// <summary>
        /// Initializes a new instance of the ClrQueryEvaluationStrategy class.
        /// </summary>
        public ClrQueryEvaluationStrategy()
        {
            this.BooleanType = new QueryClrPrimitiveType(typeof(bool), this);
            this.DoubleType = new QueryClrPrimitiveType(typeof(double), this);
            this.FloatType = new QueryClrPrimitiveType(typeof(float), this);
            this.IntegerType = new QueryClrPrimitiveType(typeof(int), this);
            this.LongIntegerType = new QueryClrPrimitiveType(typeof(long), this);
        }

        /// <summary>
        /// Gets the default boolean type.
        /// </summary>
        public QueryScalarType BooleanType { get; private set; }

        /// <summary>
        /// Gets the default dobule type.
        /// </summary>
        public QueryScalarType DoubleType { get; private set; }

        /// <summary>
        /// Gets the default float type.
        /// </summary>
        public QueryScalarType FloatType { get; private set; }

        /// <summary>
        /// Gets the default integer type.
        /// </summary>
        /// <value></value>
        public QueryScalarType IntegerType { get; private set; }

        /// <summary>
        /// Gets the default long integer type.
        /// </summary>
        /// <value></value>
        public QueryScalarType LongIntegerType { get; private set; }

        /// <summary>
        /// Gets or sets the spatial clr type resolver
        /// </summary>
        [InjectDependency]
        public ISpatialClrTypeResolver SpatialTypeResolver { get; set; }

        /// <summary>
        /// Gets or sets the spatial equality comparer
        /// </summary>
        [InjectDependency]
        public ISpatialEqualityComparer SpatialEqualityComparer { get; set; }

        /// <summary>
        /// Counts the elements in the collection and returns the result.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="collection">The collection.</param>
        /// <returns>
        /// Value representing result of Count() operation on a collection (store specific, for example may or
        /// may not include NULL values depending on store rules).
        /// </returns>
        public QueryScalarValue Count<TElement>(IEnumerable<TElement> collection)
        {
            int? value = null;
            if (collection != null)
            {
                value = collection.Count();
            }

            return this.IntegerType.CreateValue(value);
        }

        /// <summary>
        /// Counts the elements in the collection and returns the result as 64-bit integer.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="collection">The collection.</param>
        /// <returns>
        /// Value representing result of Count() operation on a collection (store specific, for example may or
        /// may not include NULL values depending on store rules).
        /// </returns>
        public QueryScalarValue LongCount<TElement>(IEnumerable<TElement> collection)
        {
            long? value = null;
            if (collection != null)
            {
                value = collection.LongCount();
            }

            return this.LongIntegerType.CreateValue(value);
        }

        /// <summary>
        /// Gets a <see cref="QueryScalarValue"/> indicating whether the source collection contains any elements.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="source">The source.</param>
        /// <returns>
        /// Instance of <see cref="QueryScalarValue"/> indicating whether the source collection contains any elements.
        /// </returns>
        /// <remarks>The value can be store-dependent w.r.t. handling of NULL values of the input collection</remarks>
        public QueryScalarValue Any<TElement>(IEnumerable<TElement> source)
        {
            if (source == null)
            {
                return this.BooleanType.CreateValue(false);
            }
            else
            {
                return this.BooleanType.CreateValue(source.Any());
            }
        }

        /// <summary>
        /// Casts a <see cref="QueryScalarValue"/> to a <see cref="QueryScalarType"/>. The cast will return the value type cast to the new type.
        /// </summary>
        /// <param name="source">The source for the cast operation.</param>
        /// <param name="type">The type for the cast operation.</param>
        /// <returns><see cref="QueryScalarValue"/> which is cast to the appropriate type</returns>
        public QueryScalarValue Cast(QueryScalarValue source, QueryScalarType type)
        {
            var targetType = (QueryClrPrimitiveType)type;

            try
            {
                return this.EvaluateCast(source.Value, targetType);
            }
            catch (InvalidCastException)
            {
                return targetType.CreateValue(null);
            }
        }

        /// <summary>
        /// Computes the Maximum value of a collection as a <see cref="QueryScalarValue"/>.
        /// </summary>
        /// <param name="collection">The collection of values.</param>
        /// <returns>The max value.</returns>
        public QueryScalarValue Max(QueryCollectionValue collection)
        {
            ExceptionUtilities.Assert(collection.Type.ElementType is QueryScalarType, "Max can only be applied on scalar types");
            ExceptionUtilities.Assert(collection.Elements.Any(v => !v.IsNull), "Collection must contain at least one non-null value in a Max operation");

            var type = collection.Type.ElementType as QueryScalarType;

            return type.CreateValue(collection.Elements.Cast<QueryScalarValue>().Max(sv => sv.Value));
        }

        /// <summary>
        /// Computes the Maximum value of a collection as a <see cref="QueryScalarValue"/>.
        /// </summary>
        /// <param name="collection">The collection of values.</param>
        /// <returns>The min value.</returns>
        public QueryScalarValue Min(QueryCollectionValue collection)
        {
            ExceptionUtilities.Assert(collection.Type.ElementType is QueryScalarType, "Min can only be applied on scalar types");
            ExceptionUtilities.Assert(collection.Elements.Any(v => !v.IsNull), "Collection must contain at least one non-null value in a Min operation");

            var type = collection.Type.ElementType as QueryScalarType;

            return type.CreateValue(collection.Elements.Cast<QueryScalarValue>().Min(sv => sv.Value));
        }

        /// <summary>
        /// Filters the specified source using given predicate.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// Filtered collection (including elements where the predicate matches).
        /// </returns>
        /// <remarks>The value can be store-dependent w.r.t. handling of NULL values of the input collection
        /// and/or result of the predicate.</remarks>
        public QueryCollectionValue Filter(QueryCollectionValue source, Func<QueryValue, QueryScalarValue> predicate)
        {
            ExceptionUtilities.CheckArgumentNotNull(source, "source");

            IEnumerable<QueryValue> result = null;
            if (!source.IsNull)
            {
                result = source.Elements.Where(
                    c =>
                    {
                        var evaluatedValue = predicate(c);
                        if (evaluatedValue.IsNull)
                        {
                            return false;
                        }

                        return (bool)evaluatedValue.Value;
                    });
            }

            return new QueryCollectionValue(source.Type, this, QueryError.GetErrorFromValues(result), result, source.IsSorted);
        }

        /// <summary>
        /// Gets a <see cref="QueryScalarValue"/> indicating whether all elements in a source collection
        /// match a given predicate.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// Instance of <see cref="QueryScalarValue"/> indicating whether all elements in a source collection match
        /// a given predicate.
        /// </returns>
        /// <remarks>The value can be store-dependent w.r.t. handling of NULL values of the input collection
        /// and/or result of the predicate.</remarks>
        public QueryScalarValue All<TElement>(IEnumerable<TElement> source, Func<TElement, QueryScalarValue> predicate)
        {
            if (source == null)
            {
                return this.BooleanType.CreateValue(false);
            }
            else
            {
                return this.BooleanType.CreateValue(source.All(c => (bool)predicate(c).Value));
            }
        }

        /// <summary>
        /// Gets a <see cref="QueryScalarValue"/> indicating whether any element in a source collection
        /// matches a given predicate.
        /// </summary>
        /// <typeparam name="TElement">The type of the element.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// Instance of <see cref="QueryScalarValue"/> indicating whether any element in a source collection matches
        /// a given predicate.
        /// </returns>
        /// <remarks>The value can be store-dependent w.r.t. handling of NULL values of the input collection
        /// and/or result of the predicate.</remarks>
        public QueryScalarValue Any<TElement>(IEnumerable<TElement> source, Func<TElement, QueryScalarValue> predicate)
        {
            if (source == null)
            {
                return this.BooleanType.CreateValue(false);
            }
            else
            {
                return this.BooleanType.CreateValue(source.Any(c => (bool)predicate(c).Value));
            }
        }

        /// <summary>
        /// Compares the primitive value to another value and returns their relative ordering.
        /// </summary>
        /// <param name="value">First value.</param>
        /// <param name="otherValue">Second value.</param>
        /// <returns>
        /// True if the values are equal.
        /// </returns>
        public bool AreEqual(QueryScalarValue value, QueryScalarValue otherValue)
        {
            return this.Compare(value, otherValue) == 0;
        }

        /// <summary>
        /// Compares the primitive value to another value and returns their relative ordering.
        /// </summary>
        /// <param name="value">First value.</param>
        /// <param name="otherValue">Second value.</param>
        /// <returns>
        /// Integer which is less than zero if this value is less than the other value, 0 if they are equal,
        /// greater than zero if this value is greater than the other value
        /// </returns>
        public int Compare(QueryScalarValue value, QueryScalarValue otherValue)
        {
            var t1 = (QueryClrPrimitiveType)value.Type;
            var t2 = (QueryClrPrimitiveType)otherValue.Type;
            object v1 = value.Value;
            object v2 = otherValue.Value;

            if (this.IsSpatialType(t1))
            {
                ExceptionUtilities.Assert(this.IsSpatialType(t2), "Because CLR types match, both values should both be spatial. Type was '{0}'", t2);
                ExceptionUtilities.CheckObjectNotNull(this.SpatialEqualityComparer, "Cannot compare spatial values without a spatial equality-comparer");
                return this.SpatialEqualityComparer.Equals(v1, v2) ? 0 : 2;
            }

            if (t1.ClrType != t2.ClrType)
            {
                Type commonClrType = LinqTypeSemantics.GetCommonType(t1.ClrType, t2.ClrType);
                commonClrType = Nullable.GetUnderlyingType(commonClrType) ?? commonClrType;

                if (v1 != null)
                {
                    v1 = ArithmeticEvaluationHelper.ChangeType(v1, commonClrType);
                }

                if (v2 != null)
                {
                    v2 = ArithmeticEvaluationHelper.ChangeType(v2, commonClrType);
                }
            }

            if (v1 == null)
            {
                if (v2 == null)
                {
                    // both null - are equal
                    return 0;
                }
                else
                {
                    // first null, second not-null
                    return -1;
                }
            }
            else
            {
                if (v2 == null)
                {
                    // first not null, second null
                    return 1;
                }
            }

            var bytes1 = v1 as byte[];
            if (bytes1 != null)
            {
                var bytes2 = (byte[])v2;

                return CompareByteArrays(bytes1, bytes2);
            }

            IComparable cv1 = (IComparable)v1;
            return cv1.CompareTo(v2);
        }

        /// <summary>
        /// Gets the common type to which both types can be promoted.
        /// </summary>
        /// <param name="leftType">First type.</param>
        /// <param name="rightType">Second type.</param>
        /// <returns>
        /// Common type to which both types can be promoted. Throws if unable to find a common type.
        /// </returns>
        public QueryScalarType GetCommonType(QueryScalarType leftType, QueryScalarType rightType)
        {
            Type commonClrType = LinqTypeSemantics.GetCommonType(((QueryClrPrimitiveType)leftType).ClrType, ((QueryClrPrimitiveType)rightType).ClrType);

            return new QueryClrPrimitiveType(commonClrType, this);
        }

        /// <summary>
        /// Removes any length constraints from the type
        /// </summary>
        /// <param name="type">The type from which to remove the constraints</param>
        /// <returns>The new type with length constraints removed.</returns>
        public QueryScalarType RemoveLengthConstraints(QueryScalarType type)
        {
            return type;
        }

        /// <summary>
        /// Determines whether a typed data can do certain operation
        /// </summary>
        /// <param name="operation">the operation</param>
        /// <param name="sourceType">the type of data to operate on</param>
        /// <returns>Value <c>true</c> if operation can be performed; otherwise, <c>false</c>.</returns>
        public bool Supports(QueryUnaryOperation operation, QueryScalarType sourceType)
        {
            switch (operation)
            {
                case QueryUnaryOperation.LogicalNegate:
                    return ((IQueryClrType)sourceType).ClrType == typeof(bool);
                default:
                    throw new TaupoNotSupportedException("Unsupported query unary operation.");
            }
        }

        /// <summary>
        /// Determines whether a type supports ordering.
        /// </summary>
        /// <param name="sourceType">the type of data to operation on</param>
        /// <returns>Value <c>true</c> if ordering can be performed; otherwise, <c>false</c>.</returns>
        public bool SupportsOrderComparison(QueryScalarType sourceType)
        {
            // Ordering is supported for all primitive types in the clr
            // Note, this is ordering in the sense of "orderby p.ProductName", not Where(p => p.ProductName < "foo" ).
            var spatialType = sourceType as QueryClrSpatialType;

            if (spatialType != null)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Determines whether a typed data can do certain operation with another typed data
        /// </summary>
        /// <param name="operation">the operation</param>
        /// <param name="sourceType">the type of data to operation on</param>
        /// <param name="otherType">the other type</param>
        /// <returns>Value <c>true</c> if operation can be performed; otherwise, <c>false</c>.</returns>
        public virtual bool Supports(QueryBinaryOperation operation, QueryScalarType sourceType, QueryScalarType otherType)
        {
            var sourceQueryClrType = (IQueryClrType)sourceType;
            var otherQueryClrType = (IQueryClrType)otherType;
            var sourceClrType = sourceQueryClrType.ClrType;
            var otherClrType = otherQueryClrType.ClrType;

            switch (operation)
            {
                case QueryBinaryOperation.Add:
                case QueryBinaryOperation.Divide:
                case QueryBinaryOperation.Modulo:
                case QueryBinaryOperation.Multiply:
                case QueryBinaryOperation.Subtract:
                    return LinqTypeSemantics.IsNumeric(sourceClrType) &&
                           LinqTypeSemantics.IsNumeric(otherClrType) &&
                           this.HaveCommonType(sourceClrType, otherClrType);

                case QueryBinaryOperation.BitwiseAnd:
                case QueryBinaryOperation.BitwiseExclusiveOr:
                case QueryBinaryOperation.BitwiseOr:
                    return LinqTypeSemantics.IsIntegralType(sourceClrType) &&
                           LinqTypeSemantics.IsIntegralType(otherClrType) &&
                           this.HaveCommonType(sourceClrType, otherClrType);

                case QueryBinaryOperation.LogicalAnd:
                case QueryBinaryOperation.LogicalOr:
                    return sourceClrType == typeof(bool) && otherClrType == typeof(bool);

                case QueryBinaryOperation.EqualTo:
                case QueryBinaryOperation.NotEqualTo:
                    return this.HaveCommonType(sourceClrType, otherClrType);

                case QueryBinaryOperation.LessThan:
                case QueryBinaryOperation.LessThanOrEqualTo:
                case QueryBinaryOperation.GreaterThan:
                case QueryBinaryOperation.GreaterThanOrEqualTo:
                    if (sourceClrType == typeof(byte[]) || otherClrType == typeof(byte[])
                        || sourceClrType == typeof(string) || otherClrType == typeof(string)
                        || sourceClrType == typeof(bool) || otherClrType == typeof(bool)
                        || sourceClrType == typeof(bool?) || otherClrType == typeof(bool?)
                        || this.IsSpatialType(sourceQueryClrType) || this.IsSpatialType(otherQueryClrType))
                    {
                        return false;
                    }
                    else
                    {
                        return this.HaveCommonType(sourceClrType, otherClrType);
                    }

                case QueryBinaryOperation.Concat:
                    return sourceClrType == typeof(string) || otherClrType == typeof(string);

                default:
                    throw new TaupoNotSupportedException("Unsupported query binary operation.");
            }
        }

        /// <summary>
        /// Do the specified UnaryOperation for the value and returns the result.
        /// </summary>
        /// <param name="operation">The binary operation to perform.</param>
        /// <param name="value">The value.</param>
        /// <returns>Result of the operation.</returns>
        public virtual QueryScalarValue Evaluate(QueryUnaryOperation operation, QueryScalarValue value)
        {
            Func<object, Type, object> evaluationMethod = null;

            switch (operation)
            {
                case QueryUnaryOperation.LogicalNegate:
                    return this.BooleanType.CreateValue(!(bool)value.Value);
                case QueryUnaryOperation.Negate:
                    evaluationMethod = ArithmeticEvaluationHelper.Negate;
                    break;
                case QueryUnaryOperation.BitwiseNot:
                    evaluationMethod = ArithmeticEvaluationHelper.BitwiseNot;
                    break;
                default:
                    throw new TaupoNotSupportedException("Unsupported query unary operation.");
            }

            ExceptionUtilities.Assert(evaluationMethod != null, "evaluationMethod should not be null.");
            Type clrType = ((QueryClrPrimitiveType)value.Type).ClrType;
            object result = evaluationMethod(value.Value, clrType);

            return value.Type.CreateValue(result);
        }

        /// <summary>
        /// Do the specified BinaryOperation for the two values and returns the result.
        /// </summary>
        /// <param name="operation">The binary operation to perform.</param>
        /// <param name="firstValue">The first value.</param>
        /// <param name="secondValue">The second value.</param>
        /// <returns>Result of the operation.</returns>
        public virtual QueryScalarValue Evaluate(QueryBinaryOperation operation, QueryScalarValue firstValue, QueryScalarValue secondValue)
        {
            Func<object, object, Type, object> evaluationMethod = null;

            switch (operation)
            {
                case QueryBinaryOperation.Add:
                    evaluationMethod = ArithmeticEvaluationHelper.Add;
                    break;
                case QueryBinaryOperation.Subtract:
                    evaluationMethod = ArithmeticEvaluationHelper.Subtract;
                    break;
                case QueryBinaryOperation.Multiply:
                    evaluationMethod = ArithmeticEvaluationHelper.Multiply;
                    break;
                case QueryBinaryOperation.Divide:
                    evaluationMethod = ArithmeticEvaluationHelper.Divide;
                    break;
                case QueryBinaryOperation.Modulo:
                    evaluationMethod = ArithmeticEvaluationHelper.Modulo;
                    break;
                case QueryBinaryOperation.BitwiseAnd:
                    evaluationMethod = ArithmeticEvaluationHelper.BitwiseAnd;
                    break;
                case QueryBinaryOperation.BitwiseOr:
                    evaluationMethod = ArithmeticEvaluationHelper.BitwiseOr;
                    break;
                case QueryBinaryOperation.BitwiseExclusiveOr:
                    evaluationMethod = ArithmeticEvaluationHelper.ExclusiveOr;
                    break;

                case QueryBinaryOperation.LogicalAnd:
                    return this.BooleanType.CreateValue((bool)firstValue.Value && (bool)secondValue.Value);
                case QueryBinaryOperation.LogicalOr:
                    return this.BooleanType.CreateValue((bool)firstValue.Value || (bool)secondValue.Value);

                case QueryBinaryOperation.EqualTo:
                    return this.BooleanType.CreateValue(this.AreEqual(firstValue, secondValue));
                case QueryBinaryOperation.NotEqualTo:
                    return this.BooleanType.CreateValue(!this.AreEqual(firstValue, secondValue));

                case QueryBinaryOperation.LessThan:
                    return this.BooleanType.CreateValue(this.Compare(firstValue, secondValue) < 0);
                case QueryBinaryOperation.LessThanOrEqualTo:
                    return this.BooleanType.CreateValue(this.Compare(firstValue, secondValue) <= 0);
                case QueryBinaryOperation.GreaterThan:
                    return this.BooleanType.CreateValue(this.Compare(firstValue, secondValue) > 0);
                case QueryBinaryOperation.GreaterThanOrEqualTo:
                    return this.BooleanType.CreateValue(this.Compare(firstValue, secondValue) >= 0);

                case QueryBinaryOperation.Concat:
                    return new QueryClrPrimitiveType(typeof(string), this).CreateValue(firstValue.Value.ToString() + secondValue.Value.ToString());

                default:
                    throw new TaupoNotSupportedException("Unsupported query binary operation.");
            }

            ExceptionUtilities.Assert(evaluationMethod != null, "evaluationMethod should not be null.");
            return this.ExecuteBinaryOperation(firstValue, secondValue, evaluationMethod);
        }

        /// <summary>
        /// Evaluates built in function with the given namespace and name.
        /// </summary>
        /// <param name="resultType">The function result type.</param>
        /// <param name="functionNamespace">The function namespace.</param>
        /// <param name="functionName">The function name.</param>
        /// <param name="arguments">Arguments for the function call.</param>
        /// <returns>Query value which is the result of function evaluation.</returns>
        public virtual QueryValue EvaluateBuiltInFunction(QueryType resultType, string functionNamespace, string functionName, params QueryValue[] arguments)
        {
            throw new TaupoInvalidOperationException("Clr Query Evaluation can't evaluate built-in functions. Function: '" + functionName + "'.");
        }

        /// <summary>
        /// Evaluates function.
        /// </summary>
        /// <param name="resultType">The function result type.</param>
        /// <param name="customFunction">The function to evaluate.</param>
        /// <param name="arguments">The arguments for the function call.</param>
        /// <returns>Query value which is the result of function evaluation.</returns>
        public virtual QueryValue EvaluateFunction(QueryType resultType, Function customFunction, params QueryValue[] arguments)
        {
            throw new TaupoInvalidOperationException("Clr Query Evaluation can't evaluate custom functions. Function: '" + customFunction.FullName + "'.");
        }

        /// <summary>
        /// Evaluates function import.
        /// </summary>
        /// <param name="resultType">The function import result type.</param>
        /// <param name="functionImport">The function import to evaluate.</param>
        /// <param name="arguments">The arguments for the function import call.</param>
        /// <returns>Query value which is the result of function import evaluation.</returns>
        public virtual QueryValue EvaluateFunctionImport(QueryType resultType, FunctionImport functionImport, params QueryValue[] arguments)
        {
            throw new TaupoInvalidOperationException("Clr Query Evaluation can't evaluate function imports. Function import: '" + functionImport.Name + "'.");
        }

        /// <summary>
        /// Evaluates member property of a spatial instance.
        /// </summary>
        /// <param name="instance">The instance of query value object</param>
        /// <param name="resultType">The property result type.</param>
        /// <param name="memberPropertyName">The member property name to evaluate.</param>
        /// <returns>Query value which is the result of method evaluation.</returns>
        public virtual QueryValue EvaluateMemberProperty(QueryValue instance, QueryType resultType, string memberPropertyName)
        {
            var clrInstance = ((QueryScalarValue)instance).Value;
            var clrType = clrInstance.GetType();
            return QueryType.UnresolvedPrimitive.CreateValue(
                        clrType.GetProperty(memberPropertyName).GetValue(clrInstance, null));
        }

        /// <summary>
        /// Evaluates member method of a spatial instance.
        /// </summary>
        /// <param name="instance">The instance of query value object</param>
        /// <param name="resultType">The function result type.</param>
        /// <param name="methodName">The member method to evaluate.</param>
        /// <param name="arguments">Arguments for the function call.</param>
        /// <returns>Query value which is the result of function evaluation.</returns>
        public virtual QueryValue EvaluateMemberMethod(QueryValue instance, QueryType resultType, string methodName, params QueryValue[] arguments)
        {
            var primitiveResultType = resultType as QueryScalarType;
            ExceptionUtilities.CheckObjectNotNull(primitiveResultType, "Only query primitive type is supported as member method's result type!");

            var clrInstance = ((QueryScalarValue)instance).Value;
            var instanceType = ((IQueryClrType)instance.Type).ClrType;

            var argTypes = arguments.Select(a => a.Type).Cast<IQueryClrType>().Select(t => t.ClrType);
            var argValues = arguments.Cast<QueryScalarValue>().Select(a => a.Value).ToArray();

            var methodToInvoke = this.FindMemberMethod(instanceType, methodName, argTypes);
            object returnValue = this.InvokeMemberMethod(clrInstance, methodToInvoke, argValues);

            return primitiveResultType.CreateValue(returnValue);
        }

        /// <summary>
        /// Compares the byte arrays lexicographically.
        /// </summary>
        /// <param name="array1">The first array.</param>
        /// <param name="array2">The second array.</param>
        /// <returns>-1 if first array is lexicographically before second array, +1 if it's after
        /// and 0 if they are equal.</returns>
        internal static int CompareByteArrays(byte[] array1, byte[] array2)
        {
            ExceptionUtilities.CheckArgumentNotNull(array1, "array1");
            ExceptionUtilities.CheckArgumentNotNull(array2, "array2");

            int compareLength = Math.Min(array1.Length, array2.Length);
            for (int i = 0; i < compareLength; ++i)
            {
                if (array1[i] < array2[i])
                {
                    return -1;
                }
                else if (array1[i] > array2[i])
                {
                    return 1;
                }
            }

            if (array1.Length < array2.Length)
            {
                return -1;
            }

            if (array1.Length > array2.Length)
            {
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// Helper method for determining if a type is spatial
        /// </summary>
        /// <param name="queryType">The query type to check</param>
        /// <returns>Whether or not the type is spatial</returns>
        protected internal bool IsSpatialType(IQueryClrType queryType)
        {
            if (queryType is QueryClrSpatialType)
            {
                return true;
            }

            if (this.SpatialTypeResolver != null)
            {
                return this.SpatialTypeResolver.IsSpatial(queryType.ClrType);
            }

            return false;
        }

        /// <summary>
        /// Finds the member method. This can be over-ridden to support extension methods.
        /// </summary>
        /// <param name="instanceType">Type of the instance.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="argTypes">The argument types.</param>
        /// <returns>The member method info.</returns>
        protected virtual MethodInfo FindMemberMethod(Type instanceType, string methodName, IEnumerable<Type> argTypes)
        {
            ExceptionUtilities.CheckArgumentNotNull(instanceType, "instanceType");
            ExceptionUtilities.CheckArgumentNotNull(methodName, "methodName");
            ExceptionUtilities.CheckArgumentNotNull(argTypes, "argTypes");

            return instanceType.GetMethod(methodName, argTypes.ToArray());
        }

        /// <summary>
        /// Invokes the member method.
        /// </summary>
        /// <param name="instance">The object instance.</param>
        /// <param name="method">The method.</param>
        /// <param name="argValues">The argument values.</param>
        /// <returns>The result of invoking the method</returns>
        protected virtual object InvokeMemberMethod(object instance, MethodInfo method, object[] argValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(method, "method");
            ExceptionUtilities.CheckArgumentNotNull(argValues, "argValues");

            if (method.IsStatic)
            {
                return method.Invoke(null, argValues);
            }
            else
            {
                return method.Invoke(instance, argValues);
            }
        }

        private bool HaveCommonType(Type t1, Type t2)
        {
            Type commonClrType;
            return LinqTypeSemantics.TryGetCommonType(t1, t2, out commonClrType);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Need to catch all exceptions.")]
        private QueryScalarValue ExecuteBinaryOperation(QueryScalarValue firstValue, QueryScalarValue secondValue, Func<object, object, Type, object> evaluationMethod)
        {
            var t1 = (QueryClrPrimitiveType)firstValue.Type;
            var t2 = (QueryClrPrimitiveType)secondValue.Type;
            object v1 = firstValue.Value;
            object v2 = secondValue.Value;

            QueryClrPrimitiveType commonType = t1;

            try
            {
                commonType = (QueryClrPrimitiveType)this.GetCommonType(t1, t2);

                if (v1 == null || v2 == null)
                {
                    return commonType.CreateErrorValue(new QueryError("Null values are not supported for the operation."));
                }

                var result = evaluationMethod(v1, v2, commonType.ClrType);
                return commonType.CreateValue(result);
            }
            catch (Exception ex)
            {
                return commonType.CreateErrorValue(new QueryError(ex.Message));
            }
        }

        private QueryScalarValue EvaluateCast(object value, QueryClrPrimitiveType targetType)
        {
            object result = null;

            if (value == null)
            {
                return targetType.NullValue;
            }

            if (targetType.ClrType == typeof(bool))
            {
                result = Convert.ToBoolean(value, CultureInfo.InvariantCulture);
            }
#if !SILVERLIGHT
            if (targetType.ClrType == typeof(byte[]))
            {
                // TODO: figure out what's the intended behavior here
                ////result = Convert.ToBase64String(value as byte[], Base64FormattingOptions.None);
                result = value as byte[];
            }
#endif
            if (targetType.ClrType == typeof(byte))
            {
                result = Convert.ToByte(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(sbyte))
            {
                result = Convert.ToSByte(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(char))
            {
                result = Convert.ToChar(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(decimal))
            {
                result = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(double))
            {
                result = Convert.ToDouble(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(float))
            {
                result = Convert.ToSingle(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(int))
            {
                result = Convert.ToInt32(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(uint))
            {
                result = Convert.ToUInt32(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(long))
            {
                result = Convert.ToInt64(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(ulong))
            {
                result = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(short))
            {
                result = Convert.ToInt16(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(ushort))
            {
                result = Convert.ToUInt16(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(string))
            {
                result = Convert.ToString(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(DateTime))
            {
                result = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
            }

            if (targetType.ClrType == typeof(Guid))
            {
                Type valueType = null;
                if (value != null)
                {
                    valueType = value.GetType();
                }

                if (valueType == typeof(Guid) || valueType == typeof(Guid?))
                {
                    result = (Guid)value;
                }
                else if (value != null)
                {
                    throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Cannot cast value of type '{0}' to guid", value.GetType()));
                }
            }

            return targetType.CreateValue(result);
        }
    }
}


text:
JWT
===

[![Build Status](https://travis-ci.org/plasmaconduit/jwt.svg?branch=master)](https://travis-ci.org/plasmaconduit/jwt)

A scala implementation of
[JSON Web Signatures](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25).

This was developed against the `draft-ietf-oauth-json-web-token-25`
specification. Currently only supports a small subset.

Install
-------

Add the following to your `Build.scala`
```
resolvers += "Plasma Conduit Repository" at "http://dl.bintray.com/plasmaconduit/releases",
libraryDependencies += "com.plasmaconduit" %% "jwt" % "0.17.0"
```

redpajama_set_name: RedPajamaGithub


text:
package org.guvnor.ala.pipeline.execution;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

/**
 * This class represents a pipeline execution task.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT)
public interface PipelineExecutorTask {

    /**
     * Indicates the pipeline execution status.
     */
    enum Status {
        SCHEDULED,
        RUNNING,
        FINISHED,
        ERROR,
        STOPPED
    }

    /**
     * @return The task definition that is being executed or was executed.
     */
    PipelineExecutorTaskDef getTaskDef();

    /**
     * The UUID for task.
     */
    String getId();

    /**
     * @return the pipeline execution status.
     */
    Status getPipelineStatus();

    /**
     * @param stage a pipeline Stage for querying the execution status.
     * @return The execution status for the given stage.
     */
    Status getStageStatus(String stage);

    /**
     * @param stage a pipeline Stage for querying the execution error.
     * @return The execution error for the Stage in cases where the Stage execution failed, null in any other case.
     */
    PipelineExecutorError getStageError(String stage);

    /**
     * @return The pipeline execution error in cases where execution failed, false in any other case.
     */
    PipelineExecutorError getPipelineError();

    /**
     * @return A config element with the pipeline output.
     */
    RegistrableOutput getOutput();
}


text:
use crate::job::{HeapJob, JobFifo};
use crate::latch::{CountLatch, Latch};
use crate::log::Event::*;
use crate::registry::{in_worker, Registry, WorkerThread};
use crate::unwind;
use std::any::Any;
use std::fmt;
use std::marker::PhantomData;
use std::mem;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::Arc;

#[cfg(test)]
mod test;

/// Represents a fork-join scope which can be used to spawn any number of tasks.
/// See [`scope()`] for more information.
///
///[`scope()`]: fn.scope.html
pub struct Scope<'scope> {
    base: ScopeBase<'scope>,
}

/// Represents a fork-join scope which can be used to spawn any number of tasks.
/// Those spawned from the same thread are prioritized in relative FIFO order.
/// See [`scope_fifo()`] for more information.
///
///[`scope_fifo()`]: fn.scope_fifo.html
pub struct ScopeFifo<'scope> {
    base: ScopeBase<'scope>,
    fifos: Vec<JobFifo>,
}

struct ScopeBase<'scope> {
    /// thread where `scope()` was executed (note that individual jobs
    /// may be executing on different worker threads, though they
    /// should always be within the same pool of threads)
    owner_thread_index: usize,

    /// thread registry where `scope()` was executed.
    registry: Arc<Registry>,

    /// if some job panicked, the error is stored here; it will be
    /// propagated to the one who created the scope
    panic: AtomicPtr<Box<dyn Any + Send + 'static>>,

    /// latch to set when the counter drops to zero (and hence this scope is complete)
    job_completed_latch: CountLatch,

    /// You can think of a scope as containing a list of closures to execute,
    /// all of which outlive `'scope`.  They're not actually required to be
    /// `Sync`, but it's still safe to let the `Scope` implement `Sync` because
    /// the closures are only *moved* across threads to be executed.
    marker: PhantomData<Box<dyn FnOnce(&Scope<'scope>) + Send + Sync + 'scope>>,
}

/// Create a "fork-join" scope `s` and invokes the closure with a
/// reference to `s`. This closure can then spawn asynchronous tasks
/// into `s`. Those tasks may run asynchronously with respect to the
/// closure; they may themselves spawn additional tasks into `s`. When
/// the closure returns, it will block until all tasks that have been
/// spawned into `s` complete.
///
/// `scope()` is a more flexible building block compared to `join()`,
/// since a loop can be used to spawn any number of tasks without
/// recursing. However, that flexibility comes at a performance price:
/// tasks spawned using `scope()` must be allocated onto the heap,
/// whereas `join()` can make exclusive use of the stack. **Prefer
/// `join()` (or, even better, parallel iterators) where possible.**
///
/// # Example
///
/// The Rayon `join()` function launches two closures and waits for them
/// to stop. One could implement `join()` using a scope like so, although
/// it would be less efficient than the real implementation:
///
/// ```rust
/// # use rayon_core as rayon;
/// pub fn join<A,B,RA,RB>(oper_a: A, oper_b: B) -> (RA, RB)
///     where A: FnOnce() -> RA + Send,
///           B: FnOnce() -> RB + Send,
///           RA: Send,
///           RB: Send,
/// {
///     let mut result_a: Option<RA> = None;
///     let mut result_b: Option<RB> = None;
///     rayon::scope(|s| {
///         s.spawn(|_| result_a = Some(oper_a()));
///         s.spawn(|_| result_b = Some(oper_b()));
///     });
///     (result_a.unwrap(), result_b.unwrap())
/// }
/// ```
///
/// # A note on threading
///
/// The closure given to `scope()` executes in the Rayon thread-pool,
/// as do those given to `spawn()`. This means that you can't access
/// thread-local variables (well, you can, but they may have
/// unexpected values).
///
/// # Task execution
///
/// Task execution potentially starts as soon as `spawn()` is called.
/// The task will end sometime before `scope()` returns. Note that the
/// *closure* given to scope may return much earlier. In general
/// the lifetime of a scope created like `scope(body) goes something like this:
///
/// - Scope begins when `scope(body)` is called
/// - Scope body `body()` is invoked
///     - Scope tasks may be spawned
/// - Scope body returns
/// - Scope tasks execute, possibly spawning more tasks
/// - Once all tasks are done, scope ends and `scope()` returns
///
/// To see how and when tasks are joined, consider this example:
///
/// ```rust
/// # use rayon_core as rayon;
/// // point start
/// rayon::scope(|s| {
///     s.spawn(|s| { // task s.1
///         s.spawn(|s| { // task s.1.1
///             rayon::scope(|t| {
///                 t.spawn(|_| ()); // task t.1
///                 t.spawn(|_| ()); // task t.2
///             });
///         });
///     });
///     s.spawn(|s| { // task s.2
///     });
///     // point mid
/// });
/// // point end
/// ```
///
/// The various tasks that are run will execute roughly like so:
///
/// ```notrust
/// | (start)
/// |
/// | (scope `s` created)
/// +-----------------------------------------------+ (task s.2)
/// +-------+ (task s.1)                            |
/// |       |                                       |
/// |       +---+ (task s.1.1)                      |
/// |       |   |                                   |
/// |       |   | (scope `t` created)               |
/// |       |   +----------------+ (task t.2)       |
/// |       |   +---+ (task t.1) |                  |
/// | (mid) |   |   |            |                  |
/// :       |   + <-+------------+ (scope `t` ends) |
/// :       |   |                                   |
/// |<------+---+-----------------------------------+ (scope `s` ends)
/// |
/// | (end)
/// ```
///
/// The point here is that everything spawned into scope `s` will
/// terminate (at latest) at the same point -- right before the
/// original call to `rayon::scope` returns. This includes new
/// subtasks created by other subtasks (e.g., task `s.1.1`). If a new
/// scope is created (such as `t`), the things spawned into that scope
/// will be joined before that scope returns, which in turn occurs
/// before the creating task (task `s.1.1` in this case) finishes.
///
/// There is no guaranteed order of execution for spawns in a scope,
/// given that other threads may steal tasks at any time. However, they
/// are generally prioritized in a LIFO order on the thread from which
/// they were spawned. So in this example, absent any stealing, we can
/// expect `s.2` to execute before `s.1`, and `t.2` before `t.1`. Other
/// threads always steal from the other end of the deque, like FIFO
/// order.  The idea is that "recent" tasks are most likely to be fresh
/// in the local CPU's cache, while other threads can steal older
/// "stale" tasks.  For an alternate approach, consider
/// [`scope_fifo()`] instead.
///
/// [`scope_fifo()`]: fn.scope_fifo.html
///
/// # Accessing stack data
///
/// In general, spawned tasks may access stack data in place that
/// outlives the scope itself. Other data must be fully owned by the
/// spawned task.
///
/// ```rust
/// # use rayon_core as rayon;
/// let ok: Vec<i32> = vec![1, 2, 3];
/// rayon::scope(|s| {
///     let bad: Vec<i32> = vec![4, 5, 6];
///     s.spawn(|_| {
///         // We can access `ok` because outlives the scope `s`.
///         println!("ok: {:?}", ok);
///
///         // If we just try to use `bad` here, the closure will borrow `bad`
///         // (because we are just printing it out, and that only requires a
///         // borrow), which will result in a compilation error. Read on
///         // for options.
///         // println!("bad: {:?}", bad);
///    });
/// });
/// ```
///
/// As the comments example above suggest, to reference `bad` we must
/// take ownership of it. One way to do this is to detach the closure
/// from the surrounding stack frame, using the `move` keyword. This
/// will cause it to take ownership of *all* the variables it touches,
/// in this case including both `ok` *and* `bad`:
///
/// ```rust
/// # use rayon_core as rayon;
/// let ok: Vec<i32> = vec![1, 2, 3];
/// rayon::scope(|s| {
///     let bad: Vec<i32> = vec![4, 5, 6];
///     s.spawn(move |_| {
///         println!("ok: {:?}", ok);
///         println!("bad: {:?}", bad);
///     });
///
///     // That closure is fine, but now we can't use `ok` anywhere else,
///     // since it is owend by the previous task:
///     // s.spawn(|_| println!("ok: {:?}", ok));
/// });
/// ```
///
/// While this works, it could be a problem if we want to use `ok` elsewhere.
/// There are two choices. We can keep the closure as a `move` closure, but
/// instead of referencing the variable `ok`, we create a shadowed variable that
/// is a borrow of `ok` and capture *that*:
///
/// ```rust
/// # use rayon_core as rayon;
/// let ok: Vec<i32> = vec![1, 2, 3];
/// rayon::scope(|s| {
///     let bad: Vec<i32> = vec![4, 5, 6];
///     let ok: &Vec<i32> = &ok; // shadow the original `ok`
///     s.spawn(move |_| {
///         println!("ok: {:?}", ok); // captures the shadowed version
///         println!("bad: {:?}", bad);
///     });
///
///     // Now we too can use the shadowed `ok`, since `&Vec<i32>` references
///     // can be shared freely. Note that we need a `move` closure here though,
///     // because otherwise we'd be trying to borrow the shadowed `ok`,
///     // and that doesn't outlive `scope`.
///     s.spawn(move |_| println!("ok: {:?}", ok));
/// });
/// ```
///
/// Another option is not to use the `move` keyword but instead to take ownership
/// of individual variables:
///
/// ```rust
/// # use rayon_core as rayon;
/// let ok: Vec<i32> = vec![1, 2, 3];
/// rayon::scope(|s| {
///     let bad: Vec<i32> = vec![4, 5, 6];
///     s.spawn(|_| {
///         // Transfer ownership of `bad` into a local variable (also named `bad`).
///         // This will force the closure to take ownership of `bad` from the environment.
///         let bad = bad;
///         println!("ok: {:?}", ok); // `ok` is only borrowed.
///         println!("bad: {:?}", bad); // refers to our local variable, above.
///     });
///
///     s.spawn(|_| println!("ok: {:?}", ok)); // we too can borrow `ok`
/// });
/// ```
///
/// # Panics
///
/// If a panic occurs, either in the closure given to `scope()` or in
/// any of the spawned jobs, that panic will be propagated and the
/// call to `scope()` will panic. If multiple panics occurs, it is
/// non-deterministic which of their panic values will propagate.
/// Regardless, once a task is spawned using `scope.spawn()`, it will
/// execute, even if the spawning task should later panic. `scope()`
/// returns once all spawned jobs have completed, and any panics are
/// propagated at that point.
pub fn scope<'scope, OP, R>(op: OP) -> R
where
    OP: for<'s> FnOnce(&'s Scope<'scope>) -> R + 'scope + Send,
    R: Send,
{
    in_worker(|owner_thread, _| {
        let scope = Scope::<'scope>::new(owner_thread);
        unsafe { scope.base.complete(owner_thread, || op(&scope)) }
    })
}

/// Create a "fork-join" scope `s` with FIFO order, and invokes the
/// closure with a reference to `s`. This closure can then spawn
/// asynchronous tasks into `s`. Those tasks may run asynchronously with
/// respect to the closure; they may themselves spawn additional tasks
/// into `s`. When the closure returns, it will block until all tasks
/// that have been spawned into `s` complete.
///
/// # Task execution
///
/// Tasks in a `scope_fifo()` run similarly to [`scope()`], but there's a
/// difference in the order of execution. Consider a similar example:
///
/// [`scope()`]: fn.scope.html
///
/// ```rust
/// # use rayon_core as rayon;
/// // point start
/// rayon::scope_fifo(|s| {
///     s.spawn_fifo(|s| { // task s.1
///         s.spawn_fifo(|s| { // task s.1.1
///             rayon::scope_fifo(|t| {
///                 t.spawn_fifo(|_| ()); // task t.1
///                 t.spawn_fifo(|_| ()); // task t.2
///             });
///         });
///     });
///     s.spawn_fifo(|s| { // task s.2
///     });
///     // point mid
/// });
/// // point end
/// ```
///
/// The various tasks that are run will execute roughly like so:
///
/// ```notrust
/// | (start)
/// |
/// | (FIFO scope `s` created)
/// +--------------------+ (task s.1)
/// +-------+ (task s.2) |
/// |       |            +---+ (task s.1.1)
/// |       |            |   |
/// |       |            |   | (FIFO scope `t` created)
/// |       |            |   +----------------+ (task t.1)
/// |       |            |   +---+ (task t.2) |
/// | (mid) |            |   |   |            |
/// :       |            |   + <-+------------+ (scope `t` ends)
/// :       |            |   |
/// |<------+------------+---+ (scope `s` ends)
/// |
/// | (end)
/// ```
///
/// Under `scope_fifo()`, the spawns are prioritized in a FIFO order on
/// the thread from which they were spawned, as opposed to `scope()`'s
/// LIFO.  So in this example, we can expect `s.1` to execute before
/// `s.2`, and `t.1` before `t.2`. Other threads also steal tasks in
/// FIFO order, as usual. Overall, this has roughly the same order as
/// the now-deprecated [`breadth_first`] option, except the effect is
/// isolated to a particular scope. If spawns are intermingled from any
/// combination of `scope()` and `scope_fifo()`, or from different
/// threads, their order is only specified with respect to spawns in the
/// same scope and thread.
///
/// For more details on this design, see Rayon [RFC #1].
///
/// [`breadth_first`]: struct.ThreadPoolBuilder.html#method.breadth_first
/// [RFC #1]: https://github.com/rayon-rs/rfcs/blob/master/accepted/rfc0001-scope-scheduling.md
///
/// # Panics
///
/// If a panic occurs, either in the closure given to `scope_fifo()` or
/// in any of the spawned jobs, that panic will be propagated and the
/// call to `scope_fifo()` will panic. If multiple panics occurs, it is
/// non-deterministic which of their panic values will propagate.
/// Regardless, once a task is spawned using `scope.spawn_fifo()`, it
/// will execute, even if the spawning task should later panic.
/// `scope_fifo()` returns once all spawned jobs have completed, and any
/// panics are propagated at that point.
pub fn scope_fifo<'scope, OP, R>(op: OP) -> R
where
    OP: for<'s> FnOnce(&'s ScopeFifo<'scope>) -> R + 'scope + Send,
    R: Send,
{
    in_worker(|owner_thread, _| {
        let scope = ScopeFifo::<'scope>::new(owner_thread);
        unsafe { scope.base.complete(owner_thread, || op(&scope)) }
    })
}

impl<'scope> Scope<'scope> {
    fn new(owner_thread: &WorkerThread) -> Self {
        Scope {
            base: ScopeBase::new(owner_thread),
        }
    }

    /// Spawns a job into the fork-join scope `self`. This job will
    /// execute sometime before the fork-join scope completes.  The
    /// job is specified as a closure, and this closure receives its
    /// own reference to the scope `self` as argument. This can be
    /// used to inject new jobs into `self`.
    ///
    /// # Returns
    ///
    /// Nothing. The spawned closures cannot pass back values to the
    /// caller directly, though they can write to local variables on
    /// the stack (if those variables outlive the scope) or
    /// communicate through shared channels.
    ///
    /// (The intention is to eventualy integrate with Rust futures to
    /// support spawns of functions that compute a value.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rayon_core as rayon;
    /// let mut value_a = None;
    /// let mut value_b = None;
    /// let mut value_c = None;
    /// rayon::scope(|s| {
    ///     s.spawn(|s1| {
    ///           // ^ this is the same scope as `s`; this handle `s1`
    ///           //   is intended for use by the spawned task,
    ///           //   since scope handles cannot cross thread boundaries.
    ///
    ///         value_a = Some(22);
    ///
    ///         // the scope `s` will not end until all these tasks are done
    ///         s1.spawn(|_| {
    ///             value_b = Some(44);
    ///         });
    ///     });
    ///
    ///     s.spawn(|_| {
    ///         value_c = Some(66);
    ///     });
    /// });
    /// assert_eq!(value_a, Some(22));
    /// assert_eq!(value_b, Some(44));
    /// assert_eq!(value_c, Some(66));
    /// ```
    ///
    /// # See also
    ///
    /// The [`scope` function] has more extensive documentation about
    /// task spawning.
    ///
    /// [`scope` function]: fn.scope.html
    pub fn spawn<BODY>(&self, body: BODY)
    where
        BODY: FnOnce(&Scope<'scope>) + Send + 'scope,
    {
        self.base.increment();
        unsafe {
            let job_ref = Box::new(HeapJob::new(move || {
                self.base.execute_job(move || body(self))
            }))
            .as_job_ref();

            // Since `Scope` implements `Sync`, we can't be sure that we're still in a
            // thread of this pool, so we can't just push to the local worker thread.
            self.base.registry.inject_or_push(job_ref);
        }
    }
}

impl<'scope> ScopeFifo<'scope> {
    fn new(owner_thread: &WorkerThread) -> Self {
        let num_threads = owner_thread.registry().num_threads();
        ScopeFifo {
            base: ScopeBase::new(owner_thread),
            fifos: (0..num_threads).map(|_| JobFifo::new()).collect(),
        }
    }

    /// Spawns a job into the fork-join scope `self`. This job will
    /// execute sometime before the fork-join scope completes.  The
    /// job is specified as a closure, and this closure receives its
    /// own reference to the scope `self` as argument. This can be
    /// used to inject new jobs into `self`.
    ///
    /// # See also
    ///
    /// This method is akin to [`Scope::spawn()`], but with a FIFO
    /// priority.  The [`scope_fifo` function] has more details about
    /// this distinction.
    ///
    /// [`Scope::spawn()`]: struct.Scope.html#method.spawn
    /// [`scope_fifo` function]: fn.scope.html
    pub fn spawn_fifo<BODY>(&self, body: BODY)
    where
        BODY: FnOnce(&ScopeFifo<'scope>) + Send + 'scope,
    {
        self.base.increment();
        unsafe {
            let job_ref = Box::new(HeapJob::new(move || {
                self.base.execute_job(move || body(self))
            }))
            .as_job_ref();

            // If we're in the pool, use our scope's private fifo for this thread to execute
            // in a locally-FIFO order.  Otherwise, just use the pool's global injector.
            match self.base.registry.current_thread() {
                Some(worker) => {
                    let fifo = &self.fifos[worker.index()];
                    worker.push(fifo.push(job_ref));
                }
                None => self.base.registry.inject(&[job_ref]),
            }
        }
    }
}

impl<'scope> ScopeBase<'scope> {
    /// Create the base of a new scope for the given worker thread
    fn new(owner_thread: &WorkerThread) -> Self {
        ScopeBase {
            owner_thread_index: owner_thread.index(),
            registry: owner_thread.registry().clone(),
            panic: AtomicPtr::new(ptr::null_mut()),
            job_completed_latch: CountLatch::new(),
            marker: PhantomData,
        }
    }

    fn increment(&self) {
        self.job_completed_latch.increment();
    }

    /// Executes `func` as a job, either aborting or executing as
    /// appropriate.
    ///
    /// Unsafe because it must be executed on a worker thread.
    unsafe fn complete<FUNC, R>(&self, owner_thread: &WorkerThread, func: FUNC) -> R
    where
        FUNC: FnOnce() -> R,
    {
        let result = self.execute_job_closure(func);
        self.steal_till_jobs_complete(owner_thread);
        result.unwrap() // only None if `op` panicked, and that would have been propagated
    }

    /// Executes `func` as a job, either aborting or executing as
    /// appropriate.
    ///
    /// Unsafe because it must be executed on a worker thread.
    unsafe fn execute_job<FUNC>(&self, func: FUNC)
    where
        FUNC: FnOnce(),
    {
        let _: Option<()> = self.execute_job_closure(func);
    }

    /// Executes `func` as a job in scope. Adjusts the "job completed"
    /// counters and also catches any panic and stores it into
    /// `scope`.
    ///
    /// Unsafe because this must be executed on a worker thread.
    unsafe fn execute_job_closure<FUNC, R>(&self, func: FUNC) -> Option<R>
    where
        FUNC: FnOnce() -> R,
    {
        match unwind::halt_unwinding(func) {
            Ok(r) => {
                self.job_completed_ok();
                Some(r)
            }
            Err(err) => {
                self.job_panicked(err);
                None
            }
        }
    }

    unsafe fn job_panicked(&self, err: Box<dyn Any + Send + 'static>) {
        // capture the first error we see, free the rest
        let nil = ptr::null_mut();
        let mut err = Box::new(err); // box up the fat ptr
        if self
            .panic
            .compare_exchange(nil, &mut *err, Ordering::Release, Ordering::Relaxed)
            .is_ok()
        {
            log!(JobPanickedErrorStored {
                owner_thread: self.owner_thread_index
            });
            mem::forget(err); // ownership now transferred into self.panic
        } else {
            log!(JobPanickedErrorNotStored {
                owner_thread: self.owner_thread_index
            });
        }

        self.job_completed_latch.set();
    }

    unsafe fn job_completed_ok(&self) {
        log!(JobCompletedOk {
            owner_thread: self.owner_thread_index
        });
        self.job_completed_latch.set();
    }

    unsafe fn steal_till_jobs_complete(&self, owner_thread: &WorkerThread) {
        // wait for job counter to reach 0:
        owner_thread.wait_until(&self.job_completed_latch);

        // propagate panic, if any occurred; at this point, all
        // outstanding jobs have completed, so we can use a relaxed
        // ordering:
        let panic = self.panic.swap(ptr::null_mut(), Ordering::Relaxed);
        if !panic.is_null() {
            log!(ScopeCompletePanicked {
                owner_thread: owner_thread.index()
            });
            let value: Box<Box<dyn Any + Send + 'static>> = mem::transmute(panic);
            unwind::resume_unwinding(*value);
        } else {
            log!(ScopeCompleteNoPanic {
                owner_thread: owner_thread.index()
            });
        }
    }
}

impl<'scope> fmt::Debug for Scope<'scope> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Scope")
            .field("pool_id", &self.base.registry.id())
            .field("owner_thread_index", &self.base.owner_thread_index)
            .field("panic", &self.base.panic)
            .field("job_completed_latch", &self.base.job_completed_latch)
            .finish()
    }
}

impl<'scope> fmt::Debug for ScopeFifo<'scope> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("ScopeFifo")
            .field("num_fifos", &self.fifos.len())
            .field("pool_id", &self.base.registry.id())
            .field("owner_thread_index", &self.base.owner_thread_index)
            .field("panic", &self.base.panic)
            .field("job_completed_latch", &self.base.job_completed_latch)
            .finish()
    }
}


text:
@echo off
set "VIRTUAL_ENV=E:\TestPython\ttornado\env"

if defined _OLD_VIRTUAL_PROMPT (
    set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
) else (
    if not defined PROMPT (
        set "PROMPT=$P$G"
    )
	set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
)
set "PROMPT=(env) %PROMPT%"

if not defined _OLD_VIRTUAL_PYTHONHOME (
    set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
)
set PYTHONHOME=

if defined _OLD_VIRTUAL_PATH (
    set "PATH=%_OLD_VIRTUAL_PATH%"
) else (
    set "_OLD_VIRTUAL_PATH=%PATH%"
)
set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%"

:END


text:
package org.kie.pmml.pmml_4_2.model;

import static org.drools.core.command.runtime.pmml.PmmlConstants.DEFAULT_ROOT_PACKAGE;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.dmg.pmml.pmml_4_2.descr.DataDictionary;
import org.dmg.pmml.pmml_4_2.descr.DataField;
import org.dmg.pmml.pmml_4_2.descr.Extension;
import org.dmg.pmml.pmml_4_2.descr.MiningField;
import org.dmg.pmml.pmml_4_2.descr.PMML;
import org.drools.core.io.impl.ClassPathResource;
import org.kie.pmml.pmml_4_2.PMML4Model;
import org.kie.pmml.pmml_4_2.PMML4Unit;
import org.kie.pmml.pmml_4_2.extensions.PMMLExtensionNames;

public class PMML4UnitImpl implements PMML4Unit {

    private static PMML4ModelFactory modelFactory = PMML4ModelFactory.getInstance();
    private PMML rawPmml;
    private Map<String, PMML4Model> modelsMap;
    private Map<String, PMMLDataField> dataDictionaryMap;

    public PMML4UnitImpl(PMML rawPmml) {
        this.rawPmml = rawPmml;
        initFromPMML();
    }

    public PMML4UnitImpl(String pmmlSourcePath) {
        ClassPathResource resource = new ClassPathResource(pmmlSourcePath);
        try {
            JAXBContext context = JAXBContext.newInstance(PMML.class.getPackage().getName());
            Unmarshaller unmarshaller = context.createUnmarshaller();
            this.rawPmml = (PMML) unmarshaller.unmarshal(resource.getInputStream());
            initFromPMML();
        } catch (JAXBException e) {
            throw new IllegalStateException("Unable to resolve the PMML from the given input", e);
        } catch (IOException e) {
            throw new IllegalStateException("Error occurred while attempting to resolve the PMML from the given input", e);
        }
    }

    /**
     * This method initializes the internal map structures. The
     * order of initialization is important. The internal structures
     * for many models will require that the data dictionary be available
     */
    private void initFromPMML() {
        if (this.rawPmml != null) {
            initDataDictionaryMap();
            initModelsMap();
        }
    }

    /**
     * Initializes the internal structure that holds data dictionary information.
     * This initializer should be called prior to any other initializers, since
     * many other structures may have a dependency on the data dictionary.
     */
    private void initDataDictionaryMap() {
        DataDictionary dd = rawPmml.getDataDictionary();
        if (dd != null) {
            dataDictionaryMap = new HashMap<>();
            for (DataField dataField : dd.getDataFields()) {
                PMMLDataField df = new PMMLDataField(dataField);
                dataDictionaryMap.put(df.getName(), df);
            }
        } else {
            throw new IllegalStateException("BRMS-PMML requires a data dictionary section in the definition file");
        }
    }

    /**
     * Initializes the internal map of models. This map includes all models that are
     * defined within the PMML, including child models (i.e. models contained within models)
     */
    private void initModelsMap() {
        modelsMap = new HashMap<>();
        List<PMML4Model> rootModels = modelFactory.getModels(this);
        if (rootModels != null && !rootModels.isEmpty()) {
            for (PMML4Model model : rootModels) {
                modelsMap.put(model.getModelId(), model);
                addChildModelsToMap(model);
            }
        } else {
            throw new IllegalStateException("BRMS-PMML requires at least one model of the model types that are recognized");
        }
    }

    /**
     * Recursive method that adds children models (i.e. models contained within models)
     * to the internal map of models
     * @param parentModel The model which may contain child models
     */
    private void addChildModelsToMap(PMML4Model parentModel) {
        Map<String, PMML4Model> childModels = parentModel.getChildModels();
        if (childModels != null && !childModels.isEmpty()) {
            for (PMML4Model model : childModels.values()) {
                modelsMap.put(model.getModelId(), model);
                addChildModelsToMap(model);
            }
        }
    }

    @Override
    public PMML getRawPMML() {
        return this.rawPmml;
    }

    /**
     * Retrieves a List of the raw MiningField objects for a
     * given model
     * @param modelId The identifier of the model for which the list of MiningField objects is retrieved
     * @return The list of MiningField objects belonging to the identified model
     */
    public List<MiningField> getMiningFieldsForModel(String modelId) {
        PMML4Model model = modelsMap.get(modelId);
        if (model != null) {
            return model.getRawMiningFields();
        }
        return null;
    }

    /**
     * Retrieves a Map with entries that consist of
     * key -> a model identifier
     * value -> the List of raw MiningField objects belonging to the model referenced by the key
     * @return The Map of model identifiers and their corresponding list of raw MiningField objects
     */
    public Map<String, List<MiningField>> getMiningFields() {
        Map<String, List<MiningField>> miningFieldsMap = new HashMap<>();
        for (PMML4Model model : getModels()) {
            List<MiningField> miningFields = model.getRawMiningFields();
            miningFieldsMap.put(model.getModelId(), miningFields);
            model.getChildModels();
        }
        return miningFieldsMap;
    }

    public Map<String, PMML4Model> getModelsMap() {
        return this.modelsMap;
    }

    /**
     * Retrieves a Map with entries that consist of
     * key -> a model identifier
     * value -> the PMML4Model object that the key refers to
     * where the PMML4Model does not indicate a parent model (i.e. the
     * model is not a child model)
     * @return The Map of model identifiers and their corresponding PMML4Model objects
     */
    @Override
    public Map<String, PMML4Model> getRootModels() {
        Map<String, PMML4Model> rootModels = new HashMap<>();
        for (PMML4Model model : this.modelsMap.values()) {
            if (model.getParentModel() == null) {
                rootModels.put(model.getModelId(), model);
            }
        }
        return rootModels;
    }

    @Override
    public Miningmodel getRootMiningModel() {
        for (PMML4Model model : this.modelsMap.values()) {
            if (model.getParentModel() == null && model instanceof Miningmodel) {
                return (Miningmodel) model;
            }
        }
        return null;
    }

    /**
     * Retrieves a Map whose entries consist of
     * key -> a model identifier
     * value -> the PMML4Model object that the key refers to
     * where the PMML4Model indicates that it
     * @param parentModelId
     * @return
     */
    public Map<String, PMML4Model> getChildModels(String parentModelId) {
        PMML4Model parent = modelsMap.get(parentModelId);
        Map<String, PMML4Model> childMap = parent.getChildModels();
        return (childMap != null && !childMap.isEmpty()) ? new HashMap<>(childMap) : new HashMap<>();
    }

    @Override
    public Map<String, PMML4Model> getModels(PMML4ModelType type, PMML4Model parent) {
        Map<String, PMML4Model> filteredModels = new HashMap<>();
        Map<String, PMML4Model> unfilteredModels = parent == null ?
                getRootModels() : getChildModels(parent.getModelId());
        if (unfilteredModels != null && !unfilteredModels.isEmpty()) {
            for (PMML4Model model : unfilteredModels.values()) {
                if (model.getModelType() == type) {
                    filteredModels.put(model.getModelId(), model);
                }
            }
        }
        return filteredModels;
    }

    @Override
    public PMML4Model getRootModel() {
        for (PMML4Model model : this.modelsMap.values()) {
            if (model.getParentModel() == null) {
                return model;
            }
        }
        return null;
    }

    @Override
    public boolean containsMiningModel() {
        for (PMML4Model model : this.modelsMap.values()) {
            if (model.getModelType() == PMML4ModelType.MINING) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<PMML4Model> getModels() {
        Collection<PMML4Model> models = getModelsMap().values();
        return (models != null && !models.isEmpty()) ? new ArrayList<>(models) : new ArrayList<>();
    }

    @Override
    public List<PMMLDataField> getDataDictionaryFields() {
        return (dataDictionaryMap != null && !dataDictionaryMap.isEmpty()) ?
                new ArrayList<>(dataDictionaryMap.values()) : new ArrayList<>();
    }

    public Map<String, PMMLDataField> getDataDictionaryMap() {
        return new HashMap<>(dataDictionaryMap);
    }

    private String packageFromRawPmml() {
        if (rawPmml.getHeader() != null && rawPmml.getHeader().getExtensions() != null) {
            for (Extension ext : rawPmml.getHeader().getExtensions()) {
                if (PMMLExtensionNames.MODEL_PACKAGE.equals(ext.getName())) {
                    return ext.getValue();
                }
            }
        }
        return null;
    }

    @Override
    public String getRootPackage() {
        return packageFromRawPmml() != null ? packageFromRawPmml() : DEFAULT_ROOT_PACKAGE;
    }

    public Map<String, String> getModelPackageNames() {
        Map<String, String> packageNames = new HashMap<>();
        packageNames.put("root", getRootPackage());
        for (PMML4Model model : this.getModels()) {
            packageNames.put(model.getModelId(), model.getModelPackageName());
        }

        return packageNames;
    }

    @Override
    public String getModelExternalMiningBeansRules(String modelName) {
        PMML4Model model = getModelsMap().get(modelName);
        return model != null ? model.getExternalBeansMiningRules() : null;
    }

    @Override
    public PMMLDataField findDataDictionaryEntry(String fieldName) {
        return this.dataDictionaryMap.get(fieldName);
    }
}


text:
package com.microsoft.reef.examples.nggroup.bgd.loss;

import javax.inject.Inject;

public final class LogisticLossFunction implements LossFunction {

  /**
   * Trivial constructor.
   */
  @Inject
  public LogisticLossFunction() {
  }

  @Override
  public double computeLoss(final double y, final double f) {
    final double predictedTimesLabel = y * f;
    return Math.log(1 + Math.exp(-predictedTimesLabel));
  }

  @Override
  public double computeGradient(final double y, final double f) {
    final double predictedTimesLabel = y * f;
    return -y / (1 + Math.exp(predictedTimesLabel));
  }

  @Override
  public String toString() {
    return "LogisticLossFunction{}";
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/auth/ldap/locale/pt_BR/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * LDAP authentication plugin localization strings for the pt_BR locale.
  *
  -->

<locale name="pt_BR" full_name="Português do Brasil">
	<message key="plugins.auth.ldap.displayName">Autenticação LDAP</message>
	<message key="plugins.auth.ldap.description">Plugin de Autenticação LDAP, que permite a sincronização de contas de usuários em uma fonte externa LDAP.</message>

	<message key="plugins.auth.ldap.settings">Configurações LDAP</message>
	<message key="plugins.auth.ldap.settings.hostname">Servidor</message>
	<message key="plugins.auth.ldap.settings.hostname.description">Ex.: "ldap.example.com", ou "ldaps://ldap.example.com" (para uso com SSL)</message>
	<message key="plugins.auth.ldap.settings.port">Porta</message>
	<message key="plugins.auth.ldap.settings.port.description">Opcional. Valor padrão é 389 (LDAP) ou 636 (LDAP sobre SSL)</message>
	<message key="plugins.auth.ldap.settings.basedn">Base DN</message>
	<message key="plugins.auth.ldap.settings.basedn.description">Ex.: "ou=people,dc=example,dc=com"</message>
	<message key="plugins.auth.ldap.settings.managerdn">Gerente DN</message>
	<message key="plugins.auth.ldap.settings.managerdn.description">Ex.: "cn=Manager,dc=example,dc=com"</message>
	<message key="plugins.auth.ldap.settings.managerpwd">Senha</message>
	<message key="plugins.auth.ldap.settings.managerpwd.description">O Gerente DN e a Senha são obrigatórios apenas quando se utiliza a sincronização de cadastro/senha ou as opções de criação de usuário são habilitadas. Caso o LDAP seja usado apenas para autenticação, estas opções podem ser ignoradas.</message>
	<message key="plugins.auth.ldap.settings.pwhash">Criptografia da senha</message>
	<message key="plugins.auth.ldap.settings.saslopt">Configurações SASL (opcional)</message>
	<message key="plugins.auth.ldap.settings.saslmech">Mecanismo SASL</message>
	<message key="plugins.auth.ldap.settings.saslmech.description">Ex.: "DIGEST-MD5"</message>
	<message key="plugins.auth.ldap.settings.saslrealm">Domínio</message>
	<message key="plugins.auth.ldap.settings.saslauthzid">ID de Autorização Solicitado</message>
	<message key="plugins.auth.ldap.settings.saslprop">Propriedades de segurança SASL</message>
	<message key="plugins.auth.ldap.settings.uid">Atributo de nome de conta</message>
	<message key="plugins.auth.ldap.settings.uid.description">O atributo cujo valor identifica de forma única um objeto usuário, como um uid ou cn ou sAMAccountName.</message>
</locale>


text:
package org.apache.metron.common.utils;

import java.lang.reflect.InvocationTargetException;

public class ReflectionUtils {

  public static <T> T createInstance(String className, T defaultClass) {
    T instance;
    if (className == null || className.length() == 0 || className.charAt(0) == '$') {
      return defaultClass;
    } else {
      instance = createInstance(className);
    }
    return instance;
  }

  /**
   * Attempts to create instance from specified class name. No-arg constructor assumed.
   *
   * @param className fully qualified name of class to instantiate. e.g. foo.bar.Baz
   * @param <T> Instance created from passed class
   * @return Object of type T
   */
  public static <T> T createInstance(String className) {
    T instance;
    try {
      Class<? extends T> clazz = (Class<? extends T>) Class.forName(className);
      instance = createInstance(clazz);
    } catch (ClassNotFoundException e) {
      throw new IllegalStateException("Unable to instantiate connector: class not found", e);
    }
    return instance;
  }

  /**
   * Create instance from no-args constructor
   *
   * @param clazz Class to create instance from
   * @param <T> Instance created from passed class
   * @return Object of type T
   */
  public static <T> T createInstance(Class<? extends T> clazz) {
    return createInstance(clazz, null, null);
  }

  /**
   * Create instance from passed class with specified parameter types and arguments. If parameter
   * types is null, defaults to attempting to instantiate the no-arg constructor.
   *
   * @param clazz Class to create instance from
   * @param parameterTypes parameter types to use for looking up the desired constructor
   * @param parameters arguments to pass into the constructor when instantiating the object.
   * @param <T> Instance created from passed class
   * @return Object of type T
   */
  public static <T> T createInstance(Class<? extends T> clazz, Class<?>[] parameterTypes, Object[] parameters) {
    T instance;
    try {
      if (parameterTypes != null) {
        instance = clazz.getConstructor(parameterTypes).newInstance(parameters);
      } else {
        instance = clazz.getConstructor().newInstance();
      }
    } catch (InstantiationException e) {
      throw new IllegalStateException("Unable to instantiate connector.", e);
    } catch (IllegalAccessException e) {
      throw new IllegalStateException("Unable to instantiate connector: illegal access", e);
    } catch (InvocationTargetException e) {
      throw new IllegalStateException("Unable to instantiate connector", e);
    } catch (NoSuchMethodException e) {
      throw new IllegalStateException("Unable to instantiate connector: no such method", e);
    }
    return instance;
  }

  /**
   * Create instance from passed class name with specified parameter types and arguments. If parameter
   * types is null, defaults to attempting to instantiate the no-arg constructor.
   *
   * @param clazz Class to create instance from
   * @param parameterTypes parameter types to use for looking up the desired constructor
   * @param parameters arguments to pass into the constructor when instantiating the object.
   * @param <T> Instance created from passed class
   * @return Object of type T
   */
  public static <T> T createInstance(String className, Class<?>[] parameterTypes, Object[] parameters) {
    T instance;
    try {
      Class<? extends T> clazz = (Class<? extends T>) Class.forName(className);
      instance = createInstance(clazz, parameterTypes, parameters);
    } catch (ClassNotFoundException e) {
      throw new IllegalStateException("Unable to instantiate connector: class not found", e);
    }
    return instance;
  }

}


text:
#ifndef _RTP_MESH_H_
#define _RTP_MESH_H_

#include <SIRTProcess.h>
#include <SIBaseApplication.h>
#include <Scene.h>
#include <TriangleList.h>
#include <TriangleStrip.h>
#include <PolygonList.h>
#include <BaseShape.h>
#include <Material.h>
#include <Primitive.h>

#include <RTP_BasicProcessesTypes.h>

/**
* Mesh runtime process
*
* When evaluated, the mesh will loop thru all it's list of CSIMaterialCluster and will update the associated CSIRTP_Material.
*
*/
SI_Error	RegisterSIMesh ( CSIBaseApplication* in_pApplication, CSLScene *in_pCurrentScene );

class XSIEXPORT CSIRTP_Mesh : public CSIRTProcess
{
public:

	//! Constructor for the CSIRTP_Mesh class
	/*!
	\return a new pointer to a CSIRTP_Mesh
	*/
	CSIRTP_Mesh();

	//! Destructor for the CSIRTP_Mesh class
	/*!
	\return Error code
	*/
	~CSIRTP_Mesh();

	static	SLTemplateCallback	m_sNativeCallbacks;

	//! Evaluates this mesh
	/*! During this call, the mesh will send all its triangle lists or polygon lists
	/*! To their CSIRTP_Material they reference, causing them to be rendered during the Material pass
	\return Error code
	*/

	virtual SI_Error			Evaluate();

	//! Initialize this mesh from a CSLPrimitive object
	/*! When this is called, the CSIRTP_Mesh will create lists of CSIMaterialCluster for each
	/*! triangle list, polygon list or tri-strip list contained in the CSLPrimitive.
	/*! This primitive's bounding volume is also calculated here
	\return Error code
	*/
	SI_Error					Initialize ( CSLPrimitive * );

	/*!
	\return the classification of the runtime process
	*/
	virtual CSIRTProcessType	GetType() {return CSIRTProcess::RENDER;}

	SI_Error					GetMaterialProcessList ( CSIBCArray<CSIRTProcess*>& in_pProcessList );

	//! class factory for runtime linked runtime processes
	/*! This is used when an external entity wants to create a process of this
	/*! type without having to link at compile time. The mechanism is simple.
	/*! the external entity uses the class factory to create a new CSIRTProcess
	/*! and sets the initialization parameters in the user data "SIRTINIT".
	/*! The external entity then calls CSIRTProcess::Init to initialize the data
	/*! extracted from the user data
	/*!
	\return a new CSIRTProcess
	*/
	virtual SI_Error			CreateRTProcess( CSIRTProcess**out_pProcess );

private:

	//! Converts a CSLTriangleList to a format compatible with the realtime shader architecture
	/*! (see CSIMaterialCluster)
	\param CSLBaseShape*	The shape containing the vertex, normnal UV and color information
	\param	CSLTriangleList* The triangle list to convert
	\param	CSIRTP_BoundingVolume*	A pointer to a bounding volume structure
	\return Error code
	*/
	SI_Error	CompileTriangleList ( CSLBaseShape *in_pShape, CSLTriangleList *in_pTriList, CSIRTP_BoundingVolume* in_pBV );

	//! Converts a CSLTriangleStripList to a format compatible with the realtime shader architecture
	/*! (see CSIMaterialCluster)
	\param CSLBaseShape*	The shape containing the vertex, normnal UV and color information
	\param	CSLTriangleStripList* The triangle strip list to convert
	\param	CSIRTP_BoundingVolume*	A pointer to a bounding volume structure
	\param	CSLBaseMaterial*	A pointer to the material assigned to the strip
	\return Error code
	*/
	SI_Error	CompileTriangleStripList ( CSLBaseShape *in_pShape,
											CSLTriangleStrip *in_pTriStrip,
											CSIRTP_BoundingVolume* in_pBV,
											CSLBaseMaterial* in_pMaterial );

	//! Converts a CSLPolygonList to a format compatible with the realtime shader architecture
	/*! (see CSIMaterialCluster)
	\param CSLBaseShape*	The shape containing the vertex, normnal UV and color information
	\param	CSLPolygonList* The polygon list to convert
	\param	CSIRTP_BoundingVolume*	A pointer to a bounding volume structure
	\return Error code
	*/
	SI_Error	CompilePolygonList	( CSLBaseShape *in_pShape, CSLPolygonList *in_pPolygonList, CSIRTP_BoundingVolume* in_pBV );

	CSIBCArray<CSIMaterialCluster>	m_aLists;

	SI_Char*	m_pStripData;
	SI_Long		m_lDataSize;
	SI_Int		m_iClusterCount;
	SI_Void		*m_pUnused;
	SI_Int		m_iUserDataIndex;

};

#endif


text:
#include "ex15_27.h"

// FOR QUOTE

Quote::Quote(const std::string &book, double sales_price) :
	bookNo(book), price(sales_price) {}

double Quote::net_price(std::size_t n) const
{
	return n * price;
}

void Quote::debug() const {
	std::cout << "bookNo = " << bookNo
		<< ", price = " << price << std::endl;
}

Quote::Quote(const Quote& q) : bookNo(q.bookNo), price(q.price) {
	//std::cout << "Quote copy-constructor" << std::endl;
}

Quote::Quote(Quote&& q) noexcept : bookNo(std::move(q.bookNo)), price(std::move(q.price)) {
	//std::cout << "Quote move-constructor" << std::endl;
}

Quote& Quote::operator=(const Quote& rhs) {
	bookNo = rhs.bookNo;
	price = rhs.price;
	//std::cout << "Quote copy-assignment" << std::endl;
	return *this;
}

Quote& Quote::operator=(Quote&& rhs) noexcept {
	bookNo = std::move(rhs.bookNo);
	price = std::move(rhs.price);
	//std::cout << "Quote move-assignment" << std::endl;
	return *this;
}

Quote::~Quote() {
	//std::cout << "Quote destructor" << std::endl;
}

//  FOR DISC_QUOTE

Disc_quote::Disc_quote(const std::string &book, double price,
	std::size_t qty, double disc) :
	Quote(book, price), quantity(qty), discount(disc) {}

Disc_quote::Disc_quote(const Disc_quote& dq) :
	Quote(dq), quantity(dq.quantity), discount(dq.discount) {
	//std::cout << "Disc_quote copy-constructor" << std::endl;
}

Disc_quote::Disc_quote(Disc_quote&& dq)noexcept :
	Quote(std::move(dq)), quantity(std::move(dq.quantity)), discount(std::move(dq.discount)) {
	//std::cout << "Disc_quote move-constructor" << std::endl;
}

Disc_quote& Disc_quote::operator=(const Disc_quote& dq) {
	Quote::operator=(dq);
	quantity = dq.quantity;
	discount = dq.discount;
	//std::cout << "Disc_quote copy-assignment" << std::endl;
	return *this;
}

Disc_quote& Disc_quote::operator=(Disc_quote&& dq)noexcept {
	Quote::operator=(std::move(dq));
	quantity = std::move(dq.quantity);
	discount = std::move(dq.discount);
	//std::cout << "Disc_quote move-assignment" << std::endl;
	return *this;
}

Disc_quote::~Disc_quote() {
	//std::cout << "Disc_quote destructor" << std::endl;
}

// FOR BULK_QUOTE

/*Bulk_quote::Bulk_quote(const std::string &book, double price,
	std::size_t qty, double disc) :
	Disc_quote(book, price, qty, disc) {}*/

double Bulk_quote::net_price(std::size_t n) const {
	if (n >= quantity)
		return quantity*(1 - discount)*price + (n - quantity)*price;
	else
		return n * (1 - discount) * price;
}

Bulk_quote::Bulk_quote(const Bulk_quote& bq) : Disc_quote(bq) {
	//std::cout << "Bulk_quote copy-constructor" << std::endl;
}

Bulk_quote::Bulk_quote(Bulk_quote&& bq)noexcept : Disc_quote(std::move(bq)) {
	//std::cout << "Bulk_quote move-constructor" << std::endl;
}

Bulk_quote& Bulk_quote::operator=(const Bulk_quote& bq) {
	Disc_quote::operator=(bq);
	//std::cout << "Bulk_quote copy-assignment" << std::endl;
	return *this;
}

Bulk_quote& Bulk_quote::operator=(Bulk_quote&& bq) {
	Disc_quote::operator=(std::move(bq));
	//std::cout << "Bulk_quote move-assignment" << std::endl;
	return *this;
}

Bulk_quote::~Bulk_quote() {
	//std::cout << "Bulk_quote destructor" << std::endl;
}


text:
'use strict';
$(document).ready(function() {

    var decodeMedia = function(media, year) {
        let parts = media.split(':', 2);
        if (parts[0] === 'yt') {
            let cont = $('
', {class: 'yt-video-container'});
            cont.append($('', {src: '//youtube.com/embed/{videoId}?rel=0&showinfo=0'.supplant({videoId: parts[1]})}));
            return cont;
        } else if (parts[0] === 'li') {
            return $('', {src: 'static/img/seasons/{year}/{url}'.supplant({year: year, url: parts[1]})});
        } else if (parts[0] == 'nu') {
            return $('', {src: 'static/img/no-image.png'});
        }
    };

    var fail = function() {
        console.log('fail'); // TDOO Indicate failure to the end user
    };

    var q = document.parseQuery();

    if (q.y) {
        let year = q.y.trim().toLowerCase();
        $.getJSON('static/json/seasons.json', {}, function(r) {
            if (!r[year])
                return fail();
            let yData = r[year];
            let cardParent = $('#main-content');

            // Set page title to the season
            document.title = document.title.replace(/Seasons/, q.y);

            // Set the heading title and banner image
            $('#heading-banner').css('background-image', 'url(static/img/seasons/{year}/{url})'.supplant({year: year, url: yData.banner}));
            $('#heading-banner-title').html('{year} {name}'.supplant({name: yData.name.toUpperCase(), year: q.y}));

            // Game description card
            $('#game-desc-container').prepend(decodeMedia(yData.game.media, year));
            $('#game-desc').text(yData.game.desc);

            // Robot description card
            $('#robot-desc-container').prepend(decodeMedia(yData.robot.media, year));
            $('#robot-desc-title').text('Meet {name}, Our Robot'.supplant({name: yData.robot.name}));
            $('#robot-desc-goal').text(yData.robot.goal);
            let featList = $('#robot-desc-features');
            $.each(yData.robot.features, (i, feat) => {
                let elem = $('
');
                elem.text(feat);
                featList.append(elem);
            });

            // Regionals
            $.each(yData.regionals, (ind, rg) => {
                let card = $('
', {class: 'season-content-card card'});
                let contentWrapper = $('
');
                let text = $('
', {class: 'card-text'});

                let header = $('
');
                header.text(rg.name);
                text.append(header);

                let placement = $('
');
                placement.html('Placing: {placing}'.supplant({placing: rg.placing}));
                text.append(placement);

                if (rg.notes) {
                    let notes = $('
');
                    notes.text(rg.notes);
                    text.append(notes);
                }

                contentWrapper.append(decodeMedia(rg.media, year));
                contentWrapper.append(text);
                card.append(contentWrapper);
                addCard(cardParent, card);
            });

            // Gallery
            ((gal, yData) => {
                let card = $('
', {class: 'season-content-card card'});
                let contentWrapper = $('
');

                let mediaContainer = $('
', {class: 'media-gallery'});
                let media = $('
', {class: 'media-gallery-backplate'});
                let back = $('
', {class: 'media-gallery-back text-light'});
                let fwd = $('
', {class: 'media-gallery-fwd text-light'});
                back.append($('', {class: 'mdi mdi-arrow-left'}));
                fwd.append($('', {class: 'mdi mdi-arrow-right'}));
                mediaContainer.append(media);
                mediaContainer.append(back);
                mediaContainer.append(fwd);
                contentWrapper.append(mediaContainer);

                let text = $('
', {class: 'card-text'});
                let header = $('
');
                header.text('Media Gallery');
                let caption = $('
');
                text.append(header);
                text.append(caption);
                contentWrapper.append(text);

                yData['galInd'] = 0;
                $.each(gal, (ind, elem) => {
                    let mediaWrap = $('
', {class: 'media-gallery-media'});
                    mediaWrap.append(decodeMedia(elem.media, year));
                    media.append(mediaWrap);
                });
                let updateGallery = function() {
                    media.css('right', '{perc}%'.supplant({perc: 100 * yData.galInd}));
                    caption.text(gal[yData.galInd].caption);
                };
                back.click(() => {
                   if (--yData.galInd < 0)
                       yData.galInd = gal.length - 1;
                    updateGallery();
                });
                fwd.click(() => {
                    yData.galInd = (yData.galInd + 1) % gal.length;
                    updateGallery();
                });
                updateGallery();

                card.append(contentWrapper);
                addCard(cardParent, card);
            })(yData.gallery, yData);

            // Auxillary cards
            if (!!yData.other) {
                $.each(yData.other, (ind, cData) => {
                    let card = $('
', {class: 'season-content-card card'});
                    let contentWrapper = $('
');
                    let text = $('
', {class: 'card-text'});

                    if (!!cData.title) {
                        let header = $('
');
                        header.text(cData.title);
                        text.append(header);
                    }

                    if (!!cData.content) {
                        let content = $('
');
                        content.text(cData.content);
                        text.append(content);
                    }

                    if (!!cData.media)
                        contentWrapper.append(decodeMedia(cData.media, year));

                    contentWrapper.append(text);
                    card.append(contentWrapper);
                    addCard(cardParent, card);
                });
            }
        });
    }
    else
        fail();

});


text:
package io.github.kimkr.presentation.view.auth;

import android.content.Context;

import com.facebook.CallbackManager;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInApi;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiClient;

import java.lang.ref.WeakReference;

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;
import io.github.kimkr.data.injection.ActivityScope;
import io.github.kimkr.presentation.R;
import io.github.kimkr.presentation.viewcomponent.input.InputViewModel;

/**
 * Created by kkr on 2017. 10. 31..
 */

@Module
public class AuthModule {

    @Provides
    @ActivityScope
    WeakReference<AuthActivity> provideAuthActivityWeakReference(AuthActivity authActivity) {
        return new WeakReference<>(authActivity);
    }

    @Provides
    @ActivityScope
    GoogleSignInOptions provideGoogleSignInOptions(Context context) {
        return new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(context.getString(R.string.google_client_id))
                .requestEmail()
                .build();
    }

    @Provides
    @ActivityScope
    GoogleApiClient provideGoogleApiClient(AuthActivity authActivity, GoogleSignInOptions gso) {
        return new GoogleApiClient.Builder(authActivity)
                .enableAutoManage(authActivity, authActivity)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    @Provides
    @ActivityScope
    GoogleSignInApi provideGoogleSignInApi() {
        return Auth.GoogleSignInApi;
    }

    @Provides
    @ActivityScope
    CallbackManager provideCallbackManager() {
        return CallbackManager.Factory.create();
    }

    @Provides
    @ActivityScope
    @Named("auth_sign_up_id_invalid")
    String provideErrorFieldId(Context context) {
        return context.getString(R.string.auth_all_id_invalid_message);
    }

    @Provides
    @ActivityScope
    @Named("auth_sign_up_pwd_invalid")
    String provideErrorFieldPwd(Context context) {
        return context.getString(R.string.auth_all_pwd_invalid_message);
    }

    @Provides
    @ActivityScope
    @Named("auth_sign_up_repwd_invalid")
    String provideErrorFieldRePwd(Context context) {
        return context.getString(R.string.auth_all_repwd_invalid_message);
    }

    @Provides
    @ActivityScope
    @Named("auth_id_view_model")
    InputViewModel provideIdInputViewModel() {
        return new InputViewModel(true, false);
    }

    @Provides
    @ActivityScope
    @Named("auth_pwd_view_model")
    InputViewModel providePwdInputViewModel() {
        return new InputViewModel(true, true);
    }

    @Provides
    @ActivityScope
    @Named("auth_repwd_view_model")
    InputViewModel provideRePwdInputViewModel() {
        return new InputViewModel(true, true);
    }
}