Exemplo n.º 1
0
        public void TestAddAndGrow()
        {
            var d = new Deque<int>(0);
            Assert.IsTrue(d.Count == 0);
            Assert.IsTrue(d.Capacity == 0);

            d.AddFirst(1);
            Assert.IsTrue(d.Count == 1);
            Assert.IsTrue(d.Capacity == 4);

            d.AddFirst(0);
            Assert.IsTrue(d.Count == 2);
            Assert.IsTrue(d.Capacity == 4);

            d.AddLast(2);
            d.AddLast(3);
            Assert.IsTrue(d.Count == 4);
            Assert.IsTrue(d.Capacity == 4);

            d.AddLast(4);
            Assert.IsTrue(d.Count == 5);
            Assert.IsTrue(d.Capacity == 8);

            var arr = d.ToArray();
            var exp = new int[] { 0, 1, 2, 3, 4 };
            Assert.IsTrue(arr.Length == exp.Length);
            for (int i = 0; i < arr.Length; i++) {
                Assert.IsTrue(arr[i] == exp[i]);
            }
        }
 /// <summary>
 /// Add a buffer to the end of the queue and associate a promise with it that should be completed when
 /// all the buffer's bytes have been consumed from the queue and written.
 /// </summary>
 /// <param name="buf">to add to the tail of the queue</param>
 /// <param name="promise">to complete when all the bytes have been consumed and written, can be void.</param>
 public void Add(IByteBuffer buf, IPromise promise)
 {
     // buffers are added before promises so that we naturally 'consume' the entire buffer during removal
     // before we complete it's promise.
     _bufAndListenerPairs.AddLast​(buf);
     if (promise is object && !promise.IsVoid)
     {
         _bufAndListenerPairs.AddLast​(promise);
     }
     IncrementReadableBytes(buf.ReadableBytes);
 }
 void EnqueueFrameWithoutMerge(IHttp2RemoteFlowControlled frame)
 {
     _pendingWriteQueue.AddLast​(frame);
     // This must be called after adding to the queue in order so that hasFrame() is
     // updated before updating the stream state.
     IncrementPendingBytes(frame.Size, true);
 }
Exemplo n.º 4
0
        private static Deque <EventType> Events(bool inbound, int size)
        {
            EventType[] events;
            if (inbound)
            {
                events = new EventType[] {
                    EventType.USER_EVENT, EventType.MESSAGE_RECEIVED, EventType.MESSAGE_RECEIVED_LAST,
                    EventType.EXCEPTION_CAUGHT
                };
            }
            else
            {
                events = new EventType[] {
                    EventType.READ, EventType.WRITE, EventType.EXCEPTION_CAUGHT
                };
            }

            Random            random         = new Random();
            Deque <EventType> expectedEvents = new Deque <EventType>();

            for (int i = 0; i < size; i++)
            {
                expectedEvents.AddLast​(events[random.Next(events.Length)]);
            }
            return(expectedEvents);
        }
Exemplo n.º 5
0
        /// <summary>
        /// <para><paramref name="from"/> からの最短経路長を01-BSFで求める。</para>
        /// <para>計算量: O(|E| + |V|)</para>
        /// </summary>
        public static T[] ShortestPath01BFS <T, TOp, TNode, TEdge>(this IWGraph <T, TOp, TNode, TEdge> graph, int from)
            where T : struct
            where TOp : struct, INumOperator <T>
            where TNode : IGraphNode <TEdge>
            where TEdge : IWGraphEdge <T>
        {
            TOp op       = default;
            var graphArr = graph.AsArray();
            var INF      = op.MaxValue;
            var res      = new T[graphArr.Length];

            System.Array.Fill(res, INF);
            res[from] = default;

            var used    = new bool[graphArr.Length];
            int count   = 0;
            var remains = new Deque <int>(graphArr.Length)
            {
                from
            };

            while (remains.Count > 0)
            {
                var ix = remains.PopFirst();
                if (used[ix])
                {
                    continue;
                }
                used[ix] = true;
                if (++count >= graphArr.Length)
                {
                    break;
                }
                var len = res[ix];
                foreach (var e in graphArr[ix].Children)
                {
                    var to         = e.To;
                    var nextLength = len;
                    if (EqualityComparer <T> .Default.Equals(e.Value, default))
                    {
                        if (op.GreaterThan(res[to], nextLength))
                        {
                            res[to] = nextLength;
                            remains.AddFirst(to);
                        }
                    }
                    else
                    {
                        nextLength = op.Increment(nextLength);
                        if (op.GreaterThan(res[to], nextLength))
                        {
                            res[to] = nextLength;
                            remains.AddLast(to);
                        }
                    }
                }
            }
            return(res);
        }
