예제 #1
0
파일: Program.cs 프로젝트: sideroff/Softuni
        static void Main(string[] args)
        {
            OrderedSet<int> orderedSet = new OrderedSet<int>();
            orderedSet.Add(5);
            orderedSet.Add(3);
            orderedSet.Add(7);
            orderedSet.Add(1);
            orderedSet.Add(4);
            orderedSet.Add(6);
            orderedSet.Add(8);
            orderedSet.Add(2);

            foreach (var i in orderedSet)
            {
                Console.WriteLine(i);
            }

            Console.WriteLine($"Number of elements (should be 7): {orderedSet.Count}");
            Console.WriteLine($"Check if set contains 3 (it should): {orderedSet.Contains(3)}");
            Console.WriteLine($"Try removing 3 (should succeed): {orderedSet.Remove(3)}");
            Console.WriteLine($"Try removing 3 (should fail): {orderedSet.Remove(3)}");
            Console.WriteLine($"Try removing 5 (should succeed): {orderedSet.Remove(5)}");
            Console.WriteLine($"Check if set contains 5 (it should not): {orderedSet.Contains(5)}");
            Console.WriteLine($"Number of elements (should be 5): {orderedSet.Count}");

            foreach (var i in orderedSet)
            {
                Console.WriteLine(i);
            }
        }
예제 #2
0
        public void ContainsTest()
        {
            OrderedSet<int> actual = new OrderedSet<int> {12, 19, 1, 23};

            Assert.IsTrue(actual.Contains(19));
            Assert.IsFalse(actual.Contains(99));
        }
        public static void Main()
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(6);
            set.Add(25);
            set.Add(4);
            set.Add(8);
            set.Add(10);
            set.Add(14);
            set.Add(18);
            set.Add(22);
            set.Add(20);
            set.Add(24);
            set.Add(28);
            set.Add(26);
            set.Add(30);
            set.Add(2);
            set.Add(1);

            Console.WriteLine(set.Contains(12));
            Console.WriteLine(set.Contains(60));

            foreach (var child in set)
            {
                Console.WriteLine(child);
            }

            // set.Remove(12);
            set.Remove(9);
        }
예제 #4
0
        static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);

            Console.WriteLine("Set contains 12: {0}", set.Contains(12));
            Console.WriteLine("Set contains 123: {0}", set.Contains(123));
            Console.WriteLine("Number of elements: {0}",set.Count);
            Console.WriteLine("=========");
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }
            Console.WriteLine("Remove 17:");
            set.Remove(17);
            Console.WriteLine(string.Join(" -> ", set.ToList()));
            Console.WriteLine("=========");
            Console.WriteLine("Set contains 17: {0}", set.Contains(17));
            Console.WriteLine("Number of elements: {0}", set.Count);
            Console.WriteLine("=========");
        }
예제 #5
0
        public void ContainsTest()
        {
            OrderedSet <int> actual = new OrderedSet <int> {
                12, 19, 1, 23
            };

            Assert.IsTrue(actual.Contains(19));
            Assert.IsFalse(actual.Contains(99));
        }
예제 #6
0
        public void ClearAllItems()
        {
            var set = new OrderedSet <int> {
                1, 2, 3
            };

            set.Clear();
            Assert.Equal(set.Count, 0);
            Assert.False(set.Contains(1));
            Assert.False(set.Contains(2));
            Assert.False(set.Contains(3));
        }
예제 #7
0
        public void RemovalWorks()
        {
            var set = new OrderedSet <int> {
                3, 1, 2
            };

            Assert.True(set.Contains(1));
            Assert.Equal(set.Count, 3);
            Assert.True(set.Remove(1));
            Assert.False(set.Contains(1));
            Assert.Equal(set.Count, 2);
            List <int> setItems = set.ToList();

            Assert.Equal(setItems[0], 3);
            Assert.Equal(setItems[1], 2);
        }
예제 #8
0
        public static void Recursive(int index, Frame[] result, int start)
        {
            if (index == result.Length)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < result.Length - 1; i++)
                {
                    sb.Append(result[i].ToString());
                    sb.Append(" | ");
                }

                sb.Append(result[result.Length - 1].ToString());

                if (!combinations.Contains(sb.ToString()))
                {
                    combinations.Add(sb.ToString());
                }
            }
            else
            {
                for (int i = start; i < frames.Length; i++)
                {
                    if (!used[i])
                    {
                        used[i]       = true;
                        result[index] = frames[i];
                        Recursive(index + 1, result, start);
                        result[index] = new Frame(frames[i].Height, frames[i].Width);
                        Recursive(index + 1, result, start);
                        used[i] = false;
                    }
                }
            }
        }
        public override bool VisitDeclaration(Declaration decl)
        {
            if (AlreadyVisited(@decl))
            {
                return(false);
            }

            if (Declarations.Contains(@decl))
            {
                return(false);
            }

            if (decl == TranslationUnit)
            {
                return(true);
            }

            if (decl is TranslationUnit)
            {
                return(false);
            }

            if (decl is Class || decl is Enumeration || decl is TypedefDecl)
            {
                Declarations.Add(decl);
            }

            // No need to continue visiting after a declaration of another
            // translation unit is encountered.
            return(decl.Namespace != null && decl.Namespace.TranslationUnit == TranslationUnit);
        }
예제 #10
0
        static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            set.Remove(9);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(set.Contains(9));
            Console.WriteLine();
            set.Add(25);
            set.Add(25);
            set.Add(25);
            set.Add(25);
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }
        }
