Ejemplo n.º 1
0
 public FlatXml Parse(XmlReader reader)
 {
     var nodes = new SortedSet<FlatXmlNode>();
     var position = 0;
     while (reader.Read())
     {
         switch (reader.NodeType)
         {
             case XmlNodeType.Element:
                 var element = new FlatXmlNode {Name = reader.Name, Depth = reader.Depth, Position = position};
                 nodes.Add(element);
                 if (reader.HasAttributes)
                 {
                     while (reader.MoveToNextAttribute())
                     {
                         position += 1;
                         var attribute = new FlatXmlNode {Name = reader.Name, Value = reader.Value, Position = position, Depth = reader.Depth};
                         nodes.Add(attribute);
                     }
                 }
                 break;
             case XmlNodeType.Text:
                 var t = new FlatXmlNode {Value = reader.Value, Depth = reader.Depth, Position = position};
                 nodes.Add(t);
                 break;
         }
         position += 1;
     }
     return new FlatXml(nodes);
 }
Ejemplo n.º 2
0
        public static void AddMembers(this IMemberContainer parent,
                                      MemberDeclarationSyntax s,
                                      SortedSet <FieldInfo> fields        = null,
                                      SortedSet <PropertyInfo> properties = null,
                                      SortedSet <IndexerInfo> indexers    = null,
                                      SortedSet <MemberInfoBase> methods  = null)
        {
            // ugly but works
            switch (s)
            {
            case FieldDeclarationSyntax decl:
                fields?.Add(new FieldInfo(decl, parent)); break;

            case PropertyDeclarationSyntax decl:
                properties?.Add(new PropertyInfo(decl, parent)); break;

            case IndexerDeclarationSyntax decl:
                indexers?.Add(new IndexerInfo(decl, parent)); break;

            case MethodDeclarationSyntax decl:
                methods?.Add(new MethodInfo(decl, parent)); break;

            case ConstructorDeclarationSyntax decl:
                methods?.Add(new ConstructorInfo(decl, parent)); break;

            case OperatorDeclarationSyntax decl:
                methods?.Add(new OperatorInfo(decl, parent)); break;
            }
        }
        public static void Main()
        {
            var numberOfDigits = int.Parse(Console.ReadLine());

            var digits = new int[numberOfDigits];
            for (int i = 0; i < numberOfDigits; i++)
            {
                digits[i] = int.Parse(Console.ReadLine());
            }

            Array.Sort(digits);
            var allNumbers = new HashSet<int>();
            PermuteRep(digits, 0, digits.Length, allNumbers);

            var numbersWithMinNumberOfDivisors = new SortedSet<int>();
            var minCountOfDivisors = 10000;
            foreach (var number in allNumbers)
            {
                var divisorsCount = CalculateDivisors(number);
                if (divisorsCount < minCountOfDivisors)
                {
                    numbersWithMinNumberOfDivisors.Clear();
                    numbersWithMinNumberOfDivisors.Add(number);
                    minCountOfDivisors = divisorsCount;
                }
                else if (divisorsCount == minCountOfDivisors)
                {
                    numbersWithMinNumberOfDivisors.Add(number);
                }
            }

            Console.WriteLine(numbersWithMinNumberOfDivisors.Min);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            primes = new SortedSet<int>();
            not_primes = new SortedSet<int>();

            primes.Add(2);
            primes.Add(3);
            primes.Add(5);
            primes.Add(7);
            not_primes.Add(9);

            maxNumPrimes = 0;

            foreach(int a in Enumerable.Range(0, 1000))
            {
                foreach(int b in Enumerable.Range(0, 1000))
                {
                    TestQuadratic(a, b);
                    TestQuadratic(-a, b);
                    TestQuadratic(a, -b);
                    TestQuadratic(-a, -b);

                }
            }

            Console.WriteLine(maxNumPrimes);
            Console.WriteLine(maxA * maxB);
            Console.ReadLine();
        }
        /// <summary>
        /// FanIn
        /// </summary>
        public IEnumerable<Activity> Load(Feed feed)
        {
            var snapshot = new Dictionary<byte[], Queue<Activity>>(activityStreamStore.Count);
            foreach (var item in activityStreamStore)
            {
                snapshot.Add(item.Key, new Queue<Activity>(item.Value));
            }

            SortedSet<Activity> buffer = new SortedSet<Activity>(Activity.Comparer);
            var streams = feed.FeedStreams.ToList();
            var streamsCount = streams.Count;

            //  Init
            for (int streamIndexInsideSubsciption = 0; streamIndexInsideSubsciption < streamsCount; streamIndexInsideSubsciption++)
            {
                var streamId = streams[streamIndexInsideSubsciption];
                var activity = snapshot[streamId].Dequeue();
                buffer.Add(activity);
            }

            while (buffer.Count > 0)
            {
                Activity nextActivity = buffer.FirstOrDefault();
                buffer.Remove(nextActivity);
                var streamQueue = snapshot[nextActivity.StreamId];
                if (streamQueue.Count > 0)
                {
                    var candidate = snapshot[nextActivity.StreamId].Dequeue();
                    buffer.Add(candidate);
                }
                yield return nextActivity;
            }
        }
Ejemplo n.º 6
0
 static void Main()
 {
     string[] input = Console.ReadLine().Split(new char []{' ',',','.','?','!'},StringSplitOptions.RemoveEmptyEntries);
     SortedSet<string> palindromes = new SortedSet<string>();
     for (int i = 0; i < input.Length; i++)
     {
         StringBuilder sb = new StringBuilder(input[i]);
         if (sb.Length == 1)
         {
             palindromes.Add(input[i]);
         }
         else
         {
             for (int j = 0; j < input[i].Length/2; j++)
             {
                 if (sb[j].Equals(sb[sb.Length - 1 - j]))
                 {
                     palindromes.Add(input[i]);
                 }
             }
         }
     }
     Console.Write(string.Join(", ",palindromes));
     Console.WriteLine();
 }
Ejemplo n.º 7
0
        private int FindLongestPath(int maxSalary, int startSalary)
        {
            IDictionary<int, int> longestPaths = new Dictionary<int, int>() { { startSalary, 1 }};
            SortedSet<int> salaries = new SortedSet<int>();
            salaries.Add(startSalary);

            while (salaries.Count != 0)
            {
                int salary = salaries.Min;
                int path = longestPaths[salary];

                foreach (int nextSalary in GetNextSalaries(maxSalary, salary))
                {
                    if (!salaries.Contains(nextSalary))
                    {
                        salaries.Add(nextSalary);
                        longestPaths.Add(nextSalary, path + 1);
                    }
                    else
                        if (longestPaths[nextSalary] < path + 1)
                            longestPaths[nextSalary] = path + 1;
                }

                salaries.Remove(salary);
            }

            return longestPaths.Values.Max();
        }
Ejemplo n.º 8
0
    static void Main()
    {
        string text = Console.ReadLine();
        char[] splitters = { ' ', '.', ',', '!', '?' };
        string[] word = text.Split(splitters, StringSplitOptions.RemoveEmptyEntries);
        SortedSet<string> palyndromes = new SortedSet<string>();

        for (int i = 0; i < word.Length; i++)
        {
            string wordToCheck = word[i];
            int len = wordToCheck.Length;
            int halflen = len / 2;
            if (len == 1)
            {
                palyndromes.Add(wordToCheck);
            }
            else
            {
                string firstpart = wordToCheck.Substring(0, halflen);
                char[] temp = wordToCheck.Substring(len - halflen).ToCharArray();
                Array.Reverse(temp);
                string secondpart = new string(temp);

                if (firstpart == secondpart)
                {
                    palyndromes.Add(wordToCheck);
                }
            }
        }
        Console.WriteLine(String.Join(", ", palyndromes));
    }
Ejemplo n.º 9
0
        public int find(int[] array, int k)
        {
            if (array == null || array.Length == 0) return -1;

            SortedSet<int> queue = new SortedSet<int>();
            int maxItem = array[0];
            queue.Add(array[0]);

            foreach (int v in array)
            {
                if (queue.Count < k)
                    queue.Add(v);
                // can enqueue
                else if (v < queue.Max)
                {
                    queue.Remove(queue.Max);
                    queue.Add(v);
                }
            }

            int res = -1;
            foreach (var v in queue) {
                if (--k == 0) {
                    res = v;
                    break;
                }
            }

            return res;
        }
Ejemplo n.º 10
0
		internal GetGeneratedEventsResults Generate(Type baseType, SortedSet<string> namespaces,
			NameGenerator generator, MethodInformationBuilder builder)
		{
			var requiresObsoleteSuppression = false;
         var generatedEvents = new List<string>();

			foreach (var @event in baseType.GetMockableEvents(generator))
			{
				var eventHandlerType = @event.EventHandlerType;
				namespaces.Add(eventHandlerType.Namespace);

				var eventMethod = @event.AddMethod;

				var methodInformation = builder.Build(new MockableResult<MethodInfo>(
					eventMethod, RequiresExplicitInterfaceImplementation.No));
				var @override = methodInformation.DescriptionWithOverride.Contains("override") ? "override " : string.Empty;

				if (eventMethod.IsPublic)
				{
					if (eventHandlerType.IsGenericType)
					{
						var eventGenericType = eventHandlerType.GetGenericArguments()[0];
						generatedEvents.Add(EventTemplates.GetEvent(@override,
							$"EventHandler<{eventGenericType.GetSafeName()}>", @event.Name));
						namespaces.Add(eventGenericType.Namespace);
					}
					else
					{
						generatedEvents.Add(EventTemplates.GetEvent(@override,
							eventHandlerType.GetSafeName(), @event.Name));
					}

					requiresObsoleteSuppression |= @event.GetCustomAttribute<ObsoleteAttribute>() != null;
				}
				else if (!eventMethod.IsPrivate && eventMethod.IsAbstract)
				{
					var visibility = CodeTemplates.GetVisibility(eventMethod.IsFamily, eventMethod.IsFamilyOrAssembly);

					if (eventHandlerType.IsGenericType)
					{
						var eventGenericType = eventHandlerType.GetGenericArguments()[0];
						generatedEvents.Add(EventTemplates.GetNonPublicEvent(visibility,
							$"EventHandler<{eventGenericType.GetSafeName()}>", @event.Name));
						namespaces.Add(eventGenericType.Namespace);
					}
					else
					{
						generatedEvents.Add(EventTemplates.GetNonPublicEvent(visibility,
							eventHandlerType.GetSafeName(), @event.Name));
					}

					requiresObsoleteSuppression |= @event.GetCustomAttribute<ObsoleteAttribute>() != null;
				}
			}

			return new GetGeneratedEventsResults(generatedEvents.AsReadOnly(), requiresObsoleteSuppression);
      }
		/// <summary>
		///     Core method for generating normal pager items according to the page information.
		/// </summary>
		/// <param name="currentPage">The current page number.</param>
		/// <param name="totalPage">The count of total pages.</param>
		/// <param name="expandForCurrentPage">How many pages should be expanded for current page.</param>
		/// <param name="expandForEnding">How many pages should be expanded for ending.</param>
		/// <returns></returns>
		private static IEnumerable<PagerItem> GeneratePagerNormalItems(int currentPage, int totalPage, int expandForCurrentPage,
			int expandForEnding)
		{
			var pageNumberList = new SortedSet<int> {currentPage};

			// Expand for current page
			for (var i = 1; i <= expandForCurrentPage; i++)
			{
				pageNumberList.Add(currentPage + i);
				pageNumberList.Add(currentPage - i);
			}

			// Expand for ending
			for (var i = 1; i <= expandForEnding; i++)
			{
				pageNumberList.Add(i);
				pageNumberList.Add(totalPage + 1 - i);
			}

			// Remove invalid items
			pageNumberList.RemoveWhere(i => i < 1 || i > totalPage);

			var lastPageNumber = 0;

			foreach (var i in pageNumberList)
			{
				// Skipped some item
				if (i - lastPageNumber > 1)
				{
					yield return new PagerItem
					{
						ItemType = PagerItemType.Omitted,
						PageNumber = -1
					};
				}

				yield return new PagerItem
				{
					// is current page
					ItemType = i == currentPage ? PagerItemType.Current : PagerItemType.Normal,
					PageNumber = i
				};

				// Set last page
				lastPageNumber = i;
			}

			// last page omit handling
			if (lastPageNumber < totalPage)
			{
				yield return new PagerItem
				{
					ItemType = PagerItemType.Omitted,
					PageNumber = -1
				};
			}
		}