Exemplo n.º 6
0
 public override void Execute(IRunnable command)
 {
     if (command is null)
     {
         ThrowHelper.ThrowNullReferenceException_Command();
     }
     _tasks.AddLast​(command);
 }
 public void PushStack(ExpressionResultCacheStackEntry lambda)
 {
     if (callStack == null)
     {
         callStack           = new ArrayDeque <ExpressionResultCacheStackEntry>();
         lastValueCacheStack = new ArrayDeque <long?>(10);
     }
     callStack.AddLast(lambda);
 }
 public void PushContext(long contextNumber)
 {
     if (callStack == null)
     {
         callStack           = new ArrayDeque <ExpressionResultCacheStackEntry>();
         lastValueCacheStack = new ArrayDeque <long?>(10);
     }
     lastValueCacheStack.AddLast(contextNumber);
 }
Exemplo n.º 9
0
        public void RemoveLastTest()
        {
            var d1 = new Deque <int>();
            int a  = 5;

            d1.AddLast(a);

            Assert.AreEqual <int>(a, d1.RemoveLast());
        }
Exemplo n.º 10
0
 public void Given_null_item_add_should_throw_NullPointerException()
 {
     // arrange
     var deque = new Deque<string>();
     // act
     // assert
     Assert.Throws<NullReferenceException>(() => deque.AddFirst(null));
     Assert.Throws<NullReferenceException>(() => deque.AddLast(null));
 }
Exemplo n.º 11
0
 public void Add_element_should_increment_size()
 {
     // arrange
     var deque = new Deque<string>();
     // act
     deque.AddFirst("Item");
     deque.AddLast("Item2");
     // assert
     Assert.AreEqual(2, deque.Size());
 }
Exemplo n.º 12
0
        public void OnEndSession(RtpMidiEndSession rtpMidiEndSession, model.RtpMidiServer rtpMidiServer)
        {
            Log.Info("RtpMidi", "Session end from: {}", rtpMidiServer);
            RtpMidiSessionConnection midiServer = currentSessions.GetValueOrDefault(rtpMidiEndSession.Ssrc);

            if (midiServer != null)
            {
                RtpMidiSession RtpMidiSession = midiServer.RtpMidiSession;
                RtpMidiSession.Sender = null;
                RtpMidiSession.OnEndSession(rtpMidiEndSession, rtpMidiServer);
            }
            currentSessions.Remove(rtpMidiEndSession.Ssrc);
            RtpMidiSessionConnection sessionTuple = currentSessions.GetValueOrDefault(rtpMidiEndSession.Ssrc);

            if (sessionTuple != null)
            {
                sessions.AddLast(sessionTuple.RtpMidiSession);
                NotifyMaxNumberOfSessions();
            }
        }
Exemplo n.º 13
0
        public void ContainsTest()
        {
            var d1 = new Deque <int>();
            int a  = 5;
            int b  = 10;

            d1.AddLast(a);
            d1.AddFirst(b);

            Assert.IsTrue(d1.Contains(a));
        }
Exemplo n.º 14
0
        public void TestRemoveAndTrim()
        {
            var d = new Deque<int>(4);
            Assert.IsTrue(d.Count == 0);
            Assert.IsTrue(d.Capacity == 4);

            d.AddLast(0);
            d.AddLast(1);
            d.AddLast(2);
            d.AddLast(3);
            d.AddLast(4);
            d.AddLast(5);
            Assert.IsTrue(d.Count == 6);
            Assert.IsTrue(d.Capacity == 8);

            d.RemoveLast();
            d.RemoveLast();
            d.RemoveLast();
            Assert.IsTrue(d.Count == 3);
            Assert.IsTrue(d.Capacity == 8);

            d.TrimExcess();
            Assert.IsTrue(d.Count == 3);
            Assert.IsTrue(d.Capacity == 3);

            var arr = d.ToArray();
            var exp = new int[] { 0, 1, 2 };
            Assert.IsTrue(arr.Length == exp.Length);
            for (int i = 0; i < arr.Length; i++) {
                Assert.IsTrue(arr[i] == exp[i]);
            }
        }