예제 #11
0
        public static void Main(string[] args)
        {
            var ints = new OrderedSet<int> ();

            Console.WriteLine ("Initial set:");
            ints.Add (17);
            ints.Add (17);
            ints.Add (17);
            ints.Add (9);
            ints.Add (12);
            ints.Add (19);
            ints.Add (6);
            ints.Add (25);

            foreach (var val in ints) {
                Console.WriteLine (val);
            }
            Console.WriteLine ("17 exist. {0}.", ints.Contains(17));
            Console.WriteLine ("9 exist. {0}.", ints.Contains(9));
            Console.WriteLine ("12 exist. {0}.", ints.Contains(12));
            Console.WriteLine ("18 exists. {0}.", ints.Contains(18));
            Console.WriteLine ("19 exists. {0}.", ints.Contains(19));
            Console.WriteLine ("6 exists. {0}.", ints.Contains(6));
            Console.WriteLine ("25 exists. {0}.", ints.Contains(25));
            Console.WriteLine ("27 exists. {0}.", ints.Contains(27));
            Console.WriteLine ("28 exists. {0}.", ints.Contains(28));

            Console.WriteLine ("Adding some elements:");
            ints.Add (1);
            ints.Add (2);
            ints.Add (3);
            ints.Add (4);
            ints.Add (5);
            ints.Add (7);
            ints.Add (8);
            ints.Add (10);
            foreach (var val in ints) {
                Console.WriteLine (val);
            }

            Console.WriteLine ("Removing some elements:");
            ints.Remove (2);
            ints.Remove (5);
            ints.Remove (6);
            ints.Remove (9);
            ints.Remove (17);
            ints.Remove (100);

            foreach (var val in ints) {
                Console.WriteLine (val);
            }
        }
        /// <summary>
        /// Tests whether a <see cref="IGeometry" /> is sequenced correctly.
        /// <see cref="ILineString" />s are trivially sequenced.
        /// <see cref="IMultiLineString" />s are checked for correct sequencing.
        /// Otherwise, <c>IsSequenced</c> is defined
        /// to be <c>true</c> for geometries that are not lineal.
        /// </summary>
        /// <param name="geom">The <see cref="IGeometry" /> to test.</param>
        /// <returns>
        /// <value>true</value> if the <see cref="IGeometry" /> is sequenced or is not lineal.
        /// </returns>
        public static bool IsSequenced(IGeometry geom)
        {
            if (!(geom is IMultiLineString))
            {
                return(true);
            }

            IMultiLineString mls = geom as IMultiLineString;

            // The nodes in all subgraphs which have been completely scanned
            OrderedSet <Coordinate> prevSubgraphNodes = new OrderedSet <Coordinate>();

            Coordinate         lastNode  = null;
            IList <Coordinate> currNodes = new List <Coordinate>();

            for (int i = 0; i < mls.NumGeometries; i++)
            {
                ILineString line      = (ILineString)mls.GetGeometryN(i);
                Coordinate  startNode = line.GetCoordinateN(0);
                Coordinate  endNode   = line.GetCoordinateN(line.NumPoints - 1);

                /*
                 * If this linestring is connected to a previous subgraph, geom is not sequenced
                 */
                if (prevSubgraphNodes.Contains(startNode))
                {
                    return(false);
                }
                if (prevSubgraphNodes.Contains(endNode))
                {
                    return(false);
                }

                if (lastNode != null && !startNode.Equals(lastNode))
                {
                    // start new connected sequence
                    prevSubgraphNodes.AddMany(currNodes);
                    currNodes.Clear();
                }

                currNodes.Add(startNode);
                currNodes.Add(endNode);
                lastNode = endNode;
            }
            return(true);
        }
예제 #13
0
        public static void Main()
        {
            List<int> itemsToAdd = new List<int> { 17, 9, 9, 12, 19, 6, 25, 10, 15 };  

            var set = new OrderedSet<int>();

            Console.WriteLine("Adding elements: {0}", string.Join(", ", itemsToAdd));
            foreach (var item in itemsToAdd)
            {
                var added = set.Add(item);
                //// duplicate items shouldn't be added twice in the set like item 9
                Console.WriteLine("Item {0}\t: {1}", item, added ? "added" : "not added"); 
            }

            Console.WriteLine("{0}\nUsing IEnumerable foreach:", Separator);
            foreach (var element in set)
            {
                Console.WriteLine(element);
            }
            
            Console.WriteLine("{0}\nCount: {1}", Separator, set.Count);
            Console.WriteLine("{0}\nMin: {1}", Separator, set.Min);
            Console.WriteLine("{0}\nMax: {1}", Separator, set.Max);
            Console.WriteLine("{0}\nContains {1}: {2}", Separator, ContainedValue, set.Contains(ContainedValue));
            Console.WriteLine("{0}\nContains {1}: {2}", Separator, NotContainedValue, set.Contains(NotContainedValue));

            Console.WriteLine("{0}\nUsing ForEach method:", Separator);
            set.ForEach(Console.WriteLine);
            
            Console.WriteLine("{0}\nEfter removing 19:", Separator);
            set.Remove(19);
            set.ForEach(Console.WriteLine);
            Console.WriteLine("Count: {0}", set.Count);

            Console.WriteLine("{0}\nEfter removing all items:", Separator);
            set.Remove(6);
            set.Remove(9);
            set.Remove(15);
            set.Remove(25);
            set.Remove(10);
            set.Remove(12);
            set.Remove(17);
            Console.WriteLine("Count: {0}", set.Count);
            set.ForEach(Console.WriteLine); // Shouldn't print items because the set is empty
        }
예제 #14
0
 /// This is used by the context to manage the group.
 public void UpdateEntity(TEntity entity, int index, IComponent previousComponent, IComponent newComponent)
 {
     if (_entities.Contains(entity))
     {
         if (OnEntityRemoved != null)
         {
             OnEntityRemoved(this, entity, index, previousComponent);
         }
         if (OnEntityAdded != null)
         {
             OnEntityAdded(this, entity, index, newComponent);
         }
         if (OnEntityUpdated != null)
         {
             OnEntityUpdated(
                 this, entity, index, previousComponent, newComponent
                 );
         }
     }
 }
예제 #15
0
        public void AddTest([PexAssumeUnderTest]HashSet<int> newelements)
        {
            OrderedSet<int> actual = new OrderedSet<int>(newelements);
            PexAssert.AreEqual(newelements.Count, actual.Count);

            foreach (int elem in newelements)
                PexAssert.IsTrue(actual.Contains(elem));

            actual.Clear();
            PexAssert.AreEqual(0, actual.Count);
        }
예제 #16
0
    static void Main(string[] args)
    {
        var set = new OrderedSet <int>();

        set.Add(17);
        set.Add(9);
        set.Add(12);
        set.Add(19);
        set.Add(6);
        set.Add(25);
        Console.WriteLine(set.Count);
        set.Remove(12);
        Console.WriteLine(set.Contains(9));
        Console.WriteLine(set.Contains(8));
        Console.WriteLine(set.Count);
        foreach (var item in set)
        {
            Console.WriteLine(item);
        }
    }
예제 #17
0
        public override bool VisitClassDecl(Class @class)
        {
            // Check if we already handled this class.
            if (Classes.Contains(@class))
            {
                return(false);
            }

            Classes.Add(@class);

            return(base.VisitClassDecl(@class));
        }
예제 #18
0
    public int GenRandEvent()
    {
        int idx = -1;

        while (idx == -1)
        {
            idx = rnd.Next(shelves.Length);
            idx = waitingEventsId.Contains(idx) ? -1 : idx;
        }

        return(idx);
    }
예제 #19
0
        /// <summary>
        /// Tests whether a <see cref="Geometry" /> is sequenced correctly.
        /// <see cref="LineString" />s are trivially sequenced.
        /// <see cref="MultiLineString" />s are checked for correct sequencing.
        /// Otherwise, <c>IsSequenced</c> is defined
        /// to be <c>true</c> for geometries that are not lineal.
        /// </summary>
        /// <param name="geom">The <see cref="Geometry" /> to test.</param>
        /// <returns>
        /// <c>true</c> if the <see cref="Geometry" /> is sequenced or is not lineal.
        /// </returns>
        public static bool IsSequenced(IGeometry geom)
        {
            if (!(geom is IMultiLineString)) 
                return true;
        
            IMultiLineString mls = geom as IMultiLineString;

            // The nodes in all subgraphs which have been completely scanned
            OrderedSet<ICoordinate> prevSubgraphNodes = new OrderedSet<ICoordinate>();

            ICoordinate lastNode = null;
            IList<ICoordinate> currNodes = new List<ICoordinate>();
            for (int i = 0; i < mls.NumGeometries; i++) 
            {
                ILineString line = (ILineString) mls.GetGeometryN(i);
                ICoordinate startNode = line.GetCoordinateN(0);
                ICoordinate endNode   = line.GetCoordinateN(line.NumPoints - 1);

                /*
                 * If this linestring is connected to a previous subgraph, geom is not sequenced
                 */
                if (prevSubgraphNodes.Contains(startNode)) 
                    return false;
                if (prevSubgraphNodes.Contains(endNode)) 
                    return false;

                if (lastNode != null && startNode != lastNode) 
                {
                    // start new connected sequence
                    prevSubgraphNodes.AddMany(currNodes);
                    currNodes.Clear();
                }                

                currNodes.Add(startNode);
                currNodes.Add(endNode);
                lastNode = endNode;
            }
            return true;
        }