Ejemplo n.º 12
0
        static void Main()
        {
            
            int n = int.Parse(Console.ReadLine());
            var noIncommingEdges = new SortedSet<char>();

            for (int i = 0; i < n; i++)
            {
                string currentMessage = Console.ReadLine();
                Node previousNode = GetNodeByCharFromGraph(currentMessage[0]);
                for (int j = 1; j < currentMessage.Length; j++)
                {
                    Node currentNode = GetNodeByCharFromGraph(currentMessage[j]);

                    previousNode.Successors.Add(currentNode);
                    currentNode.Parents.Add(previousNode);

                    previousNode = currentNode;
                }
            }

            foreach (var node in graph.Values)
            {
                if (node.Parents.Count == 0)
                {
                    noIncommingEdges.Add(node.Value);
                }
            }

            var result = new List<char>();

            while (noIncommingEdges.Count > 0)
            {
                var currentNodeSymbol = noIncommingEdges.Min;
                noIncommingEdges.Remove(currentNodeSymbol);

                result.Add(currentNodeSymbol);

                var currentNode = graph[currentNodeSymbol];
                var children = currentNode.Successors.ToList();
                foreach (var child in children)
                {
                    child.Parents.Remove(currentNode);
                    currentNode.Successors.Remove(child);

                    if (child.Parents.Count == 0)
                    {
                        noIncommingEdges.Add(child.Value);
                    }
                }
            }

            Console.WriteLine(String.Join("", result));


        }
        public override void Initialize()
        {
            base.Initialize();

            new ControlHandler(this);

            _collided = new SortedSet<string>();
            Page p = new Page(this, "Page");
            p.Show();
            _collidedLabel = new Label(p, "CollidedLabel", new Point(0, 0));
            _collidedLabel.Body.Position = new Vector2(10, 560);
            for (int x = 0; x < 3; x++)
            {
                ResolutionTestNode c = new ResolutionTestNode(this, "A" + x);
                c.Collision.Group.AddMask(0);
                c.Collision.Pair.AddMask(0);
                c.Collision.Pair.AddMask(2);
                c.Collision.ResolutionGroup.AddMask(0);
                c.Collision.ResolutionGroup.AddMask(1);
                c.Collision.ResolutionGroup.AddMask(2);
                c.Collision.CollideEvent +=
                    manifold =>
                        _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name);
                c.Collision.Debug = true;
                c.Body.Position = new Vector2(30, 80 * x + 20);
            }
            for (int x = 0; x < 3; x++)
            {
                ResolutionTestNode c = new ResolutionTestNode(this, "B" + x);
                c.Collision.Group.AddMask(1);
                c.Collision.Pair.AddMask(0);
                c.Collision.Pair.AddMask(2);
                c.Collision.ResolutionGroup.AddMask(0);
                c.Collision.CollideEvent += manifold => _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name);
                c.Collision.Debug = true;
                c.Body.Position = new Vector2(510, 80 * x + 20);
                c.Color = Color.Orange;
                c.HoverColor = Color.Violet;
            }

            for (int x = 0; x < 3; x++)
            {
                ResolutionTestNode c = new ResolutionTestNode(this, "C" + x);
                c.Collision.Group.AddMask(2);
                c.Collision.Pair.AddMask(0);
                c.Collision.Pair.AddMask(1);
                c.Collision.ResolutionGroup.AddMask(0);
                c.Collision.ResolutionGroup.AddMask(1);
                c.Collision.CollideEvent += manifold => _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name);
                c.Collision.Immovable = true;
                c.Collision.Debug = true;
                c.Body.Position = new Vector2(50 + x * 70, 450);
                c.Color = Color.Green;
                c.HoverColor = Color.DarkBlue;
            }
        }
Ejemplo n.º 14
0
 public void WordBreakIITestErrorCase()
 {
     WordBreakII wb = new WordBreakII();
     SortedSet<string> wordset = new SortedSet<string>();
     wordset.Add("aaaa");
     wordset.Add("aaa");
     List<string> strs = (List<string>)wb.WordBreak("aaaaaaa", wordset);
     List<string> target = new List<string>() { "aaaa aaa", "aaa aaaa" };
     Assert.IsTrue(isListEqual(target, strs));
 }
Ejemplo n.º 15
0
        public static Stack<Square> Search(Map map, Square source, Square target, Func<Square, Square, int> heuristic)
        {
            Dictionary<Square, Square> parents = new Dictionary<Square, Square>();
            HashSet<Square> closed = new HashSet<Square>();
            SortedSet<Square> open = new SortedSet<Square>();

            source.Score.Cost = 0;
            source.Score.Estimate = heuristic(source, target);
            open.Add(source);

            while (open.Count > 0)
            {

                // Get node with lowest f(x) score
                Square current = open.First();

                if (current == target)
                    break;

                // Transfer node to closed set
                open.Remove(current);
                closed.Add(current);

                // Examine neighbors
                foreach (Square neighbor in map.GetNeighbors(current))
                {
                    // Check if node is already processed or not passable
                    if (closed.Contains(neighbor) || (neighbor != target && !neighbor.IsPassable))
                        continue;

                    // Tentative g score
                    float g = current.Score.Cost + 1;

                    // Add (new) node to open
                    if (!open.Contains(neighbor))
                    {
                        parents[neighbor] = current;
                        neighbor.Score.Cost = g;
                        neighbor.Score.Estimate = heuristic(neighbor, target);
                        open.Add(neighbor);
                    }

                    // Updating existing node in open
                    else if (g < neighbor.Score.Cost)
                    {
                        open.Remove(neighbor);
                        parents[neighbor] = current;
                        neighbor.Score.Cost = g;
                        open.Add(neighbor);
                    }
                }
            }

            return ReconstructPath(parents, target);
        }
Ejemplo n.º 16
0
        private int _maxProcessingTimeFromStart; //The answer to the big question

        #endregion Fields

        #region Constructors

        public Store(int cashierCount)
        {
            Debug.Assert(cashierCount > 0, "Invalid number of cashiers specified. Must be greater than zero");
            CashierIdGenerator.Reset();
            _cashiers = new SortedSet<ICashier>();
            for (int i = 0; i < cashierCount - 1; i++)
            {
                _cashiers.Add(new Cashier(CashierIdGenerator.NextCashierId));
            }
            _cashiers.Add(new CashierTrainee(CashierIdGenerator.NextCashierId));
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            primes = new SortedSet<uint>();
            primes.Add(2);
            primes.Add(3);

            uint n;
            uint.TryParse(args[0], out n);

            Console.WriteLine(NthPrime(n));
            Console.ReadLine();
        }
Ejemplo n.º 18
0
        public DataCollector()
        {
            Paths = new Dictionary<string, List<PathData>>();
              Ranks = new SortedSet<string>();
              CurrentTag = "0";
              Tags = new SortedDictionary<string, string>();
              EffectTags = new SortedDictionary<string, string>();
              Races = new SortedSet<string>();

              Ranks.Add("boss");
              Ranks.Add("thrash");
        }
Ejemplo n.º 19
0
 public void WordBreakIITestExample()
 {
     WordBreakII wb = new WordBreakII();
     SortedSet<string> wordset = new SortedSet<string>();
     wordset.Add("cat");
     wordset.Add("cats");
     wordset.Add("and");
     wordset.Add("sand");
     wordset.Add("dog");
     List<string> strs = (List<string>)wb.WordBreak("catsanddog", wordset);
     List<string> target = new List<string>(){"cats and dog", "cat sand dog"};
     Assert.IsTrue(isListEqual(target, strs));
 }
Ejemplo n.º 20
0
 static int NumDividors(uint n)
 {
     SortedSet<uint> results = new SortedSet<uint>();
     for (uint i = 1; i <= Math.Sqrt(n); i++)
     {
         if (n % i == 0)
         {
             results.Add(i);
             results.Add(n / i);
         }
     }
     return results.Count;
 }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            SortedSet<int> sortedNumbers = new SortedSet<int>();
            sortedNumbers.Add(9);
            sortedNumbers.Add(9);
            sortedNumbers.Add(1);
            sortedNumbers.Add(2);

            foreach (var item in sortedNumbers)
            {
                Console.WriteLine(item);
            }
        }
Ejemplo n.º 22
0
    static double Dijkstra(List<List<double>> t, List<List<int>> c, int x, int y, double speed)
    {
        int[] dx = new int[] {0, 1, 0, -1};
        int[] dy = new int[] {1, 0, -1, 0};
        int h = t.Count, w = t[0].Count;

        bool[,,] seen = new bool[h, w, 2];
        double[,,] dist = new double[h, w, 2];
        foreach (int i in Enumerable.Range(0, h))
            foreach (int j in Enumerable.Range(0, w))
                foreach (int k in Enumerable.Range(0, 2))
                    dist[i, j, k] = 13;

        foreach (int k in Enumerable.Range(0, 2))
        {
            dist[x, y, k] = 0;
            SortedSet<Tuple<double, int, int>> q = new SortedSet<Tuple<double, int, int>> ();
            q.Add(Tuple.Create(0.0, x, y));
            while (q.Count > 0)
            {
                var best = q.Min;
                q.Remove(best);
                if (seen[best.Item2, best.Item3, k])
                    continue;
                seen[best.Item2, best.Item3, k] = true;

                foreach (var z in Enumerable.Range(0, 4)
                        .Select(l => new {X = best.Item2 + dx[l], Y = best.Item3 + dy[l]})
                        .Where(z => z.X >= 0 && z.X < h && z.Y >= 0 && z.Y < w &&
                         Math.Abs(c[best.Item2][best.Item3] - c[z.X][z.Y]) <= 1000))
                {
                    double ndist = speed +
                        Math.Max(t[z.X][z.Y] + Convert.ToInt32(k == 0), best.Item1);

                    if (ndist < dist[z.X, z.Y, k])
                    {
                        dist[z.X, z.Y, k] = ndist;
                        q.Add(Tuple.Create(dist[z.X, z.Y, k], z.X, z.Y));
                    }
                }
            }
        }

        return (
            from i in Enumerable.Range(0, h)
            from j in Enumerable.Range(0, w)
            where dist[i, j, 0] <= 12 - dist[i, j, 1]
            select Math.Sqrt((i - x) * (i - x) + (j - y) * (j - y))
            ).Max();
    }
