Пример #1
0
 private IEnumerable <IUndoItem> PopUntil(FixedStack <IUndoItem> stack, IUndoItem sentinel)
 {
     while (stack.HasItems && stack.Peek() != sentinel)
     {
         yield return(stack.Pop());
     }
 }
Пример #2
0
        static void Main(string[] args)
        {
            try
            {
                var stack = new FixedStack <string>(8);
                // добавляем четыре элемента
                stack.Push("Kate");
                stack.Push("Sam");
                stack.Push("Alice");
                stack.Push("Tom");

                // извлекаем один элемент
                var head = stack.Pop();
                Console.WriteLine(head);    // Tom

                // просто получаем верхушку стека без извлечения
                head = stack.Peek();
                Console.WriteLine(head);    // Alice
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.Message);
            }


            Console.Read();
        }
Пример #3
0
 public unsafe void Pop_Item_Fail()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         FixedStack <TestStruct> sut = stackalloc TestStruct[1];
         sut.Pop();
     });
 }
Пример #4
0
        //Type[] definedTypes = {
        //    typeof(Vector2),
        //    typeof(Vector3),
        //    typeof(Vector4) ...
        //};

        /// <summary>
        /// Construct Weighted Mean class.
        /// </summary>
        /// <param name="valueCount">Max number of values to find the average of. Oldest added values are automatically removed.</param>
        /// <param name="md">Delegate which multiplies value type T by a float and returns the result as type T</param>
        /// <param name="ad">Delegate which adds two values of type T and returns the result as type T</param>
        public WeightedMean(int valueCount, MultiplyDelegate md, AddDelegate ad)
        {
            // We could instead check if typeof(T) is in list of definedTypes. Which is faster?
            //if(T is Vector2 || T is Vector3 || T is Vector4 || T is int || T is float || T is double || T is long) {
            //}

            multiplyFn = md;
            addFn      = ad;
            m_values   = new FixedStack <T>(valueCount);
        }
Пример #5
0
        public void ComplexPushAndPop()
        {
            var us = new FixedStack <int>(10);

            us.Push(10);
            us.Push(25);
            Assert.Equal(25, us.Pop());
            Assert.Equal(10, us.Pop());
            Assert.Throws <InvalidOperationException>(() => us.Pop());
        }
Пример #6
0
        public void SimplePushAndPop()
        {
            var us = new FixedStack <int>(10);

            Assert.False(us.HasItems);
            us.Push(12);
            Assert.True(us.HasItems);
            Assert.Equal(12, us.Pop());
            Assert.False(us.HasItems);
        }
Пример #7
0
    /*
     * InitStack - creates stack to store global state
     */
    private void InitStack()
    {
        DifficultyPersister diff = FindDiff();

        if (diff != null)
        {
            frameCount = diff.MaxFrames;
        }

        pastStates = new FixedStack <ISerialDataStore[]>(frameCount);
    }
Пример #8
0
        public void Flush()
        {
            var us = new FixedStack <int>(12);

            us.Push(10);
            us.Push(10);
            us.Push(10);
            us.Push(10);
            Assert.True(us.HasItems);
            us.Clear();
            Assert.False(us.HasItems);
        }