예제 #20
0
        /// Summary
        /// Time: 14 min 15 sec
        /// Pattern: Constructor Test, State Relation
        /// Generalizes four unit tests AddTest, ClearTest, ContainsTest, CopyIEnumerableToSetTest into one PUT
        public void AddTest([PexAssumeUnderTest] HashSet <int> newelements)
        {
            OrderedSet <int> actual = new OrderedSet <int>(newelements);

            PexAssert.AreEqual(newelements.Count, actual.Count);

            foreach (int elem in newelements)
            {
                PexAssert.IsTrue(actual.Contains(elem));
            }

            actual.Clear();
            PexAssert.AreEqual(0, actual.Count);
        }
예제 #21
0
        public bool PostValidate(Action <string> addError, Action <string> addWarning)
        {
            bool ok = true;

            IEnumerable <string> unknown_prec_symbols = ParserPrecedences.Select(it => it.UsedTokens).Flatten()
                                                        .Select(it => it.StackSymbols.Concat(it.Word)).Flatten()
                                                        .Distinct()
                                                        .Where(it => !symbolRegistry.Contains(it));

            if (unknown_prec_symbols.Any())
            {
                ok = false;
                addError("Unknown symbol(s) in precedence section: " + String.Join(", ", unknown_prec_symbols));
            }

            return(ok);
        }
        static void OrderedSetExample()
        {
            Console.WriteLine("Wintellect.PowerCollections.OrderedSet<T> example:");
            Console.WriteLine("Duplicates will be skipped when adding elements. Elements will maintain ascending order.");
            OrderedSet <string> set = new OrderedSet <string>();

            set.Add("programming");
            set.Add("C#");
            set.Add("Visual Studio");
            set.Add("dotnet");
            set.Add("C#"); // Duplicates will be skipped
            set.Add("C#"); // Duplicates will be skipped
            Console.WriteLine("Contains `dotnet`: {0}", set.Contains("dotnet"));
            Console.WriteLine("Deleted the first `C#` occurence: " + set.Remove("C#"));
            Console.WriteLine("Elements: {0}", set);
            Console.WriteLine("Range[`d`...`q`]: {0}", set.Range("d", true, "q", true));
        }
예제 #23
0
    public List <Node> AStarPath(Node _start, Node _goal)
    {
        start = _start;
        goal  = _goal;

        while (open.Count != 0)
        {
            current = open.GetFirst();
            if (current == goal)
            {
                return(RecoverPath(current));
            }
            open.RemoveFirst();
            closed.Add(current);

            foreach (Node neighbor in current.neighbors)
            {
                if (neighbor == null)
                {
                    continue;
                }
                if (closed.Contains(neighbor)) //evaluated
                {
                    continue;
                }
                float new_g = current.g + DistCost(current, neighbor);
                if (new_g < neighbor.g)
                {
                    neighbor.parent = current;
                    neighbor.g      = new_g;
                    neighbor.CalcF();
                }
                if (!open.Contains(neighbor))   //not added
                {
                    if (neighbor == goal)
                    {
                        Debug.Log(neighbor.parent);
                    }
                    open.Add(neighbor);
                }
            }
        }
        Debug.LogError("No path found.");
        return(null);
    }
예제 #24
0
        protected virtual ICollection <SimpleDataService> GetDataServiceImplementersInDirectory(string inDirectoryPath,
                                                                                                bool ignoreInstallingAssemblies)
        {
            OrderedSet <SimpleDataService> implementers = new OrderedSet <SimpleDataService>();

            if (Directory.Exists(inDirectoryPath))
            {
                OrderedSet <string>        processedAssemblies = new OrderedSet <string>();
                PluginDomainInstanceLoader loader = null;
                try
                {
                    PluginInstanceFinder pluginFinder = null;
                    foreach (string dllPath in Directory.GetFiles(inDirectoryPath, "*.dll", SearchOption.AllDirectories))
                    {
                        if (!ignoreInstallingAssemblies || !IsInstallingPluginAssemblyPath(dllPath))
                        {
                            string assemblyName = Path.GetFileName(dllPath);
                            if (!processedAssemblies.Contains(assemblyName))
                            {
                                string assemblyPath = GetPluginFilePathInDirectory(assemblyName, inDirectoryPath,
                                                                                   ignoreInstallingAssemblies);
                                if (assemblyPath != null)
                                {
                                    if (loader == null)
                                    {
                                        // Don't need to load spring objects here
                                        loader       = GetPluginInstanceLoader(null, assemblyPath);
                                        pluginFinder = loader.GetInstance <PluginInstanceFinder>();
                                    }
                                    GetDataServiceImplementers(pluginFinder, assemblyPath, ref implementers);
                                }
                                processedAssemblies.Add(assemblyName);
                            }
                        }
                    }
                }
                finally
                {
                    DisposableBase.SafeDispose(ref loader);
                }
            }
            return(implementers);
        }
예제 #25
0
        private static OrderedSet <int> FindLayersUsed(InMemoryOsmDatabase osmDatabase)
        {
            OrderedSet <int> layersUsed = new OrderedSet <int>();

            OsmDataQueryParameters queryParameters = new OsmDataQueryParameters();

            queryParameters.FetchTags    = true;
            queryParameters.SkipUntagged = true;

            foreach (OsmWay way in osmDatabase.Ways)
            {
                int layer = GetOsmObjectLayerNumber(way);
                if (false == layersUsed.Contains(layer))
                {
                    layersUsed.Add(layer);
                }
            }

            return(layersUsed);
        }
