Example #1
0
        public AssemblerResult Assemble(AssemblerOptions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");

            List<AssemblerMessage> messages = new List<AssemblerMessage>();

            try
            {
                //Get the lines
                var sourceLines = GetSourceLines(options);

                //Do the first pass
                var pass1Result = Pass1(messages, sourceLines);

                if (messages.All(m => m.ErrorLevel != ErrorLevel.Error))
                {
                    Pass2(messages, pass1Result, options.OutputFile);
                }
            }
            catch (Exception ex)
            {
                messages.Add(new AssemblerMessage(ErrorLevel.Error, ex.Message));
            }

            //We're done here
            return new AssemblerResult()
            {
                Messages = messages.ToArray(),
                Succeeded = messages.All(m => m.ErrorLevel != ErrorLevel.Error)
            };
        }
Example #2
0
        public static string FindCommonPath(string separator, List<string> paths)
        {
            string CommonPath = string.Empty;
            List<string> SeparatedPath = paths
                .First(str => str.Length == paths.Max(st2 => st2.Length))
                .Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            foreach (string PathSegment in SeparatedPath.AsEnumerable())
            {
                if (CommonPath.Length == 0 && paths.All(str => str.StartsWith(PathSegment)))
                {
                    CommonPath = PathSegment;
                }
                else if (paths.All(str => str.StartsWith(CommonPath + separator + PathSegment)))
                {
                    CommonPath += separator + PathSegment;
                }
                else
                {
                    break;
                }
            }

            return CommonPath;
        }
Example #3
0
 static bool IsRoyalFlush(List<Card> hand)
 {
     var start = 10;
     var suit = hand[0].Suit;
     return hand.All(c => c.Suit == suit) &&
         hand.All(c => c.Value == start++);
 }
        static string FindRootPath(List<string> paths)
        {
            var separator = Path.DirectorySeparatorChar;
            var commonPath = String.Empty;
            var separatedPath = paths
                .First(str => str.Length == paths.Max(st2 => st2.Length))
                .Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList();

            foreach (var pathSegment in separatedPath)
            {
                if (commonPath.Length == 0 && paths.All(str => str.StartsWith(pathSegment)))
                {
                    commonPath = pathSegment;
                }
                else if (paths.All(str => str.StartsWith(commonPath + separator + pathSegment)))
                {
                    commonPath += separator + pathSegment;
                }
                else
                {
                    break;
                }
            }

            return commonPath;
        }
		public static List<IRequiredService> DetermineMissingServices(this IEnumerable<XmlModuleConfig> modules, List<string> bootStrappedServices)
		{
			var providedServices = new List<IProvidedService>();
			var requiredServices = new Dictionary<IRequiredService, XmlModuleConfig>();

			foreach (var module in modules)
			{
				foreach (IRequiredService requiredService in module.RequiredServices)
				{
					if (requiredServices.All(r => r.Key.ServiceName != requiredService.ServiceName))
					{
						requiredServices.Add(requiredService, module);
					}
				}

				foreach (IProvidedService providedService in module.ProvidedServices)
				{
					if (providedServices.All(r => r.ServiceName != providedService.ServiceName))
					{
						providedServices.Add(providedService);
					}
				}
			}

			var query =
				requiredServices.Where(
					requiredService =>
					providedServices.All(s => s.ServiceName != requiredService.Key.ServiceName)
					&& bootStrappedServices.All(s => s != requiredService.Key.ServiceName));

			return query.Select(s => s.Key).ToList();
		}
Example #6
0
 private void For(int length, List<int[,]> maps, List<int> dileiPosition, List<int> notDileiPosition)
 {
     for (int i = 0; i < length; i++)
     {
         if (maps.All(map => map[0, i] > Safe)) dileiPosition.Add(i + 1);
         else if (maps.All(map => map[0, i] == Safe)) notDileiPosition.Add(i + 1);
     }
 }
