text:
//
using System;
using System.Collections.Generic;
using System.Linq;
using Alachisoft.NosDB.Common.DataStructures;
using Alachisoft.NosDB.Common.Enum;
using Alachisoft.NosDB.Common.ErrorHandling;
using Alachisoft.NosDB.Common.Exceptions;
using Alachisoft.NosDB.Common.JSON;
using Alachisoft.NosDB.Common.JSON.Expressions;
using Alachisoft.NosDB.Common.JSON.Indexing;
using Alachisoft.NosDB.Common.Queries.Filters;
using Alachisoft.NosDB.Common.Queries.Filters.Scalars;
using Alachisoft.NosDB.Common.Queries.Optimizer;
using Alachisoft.NosDB.Common.Queries.Results;
using Alachisoft.NosDB.Common.Server.Engine;
using Alachisoft.NosDB.Common.Storage.Indexing;
using Alachisoft.NosDB.Core.Storage.Queries.Util;
using Attribute = Alachisoft.NosDB.Common.JSON.Expressions.Attribute;

namespace Alachisoft.NosDB.Common.Queries.ParseTree.DML
{
    public class ComparisonPredicate : ITreePredicate
    {
        private IEvaluable _leftEvaluable;
        private IEvaluable _middleEvaluable;
        private IEvaluable _rightEvaluable;
        private Condition _condition = Condition.None;
        private bool _isNot;
        private bool _isExpression;

        public ComparisonPredicate(IEvaluable leftEvaluable,
            Condition condition, IEvaluable middleEvaluable = null,
            IEvaluable rightEvaluable = null)
        {
            _leftEvaluable = leftEvaluable;
            _middleEvaluable = middleEvaluable;
            _rightEvaluable = rightEvaluable;
            _condition = condition;
            _isExpression = _leftEvaluable is BinaryExpression;
        }

        private void InvertCondition()
        {
            switch (_condition)
            {
                case Condition.Like: _condition = Condition.NotLike; break;
                case Condition.Equals: _condition = Condition.NotEquals; break;
                case Condition.NotEquals: _condition = Condition.Equals; break;
                case Condition.NotLike: _condition = Condition.Like; break;
                case Condition.GreaterThan: _condition = Condition.LesserThanEqualTo; break;
                case Condition.GreaterThanEqualTo: _condition = Condition.LesserThan; break;
                case Condition.LesserThan: _condition = Condition.GreaterThanEqualTo; break;
                case Condition.LesserThanEqualTo: _condition = Condition.GreaterThan; break;
                case Condition.In: _condition = Condition.NotIn; break;
                case Condition.NotIn: _condition = Condition.In; break;
                case Condition.Between: _condition = Condition.NotBetween; break;
                case Condition.NotBetween: _condition = Condition.Between; break;
                case Condition.ContainsAny: _condition = Condition.NotContainsAny; break;
                case Condition.NotContainsAny: _condition = Condition.ContainsAny; break;
                case Condition.ContainsAll: _condition = Condition.NotContainsAll; break;
                case Condition.NotContainsAll: _condition = Condition.ContainsAll; break;
                case Condition.ArraySize: _condition = Condition.NotArraySize; break;
                case Condition.NotArraySize: _condition = Condition.ArraySize; break;
                case Condition.Exists: _condition = Condition.NotExists; break;
                case Condition.NotExists: _condition = Condition.Exists; break;
                case Condition.IsNull: _condition = Condition.IsNotNull; break;
                case Condition.IsNotNull: _condition = Condition.IsNull; break;
            }
        }

        private string ConditionString()
        {
            switch (_condition)
            {
                case Condition.Like: return " LIKE ";
                case Condition.Equals: return " = ";
                case Condition.NotEquals: return " != ";
                case Condition.NotLike: return " NOT LIKE ";
                case Condition.GreaterThan: return " > ";
                case Condition.GreaterThanEqualTo: return " >= ";
                case Condition.LesserThan: return " < ";
                case Condition.LesserThanEqualTo: return " <= ";
                case Condition.In: return " IN ";
                case Condition.NotIn: return " NOT IN ";
                case Condition.Between: return " BETWEEN ";
                case Condition.NotBetween: return " NOT BETWEEN ";
                case Condition.ContainsAny: return " CONTAINS ANY ";
                case Condition.NotContainsAny: return " NOT CONTAINS ANY ";
                case Condition.ContainsAll: return " CONTAINS ALL ";
                case Condition.NotContainsAll: return " NOT CONTAINS ALL ";
                case Condition.ArraySize: return " ARRAY SIZE ";
                case Condition.NotArraySize: return " NOT ARRAY SIZE ";
                case Condition.Exists: return " EXISTS ";
                case Condition.NotExists: return " NOT EXISTS ";
                case Condition.IsNull: return " IS NULL ";
                case Condition.IsNotNull: return " IS NOT NULL ";
            }
            return string.Empty;
        }

        public bool IsNot
        {
            set
            {
                if (_isNot != value)
                    InvertCondition();

                _isNot = value;
            }
        }

        public string InString
        {
            get
            {
                string value = "(" +_leftEvaluable.InString + ConditionString();

                if (_middleEvaluable != null)
                {
                    value += _middleEvaluable.InString;
                }

                if (_rightEvaluable != null)
                {
                    value += " AND " + _rightEvaluable.InString;
                }

                return value + ")";
            }
        }

        public bool IsBinaryExpression
        {
            get { return _isExpression; }
        }

        public PredicateType PredicateType
        {
            get
            {
                if (_leftEvaluable.EvaluationType.Equals(EvaluationType.Constant) &&
                    (_middleEvaluable == null || _middleEvaluable.EvaluationType.Equals(EvaluationType.Constant)) &&
                    (_rightEvaluable == null || _rightEvaluable.EvaluationType.Equals(EvaluationType.Constant)))
                {
                    return PredicateType.Constant;
                }

                if (_leftEvaluable.EvaluationType.Equals(EvaluationType.AllVariable) ||
                    (_middleEvaluable != null && _middleEvaluable.EvaluationType.Equals(EvaluationType.AllVariable)) ||
                    (_rightEvaluable != null && _rightEvaluable.EvaluationType.Equals(EvaluationType.AllVariable)))
                {
                    return PredicateType.AllVariable;
                }

                if (_leftEvaluable.EvaluationType.Equals(EvaluationType.MultiVariable) ||
                    (_middleEvaluable != null && _middleEvaluable.EvaluationType.Equals(EvaluationType.MultiVariable)) ||
                    (_rightEvaluable != null && _rightEvaluable.EvaluationType.Equals(EvaluationType.MultiVariable)))
                {
                    return PredicateType.MultiVariable;
                }

                //If _rightEvaluable is not null, then _middleEvaluable will always be a non-null value.
                if (_rightEvaluable != null)
                {
                    if (_leftEvaluable.EvaluationType.Equals(EvaluationType.SingleVariable) &&
                        _middleEvaluable.EvaluationType.Equals(EvaluationType.SingleVariable) &&
                        _middleEvaluable.EvaluationType.Equals(EvaluationType.SingleVariable))
                    {
                        return PredicateType.MultiVariable;
                    }
                }

                if (_middleEvaluable != null)
                {
                    if (_leftEvaluable.EvaluationType.Equals(EvaluationType.SingleVariable) &&
                        _middleEvaluable.EvaluationType.Equals(EvaluationType.SingleVariable))
                    {
                        return PredicateType.MultiVariable;
                    }
                }

                return PredicateType.SingleVariable;
            }
        }

        public List<Attribute> Attributes
        {
            get
            {
                var list = _leftEvaluable.Attributes;

                if (_middleEvaluable != null)
                {
                    list.AddRange(_middleEvaluable.Attributes);
                }
                if (_rightEvaluable != null)
                {
                    list.AddRange(_rightEvaluable.Attributes);
                }
                return list;
            }
        }

        public List<string> AttributeNames
        {
            get
            {
                return Attributes.Select(attribute => attribute.ToString()).ToList();
            }
        }

        public List<IJsonValue> ConstantValues
        {
            get
            {
                IJsonValue value;
                var values = new List<IJsonValue>();
                if (_leftEvaluable.EvaluationType == EvaluationType.Constant)
                {
                    if (_leftEvaluable.Evaluate(out value, null))
                        values.Add(value);
                }
                if (_middleEvaluable != null && _middleEvaluable.EvaluationType.Equals(EvaluationType.Constant))
                {
                    if (_middleEvaluable.Evaluate(out value, null))
                        values.Add(value);
                }
                if (_rightEvaluable != null && _rightEvaluable.EvaluationType.Equals(EvaluationType.Constant))
                {
                    if (_rightEvaluable.Evaluate(out value, null))
                        values.Add(value);
                }
                return values;
            }
        }

        public Condition Condition
        {
            get { return _condition; }
        }