예제 #26
0
        static void Main(string[] args)
        {
            OrderedSet<int> set = new OrderedSet<int>();

            set.Add(17);
            set.Add(9);
            set.Add(12);
            set.Add(19);
            set.Add(6);
            set.Add(25);

            Console.WriteLine(set.Contains(105));

            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            set.Remove(25);
            set.Remove(9);
            Console.WriteLine("\n");
            foreach (var item in set)
            {
                Console.WriteLine(item);
            }

            set = new OrderedSet<int>();

            set.Add(1);
            set.Add(2);
            set.Add(3);
            set.Add(4);
            set.Add(5);
            set.Add(6);
            set.Add(7);

            Console.WriteLine();
        }
        public static void Main()
        {
            OrderedSet<int> orderedSet = new OrderedSet<int>();
            orderedSet.Add(2);
            orderedSet.Add(-1);
            orderedSet.Add(5);
            orderedSet.Add(0);
            orderedSet.Add(555);
            orderedSet.Add(7);

            Console.WriteLine("Overall number of elements in the Ordered Set are: " + orderedSet.Count);
            Console.WriteLine("The elements of the Ordered Set are as follows:");
            orderedSet.PrintInOrder();

            Console.WriteLine("Does the Ordered Set countain node with value 7? " + orderedSet.Contains(7));
            Console.WriteLine("Is the value 2 removed from the Ordered Set? " + orderedSet.Remove(2));
            Console.WriteLine("Overall number of elements in the Ordered Set are: " + orderedSet.Count);
            Console.WriteLine("The elements of the Ordered Set are as follows:");

            foreach(var input in orderedSet)
            {
                Console.WriteLine(input);
            }
        }
예제 #28
0
        public void get_inter(Event event1, Event event2, ref OrderedSet <Point> inter_points, ref OrderedSet <Event> events, double current_x)
        {
            // upper , lower
            // get information
            Line l1          = new Line(event1.start, event1.end);
            Line l2          = new Line(event2.start, event2.end);
            int  line_index1 = event1.line_index1;
            int  line_index2 = event2.line_index1;

            // get the intresection between two segments
            List <Line>    dummy_L    = new List <Line>();
            List <Polygon> dummy_poly = new List <Polygon>();
            List <Point>   tmp_pl     = new List <Point>();

            List <Line> tmp_ll = new List <Line>();

            tmp_ll.Add(l1);
            tmp_ll.Add(l2);
            segment_segment_intersection seg_seg_inter = new segment_segment_intersection();

            seg_seg_inter.Run(new List <Point>(), tmp_ll, new List <Polygon>(), ref tmp_pl, ref dummy_L, ref dummy_poly);
            if (tmp_pl.Count != 0)
            {
                //without this we go into inf loop , why !????
                if (tmp_pl[0].X < current_x || inter_points.Contains(tmp_pl[0]))
                {
                    return;
                }
                // add to intersection points
                inter_points.Add(tmp_pl[0]);
                // we need to add the intersection point event
                Event tevent = new Event(tmp_pl[0], tmp_pl[0], 2, line_index1, line_index2);
                events.Add(tevent);
            }
            return;
        }
예제 #29
0
 internal bool Has(JsValue key)
 {
     return(_set.Contains(key));
 }
예제 #30
0
        public void AssertThat_AfterAddingItems_SetContainsItem()
        {
            ((ICollection <int>)_set).Add(1);

            Assert.IsTrue(_set.Contains(1));
        }
        void HandleEvent()
        {
            KeyValuePair <Line, Line> UpperAndLower = L.DirectUpperAndLower(currentEvent.seg1);

            if (currentEvent.eventType == Enums.EventType.Start)
            {
                Line newSegment = currentEvent.seg1;
                L.Add(newSegment);

                if (UpperAndLower.Key != null)
                {
                    Point intersectionPoint = CheckIntersection(newSegment, UpperAndLower.Key);
                    if (intersectionPoint != null && intersectionPoint.X > currentEvent._point.X)
                    {
                        EventPoint newEvent = new EventPoint(intersectionPoint, Enums.EventType.Intersection, UpperAndLower.Key, newSegment);
                        if (!Q.Contains(newEvent))
                        {
                            Q.Add(newEvent);
                        }
                    }
                }
                if (UpperAndLower.Value != null)
                {
                    Point intersectionPoint = CheckIntersection(newSegment, UpperAndLower.Value);
                    if (intersectionPoint != null && intersectionPoint.X > currentEvent._point.X)
                    {
                        EventPoint newEvent = new EventPoint(intersectionPoint, Enums.EventType.Intersection, newSegment, UpperAndLower.Value);
                        if (!Q.Contains(newEvent))
                        {
                            Q.Add(newEvent);
                        }
                    }
                }
            }
            else if (currentEvent.eventType == Enums.EventType.End)
            {
                if (UpperAndLower.Key != null && UpperAndLower.Value != null)
                {
                    Point intersectionPoint = CheckIntersection(UpperAndLower.Key, UpperAndLower.Value);
                    if (intersectionPoint != null && intersectionPoint.X > currentEvent._point.X)
                    {
                        EventPoint newEvent = new EventPoint(intersectionPoint, Enums.EventType.Intersection, UpperAndLower.Key, UpperAndLower.Value);
                        if (!Q.Contains(newEvent))
                        {
                            Q.Add(newEvent);
                        }
                    }
                }
                L.Remove(currentEvent.seg1);
            }
            else if (currentEvent.eventType == Enums.EventType.Intersection)
            {
                intersections.Add(currentEvent._point);
                Line S1below = L.DirectUpperAndLower(currentEvent.seg1).Key;
                Line S2upper = L.DirectUpperAndLower(currentEvent.seg2).Value;
                if (S1below != null)
                {
                    Point intersectionPoint = CheckIntersection(S1below, currentEvent.seg2);
                    if (intersectionPoint != null && intersectionPoint.X > currentEvent._point.X)
                    {
                        EventPoint newEvent = new EventPoint(intersectionPoint, Enums.EventType.Intersection, S1below, currentEvent.seg2);
                        if (!Q.Contains(newEvent))
                        {
                            Q.Add(newEvent);
                        }
                    }
                }
                if (S2upper != null)
                {
                    Point intersectionPoint = CheckIntersection(S2upper, currentEvent.seg1);
                    if (intersectionPoint != null && intersectionPoint.X > currentEvent._point.X)
                    {
                        EventPoint newEvent = new EventPoint(intersectionPoint, Enums.EventType.Intersection, S2upper, currentEvent.seg1);
                        if (!Q.Contains(newEvent))
                        {
                            Q.Add(newEvent);
                        }
                    }
                }
                L.Remove(currentEvent.seg1); L.Remove(currentEvent.seg2);
                //currentEvent._point.X++;
                L.Add(currentEvent.seg1); L.Add(currentEvent.seg2);
                //currentEvent._point.X--;
                // L.Remove(currentEvent.seg1);
                // L.Remove(currentEvent.seg2);
                // L.Add(new Line(currentEvent._point,currentEvent.seg1.End));
                // L.Add(new Line(currentEvent._point, currentEvent.seg2.End));
            }
        }