Example #7
0
        public bool Launch()
        {
            var workers = new List<ChiefWorkerProcess>();
            try
            {
                _log.Debug("Loading settings...");
                var configuration = ConfigurationHelper.Load(_options.Configuration);
                _log.Debug("Starting machinery...");
                try
                {
                    foreach (var workerSettings in configuration)
                    {
                        var workerProcess = new ChiefWorkerProcess(_log, workerSettings);
                        workers.Add(workerProcess);
                        workerProcess.LaunchAsync();
                    }

                    while (workers.All(worker => worker.IsAlive && !worker.ReadyToAcceptClients))
                    {
                        Thread.Sleep(1000);
                    }

                    _log.Debug("Server(s) started...");
                    ReadyToAcceptClients();

                    while (!IsExitOnDemand() && workers.All(worker => worker.IsAlive))
                    {
                        Thread.Sleep(3000);
                    }

                    if (!workers.All(worker => worker.IsAlive))
                    {
                        var error = string.Format("The following sources does not work: {0}",
                            string.Join(
                                ", ",
                                workers
                                    .Where(worker => !worker.IsAlive)
                                    .Select(worker => worker.Name)
                                    .ToArray()));
                        _log.Error(error);
                        ErrorOccured(error);
                        return false;
                    }
                }
                finally
                {
                    workers.ForEach(item => item.Dispose());
                }
                return true;
            }
            catch (Exception unhandledException)
            {
                _log.Error(unhandledException);
                return false;
            }
        }
        public List<Ship> PlaceShips(List<int> sizes, int boardHeight, int boardWidth)
        {
            Height = boardHeight;
            Width = boardWidth;

            //var ship = new Ship
            //{
            //    Direction = Direction.Vertical,
            //    Length = 3,
            //    Location = new Point(0, 0)
            //};

            //var newShip = new Ship
            //{
            //    Direction = Direction.Vertical,
            //    Length = 3,
            //    Location = new Point(0, 3)
            //};

            //Console.WriteLine(ship.Neighbour(newShip));

            var ships = new List<Ship>();

            for (int i = 0; i < sizes.Count; i++)
            {
                var size = sizes[i];

                // Create new ship
                var newShip = new Ship
                {
                    Direction = Helpers.Random.Next(0, 1 + 1) == 0 ? Direction.Horizontal : Direction.Vertical,
                    Length = size,
                    Location = Helpers.RandomPoint(boardHeight, boardWidth)
                };

                // Check that it doesn't overlap with any other
                bool ok = ships.All(ship => !ship.Overlaps(newShip));
                ok = ok && ships.All(ship => !ship.Neighbour(newShip));

                // Do not advance to next ship,
                // repeat the same one next iteration
                if (!ok ||
                    newShip.EndPoint.X > boardWidth ||
                    newShip.EndPoint.Y >= boardHeight)
                    i--;
                else
                    ships.Add(newShip);
            }

            return ships;
        }
        public void AutofacWillDisposeAllItemsInLifetime()
        {
            List<DisposableObject> list = new List<DisposableObject>();
            using(var scope = TestSetup.Container.BeginLifetimeScope())
            {
                for (int i = 0; i < 100; i++)
                {
                    list.Add(scope.Resolve<DisposableObject>());
                }
                Assert.True(list.All(item => !item.IsDisposed));
            }

            Assert.True(list.All(item => item.IsDisposed));
        }
Example #10
0
        public void LoadParentMaps(List<INode> maps, Guid mapId)
        {
            var viewModelMaps = new List<SuperGraph.ViewModel.Node>();

            foreach (var map in maps)
            {
                if (viewModelMaps.All(q => q.Proxy.Id != map.Id))
                {
                    var viewModelNode = new SuperGraph.ViewModel.Node(MapManager);
                    viewModelNode.LoadNode(null, map);

                    viewModelMaps.Add(viewModelNode);
                }
            }

            if (viewModelMaps.Count > 1)
            {
                var breadcrumb = new MultiBreadcrumbItem(viewModelMaps);
                if (mapId != Guid.Empty)
                {
                    var currentMap = breadcrumb.Items.FirstOrDefault(q => q.Node.Proxy.Id == mapId);
                    if (currentMap != null)
                    {
                        breadcrumb.SelectedBreadcrumb = currentMap;
                    }
                }
                Breadcrumbs.BreadcrumbTrail.Insert(breadcrumb, _parentIndex);
            }
            else if (viewModelMaps.Count == 1)
            {
                var breadcrumb = new BreadcrumbItem(viewModelMaps[0]);
                Breadcrumbs.BreadcrumbTrail.Insert(breadcrumb, _parentIndex);
            }
        }
    static void Main()
    {
        string input = Console.ReadLine();
        int[] nums = input.Split(' ').Select(int.Parse).ToArray();

        var values = new List<int>();
        var diffs = new List<int>();
        for (int i = 0; i < nums.Length; i += 2)
        {
            values.Add(nums[i] + nums[i + 1]);
        }

        for (int i = 1; i < values.Count; i++)
        {
            diffs.Add(Math.Abs(values[i] - values[i - 1]));
        }

        if (values.All(o => o == values[0]))
        {
            Console.WriteLine("Yes, value={0}", values[0]);
        }
        else
        {
            Console.WriteLine("No, maxdiff={0}", diffs.Max());
        }
    }