        //ax + b = 0 => x = -b/a
        public void SolveLinearExpression()
        {
            if (!PredicateType.Equals(PredicateType.SingleVariable))
                return;

            if (_leftEvaluable.EvaluationType.Equals(EvaluationType.Constant)
                && _leftEvaluable is BinaryExpression)
            {
                //_leftEvaluable = ExpressionHelper.GetConstant(_middleEvaluable.Evaluate(null));
            }

            if (_middleEvaluable != null &&
                _middleEvaluable.EvaluationType.Equals(EvaluationType.Constant) &&
                _middleEvaluable is BinaryExpression)
            {
               // _middleEvaluable = ExpressionHelper.GetConstant(_middleEvaluable.Evaluate(null));
            }

            if (_rightEvaluable != null &&
                _rightEvaluable.EvaluationType.Equals(EvaluationType.Constant) &&
                _rightEvaluable is BinaryExpression)
            {
                //_rightEvaluable = ExpressionHelper.GetConstant(_rightEvaluable.Evaluate(null));
            }
        }

        public IPredicate AssignIndexPredicate(IIndex index, IQueryStore queryStore)
        {
            bool singleIndex = true;
            IPredicate predicate = null;
            List<AttributeValue> values;
            IJsonValue value = ConstantValues.Count > 0 ? ConstantValues[0] : null;

            if (value == null && (_condition != Condition.Exists))
            {
                return new StorePredicate(this, queryStore);
            }

            switch (_condition)
            {
                case Condition.Equals:
                case Condition.Like:
                    if (value.DataType.Equals(FieldDataType.Array))
                    {
                        predicate = new ArrayEqualsPredicate(index,
                            GetAttributeValues(value, singleIndex));
                    }
                    else
                    {
                        predicate = new EqualsPredicate(index,
                            GetAttributeValue(value, false, false, singleIndex));
                    }
                    break;

                case Condition.NotEquals:
                case Condition.NotLike:
                    if (value.DataType.Equals(FieldDataType.Array))
                    {
                        predicate = new ArrayEqualsPredicate(index,
                            GetAttributeValues(value, singleIndex), true);
                    }
                    else
                    {
                        predicate = new EqualsPredicate(index,
                            GetAttributeValue(value, false, false, singleIndex), true);
                    }
                    break;

                // If JSON array, then use only one value for comparison... else return a terminal predicate.
                case Condition.GreaterThan:

                    if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                    {
                        return new EmptyPredicate();
                    }

                    predicate = new GreaterPredicate(index,
                        GetAttributeValue(value, value.DataType.Equals(FieldDataType.Array),
                            true, singleIndex));
                    break;

                // If JSON array, then use only one value for comparison... else return a terminal predicate.
                case Condition.GreaterThanEqualTo:

                    if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                    //Exception!!!!
                    if (value.DataType.Equals(FieldDataType.Array) && ((ArrayJsonValue)value.Value).Length > 1)
                    {
                        return new EmptyPredicate();
                    }

                    predicate = new LesserPredicate(index,
                        GetAttributeValue(value, value.DataType.Equals(FieldDataType.Array),
                            true, singleIndex), true);
                    break;

                // If JSON array, then use only one value for comparison... else return a terminal predicate.
                case Condition.LesserThan:

                    if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                    {
                        return new EmptyPredicate();
                    }

                    predicate = new LesserPredicate(index,
                        GetAttributeValue(value, value.DataType.Equals(FieldDataType.Array),
                            true, singleIndex));
                    break;

                // If JSON array, then use only one value for comparison... else return a terminal predicate.
                case Condition.LesserThanEqualTo:

                    if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                    {
                        return new EmptyPredicate();
                    }

                     predicate = new GreaterPredicate(index,
                        GetAttributeValue(value, value.DataType.Equals(FieldDataType.Array),
                            true, singleIndex), true);
                    break;

                // If JSON array, then use only one value for comparison... else return a terminal predicate.
                //IN's handling: the left hand side will always be a single value, where the right hand side will always
                //be a value list, we as an element of the array also support DateAndTime and Scalar-functions (UDFs/Built-ins).
                case Condition.In:
                    //ValueList of Constant evaluables will be sent here... they don't need a document to get evaluated.
                    //if (!(value is ValueList))
                    //{
                    //    throw new QuerySystemException(ErrorCodes.Query.INVALID_IN_OPERATOR_ARGUMENTS);
                    //}

                    values = new List<AttributeValue>();

                    IJsonValue outValue;
                    foreach (var evaluable in ((ValueList)value).Values)
                    {
                        if (evaluable.Evaluate(out outValue, null))
                        {
                            values.Add(GetAttributeValue((IComparable)outValue.Value,
                                singleIndex));
                        }
                    }

                    predicate = new INPredicate(index, values.ToArray());
                    break;

                //IN's handling: the left hand side will always be a single value, where the right hand side will always
                //be a value list, we as an element of the array also support DateAndTime and Scalar-functions (UDFs/Built-ins).
                case Condition.NotIn:
                    //ValueList of Constant evaluables will be sent here... they don't need a document to get evaluated.
                    //if (!(value is ValueList))
                    //{
                    //    throw new QuerySystemException(ErrorCodes.Query.INVALID_IN_OPERATOR_ARGUMENTS);
                    //}

                    values = new List<AttributeValue>();

                    foreach (var evaluable in ((ValueList)value).Values)
                    {
                        if (evaluable.Evaluate(out outValue, null))
                            values.Add(GetAttributeValue((IComparable)outValue.Value, singleIndex));
                    }

                    predicate = new INPredicate(index, values.ToArray(), true);
                    break;

                //TSQL values' check... X BETWEEN Y AND Z :: Y should be always less than Z
                case Condition.Between:

                    IJsonValue value2 = ConstantValues[1];

                    if (value.CompareTo(value2) > 0)
                    {
                        throw new QuerySystemException(ErrorCodes.Query.INVALID_BETWEEN_OPERATOR_ARGUMENTS);
                    }

                    //If both values are =
                    if (value.Equals(value2))
                    {
                        if (value.DataType.Equals(FieldDataType.Array))
                        {
                            if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            if (value2.DataType.Equals(FieldDataType.Array) && ((object[])value2.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            predicate = new ArrayAnyPredicate(index, GetAttributeValues(value, singleIndex));
                        }
                        else
                        {
                            predicate = new EqualsPredicate(index,
                                GetAttributeValue(value2, false, false,singleIndex));
                        }
                    }
                    else
                    {
                        if (value.DataType.Equals(FieldDataType.Array))
                        {
                            if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            if (value2.DataType.Equals(FieldDataType.Array) && ((object[])value2.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            predicate = new ArrayRangePredicate(index,
                                GetAttributeValue(value, true, true, singleIndex),
                                false,
                                GetAttributeValue(value2, true, false, singleIndex),
                                false, false);
                        }
                        else
                        {
                            predicate = new RangePredicate(index,
                                GetAttributeValue(value, false, false, singleIndex),
                                false,
                                GetAttributeValue(value2, false, false, singleIndex),
                                false, false);
                        }
                    }
                    break;

                //TSQL values' check... X BETWEEN Y AND Z :: Y should be always less than Z
                case Condition.NotBetween:

                    value2 = ConstantValues[1];

                    if (value.CompareTo(value2) > 0)
                    {
                        throw new QuerySystemException(ErrorCodes.Query.INVALID_BETWEEN_OPERATOR_ARGUMENTS);
                    }

                    //If both values are =
                    if (value.Equals(value2))
                    {
                        if (value.DataType.Equals(FieldDataType.Array))
                        {
                            if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            if (value2.DataType.Equals(FieldDataType.Array) && ((object[])value2.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            predicate = new ArrayAnyPredicate(index,
                                GetAttributeValues(value, singleIndex), true);
                        }
                        else
                        {
                            predicate = new EqualsPredicate(index,
                                GetAttributeValue(value2, false, false,
                                singleIndex), true);
                        }
                    }
                    else
                    {
                        if (value.DataType.Equals(FieldDataType.Array))
                        {
                            if (value.DataType.Equals(FieldDataType.Array) && ((object[])value.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            if (value2.DataType.Equals(FieldDataType.Array) && ((object[])value2.Value).Length > 1)
                            {
                                return new EmptyPredicate();
                            }

                            predicate = new ArrayRangePredicate(index,
                                GetAttributeValue(value, true, true, singleIndex),
                                true,
                                GetAttributeValue(value2, true, false, singleIndex),
                                true, true);
                        }
                        else
                        {
                            predicate = new RangePredicate(index,
                                GetAttributeValue(value, false, false, singleIndex),
                                true,
                                GetAttributeValue(value2, false, false, singleIndex),
                                true, true);
                        }
                    }
                    break;

                case Condition.ContainsAny:
                    predicate = new ArrayAnyPredicate(index,
                        GetAttributeValues(value, singleIndex));
                    break;

                case Condition.NotContainsAny:
                    predicate = new ArrayAnyPredicate(index,
                        GetAttributeValues(value, singleIndex), true);
                    break;

                case Condition.ContainsAll:
                    predicate = new ArrayAllPredicate(index,
                        GetAttributeValues(value, singleIndex));
                    break;

                case Condition.NotContainsAll:
                    predicate = new ArrayAllPredicate(index,
                        GetAttributeValues(value, singleIndex), true);
                    break;

                case Condition.Exists:
                    predicate = new AllPredicate(index);
                    break;

                case Condition.IsNull:
                    AttributeValue nullValue = new SingleAttributeValue(NullValue.Null);
                    if (!singleIndex)
                    {
                        nullValue = new MultiAttributeValue(NullValue.Null);
                    }
                    predicate = new EqualsPredicate(index, nullValue);
                    break;

                case Condition.IsNotNull:
                    nullValue = new SingleAttributeValue(NullValue.Null);
                    if (!singleIndex)
                    {
                        nullValue = new MultiAttributeValue(NullValue.Null);
                    }
                    predicate = new EqualsPredicate(index, nullValue, true);
                    break;
            }
            return predicate;
        }

        private bool CheckValuesEquality(IEvaluable leftEvaluable, IEvaluable middleEvaluable, IEvaluable rightEvaluable)
        {
            if ((_rightEvaluable != null && rightEvaluable == null) ||
                (_rightEvaluable == null && rightEvaluable != null))
                return false;

            if (_rightEvaluable != null && rightEvaluable != null
                && !_rightEvaluable.ToString().Equals(rightEvaluable.ToString()))
                return false;

            if (_rightEvaluable != null && (_middleEvaluable == null || middleEvaluable == null))
                return false;

            if (_middleEvaluable != null && middleEvaluable == null ||
                _middleEvaluable == null && middleEvaluable != null)
                return false;

            if (!_leftEvaluable.ToString().Equals(leftEvaluable.ToString()) && _middleEvaluable != null
                && !_middleEvaluable.ToString().Equals(leftEvaluable.ToString()))
                return false;

            if( !(_middleEvaluable != null && middleEvaluable != null &&
                (_middleEvaluable.ToString().Equals(middleEvaluable.ToString()) ||
                _leftEvaluable.ToString().Equals(middleEvaluable.ToString()))))
                return false;

            return true;
        }

        #region ITreePredicate members

        public bool Completed { get; set; }

        public bool IsTerminal { get{ return true; }}

        public bool HasOr { get { return false; } }

        public List<ITreePredicate> AtomicTreePredicates
        {
            get
            {
                var predciates = new List<ITreePredicate>() { this };
                return predciates;
            }
        }

        public ITreePredicate Contract()
        {
            return null;
        }

        public ITreePredicate Expand()
        {
            return null;
        }

        public bool IsTrue(IJSONDocument entry)
        {
            IJsonValue value1, value2 = null, value3 = null;

            if (!_leftEvaluable.Evaluate(out value1, entry))
            {
                if (_condition == Condition.NotExists)
                {
                    return true;
                }
                return false;
            }

            if (_middleEvaluable != null && !_middleEvaluable.Evaluate(out value2, entry))
            {
                return false;
            }

            if (_rightEvaluable != null && !_rightEvaluable.Evaluate(out value3, entry))
            {
                return false;
            }

            if (InValidCompareCheck(value1, value2, value3, _condition))
            {
                return false;
            }

            switch (_condition)
            {
                case Condition.Equals:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Equals(value1, value2);
                    }
                    return value1.Equals(value2);

                case Condition.NotEquals:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return !EmbeddedHelper.Equals(value1, value2);
                    }
                    return !value1.Equals(value2);

                case Condition.Like:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        if (value2 is StringConstantValue)
                        {
                            return EmbeddedHelper.Equals(value1, value2, true);
                        }
                        return EmbeddedHelper.Equals(value1, value2);
                    }

                    if(!(value2 is StringConstantValue))
                        return value1.Equals(value2);

                    if (value1.Value is string)
                    {
                        return ((StringConstantValue)value2).WildCompare((string)value1.Value);
                    }
                    return false;

                case Condition.NotLike:
                     if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        if (value2 is StringConstantValue)
                        {
                            return !EmbeddedHelper.Equals(value1, value2, true);
                        }
                        return !EmbeddedHelper.Equals(value1, value2);
                    }

                    if(!(value2 is StringConstantValue))
                        return !value1.Equals(value2);

                    if (value1.Value is string)
                    {
                        return !((StringConstantValue)value2).WildCompare((string)value1.Value);
                    }
                    return false;

                case Condition.GreaterThan:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Compare(value1, value2, false) > 0;
                    }
                    return value1.CompareTo(value2) > 0;

                case Condition.GreaterThanEqualTo:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Compare(value1, value2, false) >= 0;
                    }
                    return value1.CompareTo(value2) >= 0;

                case Condition.LesserThan:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Compare(value1, value2) < 0;
                    }
                    return value1.CompareTo(value2) < 0;

                case Condition.LesserThanEqualTo:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Compare(value1, value2) <= 0;
                    }
                    return value1.CompareTo(value2) <= 0;

                //IN's handling: the right hand side will always be a value list or ArrayJsonValue, we as an element of the array (in ValueList)
                //also support DateAndTime and Scalar-functions (UDFs/Built-ins).
                case Condition.In:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return EmbeddedHelper.Contains(value1, value2, entry);
                    }

                    if (value2 is ValueList)
                    {
                        return ((ValueList) value2).Contains(entry, value1);
                    }
                    if (value2 is ArrayJsonValue)
                    {
                        return ((ArrayJsonValue)value2).Contains(value1);
                    }
                    return false;

                case Condition.NotIn:
                    if (value1 is EmbeddedList || value2 is EmbeddedList)
                    {
                        return !EmbeddedHelper.Contains(value1, value2, entry);
                    }

                    if (value2 is ValueList)
                    {
                        return !((ValueList)value2).Contains(entry, value1);
                    }
                    if (value2 is ArrayJsonValue)
                    {
                        return !((ArrayJsonValue)value2).Contains(value1);
                    }
                    return true;

                case Condition.ContainsAny:
                    if (value1 is EmbeddedList)
                    {
                        return EmbeddedHelper.ArrayContainsAny(value1,
                            value2 as ValueList, entry);
                    }

                    if (value1.DataType.Equals(FieldDataType.Array) && value2 is ValueList)
                    {
                        ArrayJsonValue jsonArray = ((ArrayJsonValue) value1);
                        foreach (var evaluable in ((ValueList)value2))
                        {
                            IJsonValue value;
                            if (!evaluable.Evaluate(out value, entry))
                            {
                                return false;
                            }
                            if (jsonArray.Contains(value))
                            {
                                return true;
                            }
                        }
                    }
                    return false;

                case Condition.NotContainsAny:
                    if (value1 is EmbeddedList)
                    {
                        return !EmbeddedHelper.ArrayContainsAny(value1,
                            value2 as ValueList, entry);
                    }

                    if (value1.DataType.Equals(FieldDataType.Array) && value2 is ValueList)
                    {
                        ArrayJsonValue jsonArray = ((ArrayJsonValue) value1);
                        foreach (var evaluable in ((ValueList)value2))
                        {
                            IJsonValue value;
                            if (!evaluable.Evaluate(out value, entry))
                            {
                                return false;
                            }
                            if (jsonArray.Contains(value))
                            {
                                return false;
                            }
                        }
                        return true;
                    }
                    return false;

                case Condition.ContainsAll:
                    if (value1 is EmbeddedList)
                    {
                        return EmbeddedHelper.ArrayContainsAll(value1,
                            value2 as ValueList, entry);
                    }

                    if (value1.DataType.Equals(FieldDataType.Array) && value2 is ValueList)
                    {
                        ArrayJsonValue jsonArray = ((ArrayJsonValue) value1);
                        foreach (var evaluable in ((ValueList)value2))
                        {
                            IJsonValue value;
                            if (!evaluable.Evaluate(out value, entry))
                            {
                                return false;
                            }

                            if (!jsonArray.Contains(value))
                                return false;
                        }
                        return true;
                    }
                    return false;

                case Condition.NotContainsAll:
                    if (value1 is EmbeddedList)
                    {
                        return !EmbeddedHelper.ArrayContainsAll(value1,
                            value2 as ValueList, entry);
                    }

                    if (value1.DataType.Equals(FieldDataType.Array) && value2 is ValueList)
                    {
                        ArrayJsonValue jsonArray = ((ArrayJsonValue) value1);
                        foreach (var evaluable in ((ValueList)value2))
                        {
                            IJsonValue value;
                            if (!evaluable.Evaluate(out value, entry))
                            {
                                return false;
                            }

                            if (jsonArray.Contains(value))
                                return false;
                        }
                        return true;
                    }

                    return false;

                case Condition.ArraySize:
                    if (value1 is EmbeddedList)
                    {
                        return EmbeddedHelper.ArraySize(value1, (long)value2.Value);
                    }
                    if (value1.DataType.Equals(FieldDataType.Array))
                    {
                        return ((IComparable)value2.Value).CompareTo((long)((ArrayJsonValue)value1).Length) == 0;
                    }
                    return false;

                case Condition.NotArraySize:
                    if (value1 is EmbeddedList)
                    {
                        return !EmbeddedHelper.ArraySize(value1, (long)value2.Value);
                    }
                    if (value1.DataType.Equals(FieldDataType.Array))
                    {
                        return ((IComparable)value2.Value).CompareTo((long)((ArrayJsonValue)value1).Length) != 0;
                    }
                    return false;

                case Condition.Between:
                    if (value1 is EmbeddedList || value2 is EmbeddedList || value3 is EmbeddedList)
                    {
                        return EmbeddedHelper.Between(value1, value2, value3);
                    }
                    return value1.CompareTo(value2) >= 0 && value1.CompareTo(value3) <= 0;

                case Condition.NotBetween:
                    if (value1 is EmbeddedList || value2 is EmbeddedList || value3 is EmbeddedList)
                    {
                        return EmbeddedHelper.Between(value1, value2, value3);
                    }
                    return value1.CompareTo(value2) < 0 || value1.CompareTo(value3) > 0;

                case Condition.Exists:
                    IJsonValue existValue;
                    if (_leftEvaluable.Evaluate(out existValue, entry))
                    {
                        return true;
                    }
                    return false;

                case Condition.IsNull:
                    if (value1 is EmbeddedList)
                    {
                        return EmbeddedHelper.Equals(value1, NullValue.Null);
                    }
                    if (value1 is NullValue)
                    {
                        return true;
                    }
                    return false;

                case Condition.IsNotNull:
                    if (value1 is EmbeddedList)
                    {
                        return !EmbeddedHelper.Equals(value1, NullValue.Null);
                    }
                    if (!(value1 is NullValue))
                    {
                        return true;
                    }
                    return false;
            }
            return false;
        }