예제 #32
0
    static void Main()
    {
        var set = new OrderedSet <int>();

        Console.WriteLine("Add: 29, 11, 35, 7, 16, 23, 37, 17");
        set.Add(29);
        set.Add(11);
        set.Add(35);
        set.Add(7);
        set.Add(16);
        set.Add(23);
        set.Add(37);
        set.Add(17);

        Console.WriteLine();

        Console.WriteLine("In-order print: ");
        set.PrintInorder(set.Root);

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("Foreach: ");
        foreach (var item in set)
        {
            Console.Write(item + " ");
        }

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("EachInOrder(Action<T> action): ");
        set.EachInOrder(n => Console.Write(n + " "));

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("Insert 23: ");
        set.Add(23);
        set.EachInOrder(n => Console.Write(n + " "));

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("Remove 16: ");
        set.Remove(16);
        set.EachInOrder(n => Console.Write(n + " "));

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("Find 7: ");
        var find7 = set.Find(7) != null ? "7" : "null";

        Console.WriteLine(find7);


        Console.WriteLine();

        Console.WriteLine("Find 200: ");
        var find200 = set.Find(200) != null ? "200" : "null";

        Console.WriteLine(find200);

        Console.WriteLine();

        Console.WriteLine("Contains 7: ");
        var contains7 = set.Contains(7) == true ? "true" : "false";

        Console.WriteLine(contains7);

        Console.WriteLine();

        Console.WriteLine("Contains 200: ");
        var contains200 = set.Contains(200) == true ? "true" : "false";

        Console.WriteLine(contains200);

        Console.WriteLine();

        Console.WriteLine("Count:");
        Console.WriteLine(set.Count);

        Console.WriteLine(
            "Count after Add and Remove: Add 1, Remove 23, Add 5, " +
            "Add 14, Add 108, Remove 5, Remove 12 (no such value)");
        set.Add(1);
        set.Remove(23);
        set.Add(5);
        set.Add(14);
        set.Add(108);
        set.Remove(5);
        set.Remove(12);// no such value
        Console.WriteLine("Count: {0}", set.Count);
        set.EachInOrder(n => Console.Write(n + " "));

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine("Min value: {0}", set.Min());

        Console.WriteLine();

        Console.WriteLine("Min value: {0}", set.Max());

        Console.WriteLine();

        set.Clear();
        Console.WriteLine("Clear: {0} (Count)", set.Count);
    }
예제 #33
0
 /// <summary>
 /// Returns <c>true</c> if the set contains this endpoint.
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public bool Contains(IKProtocolEndpoint <TNodeId> item)
 {
     using (sync.BeginReadLock())
         return(set.Contains(item));
 }
예제 #34
0
        public EstimationResult EstimateAlgorithm(ISearchAlgorithm algorithm, object parameters = null)
        {
            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            Dictionary <SHA1Hash, Dictionary <SHA1Hash, int> > AutoScores = new Dictionary <SHA1Hash, Dictionary <SHA1Hash, int> >();

            List <Audio> Audios        = Core.GetAudios().ToList();
            List <Audio> ReferenceList = Audios.ToList();

            foreach (Audio ReferenceAudio in ReferenceList)
            {
                IList <Audio> Series = Audios.Search(ReferenceAudio, algorithm, parameters)
                                       .Where(audio => HashMap.Contains(audio.GetHash()))
                                       .ToList();

                SHA1Hash ReferenceHash = ReferenceAudio.GetHash();

                AutoScores.Add(ReferenceHash, new Dictionary <SHA1Hash, int>());

                int Rank = 0;
                foreach (Audio TargetAudio in Series)
                {
                    AutoScores[ReferenceHash].Add(TargetAudio.GetHash(), TransformRankToScore(Rank++, Series.Count));
                }
            }

            List <double> Errors                = new List <double>();
            List <double> ManualScoresList      = new List <double>();
            List <double> ReducedAutoScoresList = new List <double>();

            foreach (SHA1Hash Reference in ManualScores.Keys)
            {
                foreach (SHA1Hash Target in ManualScores[Reference].Keys)
                {
                    if (AutoScores.ContainsKey(Reference) && AutoScores[Reference].ContainsKey(Target))
                    {
                        int ReferenceScore = ManualScores[Reference][Target];

                        int AutoScore = AutoScores[Reference][Target];

                        int Error = ReferenceScore - AutoScore;

                        Errors.Add(Error);
                        ManualScoresList.Add(ReferenceScore);
                        ReducedAutoScoresList.Add(AutoScore);
                    }
                }
            }

            double Mean = Errors.Mean();

            double StandardDeviation = Errors.StandardDeviation();

            double Covariance   = ManualScoresList.Covariance(ReducedAutoScoresList);
            double PearsonCoeff = Correlation.Pearson(ManualScoresList, ReducedAutoScoresList);

            EstimationResult Result = new EstimationResult()
            {
                AlgorithmName     = algorithm.DisplayName,
                Parameters        = Convert.ToString(parameters),
                Mean              = Mean,
                StandardDeviation = StandardDeviation,
                Covariance        = Covariance,
                PearsonCoeff      = PearsonCoeff,
                Scores            = AutoScores
            };

            return(Result);
        }
예제 #35
0
        internal void AddProductions(IEnumerable <Production> productions)
        {
            foreach (SymbolInfo sym_info in productions.Select(it => it.LhsSymbol).Where(it => it.TypeName != null))
            {
                {
                    string typename;
                    if (!this.types.TryGetValue(sym_info.SymbolName, out typename))
                    {
                        setTypeNameOfSymbol(sym_info.SymbolName, sym_info.TypeName);
                    }
                    else if (typename != sym_info.TypeName)
                    {
                        throw ParseControlException.NewAndRun(sym_info.SymbolName + " defined as " + sym_info.TypeName + " has already type " + typename);
                    }
                }
            }

            foreach (Production prod in productions)
            {
                foreach (AltRule alt in prod.RhsAlternatives.Where(it => it.Code != null))
                {
                    string guess = alt.Code.BuildBody(presentVariables: null).GuessTypeName();

                    string typename;
                    if (!this.guessed_types.TryGetValue(prod.LhsSymbol.SymbolName, out typename))
                    {
                        // it can be null, meaning it was not recognized
                        this.guessed_types.Add(prod.LhsSymbol.SymbolName, guess);
                    }
                    // if there is a conflict with guessing set it is as not recognized
                    else if (typename != guess)
                    {
                        this.guessed_types[prod.LhsSymbol.SymbolName] = null;
                    }
                }
            }

            parserProductions.AddRange(productions);

            this.nonTerminalRegistry = new HashSet <string>(ParserProductions.Select(prod => prod.LhsSymbol.SymbolName));

            var unknown       = new HashSet <string>();
            var lhs_terminals = new List <string>();

            foreach (Production prod in productions)
            {
                foreach (AltRule alt in prod.RhsAlternatives)
                {
                    foreach (IEnumerable <RhsSymbol> symbols in alt.RhsGroups.Select(it => it.GetSymbols()))
                    {
                        unknown.AddRange(symbols
                                         .Where(sym => !terminalRegistry.Contains(sym.SymbolName) &&
                                                !nonTerminalRegistry.Contains(sym.SymbolName) &&
                                                !types.ContainsKey(sym.SymbolName) &&
                                                sym.SymbolName != ErrorSymbol)
                                         .Select(it => it.Coords.XYString() + " " + it.SymbolName));
                    }
                }

                if (terminalRegistry.Contains(prod.LhsSymbol.SymbolName))
                {
                    lhs_terminals.Add(prod.LhsSymbol.SymbolName);
                }
            }

            var errors = new List <string>();

            if (lhs_terminals.Any())
            {
                errors.Add("Terminal(s) " + lhs_terminals.Join(",") + " cannot be used at LHS of the production");
            }
            if (unknown.Any())
            {
                errors.Add("Undefined symbol(s): " + String.Join(",", unknown));
            }

            ParseControlException.ThrowAndRun(errors);
        }