Ejemplo n.º 23
0
 public DataCollector()
 {
     DungeonPaths = new Dictionary<string, List<PathData>>();
       FractalPaths = new List<PathData>();
       RaidPaths = new Dictionary<string, List<PathData>>();
       Ranks = new SortedSet<string>();
       NextShortTag = "0";
       OtherTagToShortTag = new SortedDictionary<string, string>();
       EffectTagToShortTag = new SortedDictionary<string, string>();
       Races = new SortedSet<string>();
       // Special hardcoded ranks. Boss includes champions and legendaries. Thrash includes elites, veterans and normals.
       Ranks.Add("boss");
       Ranks.Add("thrash");
 }
        public override void Initialize()
        {
            base.Initialize();

            ControlHandler ch = new ControlHandler(this);

            _collided = new SortedSet<string>();

            Page p = new Page(this, "Page");
            p.Show();

            _collidedLabel = new Label(p, "CollidedLabel", new Point(0, 0));
            _collidedLabel.Body.Position = new Vector2(10, 500);

            Random rand = new Random();

            for (int x = 0; x < 3; x++)
            {
                AabbNode c = new AabbNode(this, "A" + x);
                c.Collision.Group.AddMask(0);
                c.Collision.Pair.AddMask(0);
                c.Collision.CollideEvent += manifold => _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name);
                c.Collision.Debug = true;
                c.Body.Position = new Vector2(0, 100 * x + 20);
                c.Shape.Debug = true;
            }
            for (int x = 0; x < 3; x++)
            {
                AabbNode c = new AabbNode(this, "B" + x);
                c.Collision.Group.AddMask(1);
                c.Collision.Pair.AddMask(0);
                c.Collision.CollideEvent += manifold => _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name);
                c.Body.Position = new Vector2(510, 80 * x + 20);
                c.Color = Color.Orange;
                c.HoverColor = Color.Black;
                c.Collision.Debug = true;
            }

            for (int x = 0; x < 3; x++)
            {
                CircleNode c = new CircleNode(this, "C" + x);
                c.Collision.Group.AddMask(2);
                c.Collision.Pair.AddMask(2);
                c.Collision.CollideEvent += manifold => _collided.Add(manifold.A != c.Collision ? manifold.A.Parent.Name : manifold.B.Parent.Name); ;
                c.Body.Position = new Vector2(80 * x + 20, 300);
                c.Color = Color.LightBlue;
                c.HoverColor = Color.DarkRed;
                c.Shape.Debug = true;
            }
        }
Ejemplo n.º 25
0
        private static void F3()
        {
            SortedSet<MyPoint> set = new SortedSet<MyPoint>();
            set.Add(new MyPoint { x = 20, y = 20 });
            set.Add(new MyPoint { x = 11, y = 20 });
            set.Add(new MyPoint { x = 22, y = 20 });
            set.Add(new MyPoint { x = 20, y = 20 });
            set.Add(new MyPoint { x = 20, y = 21 });

            foreach (MyPoint p in set)
            {
                Console.WriteLine(p.ToString());
            }
        }
Ejemplo n.º 26
0
        // Originally wrote this as a delegate function, changed my mind, this is clearer
        public static SortedSet<double> GetSeries(double firstNumber, double growthRate, int length)
        {
            if (length == 0) return null;

            var set = new SortedSet<double>();
            set.Add(RoundToQuarter(firstNumber));

            for (int index = 1; index < length; index++)
            {
                double nextInSeries = RoundToQuarter(growthRate*(Math.Pow(firstNumber, index)));
                set.Add(nextInSeries);
            }

            return set;
        }
Ejemplo n.º 27
0
        public void WillOrderLastClassWithSameScoreFirst()
        {
            var set = new SortedSet<BackgroundImageClass>(new SelectorComparer());
            set.Add(new BackgroundImageClass("h1{{width:5}}", 1));
            set.Add(new BackgroundImageClass("h1{{width:10}}", 2));
            BackgroundImageClass result = null;

            foreach (var backgroundImageClass in set)
            {
                result = backgroundImageClass;
                break;
            }

            Assert.Equal(10, result.Width);
        }
Ejemplo n.º 28
0
        public void WillOrderClassWithHighestSpecificityHighest()
        {
            var set = new SortedSet<BackgroundImageClass>(new SelectorComparer());
            set.Add(new BackgroundImageClass("h1{{color:blue}}", 0));
            set.Add(new BackgroundImageClass("h1#myid{{color:blue}}", 0));
            BackgroundImageClass result = null;

            foreach (var backgroundImageClass in set)
            {
                result = backgroundImageClass;
                break;
            }

            Assert.Equal("h1#myid", result.Selector);
        }
Ejemplo n.º 29
0
        public static void Main()
        {
            var priority = new SortedSet<Edge>();
            const int numberOfNodes = 6;
            var used = new bool[numberOfNodes + 1];
            var mpdNodes = new List<Edge>();
            var edges = new List<Edge>();

            edges.Add(new Edge(1, 3, 5));
            edges.Add(new Edge(1, 2, 4));
            edges.Add(new Edge(1, 4, 9));
            edges.Add(new Edge(2, 4, 2));
            edges.Add(new Edge(3, 4, 20));
            edges.Add(new Edge(3, 5, 7));
            edges.Add(new Edge(4, 5, 8));
            edges.Add(new Edge(5, 6, 12));

            foreach (var edge in edges)
            {
                if (edge.StartNode == edges[0].StartNode)
                {
                    priority.Add(edge);
                }
            }

            used[edges[0].StartNode] = true;

            FindMinimumSpanningTree(used, priority, mpdNodes, edges);

            PrintMinimumSpanningTree(mpdNodes);
        }