        public bool TryGetProxyKeyPredicate(IEnumerable<long> rowsEnumerator, out DocumentKey comparisonKey)
        {
            if (Attributes.Count > 0 && _condition == Condition.Equals)
            {
                if (Attributes[0].ToRealString().Equals(JsonDocumentUtil.DocumentKeyAttribute))
                {
                    StringConstantValue stringValue = _middleEvaluable as StringConstantValue;
                    if (stringValue != null)
                    {
                        comparisonKey = new DocumentKey(stringValue.Value.ToString());
                        return true;
                    }
                }
            }
            comparisonKey = null;
            return false;
        }

        public IProxyPredicate GetProxyExecutionPredicate(IIndexProvider indexManager, IQueryStore queryStore, IEnumerable<long> rowsEnumerator )
        {
            if (PredicateType.Equals(PredicateType.Constant))
            {
                if (IsTrue(null))
                {
                    return new ProxyPredicate(new StorePredicate(new TrueCondition(), queryStore), this);
                }
                return new ProxyPredicate(new EmptyPredicate(), null);
            }

            OrderedList<int, IIndex> indexes = indexManager.OrderedIndexList;
            bool isCompoundIndex = IsCompoundIndex(indexes);

            if (PredicateType.Equals(PredicateType.SingleVariable) && !isCompoundIndex)
            {
                foreach (var index in indexes.Values.Reverse())
                {
                    //Todo: Consider candidate list for this...
                    //Incase of binary expression evaluate full store.
                    if (!_isExpression && Attributes[0].ToRealString().Equals(index.Attributes.Name))
                    {
                        return new ProxyPredicate(AssignIndexPredicate(index, queryStore), this);
                    }
                }
            }
            else if (PredicateType.Equals(PredicateType.MultiVariable) || isCompoundIndex)
            {
                var candidatesList = new OrderedList<int, IIndex>();
                foreach (var index in indexes.Values)
                {
                        continue;
                    List<string> indexAttributes = new List<string>();
                    //foreach (var attribute in index.Attributes)
                    //{
                    //    indexAttributes.Add(attribute.Name);
                    //}

                    IIndex candIndex = null;
                    foreach (var attribute in Attributes)
                    {
                        if (indexAttributes.Contains(attribute.ToString()))
                        {
                            candIndex = index;
                            continue;
                        }
                        candIndex = null;
                        break;
                    }

                    if (candIndex != null)
                    {
                        candidatesList.Add(candIndex.ValueCount, candIndex);
                    }
                }

                if (candidatesList.Count > 0)
                {
                    IPredicate predicate = new FilterPredicate(this, candidatesList.FirstValues[0]);
                    predicate.AddChildPredicate(new AllPredicate(candidatesList.FirstValues[0]));
                    return new ProxyPredicate(predicate, this);
                }
            }
            return new ProxyPredicate(new StorePredicate(this, queryStore), this);
        }