예제 #36
0
        public static void Main(string[] args)
        {
            var set = new OrderedSet<int>();
            Console.WriteLine("Add numbers --> 19, 21, 55, 27, 66, 33, 17, 85");
            set.Add(19);
            set.Add(21);
            set.Add(55);
            set.Add(27);
            set.Add(66);
            set.Add(33);
            set.Add(17);
            set.Add(85);
            Console.WriteLine();
            Console.WriteLine("In-order print --> ");
            set.PrintInOrder(set.Root);
            Console.WriteLine();
            Console.WriteLine("Foreach --> ");
            foreach (var item in set)
            {
                Console.Write(item + " ");
            }

            Console.WriteLine();
            Console.WriteLine("EachInOrder(Action<T> action) --> ");
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Insert 44 --> ");
            set.Add(44);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Remove 66 --> ");
            set.Remove(66);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Find 17 --> ");
            var find17 = set.Find(17) != null ? "17" : "null";
            Console.WriteLine(find17);
            Console.WriteLine();
            Console.WriteLine("Find 200 --> ");
            var find200 = set.Find(200) != null ? "200" : "null";
            Console.WriteLine(find200);
            Console.WriteLine();
            Console.WriteLine("Contains 44 --> ");
            var contains44 = set.Contains(44) == true ? "true" : "false";
            Console.WriteLine(contains44);
            Console.WriteLine();
            Console.WriteLine("Contains 200 --> ");
            var contains200 = set.Contains(200) == true ? "true" : "false";
            Console.WriteLine(contains200);
            Console.WriteLine();
            Console.WriteLine("Count --> ");
            Console.WriteLine(set.Count);
            Console.WriteLine(
            "Count after Add and Remove: Add 11, Remove 55, Add 5, Add 84, Add 18, Remove 5, Remove 18 (no such value)");
            set.Add(11);
            set.Remove(55);
            set.Add(5);
            set.Add(84);
            set.Add(18);
            set.Remove(5);
            set.Remove(18);
            Console.WriteLine("Count --> {0}", set.Count);
            set.EachInOrder(n => Console.Write(n + " "));
            Console.WriteLine();
            Console.WriteLine("Min value --> {0}", set.Min());
            Console.WriteLine();
            Console.WriteLine("Min value --> {0}", set.Max());
            Console.WriteLine();
            set.Clear();
            Console.WriteLine("Clear --> {0} (Count)", set.Count);
        }
예제 #37
0
    private static void SaveShortestPaths(Node<char> currentNode, Node<char> endNode,
        HashSet<char> visitedNodes, OrderedSet<Node<char>> nextNodes, Dictionary<char, string> paths)
    {
        if (paths.Count == 0)
        {
            paths.Add(currentNode.Symbol, currentNode.Symbol.ToString());
        }

        visitedNodes.Add(currentNode.Symbol);
        foreach (var nodeDistance in currentNode.Children)
        {
            Node<char> child = nodeDistance.Key;
            if (!visitedNodes.Contains(child.Symbol))
            {
                int temporaryWeight = nodeDistance.Value + currentNode.Weight;
                if (child.Weight == 0 || child.Weight > temporaryWeight)
                {
                    if (nextNodes.Contains(child))
                    {
                        nextNodes.Remove(child);
                    }

                    child.Weight = temporaryWeight;
                    paths[child.Symbol] = paths[currentNode.Symbol] + " -> " +
                        child.Symbol.ToString() + "(" + child.Weight + ")";
                }

                nextNodes.Add(child);
            }
        }

        Node<char> nextNode = nextNodes[0];
        nextNodes.Remove(nextNode);
        if (nextNodes.Count == 0)
        {
            return;
        }

        SaveShortestPaths(nextNode, endNode, visitedNodes, nextNodes, paths);
    }
예제 #38
0
 public bool Has(JsValue key)
 {
     return(_set.Contains(key));
 }