Exemplo n.º 15
0
 public void Remove_item_should_return_last_added_item()
 {
     // arrange
     var deque = new Deque<string>();
     deque.AddLast("LastItem");
     deque.AddFirst("Item");
     // act
     var actual = deque.RemoveFirst();
     var actualLast = deque.RemoveLast();
     // assert
     Assert.AreEqual("Item", actual);
     Assert.AreEqual("LastItem", actualLast);
 }
Exemplo n.º 16
0
        public void TestLast()
        {
            //arrange
            if (Deque <int> .IsEmpty)
            {
                Deque <int> .AddLast(1);
            }
            var expected = Deque <int> .tail.Data;
            int count    = Deque <int> .count;

            //act
            var actual = Deque <int> .Last;

            //assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 17
0
        public void TestAddLast()
        {
            //arrange
            var data                      = 365;
            int expectedCount             = Deque <int> .count + 1;
            DoublyNode <int> expectedTail = new DoublyNode <int>(data);

            //act
            Deque <int> .AddLast(data);

            DoublyNode <int> actualTail = Deque <int> .tail;
            int actualCount             = Deque <int> .count;

            //assert
            Assert.AreEqual(expectedTail.Data, actualTail.Data);
            Assert.AreEqual(expectedCount, actualCount);
        }
Exemplo n.º 18
0
        public void TestContains()
        {
            //arrange
            var  data      = 190;
            var  data2     = 270;
            bool expected  = true;
            bool expected2 = false;

            Deque <int> .Clear();

            Deque <int> .AddLast(data);

            //act

            var actual = Deque <int> .Contains(data);

            var actual2 = Deque <int> .Contains(data2);

            //assert

            Assert.AreEqual(expected, actual);
            Assert.AreEqual(expected2, actual2);
        }
Exemplo n.º 19
0
            /// <summary>
            /// 使用双向队列来完成
            /// 队列内只包含窗口内的最大值坐标,和最大值右侧的坐标
            /// 1窗口滑动前按以上从队尾添加坐标
            /// 2窗口滑动后,每滑动一次就可以增加一个返回值
            /// 3窗口滑动后,检查每次新加进的元素和队尾元素相比,如果新元素较大,就舍掉这些队尾元素,因为只需直到最大的元素位置就可以了
            /// 4当队首元素离开窗口时,要去除,由于这样的队列其实是【坐标代表元素】从大到小排列的,所以,从队首拿出来的坐标肯定是最大值
            /// </summary>
            /// <param name="nums"></param>
            /// <param name="k"></param>
            /// <returns></returns>
            public int[] MaxSlidingWindow(int[] nums, int k)
            {
                var         res = new List <int>();
                Deque <int> q   = new Deque <int>();

                for (var i = 0; i < nums.Length; ++i)
                {
                    if (!q.IsEmpty() && q.GetFirst() == i - k)
                    {
                        q.RemoveFirst();
                    }
                    while (!q.IsEmpty() && nums[q.GetLast()] < nums[i])
                    {
                        q.RemoveLast();
                    }
                    q.AddLast(i);
                    if (i >= k - 1)
                    {
                        res.Add(nums[q.GetFirst()]);
                    }
                }

                return(res.ToArray());
            }
Exemplo n.º 20
0
        public void TestEnumerator()
        {
            var exp = new int[] { 0, 1, 2, 3, 4, 5 };
            var d = new Deque<int>(4);
            d.AddLast(0);
            d.AddLast(1);
            d.AddLast(2);
            d.AddLast(3);
            d.AddLast(4);
            d.AddLast(5);

            int index = 0;
            foreach (var i in d) {
                Assert.IsTrue(i == exp[index++]);
            }
            Assert.IsTrue(index == 6);

            index = 0;
            var en = d.GetEnumerator();
            while (en.MoveNext()) {
                Assert.IsTrue(en.Current == exp[index++]);
            }
            Assert.IsTrue(index == 6);
        }
Exemplo n.º 21
0
        private static void RecursiveCompile(
            EvalFactoryNode evalNode,
            StatementContext context,
            ExprEvaluatorContext evaluatorContext,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            Deque <int> subexpressionIdStack,
            Stack <EvalFactoryNode> parentNodeStack,
            ICollection <string> allTagNamesOrdered)
        {
            var counter = 0;

            parentNodeStack.Push(evalNode);
            foreach (var child in evalNode.ChildNodes)
            {
                subexpressionIdStack.AddLast(counter++);
                RecursiveCompile(
                    child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack,
                    parentNodeStack, allTagNamesOrdered);
                subexpressionIdStack.RemoveLast();
            }
            parentNodeStack.Pop();

            LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null;
            LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes  = null;

            if (evalNode is EvalFilterFactoryNode)
            {
                var filterNode = (EvalFilterFactoryNode)evalNode;
                var eventName  = filterNode.RawFilterSpec.EventTypeName;
                if (context.TableService.GetTableMetadata(eventName) != null)
                {
                    throw new ExprValidationException("Tables cannot be used in pattern filter atoms");
                }

                var resolvedEventType = FilterStreamSpecRaw.ResolveType(
                    context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                var finalEventType       = resolvedEventType;
                var optionalTag          = filterNode.EventAsName;
                var isPropertyEvaluation = false;
                var isParentMatchUntil   = IsParentMatchUntil(evalNode, parentNodeStack);

                // obtain property event type, if final event type is properties
                if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    var optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            context.Container,
                            filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                            resolvedEventType,
                            filterNode.EventAsName,
                            context.EventAdapterService,
                            context.EngineImportService,
                            context.SchedulingService,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations,
                            subexpressionIdStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService,
                            context.StatementExtensionServicesContext);
                    finalEventType       = optionalPropertyEvaluator.FragmentEventType;
                    isPropertyEvaluation = true;
                }

                if (finalEventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName);
                }

                // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
                if (optionalTag != null)
                {
                    var       pair         = tags.TaggedEventTypes.Get(optionalTag);
                    EventType existingType = null;
                    if (pair != null)
                    {
                        existingType = pair.First;
                    }
                    if (existingType == null)
                    {
                        pair = tags.ArrayEventTypes.Get(optionalTag);
                        if (pair != null)
                        {
                            throw new ExprValidationException(
                                      "Tag '" + optionalTag + "' for event '" + eventName +
                                      "' used in the repeat-until operator cannot also appear in other filter expressions");
                        }
                    }
                    if ((existingType != null) && (existingType != finalEventType))
                    {
                        throw new ExprValidationException(
                                  "Tag '" + optionalTag + "' for event '" + eventName +
                                  "' has already been declared for events of type " + existingType.UnderlyingType.FullName);
                    }
                    pair = new Pair <EventType, string>(finalEventType, eventName);

                    // add tagged type
                    if (isPropertyEvaluation || isParentMatchUntil)
                    {
                        newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newArrayEventTypes.Put(optionalTag, pair);
                    }
                    else
                    {
                        newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newTaggedEventTypes.Put(optionalTag, pair);
                    }
                }

                // For this filter, filter types are all known tags at this time,
                // and additionally stream 0 (self) is our event type.
                // Stream type service allows resolution by property name event if that name appears in other tags.
                // by defaulting to stream zero.
                // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
                var selfStreamName = optionalTag;
                if (selfStreamName == null)
                {
                    selfStreamName = "s_" + UuidGenerator.Generate();
                }
                var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                var typePair    = new Pair <EventType, string>(finalEventType, eventName);
                filterTypes.Put(selfStreamName, typePair);
                filterTypes.PutAll(tags.TaggedEventTypes);

                // for the filter, specify all tags used
                var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes);
                filterTaggedEventTypes.Remove(optionalTag);

                // handle array tags (match-until clause)
                LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null;
                if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty())
                {
                    arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                    var patternSubexEventType = GetPatternSubexEventType(
                        context.StatementId, "pattern", subexpressionIdStack);

                    foreach (var entry in tags.ArrayEventTypes)
                    {
                        var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >();
                        specificArrayType.Put(entry.Key, entry.Value);
                        var arrayTagCompositeEventType =
                            context.EventAdapterService.CreateSemiAnonymousMapType(
                                patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(),
                                specificArrayType, isInsertInto);
                        context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType);

                        var tag = entry.Key;
                        if (!filterTypes.ContainsKey(tag))
                        {
                            var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag);
                            filterTypes.Put(tag, pair);
                            arrayCompositeEventTypes.Put(tag, pair);
                        }
                    }
                }

                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    filterTypes, context.EngineURI, true, false);
                var exprNodes = filterNode.RawFilterSpec.FilterExpressions;

                var spec = FilterSpecCompiler.MakeFilterSpec(
                    resolvedEventType, eventName, exprNodes,
                    filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                    filterTaggedEventTypes,
                    arrayCompositeEventTypes,
                    streamTypeService,
                    null, context, subexpressionIdStack);
                filterNode.FilterSpec = spec;
            }
            else if (evalNode is EvalObserverFactoryNode)
            {
                var observerNode = (EvalObserverFactoryNode)evalNode;
                try
                {
                    var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "observer", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters,
                        validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    observerNode.ObserverFactory = observerFactory;
                    observerFactory.SetObserverParameters(validated, convertor, validationContext);
                }
                catch (ObserverParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " +
                              e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message,
                              e);
                }
            }
            else if (evalNode is EvalGuardFactoryNode)
            {
                var guardNode = (EvalGuardFactoryNode)evalNode;
                try
                {
                    var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "guard", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    guardNode.GuardFactory = guardFactory;
                    guardFactory.SetGuardParameters(validated, convertor);
                }
                catch (GuardParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
            }
            else if (evalNode is EvalEveryDistinctFactoryNode)
            {
                var distinctNode             = (EvalEveryDistinctFactoryNode)evalNode;
                var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode);
                var streamTypeService        = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                    subexpressionIdStack, "every-distinct", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);
                IList <ExprNode> validated;
                try
                {
                    validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext);
                }
                catch (ExprValidationPropertyException ex)
                {
                    throw new ExprValidationPropertyException(
                              ex.Message +
                              ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                              ex.InnerException);
                }

                MatchedEventConvertor convertor =
                    new MatchedEventConvertorImpl(
                        matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                        allTagNamesOrdered, context.EventAdapterService);

                distinctNode.Convertor = convertor;

                // Determine whether some expressions are constants or time period
                IList <ExprNode>             distinctExpressions  = new List <ExprNode>();
                ExprTimePeriodEvalDeltaConst timeDeltaComputation = null;
                ExprNode expiryTimeExp = null;
                var      count         = -1;
                var      last          = validated.Count - 1;
                foreach (var expr in validated)
                {
                    count++;
                    if (count == last && expr is ExprTimePeriod)
                    {
                        expiryTimeExp = expr;
                        var timePeriodExpr = (ExprTimePeriod)expiryTimeExp;
                        timeDeltaComputation =
                            timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false));
                    }
                    else if (expr.IsConstantResult)
                    {
                        if (count == last)
                        {
                            var evaluateParams = new EvaluateParams(null, true, evaluatorContext);
                            var value          = expr.ExprEvaluator.Evaluate(evaluateParams);
                            if (!(value.IsNumber()))
                            {
                                throw new ExprValidationException(
                                          "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                            }

                            var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams);

                            long?timeExpire;
                            if (secondsExpire == null)
                            {
                                timeExpire = null;
                            }
                            else
                            {
                                timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire);
                            }

                            if (timeExpire != null && timeExpire > 0)
                            {
                                timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value);
                                expiryTimeExp        = expr;
                            }
                            else
                            {
                                Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr));
                            }
                        }
                        else
                        {
                            Log.Warn(
                                "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list",
                                expr.ToExpressionStringMinPrecedenceSafe());
                        }
                    }
                    else
                    {
                        distinctExpressions.Add(expr);
                    }
                }
                if (distinctExpressions.IsEmpty())
                {
                    throw new ExprValidationException(
                              "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
                }
                distinctNode.SetDistinctExpressions(distinctExpressions, timeDeltaComputation, expiryTimeExp);
            }
            else if (evalNode is EvalMatchUntilFactoryNode)
            {
                var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode;

                // compile bounds expressions, if any
                var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes);
                var streamTypeService   = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack,
                    "until", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext);
                matchUntilNode.LowerBounds = lower;

                var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext);
                matchUntilNode.UpperBounds = upper;

                var single = ValidateBounds(matchUntilNode.SingleBound, validationContext);
                matchUntilNode.SingleBound = single;

                var convertor = new MatchedEventConvertorImpl(
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered,
                    context.EventAdapterService);
                matchUntilNode.Convertor = convertor;

                // compile new tag lists
                ISet <string> arrayTags = null;
                var           matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        if (arrayTags == null)
                        {
                            arrayTags = new HashSet <string>();
                        }
                        arrayTags.Add(optionalTag);
                    }
                }

                if (arrayTags != null)
                {
                    foreach (var arrayTag in arrayTags)
                    {
                        if (!tags.ArrayEventTypes.ContainsKey(arrayTag))
                        {
                            tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag));
                            tags.TaggedEventTypes.Remove(arrayTag);
                        }
                    }
                }
                matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags);
            }
            else if (evalNode is EvalFollowedByFactoryNode)
            {
                var followedByNode = (EvalFollowedByFactoryNode)evalNode;
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService,
                    evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                if (followedByNode.OptionalMaxExpressions != null)
                {
                    IList <ExprNode> validated = new List <ExprNode>();
                    foreach (var maxExpr in followedByNode.OptionalMaxExpressions)
                    {
                        if (maxExpr == null)
                        {
                            validated.Add(null);
                        }
                        else
                        {
                            var visitor = new ExprNodeSummaryVisitor();
                            maxExpr.Accept(visitor);
                            if (!visitor.IsPlain)
                            {
                                var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() +
                                                   " are not allowed within the expression";
                                Log.Error(errorMessage);
                                throw new ExprValidationException(errorMessage);
                            }

                            var validatedExpr = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext);
                            validated.Add(validatedExpr);
                            if ((validatedExpr.ExprEvaluator.ReturnType == null) ||
                                (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric()))
                            {
                                var message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                                throw new ExprValidationException(message);
                            }
                        }
                    }
                    followedByNode.OptionalMaxExpressions = validated;
                }
            }

            if (newTaggedEventTypes != null)
            {
                tags.TaggedEventTypes.PutAll(newTaggedEventTypes);
            }
            if (newArrayEventTypes != null)
            {
                tags.ArrayEventTypes.PutAll(newArrayEventTypes);
            }
        }