        public void AssignConstants(IList<IParameter> parameters)
        {
            _leftEvaluable.AssignConstants(parameters);

            if (_middleEvaluable != null)
            {
                _middleEvaluable.AssignConstants(parameters);
            }

            if (_rightEvaluable != null)
            {
                _rightEvaluable.AssignConstants(parameters);
            }

            //'BETWEEN' valid constants check.
            if (_condition == Condition.Between || _condition == Condition.NotBetween)
            {
                if (_middleEvaluable != null && _middleEvaluable.EvaluationType == EvaluationType.Constant &&
                    _rightEvaluable != null && _rightEvaluable.EvaluationType == EvaluationType.Constant)
                {
                    IJsonValue startRange, endRange;
                    if(!_middleEvaluable.Evaluate(out startRange, null) ||  !_rightEvaluable.Evaluate(out endRange, null))
                    {
                        throw new QuerySystemException(ErrorCodes.Query.INVALID_CONSTANT_BINARY_EXPRESSION_SPECIFIED);
                    }

                    if (startRange.CompareTo(endRange) > 0)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_BETWEEN_OPERATOR_ARGUMENTS);
                    }
                }
            }
        }

        public void AssignScalarFunctions()
        {
            if (_middleEvaluable!=null)
            {
                foreach (Function function in _middleEvaluable.Functions)
                    AssignFunction(function);
            }

            if (_rightEvaluable != null)
            {
                foreach (Function function in _rightEvaluable.Functions)
                    AssignFunction(function);

            }

            if (_leftEvaluable == null)
                return;

            foreach (Function function in _leftEvaluable.Functions)
                AssignFunction(function);

        }

        private void AssignFunction(Function function)
        {
            IFunction scalarFunction = ScalarFunctionsStore.GetScalarFunction(function);
            if (scalarFunction != null)
            {
                function.ExecutionInstance = scalarFunction;
                return;
            }
            throw new QuerySystemException(ErrorCodes.Query.INVALID_FUNCTION_NAME_SPECIFIED, new[] { function.FunctionNameActual });

        }

        #endregion

        #region ICloneable members

        public object Clone()
        {
            return this;
        }

        #endregion

        #region static helpers

        private static bool InValidCompareCheck(IJsonValue value1, IJsonValue value2,
            IJsonValue value3, Condition condition)
        {
            switch (condition)
            {
                case Condition.GreaterThan:
                case Condition.GreaterThanEqualTo:
                case Condition.LesserThan:
                case Condition.LesserThanEqualTo:
                    return InValidCompareValue(value1, value2);
                case Condition.Between:
                case Condition.NotBetween:
                    return InValidCompareValue(value1, value2, value3);
            }
            return false;
        }

        private static bool InValidCompareValue(IJsonValue value1, IJsonValue value2, IJsonValue value3 = null)
        {
            if (value1.DataType.Equals(FieldDataType.Embedded))
                return false;
            if (value1.DataType.Equals(FieldDataType.Array) || value1.DataType.Equals(FieldDataType.Object))
                return true;

            if (value2.DataType.Equals(FieldDataType.Array) || value2.DataType.Equals(FieldDataType.Object))
                return true;

            if (value3 != null && (value1.DataType.Equals(FieldDataType.Array) || value1.DataType.Equals(FieldDataType.Object)))
                return true;

            return false;
        }

        private static AttributeValue[] GetAttributeValues(IJsonValue arrayValue, bool singleIndex)
        {
            object[] array = (object[])((ArrayJsonValue)arrayValue).Value;
            AttributeValue[] values = new AttributeValue[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                values[i] = new SingleAttributeValue((IComparable)array[i]);
            }

            if (!singleIndex)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    if(values[i] == null)
                        values[i] = new MultiAttributeValue(NullValue.Null);
                    else
                        values[i] = new MultiAttributeValue(values[i]);
                }
            }

            return values;
        }

        private static AttributeValue GetAttributeValue(IJsonValue jsonValue, bool isArray, bool minRange, bool singleIndex)
        {
            IComparable returnValue = (IComparable)jsonValue.Value;

            if (isArray)
            {
                object[] array = (object[])jsonValue.Value;

                if (array.Length != 1)
                {
                    throw new QuerySystemException(ErrorCodes.Query.INVALID_NUMBER_OF_ARRAY_RANGE_ELEMENTS,
                        new[] { jsonValue.ToString() });
                }

                returnValue = new ArrayElement(
                    new SingleAttributeValue(array[0] as IComparable), minRange ? 0 : int.MaxValue);
            }
            AttributeValue attributeValue;

            if (jsonValue is NullValue)
            {
                attributeValue = new NullValue();
            }
            else
            {
                attributeValue = new SingleAttributeValue(returnValue);
            }

            if (!singleIndex)
            {
                attributeValue = new MultiAttributeValue(attributeValue);
            }
            return attributeValue;
        }

        private static AttributeValue GetAttributeValue(IComparable value, bool singleIndex)
        {
            AttributeValue attributeValue = new SingleAttributeValue(value);
            if (!singleIndex)
            {
                if(value == null || value is NullValue)
                    attributeValue = new MultiAttributeValue(NullValue.Null);
                else
                    attributeValue = new MultiAttributeValue(attributeValue);
            }
            return attributeValue;
        }

        private static AttributeValue[] GetAttributes(AttributeValue attributeValue, int attrNum)
        {
            List<AttributeValue> attributeValues =
                new List<AttributeValue> {attributeValue};
            for (int i = 0; i < attrNum - 1; i++)
            {
                attributeValues.Add(new AllValue());
            }
            return attributeValues.ToArray();
        }

        #endregion

        public override bool Equals(object obj)
        {
            if (!(obj is ComparisonPredicate))
            {
                return false;
            }

            ComparisonPredicate predicate = ((ComparisonPredicate)obj);

            if (!Condition.Equals(predicate.Condition))
                return false;

            return predicate.CheckValuesEquality(_leftEvaluable, _middleEvaluable, _rightEvaluable);
        }

        public void Print(System.IO.TextWriter output)
        {
            output.Write("ComparisonPredicate:{");
            output.Write("LHS=");
            if (_leftEvaluable != null)
            {
                _leftEvaluable.Print(output);
            }
            else
            {
                output.Write("null");
            }
            output.Write(",Op="+_condition.ToString());
            output.Write(",RHS=");
            if (_rightEvaluable != null)
            {
                _rightEvaluable.Print(output);
            }
            else
            {
                output.Write("null");
            }
            output.Write(",IsNot="+_isNot.ToString());
            output.Write(",MHS=");
            if (_middleEvaluable != null)
            {
                _middleEvaluable.Print(output);
            }
            else
            {
                output.Write("null");
            }
            output.Write("}");
        }

        private bool IsCompoundIndex(OrderedList<int, IIndex> indexes)
        {
            return false;
        }
    }
}