예제 #39
0
        internal Grammar(IEnumerable <Tuple <GrammarElementEnum, object> > elements,
                         IEnumerable <LexItem> implicitLexerRules,
                         List <string> warnings)
        {
            var throw_errors = new List <string>();

            {
                Dictionary <GrammarElementEnum, int> elem_counts = EnumExtensions.GetValues <GrammarElementEnum>().ToDictionary(it => it, it => 0);
                foreach (Tuple <GrammarElementEnum, object> elem in elements)
                {
                    if (elem.Item2 != null)
                    {
                        ++elem_counts[elem.Item1];
                    }
                }

                var optionals = new HashSet <GrammarElementEnum>(new GrammarElementEnum[] {
                    GrammarElementEnum.Types,
                    GrammarElementEnum.Terminals,
                    GrammarElementEnum.Options,
                    GrammarElementEnum.Prededence,
                    GrammarElementEnum.LexerTypeInfo,
                    GrammarElementEnum.ExplicitLexerRules,
                    GrammarElementEnum.LexerStates,
                    GrammarElementEnum.ParserTypeInfo,
                    GrammarElementEnum.ParserRules,
                    GrammarElementEnum.PatternsInfo,
                    GrammarElementEnum.Using
                });

                foreach (KeyValuePair <GrammarElementEnum, int> count in elem_counts.Where(it => it.Value != 1))
                {
                    if (count.Value > 1)
                    {
                        throw ParseControlException.NewAndRun(count.Key.ToString() + " section is duplicated");
                    }
                    // if not optional section
                    else if (!optionals.Contains(count.Key))
                    {
                        throw ParseControlException.NewAndRun(count.Key.ToString() + " section is missing");
                    }
                }


                {
                    // if we have lexer name section, then we have to have lexer rules as well
                    // in reverse -- if we don't have the first, we cannot have the latter one and lexer states section
                    // so it is not symmetric!
                    var lexer_count = elem_counts[GrammarElementEnum.LexerTypeInfo];
                    if (elem_counts[GrammarElementEnum.LexerStates] > lexer_count ||
                        elem_counts[GrammarElementEnum.ExplicitLexerRules] != lexer_count)
                    {
                        throw ParseControlException.NewAndRun("Lexer definition is given only partially: lexer name section "
                                                              + (lexer_count > 0 ? "exists" : "does not exist") + " while lexer states section "
                                                              + (elem_counts[GrammarElementEnum.LexerStates] > 0 ? "exists" : "does not exist") + " and lexer rules section "
                                                              + (elem_counts[GrammarElementEnum.ExplicitLexerRules] > 0 ? "exists" : "does not exist") + ".");
                    }
                }

                if (elem_counts[GrammarElementEnum.ParserRules] != elem_counts[GrammarElementEnum.ParserTypeInfo])
                {
                    throw ParseControlException.NewAndRun("Parser definition is given only partially");
                }
            }

            Dictionary <GrammarElementEnum, object> dict_elements = EnumExtensions.GetValues <GrammarElementEnum>()
                                                                    .ToDictionary(it => it, it => (object)null);

            foreach (Tuple <GrammarElementEnum, object> elem in elements)
            {
                dict_elements[elem.Item1] = elem.Item2;
            }

            this.usingList        = (((IEnumerable <string>)dict_elements[GrammarElementEnum.Using]) ?? new string[] { }).ToList();
            this.types            = (((IEnumerable <SymbolInfo>)dict_elements[GrammarElementEnum.Types]) ?? new SymbolInfo[] { }).ToDictionary(it => it.SymbolName, it => it.TypeName);
            this.guessed_types    = new Dictionary <string, string>();
            this.NamespaceName    = ((string)dict_elements[GrammarElementEnum.Namespace]);
            this.TokenTypeInfo    = ((TokenInfo)dict_elements[GrammarElementEnum.TokenName]);
            this.PatternsTypeInfo = ((PatternsInfo)dict_elements[GrammarElementEnum.PatternsInfo]) ?? new PatternsInfo(null, null);

            this.LexerTypeInfo = ((FactoryTypeInfo)dict_elements[GrammarElementEnum.LexerTypeInfo]);
            this.Options       = ((GrammarOptions)dict_elements[GrammarElementEnum.Options]) ?? new GrammarOptions();
            this.LexerStates   = ((StatesInfo)dict_elements[GrammarElementEnum.LexerStates]) ?? StatesInfo.CreateDefault();
            // implicit rules first, because lexer matches text in longest-first fashion
            // when user explicitly adds something like <anything> rule with reversed concat order
            // implicit rules will never be matched
            this.lexerRules = implicitLexerRules.Concat((((IEnumerable <IScanningRule>)dict_elements[GrammarElementEnum.ExplicitLexerRules]) ?? new LexItem[] { })
                                                        .Select(it => it as LexItem).Where(it => it != null)).ToList();
            {
                IEnumerable <LexPatternVariable> pattern_vars = (((IEnumerable <IScanningRule>)dict_elements[GrammarElementEnum.ExplicitLexerRules]) ?? new LexPatternVariable[] { })
                                                                .Select(it => it as LexPatternVariable).Where(it => it != null).ToArray();
                this.LexerPatternFields = pattern_vars.Where(it => it.WithField).ToArray();
                this.lexerPatternNames  = pattern_vars.ToDictionary(it => it.Name, it => it.Pattern);
            }

            this.lexerRules.ForEach(it => it.OutputPattern = mergeLexPatterns(it.InputPatterns));

            this.ParserTypeInfo    = ((FactoryTypeInfo)dict_elements[GrammarElementEnum.ParserTypeInfo]);
            this.parserPrecedences = (((IEnumerable <Precedence>)dict_elements[GrammarElementEnum.Prededence]) ?? Enumerable.Empty <Precedence>()).ToList();

            this.terminalRegistry = new OrderedSet <string>(
                (new[] { EOFSymbol })
                .Concat((((IEnumerable <string>)dict_elements[GrammarElementEnum.Terminals]) ?? new string[] { }))
                .Concat(
                    lexerRules.Select(lex_it => lex_it.Context.Concat(lex_it.TerminalName)).Flatten()
                    // error symbol can appear in lexer productions, it is not a terminal though
                    .Where(s => s != null && s != Grammar.ErrorSymbol)));

            this.parserProductions = new List <Production>();
            AddProductions(((IEnumerable <Production>)dict_elements[GrammarElementEnum.ParserRules]) ?? new Production[] { });

            this.symbolRegistry = new OrderedSet <string>(
                (new[] { ErrorSymbol })
                .Concat(terminalRegistry) // EOF starts that set
                .Concat(nonTerminalRegistry)
                .Concat(ParserProductions
                        .Select(prod => prod.RhsAlternatives
                                .Select(alt => alt.RhsGroups
                                        .Select(grp => grp.GetSymbols().Select(s => s.SymbolName))
                                        .Flatten())
                                .Flatten())
                        .Flatten()));

            // here we get partial mapping (useful for lexer, which sees only part of all symbols)
            InitSymbolMapping();

            if (!IsParserBuilt)
            {
                var errors = new List <string>();
                if (dict_elements[GrammarElementEnum.Types] != null)
                {
                    errors.Add("types");
                }

                if (dict_elements[GrammarElementEnum.Prededence] != null)
                {
                    errors.Add("precedence");
                }

                if (dict_elements[GrammarElementEnum.ParserRules] != null)
                {
                    errors.Add("parser productions");
                }

                if (errors.Any())
                {
                    throw ParseControlException.NewAndRun("Parser is not built (no parser name is given); " + errors.Join(", ") + " section(s) are meaningless.");
                }
            }

            {
                IEnumerable <string> undef_symbols = new HashSet <string>(types.Select(it => it.Key).Where(it => !symbolRegistry.Contains(it)));

                if (undef_symbols.Any())
                {
                    warnings.Add("Undefined symbol(s) in types section: " + String.Join(", ", undef_symbols));
                }
            }

            if (IsParserBuilt)
            {
                var rhs_symbol_names = new HashSet <string>(ParserProductions.Select(it => it.RhsAlternatives).Flatten()
                                                            .Select(it => it.RhsGroups).Flatten()
                                                            .Select(it => it.GetSymbols()).Flatten()
                                                            .Select(it => it.SymbolName));

                IEnumerable <string> unused_terminals = terminalRegistry.Where(it => it != Grammar.EOFSymbol && !rhs_symbol_names.Contains(it)).ToList();

                if (unused_terminals.Any())
                {
                    warnings.Add("Unused terminal(s) in parsing section: " + String.Join(", ", unused_terminals));
                }
            }

            ParseControlException.ThrowAndRun(throw_errors);
        }
예제 #40
0
 /// Determines whether the context has the specified entity.
 public bool HasEntity(TEntity entity)
 {
     return(_entities.Contains(entity));
 }