Exemplo n.º 22
0
    static void Main()
    {
        int[] arrFront = { 5, 4, 3, 2, 1 };
        int[] arrBack  = { 6, 7, 8, 9, 10 };

        // create new Deque using these arrays
        Deque <int> d = new Deque <int>(arrBack, arrFront);

        // iterate from first to last
        Console.Write("The Deque contains  : ");
        foreach (int i in d)
        {
            Console.Write("{0} ", i);                  // 1 to 10
        }
        Console.WriteLine();

        // iterate from last to first
        Console.Write("Or in reverse order : ");
        foreach (int i in d.Reversed)
        {
            Console.Write("{0} ", i);                           // 10 to 1
        }
        Console.WriteLine();

        // permanently reverse the order of the items
        d.Reverse();

        // iterate from first to last again
        Console.Write("After permanent reversal : ");
        foreach (int i in d)
        {
            Console.Write("{0} ", i);                  // 10 to 1
        }
        Console.WriteLine();

        // add items at front
        Console.WriteLine("Added 11 and 12 at the front");
        d.AddRangeFirst(new int[] { 11, 12 });

        // add item at back
        Console.WriteLine("Added 0 at the back");
        d.AddLast(0);

        Console.WriteLine("The first item is : {0}", d.PeekFirst()); // 12
        int num;

        if (d.TryPeekLast(out num))
        {
            Console.WriteLine("The last item is : {0}", num); // 0
        }

        // pop last item
        Console.WriteLine("Popped last item");
        num = d.PopLast();

        // pop first item
        Console.WriteLine("Popped first item");
        d.TryPopFirst(out num);

        if (d.Contains(11))
        {
            // iterate again
            Console.Write("The Deque now contains : ");
            foreach (int i in d)
            {
                Console.Write("{0} ", i);                  // 11 to 1
            }
            Console.WriteLine();
        }

        // peek at last item
        Console.WriteLine("The last item is : {0}", d.PeekLast());  // 1

        // count items
        Console.WriteLine("The number of items is : {0}", d.Count); // 11

        // convert to an array
        int[] ia = d.ToArray();

        // reload to a new Deque adding all items at front so they'll now be reversed
        d = new Deque <int>(null, ia);
        Console.Write("The new Deque contains : ");
        foreach (int i in d)
        {
            Console.Write("{0} ", i);                  // 1 to 11
        }
        Console.WriteLine("\nThe capacity is : {0}", d.Capacity);
        d.TrimExcess();
        Console.WriteLine("After trimming the capacity is now : {0}", d.Capacity);

        // copy to an existing array
        ia = new int[d.Count];
        d.CopyTo(ia, 0);

        // clear the Deque (No pun intended!)
        d.Clear();
        Console.WriteLine("After clearing the Deque is now empty : {0}", d.IsEmpty);
        Console.WriteLine("The third element used to be : {0}", ia[2]);

        Console.ReadKey();
    }