Example #12
0
        static int BruteForce()
        {
            var chrs = cipher.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            for (int i = 97; i <= 122; i++)
            {
                for (int j = 97; j <= 122; j++)
                {
                    for (int k = 97; k <= 122; k++)
                    {
                        var list = new List<int>();
                        for (int l = 0; l < chrs.Count; l = l + 3)
                        {
                            var item = i ^ chrs[l];
                            list.Add(item);   
                          if(l < chrs.Count -1)
                              list.Add(j ^ chrs[l + 1]);
                          if (l < chrs.Count - 1)
                            list.Add(k ^ chrs[l + 2]);   
                        }

                        if (list.All(IsChar))
                        {
                            Console.Out.WriteLine(string.Format("Get {0}{1}{2}", Convert.ToChar(i), Convert.ToChar(j), Convert.ToChar(k)));
                            return list.Sum();
                        }
                    }
                }
                
            }

            return 0;

        }
Example #13
0
        /// <summary>
        /// 获取某个项下所带的附件集合(去重)
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public List<PnRegDTO> GetPnRegsByItem(int itemId)
        {
            var result = new List<PnRegDTO>();
            var installControllers = _unitOfWork.CreateSet<InstallController>().Where(p => p.ItemId == itemId).ToList();
            var pnRegs = _unitOfWork.CreateSet<PnReg>().ToList();
            installControllers.ForEach(p =>
            {
                if (result.All(l => l.Id != p.PnRegId))
                {
                    var pnReg = pnRegs.FirstOrDefault(l => l.Id == p.PnRegId);
                    if (pnReg != null)
                    {
                        var dbItem = _unitOfWork.CreateSet<Item>().ToList().FirstOrDefault(l => l.Id == pnReg.ItemId);

                        var pn = new PnRegDTO
                        {
                            Id = pnReg.Id,
                            Description = pnReg.Description,
                            IsLife = pnReg.IsLife,
                            Pn = pnReg.Pn,
                            ItemId = pnReg.ItemId,
                        };
                        if (dbItem != null) pn.ItemNo = dbItem.ItemNo;
                        result.Add(pn);
                    }
                }
            });
            return result;
        }
Example #14
0
        /// <summary>
        /// Returns collection of Matches for every possible match with the cards in this deck
        /// and the card argument.
        /// Note that a single card may be a part of multiple potential matches,
        /// in which case it will appear in multiple Matches in the returned List.
        /// </summary>
        /// <param name="card">Card to be compared to other cards in this deck for matches.</param>
        public List<Match> GetAllMatches(Card card)
        {
            var matches = new List<Match>();

            for (var i = 0; i < Cards.Count; i++)
            {
                for (var j = i + 1; j < Cards.Count; j++)
                {
                    var firstCard = Cards[i];
                    var secondCard = Cards[j];

                    if (firstCard == secondCard || firstCard == card || secondCard == card)
                        continue;

                    if (!Card.IsMatch(firstCard, secondCard, card))
                        continue;

                    var match = new Match();
                    match.Cards[0] = firstCard;
                    match.Cards[1] = secondCard;
                    match.Cards[2] = card;

                    if (matches.All(x => x.Cards != match.Cards))
                        matches.Add(match);
                }
            }

            return matches;
        }
        public SqlServerEndpoint(string name, string connectionString, bool includeSystemDatabases, IEnumerable<Database> includedDatabases, IEnumerable<string> excludedDatabaseNames)
            : base(name, connectionString)
        {
            var excludedDbs = new List<string>();
            var includedDbs = new List<Database>();

            if (excludedDatabaseNames != null)
            {
                excludedDbs.AddRange(excludedDatabaseNames);
            }

            if (includedDatabases != null)
            {
                includedDbs.AddRange(includedDatabases);
            }

            if (includeSystemDatabases && includedDbs.Any())
            {
                IEnumerable<Database> systemDbsToAdd = Constants.SystemDatabases
                                                                .Where(dbName => includedDbs.All(db => db.Name != dbName))
                                                                .Select(dbName => new Database {Name = dbName});
                includedDbs.AddRange(systemDbsToAdd);
            }
            else if (!includeSystemDatabases)
            {
                IEnumerable<string> systemDbsToAdd = Constants.SystemDatabases
                                                              .Where(dbName => excludedDbs.All(db => db != dbName));
                excludedDbs.AddRange(systemDbsToAdd);
            }

            IncludedDatabases = includedDbs.ToArray();
            ExcludedDatabaseNames = excludedDbs.ToArray();
        }