예제 #41
0
        public override void Run(List <CGUtilities.Point> points, List <CGUtilities.Line> lines, List <CGUtilities.Polygon> polygons, ref List <CGUtilities.Point> outPoints, ref List <CGUtilities.Line> outLines, ref List <CGUtilities.Polygon> outPolygons)
        {
            OrderedSet <Tuple <int, int> > Intersected_lines = new OrderedSet <Tuple <int, int> >();

            EventPoint.lines = lines;

            OrderedSet <EventPoint> Q = new OrderedSet <EventPoint>(Compare_X);
            OrderedSet <EventPoint> L = new OrderedSet <EventPoint>(Compare_Y);

            for (int i = 0; i < lines.Count; ++i)
            {
                if (ComparePoints(lines[i].Start, lines[i].End) == false)
                {
                    lines[i] = new Line(lines[i].End, lines[i].Start);
                }
                Q.Add(new EventPoint(lines[i].Start, i, 1));
                Q.Add(new EventPoint(lines[i].End, i, -1));
            }
            int counter = lines.Count;

            while (Q.Count != 0)
            {
                EventPoint current_event = Q.GetFirst();
                Q.RemoveFirst();

                if (current_event.event_type == 1)
                {
                    L.Add(current_event);
                    if (lines[current_event.index].Start.X == lines[current_event.index].End.Y)
                    {
                        IEnumerable <EventPoint> vertical__ = L;
                        foreach (EventPoint e in vertical__)
                        {
                            if (TwoSegmentsIntersectionTest(lines[e.index], lines[current_event.index]))
                            {
                                Point point_of_intersection = twoLinesIntersectionPoint(lines[e.index], lines[current_event.index]);

                                if (HasValue(point_of_intersection.X) && HasValue(point_of_intersection.Y) && !Intersected_lines.Contains(new Tuple <int, int>(current_event.index, e.index)))
                                {
                                    outPoints.Add(point_of_intersection);
                                    Intersected_lines.Add(new Tuple <int, int>(current_event.index, e.index));
                                    Intersected_lines.Add(new Tuple <int, int>(e.index, current_event.index));
                                    Q.Add(new EventPoint(point_of_intersection, e, current_event, 0));
                                }
                            }
                        }
                        continue;
                    }

                    EventPoint pre  = L.DirectUpperAndLower(current_event).Key;
                    EventPoint next = L.DirectUpperAndLower(current_event).Value;
                    if (pre != null)
                    {
                        if (TwoSegmentsIntersectionTest(lines[pre.index], lines[current_event.index]))
                        {
                            Point point_of_intersection = twoLinesIntersectionPoint(lines[pre.index], lines[current_event.index]);
                            if (!Q.Contains(new EventPoint(point_of_intersection, pre, current_event, 0)) && !Intersected_lines.Contains(new Tuple <int, int>(pre.index, current_event.index)))
                            {
                                outPoints.Add(point_of_intersection);

                                Intersected_lines.Add(new Tuple <int, int>(current_event.index, pre.index));
                                Intersected_lines.Add(new Tuple <int, int>(pre.index, current_event.index));
                                Q.Add(new EventPoint(point_of_intersection, pre, current_event, 0));
                            }
                        }
                    }
                    if (next != null)
                    {
                        if (TwoSegmentsIntersectionTest(lines[current_event.index], lines[next.index]))
                        {
                            Point point_of_intersection = twoLinesIntersectionPoint(lines[current_event.index], lines[next.index]);
                            if (!Q.Contains(new EventPoint(point_of_intersection, current_event, next, 0)) && !Intersected_lines.Contains(new Tuple <int, int>(current_event.index, next.index)))
                            {
                                outPoints.Add(point_of_intersection);
                                Q.Add(new EventPoint(point_of_intersection, current_event, next, 0));
                                Intersected_lines.Add(new Tuple <int, int>(next.index, current_event.index));
                                Intersected_lines.Add(new Tuple <int, int>(current_event.index, next.index));
                            }
                        }
                    }
                }
                else if (current_event.event_type == -1)
                {
                    EventPoint pre  = L.DirectUpperAndLower(current_event).Key;
                    EventPoint next = L.DirectUpperAndLower(current_event).Value;
                    if (pre != null && next != null)
                    {
                        if (TwoSegmentsIntersectionTest(lines[pre.index], lines[next.index]))
                        {
                            Point point_of_intersection = twoLinesIntersectionPoint(lines[pre.index], lines[next.index]);
                            if (!Q.Contains(new EventPoint(point_of_intersection, pre, next, 0)) && !Intersected_lines.Contains(new Tuple <int, int>(pre.index, next.index)))
                            {
                                Intersected_lines.Add(new Tuple <int, int>(pre.index, next.index));
                                Intersected_lines.Add(new Tuple <int, int>(next.index, pre.index));
                                Q.Add(new EventPoint(point_of_intersection, pre, next, 0));
                                outPoints.Add(point_of_intersection);
                            }
                        }
                    }
                    if (current_event.index != 0)
                    {
                        List <EventPoint> LL = L.RemoveAll(p => p.index == current_event.index).ToList();
                        for (int i = 0; i < LL.Count; ++i)
                        {
                            L.Remove(LL[i]);
                        }
                    }
                    else
                    {
                        L.Remove(current_event);
                    }
                }
                else
                {
                    EventPoint s1 = current_event.intersection_segment_1;
                    EventPoint s2 = current_event.intersection_segment_2;

                    /* if (HasValue(current_event.point.X) && HasValue(current_event.point.Y) && !Intersected_lines.Contains(new Tuple<int, int>(s1.index, s2.index)))
                     * {
                     *   outPoints.Add(current_event.point);
                     *   Intersected_lines.Add(new Tuple<int, int>(s1.index, s2.index));
                     *   Intersected_lines.Add(new Tuple<int, int>(s2.index, s1.index));
                     *
                     * }*/
                    EventPoint s1_prev = L.DirectUpperAndLower(s1).Key;
                    EventPoint s2_next = L.DirectUpperAndLower(s2).Value;
                    if (s1_prev != null)
                    {
                        if (TwoSegmentsIntersectionTest(lines[s1_prev.index], lines[s2.index]))
                        {
                            Point point_of_intersection = twoLinesIntersectionPoint(lines[s1_prev.index], lines[s2.index]);
                            if (!Q.Contains(new EventPoint(point_of_intersection, s1_prev, s2, 0)) && !Intersected_lines.Contains(new Tuple <int, int>(s1_prev.index, s2.index)))
                            {
                                Q.Add(new EventPoint(point_of_intersection, s1_prev, s2, 0));
                                outPoints.Add(point_of_intersection);
                                Intersected_lines.Add(new Tuple <int, int>(s1_prev.index, s2.index));
                                Intersected_lines.Add(new Tuple <int, int>(s2.index, s1_prev.index));
                            }
                        }
                    }

                    if (s2_next != null)
                    {
                        if (TwoSegmentsIntersectionTest(lines[s1.index], lines[s2_next.index]))
                        {
                            Point point_of_intersection = twoLinesIntersectionPoint(lines[s1.index], lines[s2_next.index]);
                            if (!Q.Contains(new EventPoint(point_of_intersection, s1, s2_next, 0)) && !Intersected_lines.Contains(new Tuple <int, int>(s1.index, s2_next.index)))
                            {
                                Q.Add(new EventPoint(point_of_intersection, s1, s2_next, 0));
                                outPoints.Add(point_of_intersection);
                                Intersected_lines.Add(new Tuple <int, int>(s1.index, s2_next.index));
                                Intersected_lines.Add(new Tuple <int, int>(s2_next.index, s1.index));
                            }
                        }
                    }
                    L.Remove(s1);
                    L.Remove(s2);
                    double PX     = current_event.point.X + 0.3;
                    double PY1    = current_event.point.Y + 10000;
                    double PY2    = current_event.point.Y - 10000;
                    Line   sweepL = new Line(new Point(PX, PY1), new Point(PX, PY2));
                    Point  P1     = twoLinesIntersectionPoint(sweepL, lines[s1.index]);
                    Point  P2     = twoLinesIntersectionPoint(sweepL, lines[s2.index]);
                    s1.point = P1;
                    s2.point = P2;
                    L.Add(s1);
                    L.Add(s2);
                }
            }
        }