Пример #9
0
        public unsafe void Modify_Popped_Item_Success()
        {
            var expected = new TestStruct()
            {
                X = 3, Y = 1
            };

            FixedStack <TestStruct> sut = stackalloc TestStruct[1];

            sut.Push(expected);

            ref var actual = ref sut.Peek();
Пример #10
0
    public FixedStack <T> Copy()
    {
        FixedStack <T> retBuffer = new FixedStack <T>(this.capacity);

        retBuffer.capacity = this.capacity;
        retBuffer.isLocked = this.isLocked;
        retBuffer.length   = this.length;
        retBuffer.bottom   = this.bottom;
        retBuffer.top      = this.top;
        this.buffer.CopyTo(retBuffer.buffer, 0);

        return(retBuffer);
    }
        public void FixedStack_Pushing_16_Elements()
        {
            var entry = new TestStruct()
            {
                X = 1, Y = 1
            };

            FixedStack <TestStruct> stack = stackalloc TestStruct[16];

            for (var i = 0; i < 16; i++)
            {
                stack.Push(entry);
            }
        }
Пример #12
0
        public unsafe void Push_Item_Fail()
        {
            var expected = new TestStruct()
            {
                X = 3, Y = 1
            };

            FixedStack <TestStruct> sut = stackalloc TestStruct[1];

            sut.Push(expected);
            Assert.AreEqual(1, sut.Count);

            Assert.False(sut.Push(expected));
            Assert.AreEqual(1, sut.Count);
        }
Пример #13
0
        public unsafe void Push_Item_Success()
        {
            var expected = new TestStruct()
            {
                X = 3, Y = 1
            };

            FixedStack <TestStruct> sut = stackalloc TestStruct[1];

            Assert.AreEqual(1, sut.Capacity);
            Assert.AreEqual(0, sut.Count);

            Assert.True(sut.Push(expected));
            Assert.AreEqual(1, sut.Count);
        }
Пример #14
0
            public void PushOntoStack(FixedStack <IUndoItem> fixedStack)
            {
                switch (subItems.Count)
                {
                case 0:
                    return;

                case 1:
                    fixedStack.Push(subItems[0]);
                    return;

                default:
                    fixedStack.Push(this);
                    return;
                }
            }
Пример #15
0
        public void StackHasBottom()
        {
            int popped = 0;
            var us     = new FixedStack <int>(20);

            for (int i = 0; i < 40; i++)
            {
                us.Push(i);
            }
            Assert.Equal(0, popped);

            for (int j = 0; j < 20; j++)
            {
                Assert.Equal(39 - j, us.Pop());
            }

            Assert.Throws <InvalidOperationException>(() => us.Pop());
        }
Пример #16
0
        public unsafe void Peek_Item_Success()
        {
            var expected = new TestStruct()
            {
                X = 3, Y = 1
            };

            FixedStack <TestStruct> sut = stackalloc TestStruct[1];

            sut.Push(expected);

            var testStruct = sut.Peek();

            Assert.AreEqual(1, sut.Count);

            Assert.AreEqual(3, testStruct.X);
            Assert.AreEqual(1, testStruct.Y);
        }
Пример #17
0
    /*###################################
     *
     *       Unity Functions
     *
     #####################################*/

    void Awake()
    {
        // Init Variables
        m_ScreenHistory = new FixedStack <ScreenMeta>(k_MaxHistory);
        m_ScreenHash    = new Dictionary <string, ScreenMeta>();

        // Load Dictionary
        for (int i = 0; i < screens.Count; ++i)
        {
            m_ScreenHash.Add(screens[i].title, screens[i]);
            // Ensure Screen Title is set to value set in Inspector
            screens[i].screen.screenTitle = screens[i].title;
        }

        // Set Main Screen Data
        mainScreen.screen.screenTitle = mainScreen.title;

        // Listen for Tap Events
        EasyTouch.On_SimpleTap += CheckFocus;
    }
Пример #18
0
        public void Contains()
        {
            var us = new FixedStack <int>(10);

            Assert.False(us.Contains(10));
            Assert.False(us.Contains(25));
            Assert.False(us.Contains(35));
            us.Push(10);
            Assert.True(us.Contains(10));
            Assert.False(us.Contains(25));
            Assert.False(us.Contains(35));
            us.Push(25);
            Assert.True(us.Contains(10));
            Assert.True(us.Contains(25));
            Assert.False(us.Contains(35));
            Assert.Equal(25, us.Pop());
            Assert.True(us.Contains(10));
            Assert.False(us.Contains(25));
            Assert.False(us.Contains(35));
            Assert.Equal(10, us.Pop());
            Assert.False(us.Contains(10));
            Assert.False(us.Contains(25));
            Assert.False(us.Contains(35));
        }
Пример #19
0
 private void OnEnable()
 {
     this.rb = this.GetComponent <Rigidbody>();
     this.recordedVelocities = new FixedStack <Vector3>(this.Samples);
 }
Пример #20
0
        /// <summary>
        /// Reads reply from socket.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="replyData">Data that has been readen from socket.</param>
        /// <param name="addData">Data that has will be written at the beginning of read data. This param may be null.</param>
        /// <param name="maxLength">Maximum Length of data which may read.</param>
        /// <param name="cmdIdleTimeOut">Command idle time out in milliseconds.</param>
        /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param>
        /// <param name="removeFromEnd">Removes following string from reply.NOTE: removes only if ReadReplyCode is Ok.</param>
        /// <returns>Return reply code.</returns>
        public ReadReplyCode ReadData(Socket socket, out MemoryStream replyData, byte[] addData, int maxLength, int cmdIdleTimeOut, string terminator, string removeFromEnd)
        {
            var _replyCode = ReadReplyCode.Ok;

            replyData = new MemoryStream();

            try
            {
                FixedStack stack            = new FixedStack(terminator);
                var        nextReadWriteLen = 1;

                long lastDataTime = DateTime.Now.Ticks;
                while (nextReadWriteLen > 0)
                {
                    if (socket.Available >= nextReadWriteLen)
                    {
                        //Read byte(s)
                        byte[] b             = new byte[nextReadWriteLen];
                        var    countRecieved = socket.Receive(b);

                        // Write byte(s) to buffer, if length isn't exceeded.
                        if (_replyCode != ReadReplyCode.LengthExceeded)
                        {
                            replyData.Write(b, 0, countRecieved);
                        }

                        // Write to stack(terminator checker)
                        nextReadWriteLen = stack.Push(b, countRecieved);

                        //---- Check if maximum length is exceeded ---------------------------------//
                        if (_replyCode != ReadReplyCode.LengthExceeded && replyData.Length > maxLength)
                        {
                            _replyCode = ReadReplyCode.LengthExceeded;
                        }
                        //--------------------------------------------------------------------------//

                        // reset last data time
                        lastDataTime = DateTime.Now.Ticks;
                    }
                    else
                    {
                        //---- Idle and time out stuff ----------------------------------------//
                        if (DateTime.Now.Ticks > lastDataTime + ((long)(cmdIdleTimeOut)) * 10000)
                        {
                            _replyCode = ReadReplyCode.TimeOut;
                            break;
                        }
                        System.Threading.Thread.Sleep(50);
                        //---------------------------------------------------------------------//
                    }
                }

                // If reply is ok then remove chars if any specified by 'removeFromEnd'.
                if (_replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0)
                {
                    replyData.SetLength(replyData.Length - removeFromEnd.Length);
                }
            }
            catch
            {
                _replyCode = ReadReplyCode.UnKnownError;
            }

            return(_replyCode);
        }
Пример #21
0
    public void Init(Texture2D inputTex, Texture2D outputTex, int N, PathOverlapAttributes attributes)
    {
        this.N          = N;
        this.attributes = attributes;

        // We use outsize to get the size of the bitmap image to prevent issues when accessing bitmap images across multiple threads
        insize = new Size()
        {
            width  = inputTex.width,
            height = inputTex.height
        };

        outsize = new Size()
        {
            width  = outputTex.width,
            height = outputTex.height
        };

        colors.Clear();
        // First 2 colors represent mask colors
        colors.Add(Color.clear);
        colors.Add(Color.clear);

        byte[] indices = TileUtils.IndexColours(inputTex.GetPixels32(), colors);
        output_idx = TileUtils.IndexColours(outputTex.GetPixels32(), colors);

        FillSpecialColorIndices();

        // Instantiate masks
        Pattern.layer1 = new Mask(true, path_idx);
        Pattern.layer2 = new Mask(true);
        bufferMask     = new Mask(true, path_idx, freespace_idx, obstacle_idx);
        masks          = new Mask(false, Pattern.mask_idx_l1, Pattern.mask_idx_l2);

        // Set boundaries
        ConfigureBoundaries();
        ConfigureObstacleBoundaries();

        int tilecount = outsize.width * outsize.height;

        // Try to optimize array initialization
        if (wave == null || wave.Length != tilecount)
        {
            wave       = new bool[tilecount][];
            compatible = new int[tilecount][][];
        }

        // We set T in this function!
        ExtractPattern(indices, this.attributes.GenerateMasksFromOutput);

        if (indexstack == null || indexstack.Size() != tilecount * T)
        {
            indexstack = new FixedStack <Tuple <int, int> >(tilecount * T);
        }
        else
        {
            indexstack.Clear();
        }

        // Initialize wave and compatible arrays
        for (int i = 0; i < wave.Length; ++i)
        {
            wave[i]       = new bool[T];
            compatible[i] = new int[T][];
            for (int t = 0; t < T; ++t)
            {
                compatible[i][t] = new int[4];
            }
        }

        // Initialize fixed arrays
        weightLogWeights      = new double[T];
        sumOfWeights          = 0;
        sumOfWeightLogWeights = 0;

        for (int t = 0; t < T; t++)
        {
            weightLogWeights[t]    = weights[t] * Math.Log(weights[t]);
            sumOfWeights          += weights[t];
            sumOfWeightLogWeights += weightLogWeights[t];
        }

        startingEntropy = Math.Log(sumOfWeights) - sumOfWeightLogWeights / sumOfWeights;

        // Intialize sum arrays
        sumsOfOnes             = new int[tilecount];
        sumsOfWeights          = new double[tilecount];
        sumsOfWeightLogWeights = new double[tilecount];
        entropies = new double[tilecount];

        distribution = new double[T];

        // Populate propagator
        for (int d = 0; d < 4; ++d)
        {
            propagator[d] = new int[T][];
            for (int t = 0; t < T; ++t)
            {
                patterns[t].Overlap(patterns, DX[d], DY[d], out propagator[d][t]);
            }
        }
    }
Пример #22
0
    public static int Main()
    {
        try
        {
            Console.WriteLine("****ValType Tests****");

            FixedStack <ValType> valTypeStack = new FixedStack <ValType>(100);
            for (int i = 0; i < 100; ++i)
            {
                valTypeStack.Push(new ValType(i + 100, i + 101, i + 102));
            }

            // verification failures
            valTypeStack.stobjTest(new ValType(345, 346, 347));
            valTypeStack.initobjTest();
            valTypeStack.mkrefanyTest();
            valTypeStack.cpobjTest(new ValType(456, 457, 458));

            // verification successes
            valTypeStack.constrainedTest();
            valTypeStack.basicBlockTest();


            FixedStack <RefType> refTypeStack = new FixedStack <RefType>(100);
            for (int i = 0; i < 100; ++i)
            {
                refTypeStack.Push(new RefType(i + 100, i + 101, i + 102));
            }


            //
            // omitting the following test cases for references types,
            // because "generalizing" these instructions doesn't really allow
            // you to write generic test cases
            // the reason is that the "generalized" *obj functions have
            // reference semantics for reference types and value semantics
            // for value types. You can't really program generically in that
            // case. If, for example, initobj meant "replace object with object
            // constructed by default constructor" you could program generically
            // 1) initobj - in the case of value types, initobj intializes the
            // the value, whereas in reference types the reference is set to
            // null. I can't see any way to test this in a generic fashion.
            // 2) cpobj - omitted for same reasons, i put some comments inline

            Console.WriteLine("****RefType Tests****");

            refTypeStack.stobjTest(new RefType(345, 346, 347));
            //refTypeStack.initobjTest();
            refTypeStack.mkrefanyTest();
            //refTypeStack.cpobjTest(new RefType(456,457,458));

            // verification successes
            refTypeStack.constrainedTest();

            callTest();
            callvirtTest();

            // stind tests (verification failures)
            // i1 i2 i4 i8 r4 r8 i ref

            stind_i1Test();
            stind_i2Test();
            stind_i4Test();
            stind_i8Test();
            stind_r4Test();
            stind_r8Test();
            stind_iTest();
            stind_refTest();
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught Unexpected Exception");
            Console.WriteLine(e.ToString());
            return(1);
        }

        return(s_failed);
    }
Пример #23
0
 // Class Functions:
 public StateMachine()
 {
     stateStack = new FixedStack <IState>(STATE_STACK_CAPACITY);
 }
Пример #24
0
 // Check if the previous states trigger this combo
 public static bool StateInputIsCombo(FixedStack <IState> states)
 {
     return(false);
 }
        static void Main(string[] args)
        {
            DoublyLinkedList <string> linkedList = new DoublyLinkedList <string>();

            Console.WriteLine("Двухсвязный список");
            Console.WriteLine("Отдельно введите 4 элемента.");

            linkedList.Add(Console.ReadLine());
            linkedList.Add(Console.ReadLine());
            linkedList.Add(Console.ReadLine());
            linkedList.Add(Console.ReadLine());

            Console.WriteLine("\nСписок:");

            linkedList.Print();

            Console.WriteLine("\nВведите новый элемент перед третьим элементом.");
            linkedList.AddBefore(Console.ReadLine(), 2);

            Console.WriteLine("\nСписок:\n");

            linkedList.Print();

            Console.WriteLine("\nДобавленный элемент по индексу [3-1] - " + linkedList.GetElement(2).ToString());

            Console.WriteLine("\nУдалите элемент по наименованию.");
            linkedList.Remove(Console.ReadLine());

            Console.WriteLine("\nСписок:");

            linkedList.Print();

            Console.Write("\nПоиск расстояния от объекта (строка): ");
            string start = Console.ReadLine();

            Console.Write("До объекта (строка): ");
            string end = Console.ReadLine();

            Console.WriteLine($"Расстояние от объекта {start} до {end} равно {linkedList.GetRange(start, end)}");

            long totalMemory = GC.GetTotalMemory(false);

            Console.WriteLine($"\nЗанято памяти в куче до сборки мусора: {totalMemory}");

            Console.WriteLine("Очистка списка.");

            linkedList.Clear();

            long totalMemoryWithoutListElements = GC.GetTotalMemory(false);

            Console.WriteLine($"Занято памяти в куче после очистки списка: {totalMemoryWithoutListElements}");

            Console.WriteLine("Сборка мусора.");

            GC.Collect(1, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            long totalMemoryWithoutTrash = GC.GetTotalMemory(false);

            Console.WriteLine($"Занято памяти в куче после сборки мусора: {totalMemoryWithoutTrash}");

            FixedStack <string> stackOne = new FixedStack <string>(2);

            try
            {
                Console.WriteLine("\nСтэк.");
                // добавляем четыре элемента
                Console.WriteLine("\nОтдельно добавьте 4 элемента.");
                stackOne.Push(Console.ReadLine());
                stackOne.Push(Console.ReadLine());
                stackOne.Push(Console.ReadLine());
                stackOne.Push(Console.ReadLine());

                Console.WriteLine("\nИзвлечение верхнего элемента.");
                // извлекаем один элемент
                var head = stackOne.Pop();

                Console.WriteLine($"Извлеченный элемент - {head}");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine($"\nЗанято памяти в куче до клонирования структуры: {totalMemory}");

            Console.WriteLine("Клонирование  структуры.");

            FixedStack <string> stackTwo = new FixedStack <string>(stackOne.Count);

            stackTwo = stackOne.Copy(stackTwo);

            long totalMemoryWithClone = GC.GetTotalMemory(false);

            Console.WriteLine($"Занято памяти в куче после клонирования структуры: {totalMemoryWithClone}");

            Console.WriteLine("Сборка мусора.");

            GC.Collect(1, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            long MemoryWithoutTrash = GC.GetTotalMemory(false);

            Console.WriteLine($"Занято памяти в куче после сборки мусора: {MemoryWithoutTrash}");

            Console.Read();
        }
Пример #26
0
 public FixedStackFake(int capacity)
 {
     Stack = new FixedStack <T>(capacity);
 }
Пример #27
0
 public Enumerator(FixedStack <T> stack) => _stack = stack;