Example #16
0
        private List<Change> GetRemoves(string wrong, List<string> subMatches)
        {
            var indexesMathched = new List<int>();
            //detect
            foreach (var sub in subMatches)
            {
                var index = wrong.LastIndexOf(sub);

                for (var i = index; i < index + sub.Count(); i++)
                    indexesMathched.Add(i);
            }
            //calculate 
            var changes = new List<Change>();
            for (var i = 0; i < wrong.Count(); i++)
            {
                //if(i not in indexesMathched)
                if (indexesMathched.All(a => a != i))
                    changes.Add(new Change
                    {
                        ChangeType = ChangeType.Remove,
                        Index = i,
                        Character = wrong[i]
                    });
            }
            return changes;
        }
Example #17
0
        private List<Change> GetInsertions(string right, List<string> subMatches)
        {
            var indexesMathched = new List<int>();
            //detect
            foreach (var sub in subMatches)
            {
                var index = right.LastIndexOf(sub);

                for (var i = index; i < index + sub.Count(); i++)
                    indexesMathched.Add(i);
            }
            //calculate 
            var changes = new List<Change>();
            for (var i = 0; i < right.Count(); i++)
            {
                if (indexesMathched.All(a => a != i))
                    changes.Add(new Change
                    {
                        ChangeType = ChangeType.Insert,
                        Index = i,
                        Character = right[i]
                    });
            }
            return changes;
        }
Example #18
0
        /// <summary>
        /// Execute KMeans algorithm with given points and centroids.
        /// </summary>
        /// <param name="vectorPoints">List of all points (as Vectors) available</param>
        /// <param name="vectorCentroids">List of centroids</param>
        /// <returns>List of the calculated centroids</returns>
        public static List<Vector2D> DoKMeans(List<Vector2D> vectorPoints, List<Vector2D> vectorCentroids)
        {
            var movedCentroids = new List<Vector2D>();
            var oldCentroids = new List<Vector2D>();
            vectorCentroids.ForEach((e)=>oldCentroids.Add(e.Copy()));
            var finish = true;

            var loopCount = 0;

            //TODO Abbruchkriterium....
            while (finish)
            {
                var pointsToCentroids = MapPointsToNearestCentroids(vectorPoints, oldCentroids);
                movedCentroids = MoveCentroids(pointsToCentroids);

                finish = !movedCentroids.All(oldCentroids.Contains);

                oldCentroids.Clear();
                movedCentroids.ForEach((e)=>oldCentroids.Add(e.Copy()));
                loopCount++;
                finish = false;
            }

            return movedCentroids;
        }
    public HtmlString AddPrice(List<Price> oldPrices, Price newPrice)
    {
      List<Price> result = new List<Price>();
      DateTime endingDatePrevious = newPrice.StartingDate.AddDays(-1);

      if (oldPrices != null)
      {
        if (oldPrices.All(price => !price.EndingDate.HasValue || newPrice.StartingDate > price.EndingDate.Value))
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => !price.EndingDate.HasValue);
          if (currentPrice != null)
          {
            currentPrice.EndingDate = endingDatePrevious;
          }
        }
        else
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => price.EndingDate > newPrice.StartingDate);
          DateTime? oldEndingDate = currentPrice.EndingDate;
          currentPrice.EndingDate = endingDatePrevious;
          if (newPrice.EndingDate.HasValue && oldEndingDate > newPrice.EndingDate.Value)
          {
            result.Add(new Price() { Article = currentPrice.Article, BasePrice = currentPrice.BasePrice, StartingDate = newPrice.EndingDate.Value.AddDays(1), EndingDate = oldEndingDate });
          }
        }

        result.AddRange(oldPrices);
      }

      result.Add(newPrice);

      return result.ToHtmlJson();
    }
Example #20
0
        static void MaximumEquality(int[] cars)
        {
            int moves = 0;
            int maxIndex, minIndex;
            List<int> c = cars.ToList();
            List<int> tempC = new List<int>();

            //Initial print
            Console.WriteLine(PrintList(c));

            while (true)
            {
                maxIndex = c.IndexOf(c.Max());
                minIndex = c.IndexOf(c.Min());

                //copy c to tempC by value
                tempC = new List<int>();
                tempC.AddRange(c);

                c[minIndex]++;
                c[maxIndex]--;
                if (tempC.All(c.Contains))
                    break;

                ++moves;
                Console.WriteLine(PrintList(c) + " move #" + moves);
            }
            var equalCars = c.GroupBy(i => i).OrderByDescending(grp => grp.Count()).Select(grp => grp.Count()).First();

            Console.WriteLine("Equal cars: {0}\nNumber of moves: {1}", equalCars, moves);
            Console.ReadLine();
        }