text:
// To create your own client for OAuth routine,
// your client must support the following methods:
// 1. getAuthorizationUrl - gets request token/secret pair, creates and returns
//    authorization url, based on received data
// 2. getAccessToken(requestToken, requestTokenSecret, verifier, callback) -
//    requests access token/secret pair using known request token/secret pair and verifier
// 3. setAccessToken(token, secret, callback) - sets known access token/secret pair
// 4. get|post|put|delete(path, data, callback) - for GET, POST, PUT and DELETE methods respectively
// 5. setEntryPoint(entryPoint) - allows setup different entry point for base url

/**
 * @module client
 * @requires node-upwork
 */

debug('export client module');

var upwork = require('node-upwork');

/**
 * @class Client
 * @constructor
 */
exports.Client = function(config) {
  debug('starting client')
  debug(config.consumerKey, 'with consumer key');
  debug(config.consumerSecret, 'with consumer secret');

  var o = new upwork(config.consumerKey, config.consumerSecret);
  debug(o, 'got a client');

  return o;
}

/**
 * Set access token key/secret pair
 *
 * @method setAccessToken
 * @param token {String} Access token
 * @param secret {String} Access token secret
 * @param callback {String} Callback
 * @async
 */
upwork.prototype.setAccessToken = function(token, secret, callback) {
  debug('setting access/token pair');
  debug(token, 'token will be setup to');
  debug(secret, 'secret will be setup to');

  this.OAuth.accessToken = token;
  this.OAuth.accessTokenSecret = secret;

  return callback();
}

/**
 * Get authorization URL and request token
 *
 * @method getAuthorizationUrl
 * @param callbackUrl {String} Callback URL
 * @param callback
 * @async
 */
upwork.prototype.getAuthorizationUrl = function(callbackUrl, callback) {
  return this.OAuth.getAuthorizeUrl(callbackUrl, callback);
}

/**
 * Get access token key/secret pair
 *
 * @method getAccessToken
 * @param requestToken {String} Request token
 * @param requestTokenSecret {String} Request token secret
 * @param verifier {String} Verifier got on authorization step
 * @param callback
 * @async
 */
upwork.prototype.getAccessToken = function(requestToken, requestTokenSecret, verifier, callback) {
  return this.OAuth.getAccessToken(requestToken, requestTokenSecret, verifier, callback);
}

/**
 * Specify entry point used in base url
 *
 * @method setEntryPoint
 * @param entryPoint {String} Entry point, e.g. 'api' or 'gds'
 */