Ejemplo n.º 30
0
        private static void FindMinimumSpanningTree(bool[] used, SortedSet<Edge> priority, List<Edge> mpdNodes, List<Edge> edges)
        {
            while (priority.Count > 0)
            {
                var edge = priority.Min;
                priority.Remove(edge);

                if (!used[edge.EndNode])
                {
                    used[edge.EndNode] = true;
                    mpdNodes.Add(edge);

                    for (int i = 0; i < edges.Count; i++)
                    {
                        if (!mpdNodes.Contains(edges[i]))
                        {
                            if (edge.EndNode == edges[i].StartNode && !used[edges[i].EndNode])
                            {
                                priority.Add(edges[i]);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 31
0
        public static void TestCopyConstructor()
        {
            SortedSet<int> sortedSet = new SortedSet<int>();

            List<int> listOfItems = new List<int>();
            for (int i = 0; i < 10000; i++)
            {
                if (!sortedSet.Contains(i))
                {
                    sortedSet.Add(i);
                    listOfItems.Add(i);
                }
            }

            SortedSet<int> newTree1 = new SortedSet<int>(listOfItems);

            Assert.True(newTree1.SetEquals(listOfItems)); //"Expected to be the same set."

            SortedSet<int> newTree2 = new SortedSet<int>(sortedSet);

            Assert.True(sortedSet.SetEquals(newTree2)); //"Expected to be the same set."

            Assert.Equal(sortedSet.Count, newTree1.Count); //"Should be equal."
            Assert.Equal(sortedSet.Count, newTree2.Count); //"Copied tree not the same as base"
        }
Ejemplo n.º 32
0
        private void FillAssemblyNames(HashSet <AssemblyName> hashSet, IEnumerable <AssemblyName> assemblyNames, ref SortedSet <string> errors)
        {
            foreach (AssemblyName assemblyName in assemblyNames.OrderBy(assemblyName => assemblyName.FullName))
            {
                if (hashSet.Add(assemblyName))
                {
                    AssemblyName[] referencedAssemblies;

                    try
                    {
                        referencedAssemblies = this.assemblyInformationLoader.GetReferencedAssemblies(assemblyName);
                    }
                    catch (FileNotFoundException)
                    {
                        errors?.Add(assemblyName.FullName);
                        continue;
                    }

                    this.FillAssemblyNames(hashSet, referencedAssemblies, ref errors);
                }
            }
        }
Ejemplo n.º 33
0
        public static void AddChildTypes(this ITypeContainer parent,
                                         MemberDeclarationSyntax s,
                                         SortedSet <ClassInfo> classes        = null,
                                         SortedSet <StructInfo> structs       = null,
                                         SortedSet <InterfaceInfo> interfaces = null,
                                         SortedSet <EnumInfo> enums           = null)
        {
            // ugly but works
            switch (s)
            {
            case ClassDeclarationSyntax decl:
                new ClassInfo(decl, parent).AddOrReuse(decl, classes); break;

            case EnumDeclarationSyntax decl:
                enums?.Add(new EnumInfo(decl, parent)); break;

            case StructDeclarationSyntax decl:
                new StructInfo(decl, parent).AddOrReuse(decl, structs); break;

            case InterfaceDeclarationSyntax decl:
                new InterfaceInfo(decl, parent).AddOrReuse(decl, interfaces); break;
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Adds a player-owned house to the rent queue
        /// </summary>
        private static void AddRentQueue(IPlayer player, House house)
        {
            var playerHouse = new PlayerHouse(player, house);

            RentQueue.Add(playerHouse);
        }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            List <string> codes = new List <string>();

            using (TextReader reader = File.OpenText("input.txt"))
            {
                while (reader.Peek() >= 0)
                {
                    string line = reader.ReadLine();
                    codes.Add(line);
                }
            }

            int             highestId = 0;
            SortedSet <int> sortedIds = new SortedSet <int>();

            foreach (string code in codes)
            {
                Func <string, int, int, char, char, int> BinaryChop = (string str, int lowerStart, int upperStart, char lowerChar, char upperChar) =>
                {
                    int lower = lowerStart;
                    int upper = upperStart;

                    for (int i = 0; i < str.Length; ++i)
                    {
                        int range = upper - lower;
                        if (str[i] == lowerChar)
                        {
                            upper -= range / 2;
                        }
                        else if (str[i] == upperChar)
                        {
                            lower += range / 2;
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }

                    if (upper - lower != 1)
                    {
                        throw new Exception();
                    }

                    return(lower);
                };

                string rows    = code.Substring(0, 7);
                int    row     = BinaryChop(rows, 0, 128, 'F', 'B');
                string columns = code.Substring(7, 3);
                int    column  = BinaryChop(columns, 0, 8, 'L', 'R');

                int id = (row * 8) + column;
                Console.WriteLine("{0}: row {1} column {2} - ID {3}", code, row, column, id);

                sortedIds.Add(id);
                highestId = Math.Max(highestId, id);
            }

            Console.WriteLine("Highest ID: {0}", highestId);

            int lastID = -1;

            foreach (int id in sortedIds)
            {
                if (id - lastID == 2)
                {
                    Console.WriteLine("ID space at: {0}", lastID + 1);
                }
                lastID = id;
            }
        }
Ejemplo n.º 36
0
        public static void Main(string[] args)
        {
            System.Threading.ThreadPool.SetMinThreads(64, 16);
            if (args.Length == 1)
            {
                foreach (string str in System.IO.File.ReadAllLines(args[0]))
                {
                    initial.Enqueue(str);
                }
            }
            SortedDictionary <int, System.Threading.Thread> jobs = new SortedDictionary <int, System.Threading.Thread> ();

            repositories = new SortedDictionary <string, ChunkRepository> ();
            Modifiers.Add("async");
            //BD2.Core.Database DB = new BD2.Core.Database ();
            string command;

            do
            {
                command = Query("Command>");
                if (command == null)
                {
                    return;
                }
                OffsetedArray <string> commandparts = command.Split(' ');
                string[] CommandParts = (string[])((string[])commandparts).Clone();
                commandparts.Offset = ExtractModifiers(CommandParts);
                SortedSet <string> CommandModifiers = new SortedSet <string> (commandparts.GetStrippedPart());
                switch (CommandParts [0])
                {
                case "Run":
                    if (CommandParts.Length < 2)
                    {
                        Console.Error.WriteLine("Run requires at least two parameter: [async] Run <Type>");
                        continue;
                    }
                    switch (CommandParts [1])
                    {
                    case "Daemon":
                        if (CommandParts.Length < 3)
                        {
                            Console.Error.WriteLine("Run Daemon requires at least one parameter: [async] Run Daemon <Daemon Type>");
                            continue;
                        }
                        switch (CommandParts [2])
                        {
                        case "SQL":
                            if (CommandModifiers.Contains("async"))
                            {
                                System.Threading.Thread t_runSourceDaemon = new System.Threading.Thread(RunSourceDaemon);
                                jobs.Add(t_runSourceDaemon.ManagedThreadId, t_runSourceDaemon);
                                t_runSourceDaemon.Start();
                            }
                            else
                            {
                                RunSourceDaemon();
                            }
                            break;                            //source

                        default:
                            Console.Error.WriteLine("Invalid Daemon Type.");
                            break;
                        }
                        break;
                    }
                    break;                    //daemon

                case "Open":
                    if (CommandParts.Length < 2)
                    {
                        Console.Error.WriteLine("Open requires at least one parameter: [async] Open <Repository Type>");
                        continue;
                    }
                    switch (CommandParts [1])
                    {
                    case "LevelDB":
                        if (CommandParts.Length < 4)
                        {
                            Console.Error.WriteLine("LevelDB repository requires at least two parameter: [async] Open File <Repository Nick> <Repository> <Path>");
                            continue;
                        }
                        if (CommandModifiers.Contains("async"))
                        {
                            System.Threading.Thread t_addrepo = new System.Threading.Thread(() => {
                                OpenLevelDBRepository(CommandParts);
                            });
                            t_addrepo.Start();
                            Console.WriteLine("[{0}]", t_addrepo.ManagedThreadId);
                        }
                        else
                        {
                            OpenLevelDBRepository(CommandParts);
                        }
                        break;                        //file

                    case "Network":
                        if (CommandParts.Length < 5)
                        {
                            Console.Error.WriteLine("Network repository requires at least three parameter: [async] Open File <Repository Nick> <Repository> <IPAddress> <Port>");
                            continue;
                        }
                        if (CommandModifiers.Contains("async"))
                        {
                            System.Threading.Thread t_addrepo = new System.Threading.Thread(() => {
                                OpenNetworkRepository(CommandParts);
                            });
                            t_addrepo.Start();
                            Console.WriteLine("[{0}]", t_addrepo.ManagedThreadId);
                        }
                        else
                        {
                            OpenNetworkRepository(CommandParts);
                        }

                        break;

                    case "Socket":
                        break;
                    }
                    break;

                case "Close":
                    break;

                case "Execute":

                    break;

                case "Convert":
                    if (CommandParts.Length < 2)
                    {
                        Console.Error.WriteLine("Open requires at least one parameter: [async] Open <Repository Type> [Parameters]");
                        continue;
                    }
                    switch (CommandParts [1])
                    {
                    case "Table":
                        string daemonIPAddress            = Query("Daemon IP Address");
                        string DaemonPort                 = Query("Daemon Port");
                        System.Net.IPAddress         IPA  = System.Net.IPAddress.Parse(daemonIPAddress);
                        System.Net.IPEndPoint        IPEP = new System.Net.IPEndPoint(IPA, int.Parse(DaemonPort));
                        System.Net.Sockets.TcpClient TC   = new  System.Net.Sockets.TcpClient();
                        TC.Connect(IPEP);
                        System.Net.Sockets.NetworkStream NS = TC.GetStream();
                        BD2.Daemon.StreamHandler         SH = new BD2.Daemon.StreamHandler(NS);
                        BD2.Daemon.ObjectBus             OB = new BD2.Daemon.ObjectBus(SH);
                        BD2.Daemon.ServiceManager        SM = new BD2.Daemon.ServiceManager(OB);
                        SM.AnounceReady();
                        SM.WaitForRemoteReady();

                        Guid serviceType_SQL = Guid.Parse("57ce8883-1010-41ec-96da-41d36c64d65d");
                        var  RS = SM.EnumerateRemoteServices();
                        BD2.Daemon.ServiceAnnounceMessage TSA = null;
                        foreach (var SA in RS)
                        {
                            if (SA.Type == serviceType_SQL)
                            {
                                TSA = SA;
                            }
                        }
                        if (TSA == null)
                        {
                            Console.WriteLine("Required services for Table Conversion not found on remote host.");
                        }
                        BD2.Daemon.TransparentAgent agent =
                            (BD2.Daemon.TransparentAgent)
                            SM.RequestService(TSA, (new BD2.Conv.Daemon.MSSQL.ServiceParameters(Query("Connection String"))).Serialize(),
                                              BD2.Daemon.TransparentAgent.CreateAgent, null);
                        Client CL = new Client(agent, repositories [Query("Repository Name")], Query("Database Name"));
                        CL.Convert();
                        break;
                    }
                    break;

                case "await":
                    string jobID    = commandparts [1];
                    int    intJobID = int.Parse(jobID);
                    jobs [intJobID].Join();
                    break;

                case "Exit":
                    return;

                default:
                    Console.Error.WriteLine(string.Format("{0} is not a valid command.", CommandParts [0]));
                    break;
                }
            } while(true);
        }
        public static IEnumerable <string> GetTrieTerms(this CrawledIssue issue)
        {
            var result = new SortedSet <string>(StringComparer.OrdinalIgnoreCase);

            AddTermsFromMarkdown(result, issue.Title);
            // TODO: Should we index the body or not?
            // AddTermsFromMarkdown(result, issue.Body);

            result.Add($"org:{issue.Repo.Org}");
            result.Add($"repo:{issue.Repo.Name}");
            result.Add($"repo:{issue.Repo.FullName}");
            result.Add($"author:{issue.CreatedBy}");

            foreach (var assignee in issue.Assignees)
            {
                result.Add($"assignee:{assignee}");
            }

            foreach (var label in issue.Labels)
            {
                result.Add($"label:{label.Name}");
            }

            foreach (var area in issue.Areas)
            {
                result.Add($"area-under:{area}");
            }

            foreach (var areaNode in issue.AreaNodes)
            {
                result.Add($"area-node:{areaNode}");
            }

            foreach (var areaLead in issue.AreaLeads)
            {
                result.Add($"area-lead:{areaLead}");
            }

            foreach (var areaOwner in issue.AreaOwners)
            {
                result.Add($"area-owner:{areaOwner}");
            }

            if (issue.Milestone is not null)
            {
                result.Add($"milestone:{issue.Milestone.Title}");
            }

            return(result);
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            var @set = new SortedSet <Guid>();

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < 2000000; i++)
            {
                var g = Guid.NewGuid();

                sw.Start();
                @set.Add(g);
                sw.Stop();
            }

            var l      = new List <Guid>(@set);
            var query  = l.AsQueryable();
            var query1 = l.AsQueryable();

            //var sw1 = Stopwatch.StartNew();
            //l.SortBy(n => n).ToList();
            //sw1.Stop();


            //var sw2 = Stopwatch.StartNew();
            //l.AsParallel().SortBy(n => n).ToList();
            //sw2.Stop();


            var ss1 = Stopwatch.StartNew();
            var dt1 = query.ToArray();

            ss1.Stop();

            var ss2 = Stopwatch.StartNew();
            var dt2 = query1.AsParallel().ToArray();

            ss2.Stop();

            Console.ReadLine();
            //var heapsortSorter = new HeapsortSorter<Guid>();
            //var mergesortSorter = new MergesortSorter<Guid>();
            //var quicksortSorter = new QuicksortSorter<Guid>();
            //var quicksort3waySorter = new Quicksort3waySorter<Guid>();
            //var quicksortIndexSorter = new QuicksortIndexSorter<Guid>();
            //var rbTreeSorter = new RbTreeSorter<Guid>();
            //var rbTreeIndexSorter = new RbTreeIndexSorter<Guid>();

            //var sw1 = Stopwatch.StartNew();
            //heapsortSorter.Sort(l, false);
            //sw1.Stop();

            //var sw2 = Stopwatch.StartNew();
            //mergesortSorter.Sort(l, false);
            //sw2.Stop();

            //var sw3 = Stopwatch.StartNew();
            //quicksortSorter.Sort(l, false);
            //sw3.Stop();

            //var sw4 = Stopwatch.StartNew();
            //quicksort3waySorter.Sort(l, false);
            //sw4.Stop();

            //var sw5 = Stopwatch.StartNew();
            //var dd = quicksortIndexSorter.Sort(l, false).GetEnumerator().MoveNext();
            //sw5.Stop();

            //var sw6 = Stopwatch.StartNew();
            //rbTreeSorter.Sort(l, false);
            //sw6.Stop();

            //var sw7 = Stopwatch.StartNew();
            //rbTreeIndexSorter.Sort(l, false);
            //sw7.Stop();
        }
Ejemplo n.º 39
0
 public void GetUniqueDate()
 {
     personsData.ForEach(p => dates.Add(p.Date));
 }
Ejemplo n.º 40
0
        protected virtual void Graph_NewMarkedNode(DependencyNodeCore <NodeFactory> obj)
        {
            var eetypeNode = obj as EETypeNode;

            if (eetypeNode != null)
            {
                _typesWithEETypesGenerated.Add(eetypeNode.Type);

                if (eetypeNode is ConstructedEETypeNode || eetypeNode is CanonicalEETypeNode)
                {
                    _typesWithConstructedEETypesGenerated.Add(eetypeNode.Type);
                }

                return;
            }

            IMethodBodyNode methodBodyNode = obj as IMethodBodyNode;

            if (methodBodyNode != null)
            {
                _methodBodiesGenerated.Add(methodBodyNode);
            }

            IMethodNode methodNode = methodBodyNode;

            if (methodNode != null)
            {
                if (AllMethodsCanBeReflectable)
                {
                    _reflectableMethods.Add(methodNode.Method);
                }
            }

            if (methodNode == null)
            {
                methodNode = obj as ShadowConcreteMethodNode;
            }

            if (methodNode != null)
            {
                _methodsGenerated.Add(methodNode.Method);
                return;
            }

            var reflectableMethodNode = obj as ReflectableMethodNode;

            if (reflectableMethodNode != null)
            {
                _reflectableMethods.Add(reflectableMethodNode.Method);
            }

            var nonGcStaticSectionNode = obj as NonGCStaticsNode;

            if (nonGcStaticSectionNode != null && nonGcStaticSectionNode.HasCCtorContext)
            {
                _cctorContextsGenerated.Add(nonGcStaticSectionNode);
            }

            var gvmEntryNode = obj as TypeGVMEntriesNode;

            if (gvmEntryNode != null)
            {
                _typeGVMEntries.Add(gvmEntryNode);
            }

            var dictionaryNode = obj as GenericDictionaryNode;

            if (dictionaryNode != null)
            {
                _genericDictionariesGenerated.Add(dictionaryNode);

                if (dictionaryNode.OwningEntity is MethodDesc method && AllMethodsCanBeReflectable)
                {
                    _reflectableMethods.Add(method);
                }
            }

            if (obj is StructMarshallingDataNode structMarshallingDataNode)
            {
                _typesWithStructMarshalling.Add(structMarshallingDataNode.Type);
            }

            if (obj is DelegateMarshallingDataNode delegateMarshallingDataNode)
            {
                _typesWithDelegateMarshalling.Add(delegateMarshallingDataNode.Type);
            }

            if (obj is DynamicInvokeTemplateNode dynamicInvokeTemplate)
            {
                _dynamicInvokeTemplates.Add(dynamicInvokeTemplate.Method);
            }

            if (obj is NativeLayoutTemplateMethodSignatureVertexNode templateMethodEntry)
            {
                _templateMethodEntries.Add(templateMethodEntry);
            }
        }
Ejemplo n.º 41
0
        public static EtwManifest ParseWmiEventTraceClass(Guid provider)
        {
            // we make a best effort attempt to fit the metadata of this Legacy (MOF) provider into the instrumentation manifest format

            // we need to find the EventTrace class where the Guid class qualifier matches our provider Guid
            // afaik you can't query for qualifiers...just classes and properties.  :-/
            // so we loop through all of the EventTrace classes and compare
            var             providerSearcher = new ManagementObjectSearcher("root\\WMI", $"SELECT * FROM meta_class WHERE __superclass = 'EventTrace'", null);
            ManagementClass providerClass    = null;

            foreach (ManagementClass candidateProviderClass in providerSearcher.Get())
            {
                foreach (QualifierData qd in candidateProviderClass.Qualifiers)
                {
                    if (qd.Name.ToLower() == "guid" && new Guid((string)qd.Value) == provider)
                    {
                        providerClass = candidateProviderClass;
                        break; // found
                    }
                }

                if (providerClass != null)
                {
                    break; // found
                }
            }

            if (providerClass == null)
            {
                throw new ApplicationException($"Provider {provider} has no corresponding EventTrace class in WMI Repository"); // not found
            }
            var manifest = new EtwManifest(string.Empty)
            {
                ProviderGuid   = provider,
                ProviderSymbol = (string)providerClass["__CLASS"]
            };

            var events      = new SortedDictionary <string, EtwEvent>();
            var templates   = new List <EtwTemplate>();
            var stringTable = new Dictionary <string, string>();

            // the provider name is usually in the Description Qualifier for the EventTrace class (but not always?)
            // and the keywords are properties for the EventTrace class
            // but we can already get both of these easily from Microsoft.Diagnostics.Tracing
            manifest.ProviderName = TraceEventProviders.GetProviderName(provider);
            manifest.Keywords     = TraceEventProviders.GetProviderKeywords(provider).Select(info => new EtwKeyword
            {
                Name    = info.Name,
                Mask    = info.Value,
                Message = info.Description
            }).ToArray();

            // event details are in the grandchildren of the top-level (EventTrace) provider class
            // WMI EventTrace children ~ a versioned category grouping
            // WMI EventTrace grandchildren ~ instrumentation manifest templates
            // note - event version can be set on the category and/or the event
            var templateNames = new SortedSet <string>();
            var taskSearcher  = new ManagementObjectSearcher("root\\WMI", $"SELECT * FROM meta_class WHERE __superclass = '{providerClass["__CLASS"]}'", null);

            foreach (ManagementClass categoryVersionClass in taskSearcher.Get())
            {
                var categoryVersion     = 0;
                var category            = string.Empty;
                var categoryDescription = string.Empty;
                var displayName         = string.Empty;
                foreach (QualifierData qd in categoryVersionClass.Qualifiers)
                {
                    if (qd.Value.GetType() == typeof(Int32) && qd.Name.ToLower() == "eventversion")
                    {
                        categoryVersion = (Int32)qd.Value;
                    }
                    else if (qd.Value.GetType() == typeof(String) && qd.Name.ToLower() == "guid")
                    {
                        category = (string)qd.Value;
                    }
                    else if (qd.Value.GetType() == typeof(String) && qd.Name.ToLower() == "description")
                    {
                        categoryDescription = (string)qd.Value;
                    }
                    else if (qd.Value.GetType() == typeof(String) && qd.Name.ToLower() == "displayname")
                    {
                        displayName = (string)qd.Value;
                    }
                }

                var templateSearcher = new ManagementObjectSearcher("root\\WMI", $"SELECT * FROM meta_class WHERE __superclass = '{categoryVersionClass["__CLASS"]}'", null);
                foreach (ManagementClass templateClass in templateSearcher.Get())
                {
                    // EventTypeName qualifier ~ OpCode
                    var template    = (string)templateClass["__CLASS"];
                    var eventType   = string.Empty;
                    var version     = categoryVersion;
                    var description = categoryDescription;
                    foreach (QualifierData qd in templateClass.Qualifiers)
                    {
                        if (qd.Value.GetType() == typeof(Int32) && qd.Name.ToLower() == "eventversion")
                        {
                            version = (Int32)qd.Value; // override category version with specific event version
                        }
                        else if (qd.Value.GetType() == typeof(String) && qd.Name.ToLower() == "eventtypename")
                        {
                            eventType = (string)qd.Value;
                        }
                        else if (qd.Value.GetType() == typeof(String) && qd.Name.ToLower() == "description")
                        {
                            description = (string)qd.Value;
                        }
                    }
                    if (!string.IsNullOrEmpty(categoryDescription))
                    {
                        stringTable.Add(template, categoryDescription);
                    }

                    // EventType -> id(s)
                    var ids = new SortedSet <Int32>();
                    foreach (QualifierData qd in templateClass.Qualifiers)
                    {
                        if (qd.Name.ToLower() == "eventtype")
                        {
                            if (qd.Value.GetType() == typeof(Int32))
                            {
                                ids.Add((Int32)qd.Value);
                            }
                            else if (qd.Value.GetType().IsArray)
                            {
                                foreach (var element in (Array)qd.Value)
                                {
                                    if (element.GetType() == typeof(Int32))
                                    {
                                        ids.Add((Int32)element);
                                    }
                                }
                            }
                            break;
                        }
                    }

                    // sort by category, id, version
                    foreach (var id in ids)
                    {
                        events.Add($"{category}{id,6}{version,6}",
                                   new EtwEvent
                        {
                            Value    = id,
                            Symbol   = template,
                            Opcode   = eventType,
                            Version  = version,
                            Template = template,
                            Keyword  = description,
                            Task     = category
                        });
                    }

                    // create a template from the properties
                    var templateData = new SortedDictionary <int, EtwTemplateData>();
                    foreach (PropertyData pd in templateClass.Properties)
                    {
                        foreach (QualifierData qd in pd.Qualifiers)
                        {
                            if (qd.Value.GetType() == typeof(Int32) && qd.Name.ToLower() == "wmidataid")
                            {
                                var id = (int)qd.Value;
                                templateData[id] = new EtwTemplateData
                                {
                                    Name = pd.Name,
                                    Type = pd.Type.ToString()
                                };
                                break;
                            }
                        }
                    }

                    templates.Add(new EtwTemplate(template, templateData.Values.ToArray()));
                }
            }

            manifest.Events      = events.Values.ToArray();
            manifest.Templates   = templates.ToArray();
            manifest.StringTable = stringTable;

            return(manifest);
        }
Ejemplo n.º 42
0
        public async Task <ImageCacherObject> GetImage(string[] tags, bool forceExplicit, DapiSearchType type,
                                                       HashSet <string> blacklistedTags = null)
        {
            tags = tags.Select(tag => tag?.ToLowerInvariant()).ToArray();

            blacklistedTags = blacklistedTags ?? new HashSet <string>();

            foreach (var item in defaultTagBlacklist)
            {
                blacklistedTags.Add(item);
            }

            blacklistedTags = blacklistedTags.Select(t => t.ToLowerInvariant()).ToHashSet();

            if (tags.Any(x => blacklistedTags.Contains(x)))
            {
                throw new Exception("One of the specified tags is blacklisted");
            }

            if (type == DapiSearchType.E621)
            {
                tags = tags.Select(tag => tag?.Replace("yuri", "female/female", StringComparison.InvariantCulture))
                       .ToArray();
            }

            await _lock.WaitAsync().ConfigureAwait(false);

            try
            {
                ImageCacherObject[] imgs;
                if (tags.Any())
                {
                    imgs = _cache.Where(x => x.Tags.IsSupersetOf(tags) && x.SearchType == type && (!forceExplicit || x.Rating == "e")).ToArray();
                }
                else
                {
                    imgs = _cache.Where(x => x.SearchType == type).ToArray();
                }
                imgs = imgs.Where(x => x.Tags.All(t => !blacklistedTags.Contains(t.ToLowerInvariant()))).ToArray();
                ImageCacherObject img;
                if (imgs.Length == 0)
                {
                    img = null;
                }
                else
                {
                    img = imgs[_rng.Next(imgs.Length)];
                }

                if (img != null)
                {
                    _cache.Remove(img);
                    return(img);
                }
                else
                {
                    var images = await DownloadImagesAsync(tags, forceExplicit, type).ConfigureAwait(false);

                    images = images
                             .Where(x => x.Tags.All(t => !blacklistedTags.Contains(t.ToLowerInvariant())))
                             .ToArray();
                    if (images.Length == 0)
                    {
                        return(null);
                    }
                    var toReturn = images[_rng.Next(images.Length)];
                    foreach (var dledImg in images)
                    {
                        if (dledImg != toReturn)
                        {
                            _cache.Add(dledImg);
                        }
                    }
                    return(toReturn);
                }
            }
            finally
            {
                _lock.Release();
            }
        }
Ejemplo n.º 43
0
 public void AddGameCellToTable(int x, int y, bool color = true)
 {
     table.Add(new GameCell(FormatX(x), FormatY(y), color));
 }
Ejemplo n.º 44
0
    public void Solve()
    {
        SortedSet <Troop> mockTroops    = mission.factory.incoming;
        List <Troop>      finalEnlisted = new List <Troop>();
        Factory           factory       = mission.factory;

        foreach (var mockTestTroop in mission.acceptedMission)
        {
            mockTroops.Add(mockTestTroop);
            finalEnlisted.Add(mockTestTroop);

            FactoryState lastState
                = new FactoryState(factory, Game.gameTime);

            bool allyLock      = factory.isAlly;
            int  armyAvailable = allyLock ? factory.count : 0;

            var ordered = mockTroops.ToList();

            //iterate through the mock states
            for (int i = 0; i < ordered.Count; i++)
            {
                Troop        troop    = ordered[i];
                FactoryState newState = new FactoryState(lastState, troop);

                //if two troops arrives at the same time
                if (i + 1 < ordered.Count && troop.endTime == ordered[i + 1].endTime)
                {
                    lastState = newState;
                    continue;
                }

                if (allyLock && newState.isEnemy)
                {
                    allyLock = false;
                    break;
                }

                if (allyLock == false && newState.isAlly)
                {
                    allyLock      = true;
                    armyAvailable = newState.count;
                }

                if (factory.isAlly && troop == mockTestTroop)
                {
                    armyAvailable = newState.count;
                }

                armyAvailable = Math.Min(armyAvailable, newState.count);
                lastState     = newState;
            }

            if (allyLock)                                                                   //mission is possible
            {
                mockTestTroop.count = Math.Max(1, mockTestTroop.count - armyAvailable + 1); //don't oversend

                foreach (Troop troop in finalEnlisted)
                {
                    Action newAction = new Action(MoveType.Move, troop.start, troop.end, troop.count);
                    Action.AddAction(newAction, troop);
                }
                return;
            }
        }
    }
Ejemplo n.º 45
0
        bool UpdateChanges()
        {
            // Get the current status of the build
            int             MaxChanges;
            int             OldestChangeNumber = -1;
            int             NewestChangeNumber = -1;
            HashSet <int>   CurrentChangelists;
            SortedSet <int> PrevPromotedChangelists;

            lock (this)
            {
                MaxChanges = PendingMaxChanges;
                if (Changes.Count > 0)
                {
                    NewestChangeNumber = Changes.First().Number;
                    OldestChangeNumber = Changes.Last().Number;
                }
                CurrentChangelists      = new HashSet <int>(Changes.Select(x => x.Number));
                PrevPromotedChangelists = new SortedSet <int>(PromotedChangeNumbers);
            }

            // Build a full list of all the paths to sync
            List <string> DepotPaths = new List <string>();

            if (SelectedClientFileName.EndsWith(".uprojectdirs", StringComparison.InvariantCultureIgnoreCase))
            {
                DepotPaths.Add(String.Format("{0}/...", BranchClientPath));
            }
            else
            {
                DepotPaths.Add(String.Format("{0}/*", BranchClientPath));
                DepotPaths.Add(String.Format("{0}/Engine/...", BranchClientPath));
                DepotPaths.Add(String.Format("{0}/...", PerforceUtils.GetClientOrDepotDirectoryName(SelectedClientFileName)));
                if (bIsEnterpriseProject)
                {
                    DepotPaths.Add(String.Format("{0}/Enterprise/...", BranchClientPath));
                }
            }

            // Read any new changes
            List <PerforceChangeSummary> NewChanges;

            if (MaxChanges > CurrentMaxChanges)
            {
                if (!Perforce.FindChanges(DepotPaths, MaxChanges, out NewChanges, LogWriter))
                {
                    return(false);
                }
            }
            else
            {
                if (!Perforce.FindChanges(DepotPaths.Select(DepotPath => String.Format("{0}@>{1}", DepotPath, NewestChangeNumber)), -1, out NewChanges, LogWriter))
                {
                    return(false);
                }
            }

            // Remove anything we already have
            NewChanges.RemoveAll(x => CurrentChangelists.Contains(x.Number));

            // Update the change ranges
            if (NewChanges.Count > 0)
            {
                OldestChangeNumber = Math.Max(OldestChangeNumber, NewChanges.Last().Number);
                NewestChangeNumber = Math.Min(NewestChangeNumber, NewChanges.First().Number);
            }

            // If we are using zipped binaries, make sure we have every change since the last zip containing them. This is necessary for ensuring that content changes show as
            // syncable in the workspace view if there have been a large number of content changes since the last code change.
            int MinZippedChangeNumber = -1;

            foreach (int ChangeNumber in ChangeNumberToZippedBinaries.Keys)
            {
                if (ChangeNumber > MinZippedChangeNumber && ChangeNumber <= OldestChangeNumber)
                {
                    MinZippedChangeNumber = ChangeNumber;
                }
            }
            if (MinZippedChangeNumber != -1 && MinZippedChangeNumber < OldestChangeNumber)
            {
                List <PerforceChangeSummary> ZipChanges;
                if (Perforce.FindChanges(DepotPaths.Select(DepotPath => String.Format("{0}@{1},{2}", DepotPath, MinZippedChangeNumber, OldestChangeNumber - 1)), -1, out ZipChanges, LogWriter))
                {
                    NewChanges.AddRange(ZipChanges);
                }
            }

            // Fixup any ROBOMERGE authors
            const string RoboMergePrefix = "#ROBOMERGE-AUTHOR:";

            foreach (PerforceChangeSummary Change in NewChanges)
            {
                if (Change.Description.StartsWith(RoboMergePrefix))
                {
                    int StartIdx = RoboMergePrefix.Length;
                    while (StartIdx < Change.Description.Length && Change.Description[StartIdx] == ' ')
                    {
                        StartIdx++;
                    }

                    int EndIdx = StartIdx;
                    while (EndIdx < Change.Description.Length && !Char.IsWhiteSpace(Change.Description[EndIdx]))
                    {
                        EndIdx++;
                    }

                    if (EndIdx > StartIdx)
                    {
                        Change.User        = Change.Description.Substring(StartIdx, EndIdx - StartIdx);
                        Change.Description = "ROBOMERGE: " + Change.Description.Substring(EndIdx).TrimStart();
                    }
                }
            }

            // Process the new changes received
            if (NewChanges.Count > 0 || MaxChanges < CurrentMaxChanges)
            {
                // Insert them into the builds list
                lock (this)
                {
                    Changes.UnionWith(NewChanges);
                    if (Changes.Count > MaxChanges)
                    {
                        // Remove changes to shrink it to the max requested size, being careful to avoid removing changes that would affect our ability to correctly
                        // show the availability for content changes using zipped binaries.
                        SortedSet <PerforceChangeSummary> TrimmedChanges = new SortedSet <PerforceChangeSummary>(new PerforceChangeSorter());
                        foreach (PerforceChangeSummary Change in Changes)
                        {
                            TrimmedChanges.Add(Change);
                            if (TrimmedChanges.Count >= MaxChanges && (ChangeNumberToZippedBinaries.Count == 0 || ChangeNumberToZippedBinaries.ContainsKey(Change.Number) || ChangeNumberToZippedBinaries.First().Key > Change.Number))
                            {
                                break;
                            }
                        }
                        Changes = TrimmedChanges;
                    }
                    CurrentMaxChanges = MaxChanges;
                }

                // Find the last submitted change by the current user
                int NewLastChangeByCurrentUser = -1;
                foreach (PerforceChangeSummary Change in Changes)
                {
                    if (String.Compare(Change.User, Perforce.UserName, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        NewLastChangeByCurrentUser = Math.Max(NewLastChangeByCurrentUser, Change.Number);
                    }
                }
                LastChangeByCurrentUser = NewLastChangeByCurrentUser;

                // Notify the main window that we've got more data
                if (OnUpdate != null)
                {
                    OnUpdate();
                }
            }
            return(true);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Check intersection between each triangles.
        /// </summary>
        /// <param name="trianglesPoints">Each three points are coordinates for triangle. (trianglesPoints.Count % 3 must equals 0)</param>
        /// <returns>Return true if some triangles intersect</returns>
        public static bool TrianglesIntersection(List <Vector2> trianglesPoints)
        {
            if (trianglesPoints == null)
            {
                throw new ArgumentNullException("trianglesPoints can't be null");
            }

            if (trianglesPoints.Count % 3 != 0)
            {
                throw new ArgumentException("trianglesPoints.Count % 3 must equals 0");
            }
            //prepare. Put each triangle into bounding rectangle.
            List <BRectangle> bRectangle = new List <BRectangle>(trianglesPoints.Count / 3);

            for (int i = 0; i < trianglesPoints.Count; i += 3)
            {
                Vector2 min = trianglesPoints[i];
                Vector2 max = trianglesPoints[i];
                for (int j = 1; j < 3; j++)
                {
                    min.X = Math.Min(min.X, trianglesPoints[i + j].X);
                    min.Y = Math.Min(min.Y, trianglesPoints[i + j].Y);
                    max.X = Math.Max(max.X, trianglesPoints[i + j].X);
                    max.Y = Math.Max(max.Y, trianglesPoints[i + j].Y);
                }

                bRectangle.Add(new BRectangle(min, max, i / 3));
            }

            List <BPoint2D> points = new List <BPoint2D>(bRectangle.Count * 2);


            //Create event-point(start, end) for each bounding rectangle
            bRectangle.ForEach(t => { points.Add(t.min); points.Add(t.max); });

            //Sort event-point
            points.Sort((a, b) =>
            {
                if (a.pos.X < b.pos.X)
                {
                    return(-1);
                }
                else if (a.pos.X > b.pos.X)
                {
                    return(1);
                }
                else
                {
                    if (a.isStart == b.isStart)
                    {
                        return(0);
                    }

                    if (!a.isStart)
                    {
                        return(-1);
                    }
                    if (!b.isStart)
                    {
                        return(1);
                    }
                    return(0);
                }
            });


            //Use scan line for OX.

            SortedSet <BRectangle> rectangles = new SortedSet <BRectangle>(Comparer <BRectangle> .Create((a, b) =>
            {
                if (a.id == b.id)
                {
                    return(0);
                }
                else
                {
                    if (a.min.pos.Y.CompareTo(b.min.pos.Y) <= 0)
                    {
                        return(-1);
                    }
                    else
                    {
                        return(1);
                    }
                }
            }));


            for (int i = 0; i < points.Count; i++) // O(N)
            {
                BRectangle temp = bRectangle[points[i].id];

                //if event is start, we should check our rectangle with each rectangle in SortedSet
                if (points[i].isStart)
                {
                    foreach (var r in rectangles)
                    {
                        if (r.min.pos.Y > temp.max.pos.Y)
                        {
                            break;
                        }

                        if (temp.min.pos.Y <= r.max.pos.Y && temp.min.pos.Y >= r.min.pos.Y || temp.max.pos.Y <= r.max.pos.Y && temp.max.pos.Y >= r.min.pos.Y)
                        {
                            List <Vector2> firstTriangle = new List <Vector2>()
                            {
                                trianglesPoints[temp.id * 3], trianglesPoints[temp.id * 3 + 1], trianglesPoints[temp.id * 3 + 2]
                            };
                            List <Vector2> secondTriangle = new List <Vector2>()
                            {
                                trianglesPoints[r.id * 3], trianglesPoints[r.id * 3 + 1], trianglesPoints[r.id * 3 + 2]
                            };

                            //Call private function. The first triangle must be greater.
                            if ((temp.max.pos.X - temp.min.pos.X) > (r.max.pos.X - r.min.pos.X))
                            {
                                if (TriangleIntersection(firstTriangle, secondTriangle))
                                {
                                    return(true);
                                }
                            }
                            else
                            {
                                if (TriangleIntersection(secondTriangle, firstTriangle))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                    //Don't forget to put rectangle.
                    rectangles.Add(temp);
                }
                else
                {
                    //End event. Delete rectangle from sorted set.
                    rectangles.Remove(temp);
                }
            }


            return(false);
        }
    //find path for moving and return it
    MGPumMoveCommand findPath(MGPumField field, MGPumUnit unit)
    {
        // can we find this out in a better way?
        queued       = new bool[8, 8];
        tilesToVisit = new SortedSet <Vector2Int>(new AStarComparer(field.coords));
        predecessors = new Dictionary <Vector2Int, Vector2Int>();
        //distance = new Dictionary<Vector2Int, int>();

        tilesToVisit.Add(unit.field.coords);
        queued[unit.field.coords.x, unit.field.coords.y] = true;

        int recursion    = 0;
        int maxRecursion = 500;

        while (tilesToVisit.Count > 0)
        {
            recursion++;
            if (recursion > maxRecursion)
            {
                break;
            }

            Vector2Int position = tilesToVisit.Min;
            tilesToVisit.Remove(position);

            if (!state.fields.inBounds(position))
            {
                continue;
            }

            //touchedTiles.Add(position);

            if (position == field.coords)
            {
                List <Vector2Int> path = new List <Vector2Int>();
                path.Add(position);

                //reconstruct path in reverse
                while (predecessors.ContainsKey(path[0]))
                {
                    path.Insert(0, predecessors[path[0]]);
                }

                MGPumMoveChainMatcher matcher = unit.getMoveMatcher();

                MGPumFieldChain chain = new MGPumFieldChain(unit.ownerID, matcher);

                for (int i = 0; i < path.Count; i++)
                {
                    chain.add(state.getField(path[i]));
                }

                if (chain.isValidChain())
                {
                    MGPumMoveCommand mc = new MGPumMoveCommand(this.playerID, chain, unit);
                    return(mc);
                }

                continue;
            }

            foreach (Vector2Int direction in getDirections())
            {
                Vector2Int neighbor = position + direction;

                if (!state.fields.inBounds(neighbor))
                {
                    continue;
                }

                if (!queued[neighbor.x, neighbor.y] && state.getUnitForField(state.getField(neighbor)) == null)
                {
                    queued[neighbor.x, neighbor.y] = true;
                    tilesToVisit.Add(neighbor);
                    predecessors.Add(neighbor, position);
                    //distance.Add(neighbor, )
                }
            }
        }
        return(null);
    }
Ejemplo n.º 48
0
 private void AcquireLock(string resource)
 {
     _lockedResources.Add($"{_storage.SchemaName}:{resource}:Lock");
 }
        public EmployerSearchModel ToEmployerSearchResult(bool keyOnly = false, List <SicCodeSearchModel> listOfSicCodeSearchModels = null)
        {
            if (keyOnly)
            {
                return(new EmployerSearchModel {
                    OrganisationId = OrganisationId.ToString()
                });
            }

            // Get the last two names for the org. Most recent name first
            string[] names = OrganisationNames.Select(n => n.Name).Reverse().Take(2).ToArray();

            var abbreviations = new SortedSet <string>(StringComparer.OrdinalIgnoreCase);

            names.ForEach(n => abbreviations.Add(n.ToAbbr()));
            names.ForEach(n => abbreviations.Add(n.ToAbbr(".")));
            var excludes = new[] { "Ltd", "Limited", "PLC", "Corporation", "Incorporated", "LLP", "The", "And", "&", "For", "Of", "To" };

            names.ForEach(n => abbreviations.Add(n.ToAbbr(excludeWords: excludes)));
            names.ForEach(n => abbreviations.Add(n.ToAbbr(".", excludeWords: excludes)));

            abbreviations.RemoveWhere(a => string.IsNullOrWhiteSpace(a));
            abbreviations.Remove(OrganisationName);

            // extract the prev org name (if exists)
            var prevOrganisationName = "";

            if (names.Length > 1)
            {
                prevOrganisationName = names[names.Length - 1];
                abbreviations.Remove(prevOrganisationName);
            }

            //Get the latest sic codes
            IEnumerable <OrganisationSicCode> sicCodes = GetSicCodes();

            Return[] submittedReports = GetSubmittedReports().ToArray();

            var result = new EmployerSearchModel {
                OrganisationId          = OrganisationId.ToString(),
                OrganisationIdEncrypted = GetEncryptedId(),
                Name         = OrganisationName,
                PreviousName = prevOrganisationName,
                PartialNameForSuffixSearches        = OrganisationName,
                PartialNameForCompleteTokenSearches = OrganisationName,
                Abbreviations      = abbreviations.ToArray(),
                Size               = GetLatestReturn() == null ? 0 : (int)GetLatestReturn().OrganisationSize,
                SicSectionIds      = sicCodes.Select(sic => sic.SicCode.SicSectionId.ToString()).Distinct().ToArray(),
                SicSectionNames    = sicCodes.Select(sic => sic.SicCode.SicSection.Description).Distinct().ToArray(),
                SicCodeIds         = sicCodes.Select(sicCode => sicCode.SicCodeId.ToString()).Distinct().ToArray(),
                Address            = GetLatestAddress()?.GetAddressString(),
                LatestReportedDate = submittedReports.Select(x => x.Created).FirstOrDefault(),
                ReportedYears      = submittedReports.Select(x => x.AccountingDate.Year.ToString()).ToArray(),
                ReportedLateYears  =
                    submittedReports.Where(x => x.IsLateSubmission).Select(x => x.AccountingDate.Year.ToString()).ToArray(),
                ReportedExplanationYears = submittedReports.Where(x => string.IsNullOrEmpty(x.CompanyLinkToGPGInfo) == false)
                                           .Select(x => x.AccountingDate.Year.ToString())
                                           .ToArray()
            };

            if (listOfSicCodeSearchModels != null)
            {
                result.SicCodeListOfSynonyms = GetListOfSynonyms(result.SicCodeIds, listOfSicCodeSearchModels);
            }

            return(result);
        }
Ejemplo n.º 50
0
 public void Add(Item item)
 {
     itemSet.Add(item);
 }
Ejemplo n.º 51
0
        public void TestExploreAllInterleavings()
        {
            SortedSet <string> results = new SortedSet <string>();

            string success = "Explored interleavings.";

            this.TestWithError(async(runtime) =>
            {
                InMemoryLogger log = new InMemoryLogger();

                Task task1 = Task.Run(async() =>
                {
                    log.WriteLine(">foo");
                    await Task.Delay(runtime.RandomInteger(10));
                    log.WriteLine("<foo");
                });

                Task task2 = Task.Run(async() =>
                {
                    log.WriteLine(">bar");
                    await Task.Delay(runtime.RandomInteger(10));
                    log.WriteLine("<bar");
                });

                await Task.WhenAll(task1, task2);

                results.Add(log.ToString());
                Specification.Assert(results.Count < 6, success);
            },
                               configuration: GetConfiguration().WithTestingIterations(1000),
                               expectedError: success);

            string expected = @">bar
<bar
>foo
<foo

>bar
>foo
<bar
<foo

>bar
>foo
<foo
<bar

>foo
<foo
>bar
<bar

>foo
>bar
<bar
<foo

>foo
>bar
<foo
<bar
";

            expected = expected.NormalizeNewLines();

            string actual = string.Join("\n", results).NormalizeNewLines();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 52
0
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            var search = SearchPattern.Parse(ref path, ref searchPattern);

            var directoryToVisit = new List <UPath>();

            directoryToVisit.Add(path);

            var entries           = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);
            var sortedDirectories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);
            var fileSystems       = new List <IFileSystem>();

            if (NextFileSystem != null)
            {
                fileSystems.Add(NextFileSystem);
            }

            // Query all filesystems just once
            lock (_fileSystems)
            {
                fileSystems.AddRange(_fileSystems);
            }

            while (directoryToVisit.Count > 0)
            {
                var pathToVisit = directoryToVisit[0];
                directoryToVisit.RemoveAt(0);
                int dirIndex = 0;
                entries.Clear();
                sortedDirectories.Clear();

                for (var i = fileSystems.Count - 1; i >= 0; i--)
                {
                    var fileSystem = fileSystems[i];

                    if (fileSystem.DirectoryExists(pathToVisit))
                    {
                        foreach (var item in fileSystem.EnumeratePaths(pathToVisit, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
                        {
                            if (!entries.Contains(item))
                            {
                                var isFile      = fileSystem.FileExists(item);
                                var isDirectory = fileSystem.DirectoryExists(item);
                                var isMatching  = search.Match(item);

                                if (isMatching && ((isFile && searchTarget != SearchTarget.Directory) || (isDirectory && searchTarget != SearchTarget.File)))
                                {
                                    entries.Add(item);
                                }

                                if (searchOption == SearchOption.AllDirectories && isDirectory)
                                {
                                    sortedDirectories.Add(item);
                                }
                            }
                        }
                    }
                }

                // Enqueue directories and respect order
                foreach (var nextDir in sortedDirectories)
                {
                    directoryToVisit.Insert(dirIndex++, nextDir);
                }

                // Return entries
                foreach (var entry in entries)
                {
                    yield return(entry);
                }
            }
        }
Ejemplo n.º 53
0
        private static void BuildBetweenDfa <T>(ref Automaat <State <T> > a, SortedSet <Tuple <T, char, SortedSet <T> > > table, ref int stateCounter, State <T> s) where T : IComparable
        {
            foreach (var symbol in a._symbols)
            {
                var toStates = new SortedSet <T>();
                foreach (var state in s.States)
                {
                    foreach (var record in table)
                    {
                        if (record.Item1.CompareTo(state) == 0 && record.Item2 == symbol)
                        {
                            record.Item3.ToList().ForEach(toState => toStates.Add(toState));
                        }
                    }
                }

                var transToState = s;
                var stateId      = stateCounter;
                var stateExsists = false;

                if (toStates.Count == 0)
                {
                    stateId = 0;
                    foreach (var state in a._states)
                    {
                        if (state.Id == stateId)
                        {
                            stateExsists = true;
                            transToState = state;
                            break;
                        }
                    }
                }
                else
                {
                    var isSameState = false;
                    foreach (var state in a._states)
                    {
                        isSameState = state.HasSameStates(toStates);
                        if (isSameState)
                        {
                            stateExsists = true;
                            transToState = state;
                            break;
                        }
                    }

                    if (!isSameState)
                    {
                        stateCounter++;
                        stateId = stateCounter;
                    }
                }

                if (!stateExsists)
                {
                    var newState = new State <T>(stateId)
                    {
                        States = toStates
                    };
                    a.AddTransition(new Transition <State <T> >(s, symbol, newState));
                    BuildBetweenDfa(ref a, table, ref stateCounter, newState);
                }
                else
                {
                    a.AddTransition(new Transition <State <T> >(s, symbol, transToState));
                }
            }
        }
Ejemplo n.º 54
0
 public bool AddSegment(Segment s)
 {
     return(_segmentSet.Add(s));
 }
Ejemplo n.º 55
0
 protected internal override void AddFontStream(PdfDictionary fontDescriptor)
 {
     if (embedded)
     {
         PdfName   fontFileName;
         PdfStream fontStream;
         if (fontProgram is IDocFontProgram)
         {
             fontFileName = ((IDocFontProgram)fontProgram).GetFontFileName();
             fontStream   = ((IDocFontProgram)fontProgram).GetFontFile();
         }
         else
         {
             if (((TrueTypeFont)GetFontProgram()).IsCff())
             {
                 fontFileName = PdfName.FontFile3;
                 try {
                     byte[] fontStreamBytes = ((TrueTypeFont)GetFontProgram()).GetFontStreamBytes();
                     fontStream = GetPdfFontStream(fontStreamBytes, new int[] { fontStreamBytes.Length });
                     fontStream.Put(PdfName.Subtype, new PdfName("Type1C"));
                 }
                 catch (PdfException e) {
                     ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Font.PdfTrueTypeFont));
                     logger.Error(e.Message);
                     fontStream = null;
                 }
             }
             else
             {
                 fontFileName = PdfName.FontFile2;
                 SortedSet <int> glyphs = new SortedSet <int>();
                 for (int k = 0; k < shortTag.Length; k++)
                 {
                     if (shortTag[k] != 0)
                     {
                         int   uni   = fontEncoding.GetUnicode(k);
                         Glyph glyph = uni > -1 ? fontProgram.GetGlyph(uni) : fontProgram.GetGlyphByCode(k);
                         if (glyph != null)
                         {
                             glyphs.Add(glyph.GetCode());
                         }
                     }
                 }
                 ((TrueTypeFont)GetFontProgram()).UpdateUsedGlyphs(glyphs, subset, subsetRanges);
                 try {
                     byte[] fontStreamBytes;
                     //getDirectoryOffset() > 0 means ttc, which shall be subset anyway.
                     if (subset || ((TrueTypeFont)GetFontProgram()).GetDirectoryOffset() > 0)
                     {
                         fontStreamBytes = ((TrueTypeFont)GetFontProgram()).GetSubset(glyphs, subset);
                     }
                     else
                     {
                         fontStreamBytes = ((TrueTypeFont)GetFontProgram()).GetFontStreamBytes();
                     }
                     fontStream = GetPdfFontStream(fontStreamBytes, new int[] { fontStreamBytes.Length });
                 }
                 catch (PdfException e) {
                     ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Font.PdfTrueTypeFont));
                     logger.Error(e.Message);
                     fontStream = null;
                 }
             }
         }
         if (fontStream != null)
         {
             fontDescriptor.Put(fontFileName, fontStream);
             if (fontStream.GetIndirectReference() != null)
             {
                 fontStream.Flush();
             }
         }
     }
 }
Ejemplo n.º 56
0
            public static string CheckSolution()
            {
                SortedSet <int> nodesVisited1 = new SortedSet <int>();
                int             currentNode   = 0;
                bool            feasible      = true;

                do
                {
                    if (nodesVisited1.Contains(currentNode))
                    {
                        return(String.Format("not feasible: Node {0} is visited twice in solution 1", currentNode));
                    }
                    nodesVisited1.Add(currentNode);

                    int nextNode = _route1[currentNode].Next;
                    if (_route2[currentNode].Prev == nextNode || _route2[currentNode].Next == nextNode)
                    {
                        Console.WriteLine(String.Format("not feasible: Arc from node {0} to node {1} is in both solutions", currentNode, nextNode));
                        feasible = false;
                    }
                    currentNode = _route1[currentNode].Next;
                } while (currentNode != 0);

                if (nodesVisited1.Count != _route1.Count)
                {
                    Console.WriteLine(String.Format("not feasible: The following nodes are not visited in solution 1: "));
                    for (int node = 0; node < _route1.Count; node++)
                    {
                        if (!nodesVisited1.Contains(node))
                        {
                            Console.WriteLine(String.Format("{0}", node));
                        }
                    }
                    feasible = false;
                }
                SortedSet <int> nodesVisited2 = new SortedSet <int>();

                currentNode = 0;
                do
                {
                    if (nodesVisited2.Contains(currentNode))
                    {
                        return(String.Format("not feasible: Node {0} is visited twice in solution 2", currentNode));
                    }
                    nodesVisited2.Add(currentNode);
                    currentNode = _route2[currentNode].Next;
                } while (currentNode != 0);

                if (nodesVisited2.Count != _route2.Count)
                {
                    Console.WriteLine(String.Format("not feasible: The following nodes are not visited in solution 3: "));
                    for (int node = 0; node < _route2.Count; node++)
                    {
                        if (!nodesVisited2.Contains(node))
                        {
                            Console.WriteLine(String.Format("{0}", node));
                        }
                    }
                    feasible = false;
                }
                return(String.Format("Is Solution Feasible? {0}", feasible));
            }
Ejemplo n.º 57
0
 public void AddClipboardObject(ClipboardObject clipboardObject)
 {
     clipboardObjects.Add(clipboardObject);
 }
Ejemplo n.º 58
0
        public SegmentMesh(ColorTemplate template)
        {
            int numGroups = template.NumSlots();

            imageWidth  = template.Width();
            imageHeight = template.Height();

            groups   = new List <SegmentGroup>();
            segments = new List <Segment>();

            //now populate the segments and segment groups
            //filter out groups that have no members (due to quantization)
            Dictionary <int, int> slotToGroup = new Dictionary <int, int>();

            for (int i = 0; i < numGroups; i++)
            {
                if (template.PixelsInSlot(i) > 0)
                {
                    slotToGroup.Add(i, groups.Count());
                    groups.Add(new SegmentGroup(template.OriginalSlotColor(i)));
                }
            }

            UnionFind <Color> uf    = new UnionFind <Color>((a, b) => (a.GetHashCode() == b.GetHashCode()));
            Bitmap            image = template.DebugQuantization();

            assignments = uf.ConnectedComponentsNoiseRemoval(Util.BitmapToArray(image));


            Dictionary <int, Segment> idToSegment            = new Dictionary <int, Segment>();
            int totalAdjacencyPerimeter                      = 0;
            Dictionary <int, HashSet <Point> > idToPerimeter = new Dictionary <int, HashSet <Point> >();

            //populate segments
            int width  = image.Width;
            int height = image.Height;

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    int id = assignments[i, j];
                    if (!idToSegment.ContainsKey(id))
                    {
                        idToSegment.Add(id, new Segment(id));
                        idToPerimeter.Add(id, new HashSet <Point>());
                    }

                    idToSegment[id].points.Add(new Point(i, j));
                    idToSegment[id].groupId = slotToGroup[template.GetSlotId(i, j)];

                    //look for 8-neighbor adjacencies, 2 pixels away
                    //TODO: measure adjacency strength and filter?
                    for (int dx = -2; dx <= 2; dx++)
                    {
                        for (int dy = -2; dy <= 2; dy++)
                        {
                            int x = i + dx;
                            int y = j + dy;
                            if (x >= 0 && x < width && y >= 0 && y < height)
                            {
                                int nid = assignments[x, y];
                                if (nid != id)
                                {
                                    idToSegment[id].adjacencies.Add(nid);

                                    //keep track of the total perimeter, and individual segment perimeters
                                    //don't double count the same point for each segment
                                    if (!idToPerimeter[id].Contains(new Point(x, y)))
                                    {
                                        idToPerimeter[id].Add(new Point(x, y));
                                        totalAdjacencyPerimeter++;

                                        //keep track of the adjacecy strength per segment
                                        if (!idToSegment[id].adjacencyStrength.ContainsKey(nid))
                                        {
                                            idToSegment[id].adjacencyStrength.Add(nid, 0);
                                        }
                                        idToSegment[id].adjacencyStrength[nid]++;
                                    }
                                    else
                                    {
                                        Console.WriteLine("Point already counted");
                                    }
                                }
                            }
                            else
                            {
                                //might as well be consistent here, and take into account the borders of the image when determining
                                //enclosure. We don't need to do this for the totalAdjacencyPerimeter, because that is just a normalization
                                //for the adjacency strengths of segments within the image
                                if (!idToPerimeter[id].Contains(new Point(x, y)))
                                {
                                    idToPerimeter[id].Add(new Point(x, y));
                                }
                            }
                        }
                    }
                }
            }

            //finalize segment list and adjacency list
            Dictionary <int, int> idToIdx = new Dictionary <int, int>();

            foreach (int id in idToSegment.Keys)
            {
                segments.Add(idToSegment[id]);
                idToIdx.Add(id, segments.Count() - 1);
            }

            //finalize adjacencies
            for (int i = 0; i < segments.Count(); i++)
            {
                SortedSet <int> renamedAdj = new SortedSet <int>();
                foreach (int a in segments[i].adjacencies)
                {
                    renamedAdj.Add(idToIdx[a]);
                }
                segments[i].adjacencies = renamedAdj;

                //finalize adjacency strengths
                int sid = assignments[segments[i].points.First().X, segments[i].points.First().Y];

                Dictionary <int, double> renamedAdjStrength = new Dictionary <int, double>();
                foreach (int nid in segments[i].adjacencyStrength.Keys)
                {
                    double pixelsAdj = segments[i].adjacencyStrength[nid];
                    renamedAdjStrength.Add(idToIdx[nid], pixelsAdj / totalAdjacencyPerimeter);
                    segments[i].enclosureStrength.Add(idToIdx[nid], new Tuple <double, double>(pixelsAdj / idToPerimeter[sid].Count(), pixelsAdj / idToPerimeter[nid].Count()));
                }
                segments[i].adjacencyStrength = renamedAdjStrength;
            }

            //finalize groups
            for (int i = 0; i < segments.Count(); i++)
            {
                int groupId = segments[i].groupId;
                groups[groupId].members.Add(i);
            }

            //finalize segment list

            ClassifySegments();

            foreach (Segment s in segments)
            {
                ComputeFeatures(s);
            }

            foreach (SegmentGroup g in groups)
            {
                ComputeFeatures(g);
            }
        }
Ejemplo n.º 59
0
        static ReqResult Req(Task task, int len)
        {
            Counter++;

            if (Counter > CounterMax || len >= BestScore)
            {
                return(new ReqResult()
                {
                    Value = BestScore,
                    AllowCash = false
                });
            }


            if (task.Path.Length <= 3)
            {
                if (len < BestScore)
                {
                    BestScore = len;
                }
                return(new ReqResult());
            }

            if (cash.ContainsKey(task.Hash))
            {
                var cashv = cash[task.Hash];
                if (cashv + len < BestScore)
                {
                    BestScore = cashv + len;
                }
                return(new ReqResult()
                {
                    Value = cashv
                });
            }

            var vertexes = new SortedSet <Task>();
            var isSkiped = false;

            for (int i = 0; i < task.Path.Length; i++)
            {
                var vert     = task.Path[i];
                var prev     = task.Path[i == 0 ? task.Path.Length - 1 : i - 1];
                var next     = task.Path[i == task.Path.Length - 1 ? 0 : i + 1];
                var cutValue = Matrix[prev, next];
                if (len + cutValue >= BestScore)
                {
                    isSkiped = true;
                    continue;
                }

                var newpath = new int[task.Path.Length - 1];
                Array.Copy(task.Path, 0, newpath, 0, i);
                Array.Copy(task.Path, i + 1, newpath, i, task.Path.Length - i - 1);

                var value = cutValue;
                for (int j = 0; j < task.Path.Length; j++)
                {
                    var curv = task.Path[j];
                    if (curv != vert && curv != prev && curv != next)
                    {
                        value -= Matrix[vert, curv];
                    }

                    if (Counter > CounterMax)
                    {
                        return(new ReqResult()
                        {
                            Value = BestScore,
                            AllowCash = false
                        });
                    }
                }

                vertexes.Add(new Task(value, newpath)
                {
                    CutValue = cutValue
                });
            }

            var result    = Int32.MaxValue;
            var allowCash = false;

            foreach (var vertex in vertexes)
            {
                var r  = Req(vertex, len + vertex.CutValue);
                var rv = r.Value == int.MaxValue ? int.MaxValue : r.Value + vertex.CutValue;
                if (result > rv)
                {
                    result    = rv;
                    allowCash = r.AllowCash;
                }
                else if (result == rv && r.AllowCash)
                {
                    allowCash = r.AllowCash;
                }

                if (Counter > CounterMax)
                {
                    return(new ReqResult()
                    {
                        Value = BestScore,
                        AllowCash = false
                    });
                }
            }

            allowCash = allowCash && !isSkiped;

            if (allowCash)
            {
                cash[task.Hash] = result;
            }

            return(new ReqResult()
            {
                Value = result,
                AllowCash = allowCash
            });
        }
Ejemplo n.º 60
0
        public static int Dijkstra2()
        {
            var Pipe = new SortedSet <Task2>();

            var path = new int[N];

            for (int i = 0; i < N; i++)
            {
                path[i] = i;
            }

            Pipe.Add(new Task2(0, new int[][] { path }));

            while (Pipe.Count > 0)
            {
                var task = Pipe.Min;
                Pipe.Remove(task);

                if (task.Parts.Length == 0)
                {
                    BestScore = task.Value;
                    return(task.Value);
                }

                if (cash.ContainsKey(task.Hash))
                {
                    continue;
                }
                cash[task.Hash] = task.Value;


                for (int i = 0; i < task.Parts.Length; i++)
                {
                    path = task.Parts[i];

                    for (int j = 0; j < path.Length - 2; j++)
                    {
                        for (int k = j + 2; k < path.Length; k++)
                        {
                            var leftpart  = (j + 1) + (path.Length - k) > 3;
                            var rightpart = k - j + 1 > 3;
                            var newparts  = new int[task.Parts.Length - 1 + (leftpart ? 1 : 0) + (rightpart ? 1 : 0)][];
                            Array.Copy(task.Parts, 0, newparts, 0, i);
                            if (leftpart)
                            {
                                var newpath = new int[(j + 1) + (path.Length - k)];
                                Array.Copy(path, 0, newpath, 0, j + 1);
                                Array.Copy(path, k, newpath, j + 1, path.Length - k);
                                newparts[i] = newpath;
                            }
                            if (rightpart)
                            {
                                var newpath = new int[k - j + 1];
                                Array.Copy(path, j, newpath, 0, newpath.Length);
                                newparts[i + (leftpart ? 1 : 0)] = newpath;
                            }
                            Array.Copy(task.Parts, i + 1, newparts, i + (leftpart ? 1 : 0) + (rightpart ? 1 : 0), task.Parts.Length - i - 1);

                            var value   = task.Value + Matrix[path[j], path[k]];
                            var newtask = new Task2(value, newparts);
                            if (cash.ContainsKey(newtask.Hash))
                            {
                                continue;
                            }
                            Pipe.Add(newtask);
                        }
                    }
                }
            }

            return(BestScore);
        }