Example #21
0
        public void UpdateData(ILongPollServerUpdates longPollServerUpdates)
        {
            if (longPollServerUpdates.FriendOnlineStatuses.Any())
            {
                _friendsService.UpdateOnline(longPollServerUpdates.FriendOnlineStatuses);
            }

            if (longPollServerUpdates.ReceivedMessages.Any())
            {
                _oldMessageIds = _dialogMessagesRepo.GetIncomingUnreadedMessages()
                    .Select(x => x.VkId)
                    .ToList();

                _dialogMessagesRepo.Add(_sessionInfoRepo.UserId, longPollServerUpdates.ReceivedMessages);

                if(_dialogMessagesRepo.GetIncomingUnreadedMessages().Any(x => _oldMessageIds.All(y => y != x.VkId)))
                    Task.Run(() => _mp3Player.Play());

                Task.Run(() => _dialogMessagesService.SaveToDB());
            }

            if (longPollServerUpdates.DroppedMessageFlags.Any())
            {
                _dialogMessagesRepo.DropFlags(longPollServerUpdates.DroppedMessageFlags);
                Task.Run(() => _dialogMessagesService.SaveToDB());
            }
        }
Example #22
0
        private static dynamic ReadJsonArray(JsonReader reader)
        {
            List<dynamic> vals = new List<dynamic>();

            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.EndArray)
                {
                    break;
                }
                else
                {
                    vals.Add(ReadJsonValue(reader, true));
                }
            }

            if (vals.Count != 0 && vals.All(v => v is IDictionary<string, object>))
            {
                if (vals.OfType<IDictionary<string, object>>().All(v => v.ContainsKey("Key") && v.ContainsKey("Value")))
                {
                    ExpandoObject obj = new ExpandoObject();

                    foreach (IDictionary<string, object> dict in vals.OfType<IDictionary<string, object>>())
                    {
                        ((IDictionary<string, object>)obj).Add(dict["Key"].ToString(), dict["Value"]);
                    }

                    return obj;
                }
            }

            return vals;
        }
Example #23
0
        public async Task<IEnumerable<Book>> GetByName(string name)
        {
            var result = new List<Book>();
            if (name.IndexOf(" ", StringComparison.Ordinal) != 0)
            {
                var terms = name.Split(' ');
                foreach (var term in terms)
                {
                    var termLocal = term.ToLowerInvariant();
                    var matches =
                        await _context.Books.Where(x => x.Name.ToLowerInvariant().Contains(termLocal)).ToListAsync();
                    if (!matches.Any()) continue;

                    foreach (var match in matches.Where(match => result.All(x => x.BookId != match.BookId)))
                    {
                        result.Add(match);
                    }
                }
            }
            else
            {
                return await _context.Books.Where(x => x.Name.ToLowerInvariant().Contains(name)).ToListAsync();
            }

            return result;
        }
            public void ConnectionsWithTheSameConnectionIdSSECloseGracefully()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyGroupEchoConnection>("/echo", config);

                        config.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());
                    });

                    string id = Guid.NewGuid().ToString("d");

                    var tasks = new List<Task>();

                    for (int i = 0; i < 1000; i++)
                    {
                        tasks.Add(ProcessRequest(host, "serverSentEvents", id));
                    }

                    ProcessRequest(host, "serverSentEvents", id);

                    Task.WaitAll(tasks.ToArray());

                    Assert.True(tasks.All(t => !t.IsFaulted));
                }
            }