upwork.prototype.setEntryPoint = function(entryPoint) {
  debug('updating entry point');
  // a trick to support different entry points in node-upwork
  this.baseUrl = this.baseUrl.replace(/\/api\//i, '/' + entryPoint + '/');
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>net.wasdev.maven.parent</groupId>
        <artifactId>java7-parent</artifactId>
        <version>1.4</version>
        <relativePath></relativePath>
    </parent>

    <groupId>net.wasdev.wlp.sample</groupId>
    <artifactId>GetStartedJava</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Bluemix Getting Started</name>
    <url>https://bluemix.net</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>https://raw.github.com/WASdev/sample.servlet/master/LICENSE</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.geronimo.specs</groupId>
                <artifactId>geronimo-servlet_3.0_spec</artifactId>
                <version>1.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>3.1.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-servlet_3.0_spec</artifactId>
            <scope>provided</scope>
        </dependency>

		<dependency>
			<groupId>com.cloudant</groupId>
			<artifactId>cloudant-client</artifactId>
			<version>2.7.0</version>
		</dependency>

		<dependency>
		    <groupId>javax.ws.rs</groupId>
		    <artifactId>javax.ws.rs-api</artifactId>
		    <version>2.0</version>
		</dependency>

		<dependency>
			<groupId>com.ibm.watson.developer_cloud</groupId>
			<artifactId>language-translator</artifactId>
			<version>3.7.0</version>
		</dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <warName>GetStartedJava</warName>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>net.wasdev.wlp.maven.plugins</groupId>
                    <artifactId>liberty-maven-plugin</artifactId>
                    <version>1.2.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>net.wasdev.wlp.maven.plugins</groupId>
                <artifactId>liberty-maven-plugin</artifactId>
                <configuration>
                    <configFile>src/main/wlp/server.xml</configFile>
                    <bootstrapProperties>
                        <appLocation>../../../../../${project.build.finalName}</appLocation>
                    </bootstrapProperties>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
'use strict';

/**
 * Requirements
 * @ignore
 */
const Base = require('../Base.js').Base;

/**
 * @class
 * @memberOf entity
 * @extends {Base}
 */
class Loader extends Base
{
    /**
     * @ignore
     */
    constructor(items)
    {
        super();
        this._items = items || [];
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': ['model/Loader.items'] };
    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'model/Loader';
    }

    /**
     * Loads & parses data and resolve it as an array
     *
     * @param {*} [changes]
     * @returns {Promise.<Array>}
     */
    load(changes)
    {
        return Promise.resolve(this._items);
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.Loader = Loader;


text:
<?php

namespace ZendTest\Db\Adapter\Driver\Pdo;

use Zend\Db\Adapter\Driver\Pdo\Statement;

class StatementIntegrationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Statement
     */
    protected $statement;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $pdoStatementMock = null;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->statement = new Statement;
        $this->statement->setDriver($this->getMock('Zend\Db\Adapter\Driver\Pdo\Pdo', ['createResult'], [], '', false));
        $this->statement->initialize(new TestAsset\CtorlessPdo(
            $this->pdoStatementMock = $this->getMock('PDOStatement', ['execute', 'bindParam']))
        );
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    public function testStatementExecuteWillConvertPhpBoolToPdoBoolWhenBinding()
    {
        $this->pdoStatementMock->expects($this->any())->method('bindParam')->with(
            $this->equalTo('foo'),
            $this->equalTo(false),
            $this->equalTo(\PDO::PARAM_BOOL)
        );
        $this->statement->execute(['foo' => false]);
    }

    public function testStatementExecuteWillUsePdoStrByDefaultWhenBinding()
    {
        $this->pdoStatementMock->expects($this->any())->method('bindParam')->with(
            $this->equalTo('foo'),
            $this->equalTo('bar'),
            $this->equalTo(\PDO::PARAM_STR)
        );
        $this->statement->execute(['foo' => 'bar']);
    }
}


text:
<?php

namespace Xivic\UserBundle\Entity;
use FOS\UserBundle\Model\UserInterface as UInterface;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        $this->roles = array();

    }
    public function addRole($role)
    {

         if (!in_array($role, $this->roles, true)) {
            $this->roles[] = $role;
        }

        return $this;
    }

    public function getRoles()
    {
        $roles = $this->roles;

        foreach ($this->getGroups() as $group) {
            $roles = array_merge($roles, $group->getRoles());
        }

        return array_unique($roles);
    }

}


text:
<?php

namespace Nova\Auth;

use Nova\Auth\DatabaseUserProvider;
use Nova\Auth\ExtendedUserProvider;
use Nova\Auth\RequestGuard;
use Nova\Auth\SessionGuard;
use Nova\Auth\TokenGuard;
use Nova\Foundation\Application;

use Closure;
use InvalidArgumentException;

class AuthManager
{
    /**
     * The application instance.
     *
     * @var \Nova\Foundation\Application
     */
    protected $app;

    /**
     * The registered custom driver creators.
     *
     * @var array
     */
    protected $customCreators = array();

    /**
     * The registered custom provider creators.
     *
     * @var array
     */
    protected $customProviderCreators = array();

    /**
     * The array of created "drivers".
     *
     * @var array
     */
    protected $guards = array();

    /**
     * The user resolver shared by various services.
     *
     * Determines the default user for Request, and the UserInterface.
     *
     * @var \Closure
     */
    protected $userResolver;

    /**
     * Create a new manager instance.
     *
     * @param  \Nova\Foundation\Application  $app
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;

        $this->userResolver = function ($guard = null)
        {
            return $this->guard($guard)->user();
        };
    }

    /**
     * Attempt to get the guard from the local cache.
     *
     * @param  string  $name
     * @return \Nova\Auth\Guard
     */
    public function guard($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();

        if (! isset($this->guards[$name])) {
            $this->guards[$name] = $this->resolve($name);
        }

        return $this->guards[$name];
    }

    /**
     * Resolve the given guard.
     *
     * @param  string  $name
     * @return \Nova\Auth\Guard
     *
     * @throws \InvalidArgumentException
     */
    protected function resolve($name)
    {
        $config = $this->getConfig($name);

        if (is_null($config)) {
            throw new InvalidArgumentException("Auth guard [{$name}] is not defined.");
        }

        if (isset($this->customCreators[$config['driver']])) {
            return $this->callCustomCreator($name, $config);
        }

        $method = 'create' .ucfirst($config['driver']) .'Driver';

        if (! method_exists($this, $method)) {
            throw new InvalidArgumentException("Auth guard driver [{$config['driver']}] is not defined.");
        }

        return call_user_func(array($this, $method), $name, $config);
    }

    /**
     * Call a custom driver creator.
     *
     * @param  string  $name
     * @param  array  $config
     * @return mixed
     */
    protected function callCustomCreator($name, array $config)
    {
        $driver = $config['driver'];

        $callback = $this->customCreators[$driver];

        return call_user_func($callback, $this->app, $name, $config);
    }

    /**
     * Create an instance of the database driver.
     *
     * @return \Nova\Auth\Guard
     */
    public function createSessionDriver($name, array $config)
    {
        $provider = $this->createUserProvider($config['provider']);

        $guard = new SessionGuard($name, $provider, $this->app['session.store']);

        // When using the remember me functionality of the authentication services we
        // will need to be set the encryption instance of the guard, which allows
        // secure, encrypted cookie values to get generated for those cookies.
        if (method_exists($guard, 'setCookieJar')) {
            $guard->setCookieJar($this->app['cookie']);
        }

        if (method_exists($guard, 'setDispatcher')) {
            $guard->setDispatcher($this->app['events']);
        }

        if (method_exists($guard, 'setRequest')) {
            $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
        }

        return $guard;
    }

    /**
     * Create a token based authentication guard.
     *
     * @param  string  $name
     * @param  array  $config
     * @return \Nova\Auth\TokenGuard
     */
    public function createTokenDriver($name, $config)
    {
        // The token guard implements a basic API token based guard implementation
        // that takes an API token field from the request and matches it to the
        // user in the database or another persistence layer where users are.
        $guard = new TokenGuard(
            $this->createUserProvider($config['provider']),
            $this->app['request']
        );

        $this->app->refresh('request', $guard, 'setRequest');

        return $guard;
    }

    /**
     * Create the user provider implementation for the driver.
     *
     * @param  string  $provider
     * @return \Nova\Auth\UserProviderInterface
     *
     * @throws \InvalidArgumentException
     */
    public function createUserProvider($provider)
    {
        $config = $this->app['config']["auth.providers.{$provider}"];

        // Retrieve the driver from configuration.
        $driver = $config['driver'];

        if (isset($this->customProviderCreators[$driver])) {
            $callback = $this->customProviderCreators[$driver];

            return call_user_func($callback, $this->app, $config);
        }

        switch ($driver) {
            case 'database':
                return $this->createDatabaseProvider($config);

            case 'extended':
                return $this->createExtendedProvider($config);

            default:
                break;
        }

        throw new InvalidArgumentException("Authentication user provider [{$driver}] is not defined.");
    }

    /**
     * Create an instance of the database user provider.
     *
     * @return \Nova\Auth\DatabaseUserProvider
     */
    protected function createDatabaseProvider(array $config)
    {
        $connection = $this->app['db']->connection();

        return new DatabaseUserProvider($connection, $this->app['hash'], $config['table']);
    }

    /**
     * Create an instance of the Extended user provider.
     *
     * @return \Nova\Auth\ExtendedUserProvider
     */
    protected function createExtendedProvider(array $config)
    {
        return new ExtendedUserProvider($this->app['hash'], $config['model']);
    }

    /**
     * Get the guard configuration.
     *
     * @param  string  $name
     * @return array
     */
    protected function getConfig($name)
    {
        return $this->app['config']["auth.guards.{$name}"];
    }

    /**
     * Get the default authentication driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->app['config']['auth.defaults.guard'];
    }

    /**
     * Set the default guard driver the factory should serve.
     *
     * @param  string  $name
     * @return void
     */
    public function shouldUse($name)
    {
        $this->setDefaultDriver($name);

        $this->userResolver = function ($name = null)
        {
            return $this->guard($name)->user();
        };
    }

    /**
     * Set the default authentication driver name.
     *
     * @param  string  $name
     * @return void
     */
    public function setDefaultDriver($name)
    {
        $this->app['config']['auth.defaults.guard'] = $name;
    }

    /**
     * Register a new callback based request guard.
     *
     * @param  string  $driver
     * @param  callable  $callback
     * @return $this
     */
    public function viaRequest($driver, callable $callback)
    {
        return $this->extend($driver, function () use ($callback)
        {
            $guard = new RequestGuard($callback, $this->app['request']);

            $this->app->refresh('request', $guard, 'setRequest');

            return $guard;
        });
    }

    /**
     * Get the user resolver callback.
     *
     * @return \Closure
     */
    public function userResolver()
    {
        return $this->userResolver;
    }

    /**
     * Set the callback to be used to resolve users.
     *
     * @param  \Closure  $userResolver
     * @return $this
     */
    public function resolveUsersUsing(Closure $userResolver)
    {
        $this->userResolver = $userResolver;

        return $this;
    }

    /**
     * Register a custom driver creator Closure.
     *
     * @param  string  $driver
     * @param  \Closure  $callback
     * @return $this
     */
    public function extend($driver, Closure $callback)
    {
        $this->customCreators[$driver] = $callback;

        return $this;
    }

    /**
     * Register a custom provider creator Closure.
     *
     * @param  string  $name
     * @param  \Closure  $callback
     * @return $this
     */
    public function provider($name, Closure $callback)
    {
        $this->customProviderCreators[$name] = $callback;

        return $this;
    }

    /**
     * Dynamically call the default driver instance.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return call_user_func_array(array($this->guard(), $method), $parameters);
    }
}


text:
import React from "react";
import { shallow, configure } from "enzyme";

import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });

import Duration from "./Duration";

test("Duration properly render the value passed in props", () => {
  const component = shallow(<Duration value="125" />);

  expect(component.text()).toEqual("125m (2h05)");
});


text:
<!--

     Copyright 2005-2015 Red Hat, Inc.

     Red Hat licenses this file to you under the Apache License, version
     2.0 (the "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied.  See the License for the specific language governing
     permissions and limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
      <groupId>org.sonatype.oss</groupId>
      <artifactId>oss-parent</artifactId>
      <version>9</version>
    </parent>

    <groupId>io.fabric8.apps.devops</groupId>
    <artifactId>fabric8-devops</artifactId>
    <version>2.3-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>Fabric8 iPaaS Apps</name>

    <url>http://fabric8.io/</url>
    <inceptionYear>2015</inceptionYear>

    <organization>
        <name>Red Hat</name>
        <url>http://redhat.com</url>
    </organization>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <prerequisites>
        <maven>3.2.1</maven>
    </prerequisites>

    <!-- including A developer as it's required by the maven poms going into central -->
    <developers>
        <developer>
            <id>geeks</id>
            <name>Fabric8 Development Team</name>
            <organization>fabric8</organization>
            <organizationUrl>http://fabric8.io/</organizationUrl>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git@github.com:fabric8io/fabric8-ipaas.git</connection>
        <developerConnection>scm:git:git@github.com:fabric8io/fabric8-ipaas.git</developerConnection>
        <url>http://github.com/fabric8io/fabric8-ipaas</url>
        <tag>fabric8-ipaas-2.0.1</tag>
    </scm>

    <properties>
        <skipTests>false</skipTests>
        <skipItests>true</skipItests>
        <integrationTestPattern>**/*KubernetesTest*.java</integrationTestPattern>

        <jube.plugin.enabled>false</jube.plugin.enabled>

        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

        <arquillian.version>1.1.8.Final</arquillian.version>
        <commons.beanutils.version>1.9.2</commons.beanutils.version>
        <docker.assembly.exportBaseDir>false</docker.assembly.exportBaseDir>
        <!-- TODO this can be removed once we upgrade the docker maven plugin -->
        <docker.assembly.exportBase>false</docker.assembly.exportBase>
        <docker.maven.plugin.version>0.13.3</docker.maven.plugin.version>
        <fabric8.dockerPrefix>docker.io/</fabric8.dockerPrefix>
        <fabric8.dockerUser>fabric8/</fabric8.dockerUser>
        <exec-maven-plugin.version>1.2.1</exec-maven-plugin.version>
        <maven.surefire.plugin.version>2.17</maven.surefire.plugin.version>
        <jube.version>2.2.0</jube.version>
        <junit.version>4.12</junit.version>
        <fabric8.version>2.2.23</fabric8.version>
        <fabric8.release.version>${fabric8.version}</fabric8.release.version>
        <maven.require.version>3.1.1</maven.require.version>
        <maven.enforcer.plugin.version>1.4</maven.enforcer.plugin.version>
    </properties>

    <distributionManagement>
      <repository>
        <id>oss-sonatype-staging</id>
        <name>Sonatype Staging Repository</name>
        <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
      </repository>
      <snapshotRepository>
        <id>oss-sonatype-snapshots</id>
        <name>OSS Sonatype Nexus Snapshots</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      </snapshotRepository>
    </distributionManagement>

    <repositories>
      <repository>
    			<id>oss-sonatype-snapshots</id>
    			<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
          <name>OSS Sonatype Nexus Snapshots</name>
    			<releases>
    				<enabled>false</enabled>
    			</releases>
    			<snapshots>
    				<enabled>true</enabled>
    			</snapshots>
    		</repository>
    </repositories>
    <pluginRepositories>
      <pluginRepository>
        <id>oss-sonatype-snapshots</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        <name>OSS Sonatype Nexus Snapshots</name>
        <releases>
          <enabled>false</enabled>
        </releases>
        <snapshots>
          <enabled>true</enabled>
        </snapshots>
      </pluginRepository>
    </pluginRepositories>

    <modules>
      <module>artifactory</module>
      <module>brackets</module>
      <module>chaos-monkey</module>
      <module>cdelivery</module>
      <module>elasticsearch</module>
      <module>fabric8-forge</module>
      <module>gerrit</module>
      <module>gogs</module>
      <module>grafana2</module>
      <module>hubot-irc</module>
      <module>hubot-letschat</module>
      <module>hubot-notifier</module>
      <module>hubot-slack</module>
      <module>image-linker</module>
      <module>jenkins</module>
      <module>keycloak</module>
      <module>kibana</module>
      <module>kiwi-irc</module>
      <module>letschat</module>
      <module>nexus</module>
      <module>orion</module>
      <module>prometheus</module>
      <module>sonarqube</module>
      <module>taiga</module>
    </modules>

    <build>
      <pluginManagement>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.5</version>
          </plugin>
        </plugins>
      </pluginManagement>
      <plugins>
        <!-- generate a .zip with all the quickstarts -->
        <plugin>
          <groupId>io.fabric8</groupId>
          <artifactId>fabric8-maven-plugin</artifactId>
          <version>${fabric8.version}</version>
          <executions>
            <execution>
              <id>json</id>
              <phase>generate-resources</phase>
              <goals>
                <goal>json</goal>
              </goals>
             </execution>
             <execution>
              <id>attach</id>
              <phase>package</phase>
              <goals>
                <goal>attach</goal>
              </goals>
            </execution>
          </executions>
          <configuration>
            <replaceReadmeLinksPrefix>/apps/</replaceReadmeLinksPrefix>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
          <configuration>
            <nonFilteredFileExtensions>
              <nonFilteredFileExtension>zip</nonFilteredFileExtension>
              <nonFilteredFileExtension>gz</nonFilteredFileExtension>
              <nonFilteredFileExtension>jar</nonFilteredFileExtension>
            </nonFilteredFileExtensions>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-enforcer-plugin</artifactId>
          <version>${maven.enforcer.plugin.version}</version>
          <executions>
            <execution>
              <id>enforce-versions</id>
              <goals>
                <goal>enforce</goal>
              </goals>
              <configuration>
                <rules>
                  <requireMavenVersion>
                    <version>${maven.require.version}</version>
                  </requireMavenVersion>
                </rules>
              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.5</version>
          <configuration>
            <releaseProfiles>docker-push,docker-public</releaseProfiles>
          </configuration>
        </plugin>
        <plugin>
          <groupId>io.fabric8.jube</groupId>
          <artifactId>jube-maven-plugin</artifactId>
          <version>${jube.version}</version>
        </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>2.17</version>
              <inherited>true</inherited>
              <configuration>
                  <skipTests>${skipTests}</skipTests>
                  <excludes>
                      <exclude>${integrationTestPattern}</exclude>
                  </excludes>
              </configuration>
              <executions>
                  <execution>
                      <id>int-test</id>
                      <goals>
                          <goal>test</goal>
                      </goals>
                      <phase>integration-test</phase>
                      <configuration>
                          <skipTests>${skipItests}</skipTests>
                          <excludes>
                              <exclude>none</exclude>
                          </excludes>
                          <includes>
                              <include>${integrationTestPattern}</include>
                          </includes>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
      </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.fabric8</groupId>
                <artifactId>fabric8-project</artifactId>
                <version>${fabric8.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.junit</groupId>
                <artifactId>arquillian-junit-container</artifactId>
                <version>${arquillian.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.fabric8</groupId>
                <artifactId>fabric8-arquillian</artifactId>
                <version>${fabric8.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>io.fabric8</groupId>
                <artifactId>kubernetes-assertions</artifactId>
                <version>${fabric8.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <profiles>
        <profile>
          <id>fabric8-snapshot</id>
          <properties>
            <fabric8.version>2.3-SNAPSHOT</fabric8.version>
            <fabric8.release.version>2.2.22</fabric8.release.version>
            <fabric8.dockerPrefix />
          </properties>
        </profile>
        <profile>
          <id>jube-snapshot</id>
          <properties>
            <jube.version>2.2-SNAPSHOT</jube.version>
          </properties>
        </profile>

        <profile>
            <id>release</id>
            <build>
                <plugins>
                  <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-gpg-plugin</artifactId>
                    <configuration>
                      <passphrase>${gpg.passphrase}</passphrase>
                      <useAgent>true</useAgent>
                    </configuration>
                  </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-enforcer-plugin</artifactId>
                        <version>${maven.enforcer.plugin.version}</version>
                        <executions>
                            <execution>
                                <id>enforce-no-snapshots</id>
                                <goals>
                                    <goal>enforce</goal>
                                </goals>
                                <configuration>
                                    <rules>
                                        <requireReleaseDeps>
                                            <message>No Snapshots Allowed!</message>
                                        </requireReleaseDeps>
                                    </rules>
                                    <fail>true</fail>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>hawtio-snapshot</id>
            <properties>
                <hawtio.version>1.5-SNAPSHOT</hawtio.version>
            </properties>
        </profile>
        <profile>
            <id>license</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.mycila</groupId>
                        <artifactId>license-maven-plugin</artifactId>
                        <version>2.6</version>
                        <configuration>
                            <includes>
                                <include>src/main/java/**</include>
                                <include>src/test/java/**</include>
                                <include>pom.xml</include>
                                <include>**/*.xml</include>
                                <include>**/*.cfg</include>
                                <include>**/*.properties</include>
                            </includes>
                            <excludes>
                                <!-- exclude sampel data -->
                                <exclude>**/src/data/**</exclude>
                                <exclude>**/resources/data/**</exclude>
                                <!-- exclude hidden dir -->
                                <exclude>**/.*/**</exclude>
                            </excludes>
                        </configuration>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>check</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>docker-build</id>
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.jolokia</groupId>
                            <artifactId>docker-maven-plugin</artifactId>
                            <version>${docker.maven.plugin.version}</version>
                            <executions>
                                <execution>
                                    <goals>
                                        <goal>build</goal>
                                    </goals>
                                    <phase>package</phase>
                                </execution>
                            </executions>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>
    </profiles>
</project>


text:
<?php
namespace Escuela\UserManagerBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Escuela\UserManagerBundle\Entity\QuestionSecurity;

use Gedmo\Translatable\Entity;

class LoadQuestionSecurityData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface{

	/**
	* @var ContainerInterface
	*/
	private $container;

	const ES = 'es_ES';
	const EN = 'en_US';

	/**
	 * {@inheritDoc}
	 */
	public function setContainer(ContainerInterface $container = null)
	{
		$this->container = $container;
	}

	public function load(ObjectManager $manager){

		$transRepository = $manager->getRepository('Gedmo\\Translatable\\Entity\\Translation');

		$id = 1;

		$em = $this->container->get('doctrine.orm.entity_manager');
		$questions = $this->getQuestionSecurity();
		$field = "question";
		foreach ($questions as $question){

			$entity = new QuestionSecurity();
			$entity->setQuestion($question[self::EN]);
			//$entity->setTranslatableLocale("en");
			// persisting multiple translations, assume default locale is ES

			$transRepository->translate($entity, $field, 'es_ES', $question[self::ES]);

			$em->persist($entity);

			$em->flush();

		}

		$q = $manager->getRepository('EscuelaUserManagerBundle:QuestionSecurity')->findOneBy(array());
		//var_dump($q->getId()); die;

		$this->addReference('question-security-admin', $q);//die;

	}

	/**
	 * {@inheritDoc}
	 */
	public function getOrder()
	{
		return 1; // the order in which fixtures will be loaded
	}

	/**
	 *
	 * @return multitype:multitype:string
	 */
	public function getQuestionSecurity(){

		return array(1=>array("es_ES"=>"¿Cuál es el segundo nombre de mi mamá?","en_US"=>"What is my mom's middle name?"),
			2=>array("es_ES"=>"¿Cuál es el nombre de mi primera mascota?","en_US"=>"What is the name of my first pet?"),
			3=>array("es_ES"=>"¿Que edad tiene mi hijo mayor?","en_US"=>"How old is my oldest son?"),
			4=>array("es_ES"=>"¿Fecha de nacimiento de su esposa?","en_US"=>"Your wife's date of birth?"));

	}

}


text:
package org.apache.druid.sql.calcite.expression;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIntervalQualifier;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.druid.math.expr.ExprEval;
import org.apache.druid.math.expr.Parser;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.sql.calcite.planner.Calcites;
import org.apache.druid.sql.calcite.planner.PlannerConfig;
import org.apache.druid.sql.calcite.planner.PlannerContext;
import org.apache.druid.sql.calcite.table.RowSignatures;
import org.apache.druid.sql.calcite.util.CalciteTests;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Assert;

import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class ExpressionTestHelper
{
  private static final PlannerContext PLANNER_CONTEXT = PlannerContext.create(
      CalciteTests.createOperatorTable(),
      CalciteTests.createExprMacroTable(),
      new PlannerConfig(),
      ImmutableMap.of(),
      ImmutableList.of(),
      CalciteTests.REGULAR_USER_AUTH_RESULT
  );

  private final RowSignature rowSignature;
  private final Map<String, Object> bindings;
  private final RelDataTypeFactory typeFactory;
  private final RexBuilder rexBuilder;
  private final RelDataType relDataType;

  ExpressionTestHelper(RowSignature rowSignature, Map<String, Object> bindings)
  {
    this.rowSignature = rowSignature;
    this.bindings = bindings;

    this.typeFactory = new JavaTypeFactoryImpl();
    this.rexBuilder = new RexBuilder(typeFactory);
    this.relDataType = RowSignatures.toRelDataType(rowSignature, typeFactory);
  }

  RelDataType createSqlType(SqlTypeName sqlTypeName)
  {
    return typeFactory.createSqlType(sqlTypeName);
  }

  RexNode makeInputRef(String columnName)
  {
    int columnNumber = rowSignature.indexOf(columnName);
    return rexBuilder.makeInputRef(relDataType.getFieldList().get(columnNumber).getType(), columnNumber);
  }

  RexNode getConstantNull()
  {
    return rexBuilder.constantNull();
  }

  RexLiteral makeFlag(Enum flag)
  {
    return rexBuilder.makeFlag(flag);
  }

  RexLiteral makeNullLiteral(SqlTypeName sqlTypeName)
  {
    return rexBuilder.makeNullLiteral(createSqlType(sqlTypeName));
  }

  RexLiteral makeLiteral(String s)
  {
    return rexBuilder.makeLiteral(s);
  }

  RexNode makeLiteral(DateTime timestamp)
  {
    return rexBuilder.makeTimestampLiteral(Calcites.jodaToCalciteTimestampString(timestamp, DateTimeZone.UTC), 0);
  }

  RexNode makeLiteral(Integer integer)
  {
    return rexBuilder.makeLiteral(new BigDecimal(integer), createSqlType(SqlTypeName.INTEGER), true);
  }

  RexNode makeLiteral(Long bigint)
  {
    return rexBuilder.makeLiteral(new BigDecimal(bigint), createSqlType(SqlTypeName.BIGINT), true);
  }

  RexNode makeLiteral(BigDecimal bigDecimal)
  {
    return rexBuilder.makeExactLiteral(bigDecimal);
  }

  RexNode makeLiteral(BigDecimal v, SqlIntervalQualifier intervalQualifier)
  {
    return rexBuilder.makeIntervalLiteral(v, intervalQualifier);
  }

  RexNode makeLiteral(Double d)
  {
    return rexBuilder.makeLiteral(d, createSqlType(SqlTypeName.DOUBLE), true);
  }

  RexNode makeCall(SqlOperator op, RexNode... exprs)
  {
    return rexBuilder.makeCall(op, exprs);
  }

  RexNode makeAbstractCast(RelDataType type, RexNode exp)
  {
    return rexBuilder.makeAbstractCast(type, exp);
  }

  /**
   * @return Representation of variable that is bound in an expression. Intended use is as one of
   * the args to {@link #buildExpectedExpression(String, Object...)}.
   */
  Variable makeVariable(String name)
  {
    return new Variable(name);
  }

  private static class Variable
  {
    private final String name;

    Variable(String name)
    {
      this.name = name;
    }

    @Override
    public String toString()
    {
      return "\"" + name + "\"";
    }
  }

  DruidExpression buildExpectedExpression(String functionName, Object... args)
  {
    String noDelimiter = "";
    String argsString = Arrays.stream(args)
                              .map(ExpressionTestHelper::quoteIfNeeded)
                              .collect(Collectors.joining(","));
    List<String> elements = Arrays.asList(functionName, "(", argsString, ")");
    return DruidExpression.fromExpression(String.join(noDelimiter, elements));
  }

  private static String quoteIfNeeded(@Nullable Object arg)
  {
    if (arg == null) {
      return "null";
    } else if (arg instanceof String) {
      return "'" + arg + "'";
    } else if (arg instanceof Boolean) {
      return (Boolean) arg ? "1" : "0";
    } else {
      return arg.toString();
    }
  }

  void testExpression(
      SqlTypeName sqlTypeName,
      SqlOperator op,
      List<RexNode> exprs,
      DruidExpression expectedExpression,
      Object expectedResult
  )
  {
    RelDataType returnType = createSqlType(sqlTypeName);
    testExpression(rexBuilder.makeCall(returnType, op, exprs), expectedExpression, expectedResult);
  }

  void testExpression(
      SqlOperator op,
      RexNode expr,
      DruidExpression expectedExpression,
      Object expectedResult
  )
  {
    testExpression(op, Collections.singletonList(expr), expectedExpression, expectedResult);
  }

  void testExpression(
      SqlOperator op,
      List<? extends RexNode> exprs,
      DruidExpression expectedExpression,
      Object expectedResult
  )
  {
    testExpression(rexBuilder.makeCall(op, exprs), expectedExpression, expectedResult);
  }

  void testExpression(
      RexNode rexNode,
      DruidExpression expectedExpression,
      Object expectedResult
  )
  {
    DruidExpression expression = Expressions.toDruidExpression(PLANNER_CONTEXT, rowSignature, rexNode);
    Assert.assertEquals("Expression for: " + rexNode, expectedExpression, expression);

    ExprEval result = Parser.parse(expression.getExpression(), PLANNER_CONTEXT.getExprMacroTable())
                            .eval(Parser.withMap(bindings));
    Assert.assertEquals("Result for: " + rexNode, expectedResult, result.value());
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Roslyn.Utilities;

namespace BuildValidator
{
    internal static class IldasmUtilities
    {
        private static string GetIldasmPath()
        {
            var ildasmExeName = PlatformInformation.IsWindows ? "ildasm.exe" : "ildasm";
            var directory = Path.GetDirectoryName(typeof(IldasmUtilities).GetTypeInfo().Assembly.Location) ?? throw new DirectoryNotFoundException();
            string ridName;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ridName = "win-x64";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                ridName = "osx-x64";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                ridName = "linux-x64";
            }
            else
            {
                throw new PlatformNotSupportedException("Runtime platform not supported for testing");
            }

            return Path.Combine(directory, "runtimes", ridName, "native", ildasmExeName);
        }

        internal static readonly string IldasmPath = GetIldasmPath();
    }
}


text:
<?php
$lang = array(

'design_user_message' =>
'User Mitteilungen Template',

'design_system_offline' =>
'System Offline Template',

'design_email_notification' =>
'E-Mail Benachrichtigung Template',

'design_member_profile_templates' =>
'Mitglied Profil Template',

'member_register_member' =>
'Mitglieder eintragen',

'member_validation' =>
'Member Überprüfung',

'member_view_members' =>
'Mitglieder zeigen',

'member_ip_search' =>
'Mitglied IP Suche',

'member_custom_profile_fields' =>
'Eigene Profil-Felder',

'member_group_manager' =>
'Mitglieder-Gruppen Verwaltung',

'member_config' =>
'Mitglied Konfiguration',

'member_banning' =>
'Mitglied sperren',

'member_search' =>
'Mitglied suchen',

'data_sql_manager' =>
'SQL Manager',

'data_search_and_replace' =>
'Suchen und Ersetzen',

'data_recount_stats' =>
'Neuzählung Stats',

'data_php_info' =>
'PHP Info',

'data_clear_caching' =>
'Caching löschen',

'file_index' =>
'Datei Manager',

'cont_field_group_management' =>
'Feldgruppen Verwaltung',

'members_member_group_manager' =>
'Mitgliedergruppen Verwaltung',

'cont_category_management' =>
'Kategorien Verwaltung',

'members_custom_profile_fields' =>
'Eigene Mitglieder-Felder',

'logs_view_cp_log' =>
'Control Panel Log zeigen',

'logs_view_throttle_log' =>
'Drosselung Log zeigen',

'logs_view_search_log' =>
'Suche Log zeigen',

'logs_view_email_log' =>
'E-Mail Log zeigen',

'util_member_import' =>
'Mitglieder Import',

'util_import_from_xml' =>
'Import von XML',

'util_translation_tool' =>
'Übersetzungshilfe',

'plug_index' =>
'Plugins',

'modu_index' =>
'Module',

'exte_index' =>
'Extensions',

'acce_index' =>
'Accessories',

'translate' =>
'Update',

''=>''
);

// End of File


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/stock_info_widget"
    android:initialLayout="@layout/stock_info_widget"
    android:minHeight="110dp"
    android:minWidth="250dp"
    android:previewImage="@drawable/stock_widget_preview"
    android:resizeMode="vertical"
    android:updatePeriodMillis="0"
    android:widgetCategory="home_screen|keyguard"/>