Exemplo n.º 23
0
        public void TestValuesAndWrapAround()
        {
            var d = new Deque<int>(4);

            d.AddLast(1);   // internally it contains [H:1, 2, 3, 4]
            d.AddLast(2);
            d.AddLast(3);
            d.AddLast(4);
            Assert.IsTrue(d.PeekFirst() == 1 & d.PeekLast() == 4);

            d.RemoveFirst();
            d.RemoveLast();  // now it's [0, H:2, 3, 0]
            Assert.IsTrue(d.Count == 2 && d.Capacity == 4);
            Assert.IsTrue(d.PeekFirst() == 2 & d.PeekLast() == 3);

            d.AddLast(4);
            d.RemoveFirst(); // now it's [0, 0, H:3, 4]
            Assert.IsTrue(d.Count == 2 && d.Capacity == 4);
            Assert.IsTrue(d.PeekFirst() == 3 & d.PeekLast() == 4);

            d.AddLast(5);
            d.RemoveFirst(); // now it's [5, 0, 0, H:4]
            Assert.IsTrue(d.Count == 2 && d.Capacity == 4);
            Assert.IsTrue(d.PeekFirst() == 4 & d.PeekLast() == 5);

            d.AddFirst(3);
            d.AddFirst(2);   // now it's [5, H:2, 3, 4]
            Assert.IsTrue(d.Count == 4 && d.Capacity == 4);
            Assert.IsTrue(d.PeekFirst() == 2 & d.PeekLast() == 5);

            d.AddFirst(1);   // reallocated to [H:1, 2, 3, 4, 5, 0, 0, 0]
            d.AddFirst(0);   // now it's [1, 2, 3, 4, 5, 0, 0, H:0]
            Assert.IsTrue(d.Count == 6 && d.Capacity == 8);
            Assert.IsTrue(d.PeekFirst() == 0 & d.PeekLast() == 5);

            var arr = d.ToArray();
            var exp = new int[] { 0, 1, 2, 3, 4, 5 };
            Assert.IsTrue(arr.Length == exp.Length);
            for (int i = 0; i < arr.Length; i++) {
                Assert.IsTrue(arr[i] == exp[i]);
            }
        }
        public void AdvancedTestDequeLast()
        {
            var deque = new Deque<String>();
            var items = new List<string>
            {
                "0",
                "1",
                "2",
                "-",
                "-",
                "3",
                "4",
                "5",
                "6",
                "7",
                "8",
                "9"
            };

            Assert.AreEqual(0, deque.Size);
            Assert.IsTrue(deque.IsEmpty);

            foreach (var item in items)
            {
                if (item != "-")
                {
                    deque.AddLast(item);
                }
                else
                {
                    if (!deque.IsEmpty)
                    {
                        deque.RemoveLast();
                    }
                }
            }

            var builder = new StringBuilder();
            foreach (var item in deque)
            {
                builder.Append(item);
            }

            Assert.AreEqual("03456789", builder.ToString());
            Assert.AreEqual(8, deque.Size);
            Assert.IsFalse(deque.IsEmpty);

            while (!deque.IsEmpty)
            {
                deque.RemoveLast();
            }

            Assert.AreEqual(0, deque.Size);
            Assert.IsTrue(deque.IsEmpty);
        }
 public void Enque_Back(GameObject key)
 {
     deQueue.AddLast(key);
 }
        public Http2ControlFrameLimitEncoderTest()
        {
            _writer   = new Mock <IHttp2FrameWriter>();
            _ctx      = new Mock <IChannelHandlerContext>();
            _channel  = new Mock <IChannel>();
            _unsafe   = new Mock <IChannelUnsafe>();
            _config   = new Mock <IChannelConfiguration>();
            _executor = new Mock <IEventExecutor>();

            _numWrites = 0;

            var configuration   = new Mock <IHttp2FrameWriterConfiguration>();
            var frameSizePolicy = new Mock <IHttp2FrameSizePolicy>();

            _writer.SetupGet(x => x.Configuration).Returns(configuration.Object);
            configuration.SetupGet(x => x.FrameSizePolicy).Returns(frameSizePolicy.Object);
            frameSizePolicy.SetupGet(x => x.MaxFrameSize).Returns(Http2CodecUtil.DefaultMaxFrameSize);

            _writer
            .Setup(x => x.WriteRstStreamAsync(
                       It.IsAny <IChannelHandlerContext>(),
                       It.IsAny <int>(),
                       It.IsAny <Http2Error>(),
                       It.IsAny <IPromise>()))
            .Returns <IChannelHandlerContext, int, Http2Error, IPromise>((ctx, streamId, errorCode, p) =>
            {
                return(HandlePromise(p, 3).Task);
            });
            _writer
            .Setup(x => x.WriteSettingsAckAsync(
                       It.IsAny <IChannelHandlerContext>(),
                       It.IsAny <IPromise>()))
            .Returns <IChannelHandlerContext, IPromise>((ctx, p) =>
            {
                return(HandlePromise(p, 1).Task);
            });
            _writer
            .Setup(x => x.WritePingAsync(
                       It.IsAny <IChannelHandlerContext>(),
                       It.IsAny <bool>(),
                       It.IsAny <long>(),
                       It.IsAny <IPromise>()))
            .Returns <IChannelHandlerContext, bool, long, IPromise>((ctx, ack, data, p) =>
            {
                var promise = HandlePromise(p, 3);
                if (ack == false)
                {
                    promise.TryComplete();
                }
                return(promise.Task);
            });
            _writer
            .Setup(x => x.WriteGoAwayAsync(
                       It.IsAny <IChannelHandlerContext>(),
                       It.IsAny <int>(),
                       It.IsAny <Http2Error>(),
                       It.IsAny <IByteBuffer>(),
                       It.IsAny <IPromise>()))
            .Returns <IChannelHandlerContext, int, Http2Error, IByteBuffer, IPromise>((ctx, streamId, errCode, debugData, p) =>
            {
                ReferenceCountUtil.Release(debugData);
                _goAwayPromises.AddLast​(p);
                return(p.Task);
            });
            IHttp2Connection connection = new DefaultHttp2Connection(false);

            connection.Remote.FlowController = new DefaultHttp2RemoteFlowController(connection);
            connection.Local.FlowController  = new DefaultHttp2LocalFlowController(connection).FrameWriter(_writer.Object);

            DefaultHttp2ConnectionEncoder defaultEncoder =
                new DefaultHttp2ConnectionEncoder(connection, _writer.Object);

            _encoder = new Http2ControlFrameLimitEncoder(defaultEncoder, 2);
            DefaultHttp2ConnectionDecoder decoder =
                new DefaultHttp2ConnectionDecoder(connection, _encoder, (new Mock <IHttp2FrameReader>()).Object);
            var builder = new Http2ConnectionHandlerBuilder();

            builder.FrameListener = (new Mock <IHttp2FrameListener>()).Object;
            Http2ConnectionHandler handler = builder.Codec(decoder, _encoder).Build();

            // Set LifeCycleManager on _encoder and decoder
            _ctx.SetupGet(x => x.Channel).Returns(_channel.Object);
            _ctx.SetupGet(x => x.Allocator).Returns(UnpooledByteBufferAllocator.Default);
            _channel.SetupGet(x => x.Allocator).Returns(UnpooledByteBufferAllocator.Default);
            _executor.SetupGet(x => x.InEventLoop).Returns(true);
            _ctx.Setup(x => x.NewPromise()).Returns(() => NewPromise());
            _ctx.SetupGet(x => x.Executor).Returns(_executor.Object);
            _channel.SetupGet(x => x.IsActive).Returns(false);
            _channel.SetupGet(x => x.Configuration).Returns(_config.Object);
            _channel.SetupGet(x => x.IsWritable).Returns(true);
            _channel.SetupGet(x => x.BytesBeforeUnwritable).Returns(long.MaxValue);
            _config.SetupGet(x => x.WriteBufferHighWaterMark).Returns(int.MaxValue);
            _config.SetupGet(x => x.MessageSizeEstimator).Returns(DefaultMessageSizeEstimator.Default);
            ChannelMetadata metadata = new ChannelMetadata(false, 16);

            _channel.SetupGet(x => x.Metadata).Returns(metadata);
            _channel.SetupGet(x => x.Unsafe).Returns(_unsafe.Object);
            handler.HandlerAdded(_ctx.Object);
        }