Example #25
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .WriteTo.Sink(sink)
                .CreateLogger()
                .ForContext<LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.Equal(4, events.Count);
            Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
        /// <summary>
        /// Alle Controller ermitteln die für das Projekt befunden werden können.
        /// </summary>
        public List<Type> GetAllProjectProxyController(ProxySettings proxySettings)
        {
            List<Type> allController = new List<Type>();

            //Alle Assemblies im aktuellen Projekt laden.
            var assemblies = Factory.CreateAssemblyManager().LoadAssemblies(proxySettings.WebProjectName, proxySettings.FullPathToTheWebProject);

            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    //Nur die Assemblies heraussuchen in denen unser BasisAttribut für die Proxy Erstellung gesetzt wurde.
                    var types = assembly.GetTypes().Where(type  => type.GetMethods().Any(p => p.GetCustomAttributes(typeof (CreateProxyBaseAttribute), true).Any())).ToList();

                    foreach (Type type in types)
                    {
                        //Prüfen das jede Klasse (Controller) nur einmal unserer Liste hinzugefügt wird.
                        if (allController.All(p => p.AssemblyQualifiedName != type.AssemblyQualifiedName))
                        {
                            allController.Add(type);
                        }
                    }
                }
                catch(Exception exception)
                {
                    Trace.WriteLine("Fehler beim Auslesen der Assemblies: " + exception.Message);
                }
            }

            return allController;
        }
Example #27
0
    public Spell FindSpell(List<Element> elements){
        
        foreach(Spell spell in _spells){
            
            if(spell.Elements.Count != elements.Count){
                continue;
            }
            bool spellAvailable = true;
            foreach(Element el in elements)
            {
                if (!el.Available)
                    spellAvailable = false;

            }
            if (!spellAvailable)
                continue;
            bool hasElements = elements.All(el => spell.Elements.Contains(el));
            if(hasElements){
                
                    return spell;
            }
        }

        return null;
    }
Example #28
0
		public IfStmt(Text.Span span, List<ConditionalStmt>/*!!*/ conditions)
			: base(span)
		{
			Debug.Assert(conditions != null && conditions.Count > 0);
			Debug.Assert(conditions.All((x) => x != null));
			this.conditions = conditions;
		}
        public static List<Def> GetResearchRequirements( this RecipeDef recipeDef )
        {
            var researchDefs = new List< Def >();

            if( recipeDef.researchPrerequisite != null )
            {
                // Basic requirement
                researchDefs.Add( recipeDef.researchPrerequisite );

                // Advanced requirement
                var advancedResearchDefs = ResearchController.AdvancedResearch.Where( a => (
                    ( a.IsRecipeToggle )&&
                    ( !a.HideDefs )&&
                    ( a.recipeDefs.Contains( recipeDef ) )
                ) ).ToList();

                if( !advancedResearchDefs.NullOrEmpty() )
                {
                    foreach( var a in advancedResearchDefs )
                    {
                        researchDefs.Add( a );
                    }
                }

            }

            // Get list of things recipe is used on
            var thingsOn = new List< ThingDef >();
            var recipeThings = DefDatabase< ThingDef >.AllDefsListForReading.Where( t => (
                ( t.recipes != null )&&
                ( !t.IsLockedOut() )&&
                ( t.recipes.Contains( recipeDef ) )
            ) ).ToList();

            if( !recipeThings.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeThings );
            }

            // Add those linked via the recipe
            if( !recipeDef.recipeUsers.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeDef.recipeUsers );
            }

            // Make sure they all have hard requirements
            if(
                ( !thingsOn.NullOrEmpty() )&&
                ( thingsOn.All( t => t.HasResearchRequirement() ) )
            )
            {
                foreach( var t in thingsOn )
                {
                    researchDefs.AddRange( t.GetResearchRequirements() );
                }
            }

            // Return the list of research required
            return researchDefs;
        }
        public IEnumerable<TableInfo> GetTablesOrdered()
        {
            var notOrderedTables = new List<TableInfo>(Tables);

            int totalTablesCount = notOrderedTables.Count;
            int orderedTablesCount = 0;
            while (orderedTablesCount < totalTablesCount)
            {
                int orderedTablesCountBeforeIter = orderedTablesCount; // ensure we not in infinite loop...

                int i = 0;
                while (i < notOrderedTables.Count)
                {
                    var table = notOrderedTables[i];

                    var parentTables = TableRelations
                        .Where(x => x.FitsForTable(table.Name) && !x.IsExternal() && !x.IsSelfRelation() && x.Importance != RelationImportance.Low)
                        .Select(x => x.ParentTable);

                    if (parentTables.All(x => notOrderedTables.All(y => !string.Equals(y.Name, x, StringComparison.InvariantCultureIgnoreCase))))
                    {
                        notOrderedTables.RemoveAt(i);
                        orderedTablesCount++;
                        yield return table;
                    }
                    else
                    {
                        i++;
                    }
                }

                if (orderedTablesCountBeforeIter == orderedTablesCount) // ensure we not in infinite loop...
                    throw ThrowHelper.CantOrderTables(notOrderedTables.Select(x => x.Name));
            }
        }