예제 #1
0
        public HomeController()
        {
            var _specials   = new List <SpecialPrice>();
            var _itemFinder = new ItemFinder();

            _itemFinder.Items.Add(new Item()
            {
                Name = "A", Price = 50, Sku = "A"
            });
            _itemFinder.Items.Add(new Item()
            {
                Name = "B", Price = 30, Sku = "B"
            });
            _itemFinder.Items.Add(new Item()
            {
                Name = "C", Price = 20, Sku = "C"
            });
            _itemFinder.Items.Add(new Item()
            {
                Name = "D", Price = 15, Sku = "D"
            });

            _specials.Add(new SpecialPrice()
            {
                ItemName = "A", ItemCount = 3, TotalAmount = 130
            });
            _specials.Add(new SpecialPrice()
            {
                ItemName = "B", ItemCount = 2, TotalAmount = 45
            });

            _checkout = new Checkout(_itemFinder, _specials);
        }
        public void Test2()
        {
            string[] lines = System.IO.File.ReadAllLines(@"Resources\words.txt");

            List<string> Dict = lines.ToList();

            ItemFinder<string> MyDic = new ItemFinder<string>(Dict, n => n);

            var res = MyDic.FindSimilarMatches("bayb", 1).ToList();
            Console.WriteLine(res);

            res.Should().Contain(new string[]{"baby","bay","bays"});

            string r = MyDic.FindExactMatches("babyy").FirstOrDefault();
            r.Should().BeNull();


            r = MyDic.FindExactMatches("Baby").FirstOrDefault();
            r.Should().Be("baby");

            r = MyDic.FindExactMatches("BABY").FirstOrDefault();
            r.Should().Be("baby");


        }
예제 #3
0
        private static Dependencies GetDependencies(Guid boundID, int itemID, int dimension)
        {
            Point2D nearest = ItemFinder.FindNearestUnreserved(itemID, Point2D.Zero, dimension);

            ObservableCollection <MagicalTask> dependency = new ObservableCollection <MagicalTask>
            {
                new GrabSpecificItemTask(boundID, nearest, dimension)
            };

            return(new Dependencies(dependency));
        }
예제 #4
0
 private void Awake()
 {
     if (_instance != null && _instance != this)
     {
         Destroy(this.gameObject);
     }
     else
     {
         _instance = this;
     }
 }
예제 #5
0
        public static void UpdateFromCache(RetainerInfo[] retData)
        {
            ClearAll();

            var mainBagsArray = InventoryManager.GetBagsByInventoryBagId(GeneralFunctions.MainBags).ToArray();

            PlayerInventory.Update(mainBagsArray);

            StoredSaddleBagInventory storedSaddlebagInventory = ItemFinder.GetCachedSaddlebagInventoryComplete();

            SaddlebagInventory.Update(storedSaddlebagInventory);

            var cachedRetInventories = ItemFinder.GetCachedRetainerInventories();

            for (var i = 0; i < retData.Length; i++)
            {
                RetainerInfo retInfo = retData[i];
                if (!retInfo.Active)
                {
                    continue;
                }

                if (cachedRetInventories.TryGetValue(retInfo.Unique, out StoredRetainerInventory storedInventory))
                {
                    if (RetainerInventories.ContainsKey(i))
                    {
                        RetainerInventories[i].Update(storedInventory);
                    }
                    else
                    {
                        RetainerInventories.Add(i, new CachedInventory(retInfo.Name, i));
                        RetainerInventories[i].Update(storedInventory);
                    }
                }
            }

            foreach (CachedInventory cachedInventory in GetAllInventories())
            {
                if (cachedInventory.AllBelong() && cachedInventory.FreeSlots == 0)
                {
                    FilledAndSortedInventories.Add(cachedInventory.Index);
                }
            }

            foreach (ItemSortInfo sortInfo in PlayerInventory.ItemCounts.Select(x => GetSortInfo(x.Key)))
            {
                if (sortInfo.ItemInfo.Unique)
                {
                    PlayerInventoryUniques.Add(sortInfo.TrueItemId);
                }
            }
        }
        public void TesterForOrdered()
        {
            IEntityFinder<IArtist> artf = new ItemFinder<IArtist>(_MS.AllArtists, ar => ar.Name);

            var no = artf.Search("bra").ToList();
            var o = artf.SearchOrdered("bra").ToList();
            var r = _MS.AllArtists.Where(ar => ar.Name.Normalized().Contains("bra")).ToList();

            o.ShouldHaveSameElements(r);
            no.ShouldHaveSameElements(r);
            no.ShouldHaveSameElements(o);

            for (int u = 0; u < 10; u++)
            {
                using (TimeTracer.TimeTrack("Not Ordered (x10000)"))
                {
                    for (int i = 0; i < 10000; i++)
                    {
                        var res = artf.Search("bra").ToList();
                        res.Count.Should().Be(28);
                    }
                }

                using (TimeTracer.TimeTrack("Ordered (x10000)"))
                {
                    for (int i = 0; i < 10000; i++)
                    {
                        var res = artf.SearchOrdered("bra").ToList();
                        res.Count.Should().Be(28);
                    }
                }

                using (TimeTracer.TimeTrack("Without Optimization (x100)"))
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var res = _MS.AllArtists.Where(ar => ar.Name.Normalized().Contains("bra")).ToList();
                        res.Count.Should().Be(28);
                    }
                }
            }

            var nullresult = artf.SearchOrdered("a");
            nullresult.Should().BeNull();


            var BrFind = artf.SearchOrdered("br").ToList();
            var BrFind2 = _MS.AllArtists.Where(ar => ar.Name.Normalized().Contains("br")).ToList();
            BrFind.ShouldHaveSameElements(BrFind2);

            artf.Dispose();
        }
예제 #7
0
        public static void Setup(out IDefinitionManager definitions, out ContentActivator activator, out IItemNotifier notifier, out FakeSessionProvider sessionProvider, out ItemFinder finder, out SchemaExport schemaCreator, out InterceptingProxyFactory proxyFactory, IWebContext context, DatabaseSection config, ConfigurationBuilderParticipator[] participators, params Type[] itemTypes)
        {
            Setup(out definitions, out activator, out notifier, out proxyFactory, itemTypes);

            var connectionStrings    = (ConnectionStringsSection)ConfigurationManager.GetSection("connectionStrings");
            var configurationBuilder = new ConfigurationBuilder(definitions, new ClassMappingGenerator(), new ThreadContext(), participators, config, connectionStrings);
            var configurationSource  = new ConfigurationSource(configurationBuilder);

            sessionProvider = new FakeSessionProvider(configurationSource, new NHInterceptor(proxyFactory, configurationSource, notifier), context);

            finder = new ItemFinder(sessionProvider, definitions);

            schemaCreator = new SchemaExport(configurationSource.BuildConfiguration());
        }
        private void BuildCacheForLocation(GameLocation gameLocation)
        {
            if (gameLocation != null)
            {
                var cacheToAdd = new Dictionary <Vector2, Chest>();
                _monitor.Log($"Starting search for connected locations at {LocationHelper.GetName(gameLocation)}");
                var items = ItemFinder.FindObjectsWithName(gameLocation, (from x in _machineConfigs select x.Name).ToList());
                foreach (var valuePair in items)
                {
                    var location = valuePair.Key;
                    if (cacheToAdd.ContainsKey(location))
                    {
                        // already found in another search
                        continue;
                    }

                    var processedLocations = new List <ConnectedTile>
                    {
                        new ConnectedTile {
                            Location = location, Object = valuePair.Value
                        }
                    };

                    ItemFinder.FindConnectedLocations(gameLocation, location, processedLocations, _allowDiagonalConnectionsForAllItems);
                    var chest = processedLocations.FirstOrDefault(c => c.Chest != null)?.Chest;
                    foreach (var connectedLocation in processedLocations)
                    {
                        cacheToAdd.Add(connectedLocation.Location, chest);
                    }
                }

                lock (_connectedChestsCache)
                {
                    if (_connectedChestsCache.ContainsKey(LocationHelper.GetName(gameLocation)))
                    {
                        // already ran?
                        _connectedChestsCache.Remove(LocationHelper.GetName(gameLocation));
                    }

                    _connectedChestsCache.Add(LocationHelper.GetName(gameLocation), new Dictionary <Vector2, Chest>());
                    foreach (var cache in cacheToAdd)
                    {
                        _connectedChestsCache[LocationHelper.GetName(gameLocation)].Add(cache.Key, cache.Value);
                    }
                }

                _monitor.Log($"Searched your {LocationHelper.GetName(gameLocation)} for machines to collect from and found a total of {_connectedChestsCache[LocationHelper.GetName(gameLocation)].Count} locations to look for");
            }
        }
 private void PlayerEvents_InventoryChanged(object sender, EventArgsInventoryChanged e)
 {
     if (_gameLoaded && ItemFinder.HaveConnectorsInInventoryChanged(e))
     {
         try
         {
             _buildingProcessor.DailyReset();
             _machinesProcessor.InvalidateCacheForLocation(Game1.player.currentLocation);
         }
         catch (Exception ex)
         {
             Monitor.Log($"an error occured with the automation mod: {ex}", LogLevel.Error);
             _machinesProcessor.DailyReset();
         }
     }
 }
예제 #10
0
        public override bool CreateDependencies(Living l)//Need to return a bool to say if this step was successful.
        {
            List <Point2D> locations = ItemFinder.LocateUnreservedQuantityOfItem(this.ItemID, this.Amount, Point2D.Zero, l.Dimension);

            if (locations != null && locations.Any())
            {
                foreach (Point2D item in locations)
                {
                    GrabSpecificItemTask task = new GrabSpecificItemTask(this.BoundID, item, l.Dimension);
                    this.Dependencies.PreRequisite.Add(task);
                }

                return(true);
            }

            return(false);
        }
예제 #11
0
        /// <summary>
        /// Drops the result of the harvesting down.
        /// </summary>
        /// <param name="l"></param>
        /// <param name="drop"></param>
        private void DropItem(Living l, Item drop)
        {
            //The tile the entity is standing on
            Tile entityOn = World.Data.World.GetTile(l.Dimension, l.MapLocation.X, l.MapLocation.Y);

            if (entityOn.Item == null || entityOn.Item.GetType() == drop.GetType())
            {
                ItemAdder.AddItem(drop, l.MapLocation, l.Dimension);
            }
            else
            {
                l.Inventory.AddItem(drop);
                Point2D      emtpyTile = ItemFinder.FindNearestNoItemResource(entityOn.MapLocation, l.Dimension);
                DropItemTask task      = new DropItemTask(emtpyTile, l.Dimension, drop, l.ID, Guid.NewGuid());
                task.ReservedFor = l.ID;
                TaskManager.Manager.AddTask(task);
            }
        }
예제 #12
0
        private void Listener_KeyPressed(object sender, KeyboardEventArgs e)
        {
            if (e.Key == Microsoft.Xna.Framework.Input.Keys.Escape)
            {
                this.HandleEscapeKey();
            }
            if (e.Key == Microsoft.Xna.Framework.Input.Keys.R)
            {
                Point2D result = ItemFinder.FindNearestLocation(0, new MagicalLifeAPI.DataTypes.Point2D(0, 0), 0);

                if (result != null)
                {
                    ItemAdder.AddItem(new StoneChunk(0), result, 0);
                    ItemAdder.AddItem(new StoneChunk(0), result, 0);
                    ItemRemover.RemoveSome(result, 0, 1);
                    ItemRemover.RemoveAllItems(result, 0);
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Drops the result of the harvesting down.
        /// </summary>
        /// <param name="l"></param>
        /// <param name="drop"></param>
        private void DropItem(Living l, Item drop)
        {
            //The tile the entity is standing on
            ComponentSelectable entityS = l.GetExactComponent <ComponentSelectable>();
            Tile entityOn = World.Data.World.GetTile(l.Dimension, entityS.MapLocation.X, entityS.MapLocation.Y);


            if (entityOn.MainObject == null || entityOn.MainObject.GetType() == drop.GetType())
            {
                ItemAdder.AddItem(drop, entityS.MapLocation, l.Dimension);
            }
            else
            {
                l.Inventory.AddItem(drop);
                Point2D      emtpyTile = ItemFinder.FindMainObjectEmptyTile(entityOn.GetExactComponent <ComponentSelectable>().MapLocation, l.Dimension);
                DropItemTask task      = new DropItemTask(emtpyTile, l.Dimension, drop, l.ID, Guid.NewGuid());
                task.ReservedFor = l.ID;
                TaskManager.Manager.AddTask(task);
            }
        }
        public void Test()
        {
            SetUp();
            _Finder = new ItemFinder<MyObject>(_Collection, o => o.Name);

            IEnumerable<MyObject> res = _Finder.Search("A");
            res.Should().BeNull();

            res = _Finder.Search("B");
            res.Should().BeNull();

            res = _Finder.Search("rt");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o=>o.Name).Should().Contain("ToRTo");


            MyObject unres = _Finder.FindExactMatches("B").FirstOrDefault();
            unres.Should().NotBeNull();
            unres.Name.Should().Be("b");

            res = _Finder.Search("ab");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o => o.Name).Should().Contain("baBA");

            res = _Finder.Search("brax");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o => o.Name).Should().Contain("Anthony Braxton");

            res = _Finder.Search("lac");
            res.Should().NotBeNull();
            res.Count().Should().Be(2);
            res.Select(o => o.Name).Should().Contain(new string[]{"Steve Lacy","lac"});

            _Collection[0].Name = "la";
            res = _Finder.Search("la");
            res.Should().NotBeNull();
            res.Count().Should().Be(3);
            res.Select(o => o.Name).Should().Contain(new string[] { "la", "Steve Lacy", "lac" });

            unres = _Finder.FindExactMatches("B").FirstOrDefault();
            unres.Should().BeNull();

            res = _Finder.Search("aa");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o => o.Name).Should().Contain(new string[] { "aaaaaa" });

            _Collection[2].Name = "aa";
            res = _Finder.Search("aa");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o => o.Name).Should().Contain(new string[] { "aa" });

            _Collection[2].Name = "BAA";
            res = _Finder.Search("aa");
            res.Should().NotBeNull();
            res.Count().Should().Be(1);
            res.Select(o => o.Name).Should().Contain(new string[] { "BAA" });

            _Collection.RemoveAt(2);
            res = _Finder.Search("aa");
            res.Should().NotBeNull();
            res.Should().BeEmpty();

            MyObject mo = new MyObject("lac", 20);
            _Collection.Add(mo);
            res = _Finder.FindExactMatches("lac");
            res.Should().NotBeNull();
            res.Count().Should().Be(2);
            res.Should().Contain(mo);
            


        }
예제 #15
0
        public static void Setup(out IDefinitionManager definitions, out ContentActivator activator, out IItemNotifier notifier, out FakeSessionProvider sessionProvider, out ItemFinder finder, out SchemaExport schemaCreator, out InterceptingProxyFactory proxyFactory, params Type[] itemTypes)
        {
            var participators             = new ConfigurationBuilderParticipator[0];
            FakeWebContextWrapper context = new Fakes.FakeWebContextWrapper();
            DatabaseSection       config  = (DatabaseSection)ConfigurationManager.GetSection("n2/database");

            Setup(out definitions, out activator, out notifier, out sessionProvider, out finder, out schemaCreator, out proxyFactory, context, config, participators, itemTypes);
        }
예제 #16
0
        public void GeneralBuildIsCorrect()
        {
            /*
             * тестовая простейшая структура сайта: с корнем, стартовой страницей, парой обычных страниц и виджетом
             * для одной из страниц специально задан дискриминатор о котором не знает IAbstractItemFactory, такие страницы не попадают в структуру сайта
             */
            var aiRepositoryMoq = new Mock <IAbstractItemRepository>();

            var aiArray = new[] {
                new AbstractItemPersistentData {
                    Id = 4, Title = "текстовая страница 2", Alias = "bar", Discriminator = typeof(StubPage).Name, IsPage = true, ParentId = 3, ExtensionId = null
                },
                new AbstractItemPersistentData {
                    Id = 2, Title = "стартовая страница", Alias = "start", Discriminator = typeof(StubStartPage).Name, IsPage = true, ParentId = 1, ExtensionId = null
                },
                new AbstractItemPersistentData {
                    Id = 5, Title = "некий виджет", Alias = "blah", Discriminator = typeof(StubWidget).Name, IsPage = false, ParentId = 3, ExtensionId = null, IndexOrder = 100, ZoneName = "zonename"
                },
                new AbstractItemPersistentData {
                    Id = 1, Title = "корневая страница", Alias = "root", Discriminator = typeof(RootPage).Name, IsPage = true, ParentId = null, ExtensionId = null
                },
                new AbstractItemPersistentData {
                    Id = 3, Title = "текстовая страница 1", Alias = "foo", Discriminator = typeof(StubPage).Name, IsPage = true, ParentId = 2, ExtensionId = null
                },
                new AbstractItemPersistentData {
                    Id = 6, Title = "несуществующая страница 1", Alias = "bar2", Discriminator = "notexisting", IsPage = true, ParentId = 3, ExtensionId = null
                }
            };

            aiRepositoryMoq.Setup(x => x.GetPlainAllAbstractItems(siteId, isStage, null)).Returns(aiArray);

            var metaInfoMoq = new Mock <IMetaInfoRepository>();

            metaInfoMoq.Setup(x => x.GetContent(abstractItemNetName, siteId, null)).Returns(new ContentPersistentData
            {
                ContentId         = abstractItemContentId,
                ContentAttributes = new List <ContentAttributePersistentData>()
            });

            //фабрика элементов структуры сайта
            var aiFactoryMoq = new Mock <IAbstractItemFactory>();

            aiFactoryMoq.Setup(x => x.Create(It.IsAny <string>())).Returns((string d) =>
            {
                if (d == typeof(RootPage).Name)
                {
                    return(new RootPage());
                }
                if (d == typeof(StubStartPage).Name)
                {
                    return(new StubStartPage());
                }
                if (d == typeof(StubPage).Name)
                {
                    return(new StubPage());
                }
                if (d == typeof(StubWidget).Name)
                {
                    return(new StubWidget());
                }
                return(null);
            });

            var builder = new QpAbstractItemStorageBuilder(aiFactoryMoq.Object,
                                                           Mock.Of <IQpUrlResolver>(),
                                                           aiRepositoryMoq.Object,
                                                           metaInfoMoq.Object,
                                                           buildSettings,
                                                           Mock.Of <ILogger <QpAbstractItemStorageBuilder> >());

            var aiStorage = builder.Build();

            //проверим корень
            Assert.NotNull(aiStorage.Root);
            Assert.Equal(1, aiStorage.Root.Id);

            //проверим получение по id
            Assert.NotNull(aiStorage.Get(3));
            Assert.NotNull(aiStorage.Get(4));
            Assert.Null(aiStorage.Get(6));
            Assert.Null(aiStorage.Get(100));

            //проверим типы
            Assert.IsType <RootPage>(aiStorage.Get(1));
            Assert.IsType <StubStartPage>(aiStorage.Get(2));
            Assert.IsType <StubPage>(aiStorage.Get(3));
            Assert.IsType <StubPage>(aiStorage.Get(4));
            Assert.IsType <StubWidget>(aiStorage.Get(5));

            //проверим формирование trail для страниц
            Assert.Equal("/foo", aiStorage.Get(3).GetTrail());
            Assert.Equal("/foo/bar", aiStorage.Get(4).GetTrail());

            //проверим стартовую страницу
            var startPage = aiStorage.GetStartPage(StubStartPage.DnsRegistered, null);

            Assert.NotNull(startPage);
            Assert.Equal(2, startPage.Id);

            //проверим, что все базовые поля присваиваются корректно (на примере виджета)
            var widget   = aiStorage.Get(5) as IAbstractWidget;
            var aiWidget = aiArray.First(a => a.Id == 5);

            Assert.Equal(aiWidget.Title, widget.Title);
            Assert.Equal(aiWidget.Alias, widget.Alias);
            Assert.NotNull(widget.Parent);
            Assert.Equal(aiWidget.ParentId, widget.Parent.Id);
            Assert.Equal(aiWidget.IndexOrder, widget.SortOrder);
            Assert.Equal(aiWidget.ZoneName, widget.ZoneName);
            Assert.Equal("", widget.GetTrail());

            //проверим получение дочерних элементов по алиасу
            Assert.NotNull(startPage.GetChildPageByAlias("foo"));
            Assert.Equal(3, startPage.GetChildPageByAlias("foo").Id);
            Assert.NotNull(startPage.GetChildPageByAlias("foo").GetChildPageByAlias("bar"));
            Assert.Equal(4, startPage.GetChildPageByAlias("foo").GetChildPageByAlias("bar").Id);
            Assert.Null(startPage.GetChildPageByAlias("xxx"));
            Assert.Null(startPage.GetChildPageByAlias("foo").GetChildPageByAlias("bar2"));

            //проверим ItemFinder
            var targetingAccessorMoq = new Mock <ITargetingFilterAccessor>();

            targetingAccessorMoq.Setup(x => x.Get()).Returns(new NullFilter());
            var finder = new ItemFinder(targetingAccessorMoq.Object);

            var barPage = finder.Find(aiStorage.Root, p => p.Alias == "bar");

            Assert.NotNull(barPage);
            Assert.Equal(4, barPage.Id);
        }
예제 #17
0
        public static void Setup(out ContentPersister persister, ISessionProvider sessionProvider, N2.Persistence.IRepository <int, ContentItem> itemRepository, INHRepository <int, ContentDetail> linkRepository, ItemFinder finder, SchemaExport schemaCreator)
        {
            persister = new ContentPersister(itemRepository, linkRepository, finder);

            schemaCreator.Execute(false, true, false, sessionProvider.OpenSession.Session.Connection, null);
        }
예제 #18
0
        private bool SetStatus(bool status)
        {
            if (status == true)
            {
                try
                {
                    Process[] processes = Process.GetProcessesByName("Diablo III");
                    if (processes.Length > 1)
                    {
                        SelectProcessDialog dialog = new SelectProcessDialog(processes);
                        if (dialog.ShowDialog(this) == DialogResult.OK)
                        {
                            finder = new ItemFinder(dialog.GetID());
                        }
                        else
                            return false;
                    }
                    else
                    {
                        finder = new ItemFinder();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not find the diablo process!");
                    return false;
                }
                timer.Enabled = true;
            }

            if (status == false)
            {
                try
                {
                    finder.Dispose();
                }
                catch (Exception)
                {
                }
                timer.Enabled = false;
            }

            return true;
        }
예제 #19
0
파일: TaskInfo.cs 프로젝트: zquall/Makiwara
        private void RepResourceCodeButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var tmpResource = viewResources.GetFocusedRow() as ResourceDto;
            if (tmpResource != null && tmpResource.ResourceType.Name == "PRODUCTO")
            {
                var itemFinder = new ItemFinder();
                if (itemFinder.ShowDialog() == DialogResult.OK)
                {
                    var itemDto = itemFinder.Tag as ItemDto;
                    LoadItem(itemDto);
                }
            }

            if (tmpResource != null && tmpResource.ResourceType.Name == "ALQUILERES")
            {
                var employeeFinder = new RentalItemFinder();
                if (employeeFinder.ShowDialog() == DialogResult.OK)
                {
                    var rentalItemDto = employeeFinder.Tag as RentalItemDto;
                    LoadRentalItem(rentalItemDto);
                }
            }

            if (tmpResource != null && tmpResource.ResourceType.Name == "PLANILLA")
            {
                //var employeeFinder = new EmployeeFinder();
                //if (employeeFinder.ShowDialog() == DialogResult.OK)
                //{
                //    var employeeDto = employeeFinder.Tag as EmployeeDto;
                //    LoadEmployee(employeeDto);
                //}
                var postFinder = new PostFinder();
                if (postFinder.ShowDialog() == DialogResult.OK)
                {
                    var postDto = postFinder.Tag as PostDto;
                    LoadPost(postDto);
                }
            }
        }
예제 #20
0
        private async Task <bool> Run()
        {
            if (AutoRetainerSortSettings.Instance.InventoryOptions.Count == 0)
            {
                LogCritical("You don't have any inventories (or sorting rules for them) added yet! Go check the settings?");
                TreeRoot.Stop("No sort settings.");
                return(false);
            }

            if (!ItemSortStatus.AnyRulesExist())
            {
                LogCritical("You don't have any sorting rules set up... maybe go hit the Auto-Setup button?");
                TreeRoot.Stop("No sort settings.");
                return(false);
            }

            LogCritical($"The journey begins! {Strings.AutoSetup_CacheAdvice}");
            await GeneralFunctions.StopBusy(true, true, false);

            var retData = await HelperFunctions.GetOrderedRetainerArray(true);

            if (retData.Length == 0)
            {
                LogCritical("No retainers. Exiting.");
                TreeRoot.Stop("No retainer data found.");
                return(false);
            }

            foreach (var pair in AutoRetainerSortSettings.Instance.InventoryOptions)
            {
                if (pair.Key < 0)
                {
                    continue;
                }

                if (pair.Key >= retData.Length)
                {
                    LogCritical($"{pair.Value.Name}'s index of {pair.Key.ToString()} doesn't exist in retainer data.");
                    TreeRoot.Stop("Invalid index.");
                    return(false);
                }

                if (!retData[pair.Key].Active)
                {
                    LogCritical($"{pair.Value.Name} isn't an active retainer!");
                    TreeRoot.Stop("Retainer inactive.");
                    return(false);
                }
            }

            ItemSortStatus.ItemSortInfoCache.Clear();

            await ItemFinder.FlashSaddlebags();

            ItemSortStatus.UpdateFromCache(retData);

            if (AutoRetainerSortSettings.Instance.PrintMoves)
            {
                alreadyPrintedUniques.Clear();
                foreach (CachedInventory cachedInventory in ItemSortStatus.GetAllInventories())
                {
                    PrintMoves(cachedInventory.Index);
                }
            }

            while (ItemSortStatus.AnyUnsorted())
            {
                if (ItemSortStatus.FilledAndSortedInventories.Contains(ItemSortStatus.PlayerInventoryIndex))
                {
                    LogCritical("Everything currently in the player's inventory belongs there, but it's full! Can't move items like this. I quit.");
                    break;
                }

                await DepositFromPlayer();
                await RetrieveFromInventories();

                await Coroutine.Sleep(250);

                ItemSortStatus.UpdateFromCache(retData);
                await Coroutine.Sleep(250);
            }

            foreach (CachedInventory cachedInventory in ItemSortStatus.GetAllInventories())
            {
                foreach (ItemSortInfo sortInfo in cachedInventory.ItemCounts.Select(x => ItemSortStatus.GetSortInfo(x.Key)))
                {
                    int[] localIndexCache = sortInfo.MatchingIndexes.ToArray();
                    if (localIndexCache.Length == 0)
                    {
                        continue;
                    }
                    if (sortInfo.SortStatus(cachedInventory.Index) == SortStatus.MoveButUnable)
                    {
                        if (ItemSortStatus.FilledAndSortedInventories.Contains(cachedInventory.Index) || (cachedInventory.FreeSlots == 0 && cachedInventory.AllBelong()))
                        {
                            LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} but it's full and everything there belongs. Too bad!");
                        }
                        else if (sortInfo.ItemInfo.Unique)
                        {
                            if (localIndexCache.Length == 1)
                            {
                                LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} but it's unique and that inventory already has one. Too bad!");
                            }
                            else
                            {
                                LogCritical($"We want to move {sortInfo.Name} but it's unique and all inventories set for it already have one. Too bad!");
                            }
                        }
                        else
                        {
                            LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} " +
                                        $"but it can't be moved there for... some reason. IndexStatus: {sortInfo.IndexStatus(cachedInventory.Index).ToString()}");
                        }
                    }
                }
            }

            await GeneralFunctions.ExitRetainer(true);

            if (AutoRetainerSortSettings.Instance.AutoGenLisbeth)
            {
                string lisbethSettingsPath = LisbethRuleGenerator.GetSettingsPath();
                if (!string.IsNullOrEmpty(lisbethSettingsPath))
                {
                    LisbethRuleGenerator.PopulateSettings(lisbethSettingsPath);
                    LogSuccess("Auto-populated Lisbeth's retainer item rules!");
                    MessageBox.Show(
                        Strings.LisbethRules_RestartRB,
                        "Just Letting You Know...",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else
                {
                    LogCritical("Couldn't find Lisbeth settings path! We won't auto-generate retainer rules.");
                }
            }

            TreeRoot.Stop("Done sorting inventories.");
            return(false);
        }
        private void PerFilterTrackGeneric(IMusicSession ms)
        {
            using (TimeTracer.TimeTrack(string.Format("Generic Finder")))
            {
                ItemFinder<ITrack> f = null;
                using (TimeTracer.TimeTrack(string.Format("1-Finder creation")))
                {
                    f = new ItemFinder<ITrack>(ms.AllTracks, (t) => t.Name);
                }

                IEnumerable<ITrack> Res = null;

                using (TimeTracer.TimeTrack(string.Format("Generic Finder usage")))
                {
                    foreach (string s in this.ForTest)
                    {
                        Res = f.Search(s).ToList();
                    }
                }
            }

            using (TimeTracer.TimeTrack(string.Format("Raw")))
            {
                foreach (string s in this.ForTest)
                {
                    IEnumerable<ITrack> Res2 = this.FilterCount2(s, ms.AllTracks).ToList();
                }
            }
        }
예제 #22
0
        private static void ProcessMachineBuilding(MachineBuilding building, string direction)
        {
            var connectedTileList = new List <ConnectedTile>
            {
                new ConnectedTile
                {
                    Location = (direction == "IN") ? building.InputLocation : building.OutputLocation,
                    Object   = (direction == "IN") ? building.Input : building.Output
                }
            };

            ItemFinder.FindConnectedLocations(Game1.getLocationFromName("Farm"), direction == "IN" ? building.InputLocation : building.OutputLocation, connectedTileList, false);
            var connectedTile = connectedTileList.FirstOrDefault(c => c.Chest != null);
            var chest         = connectedTile?.Chest;

            if (chest != null)
            {
                var items = new List <Object>();
                _monitor.Log($"{building.BuildingConfig.Name} found and chest connected.  Processing {direction.ToLower()}put.");
                try
                {
                    var i = 0;
                    switch (direction)
                    {
                    case "IN":
                        chest.items.Where(t =>
                        {
                            if (building.BuildingConfig.AcceptableObjects != null &&
                                building.BuildingConfig.AcceptableObjects.Any(b =>
                            {
                                if (b.Name != t.Name)
                                {
                                    return(b.Index == t.parentSheetIndex);
                                }

                                return(true);
                            }))
                            {
                                return(true);
                            }

                            return(building.BuildingConfig.AcceptableCategories != null && building.BuildingConfig.AcceptableCategories.Any(b => b.Index == t.category));
                        }).ToList().ForEach(x =>
                        {
                            if (building.Input.items.Count >= 36)
                            {
                                return;
                            }

                            var item = x as Object;

                            if (item != null)
                            {
                                items.Add(item);
                                ++i;
                            }
                        });
                        break;

                    case "OUT":
                        building.Output.items.ForEach(x =>
                        {
                            if (chest.items.Count >= 36)
                            {
                                return;
                            }

                            var item = x as Object;

                            if (item != null)
                            {
                                item.stack = x.Stack;
                                {
                                    var newItem   = item;
                                    newItem.stack = item.stack;
                                    items.Add(newItem);
                                    ++i;
                                }
                            }
                        });
                        break;
                    }

                    ItemHelper.TransferBetweenInventories((direction == "IN") ? chest : building.Output, (direction == "IN") ? building.Input : chest, items);
                    _monitor.Log($"{building.BuildingConfig.Name} {direction.ToLower()}put processed: {i} stacks moved.", LogLevel.Info);
                }
                catch (Exception exception)
                {
                    _monitor.Log(exception.Message, LogLevel.Error);
                }
            }
        }
예제 #23
0
 private void lvRecords_KeyDown(object sender, KeyEventArgs e)
 {
     //响应Ctrl + F 事件
     if (e.KeyData == (Keys.F | Keys.Control))
     {
         //打开查找窗口
         if (m_finder == null)
         {
             m_finder = new ItemFinder(this.m_lvRecords);
         }
         m_lvRecords.MultiSelect = false;
         m_finder.Show();
         m_finder.Activate();
     }
     else if (e.KeyData == Keys.Delete)
     {
         btnDel_Click(sender, e);
     }
     else if (e.KeyData == Keys.Enter && m_finder != null)
     {
         if(m_finder.Visible)
         {
             //m_finder.Focus();
             m_finder.btnNext_Click(null, e);
         }
     }
 }
        public void TesterForSimiliraty()
        {
            IEntityFinder<IArtist> artf = new ItemFinder<IArtist>(_MS.AllArtists, ar => ar.Name);


            IArtist arn = _MS.AllArtists.Where(al=>al.Name=="Anthony Braxton").FirstOrDefault();
            arn.Should().NotBeNull();

            using (TimeTracer.TimeTrack("Without TesterForSimiliraty"))
            {
                var similirities = artf.FindSimilarMatches("anthony baxton").ToList();
                similirities.Should().Contain(arn);
            }

            using (TimeTracer.TimeTrack("Without TesterForSimiliraty"))
            {
                var similirities = artf.FindSimilarMatches("anthony braxtone").ToList();
                similirities.Should().Contain(arn);
            }

            using (TimeTracer.TimeTrack("Without TesterForSimiliraty"))
            {
                var similirities = artf.FindSimilarMatches("anthoni braxton").ToList();
                similirities.Should().Contain(arn);
            }
            

            


            using (TimeTracer.TimeTrack("Without TesterForSimiliraty"))
            {
                var similirities = artf.FindPotentialMisname().ToList();
                similirities.Should().HaveCount(27);
            }

          

            artf.Dispose();
        }
        public void ProcessAnimalBuildings()
        {
            if (_dailiesDone)
            {
                return;
            }
            if (MuteWhenCollecting)
            {
                SoundHelper.MuteTemporary(1500);
            }
            Log.Info("Petting animals and processing their buildings to collect items");
            var farms = Game1.locations.OfType <Farm>();

            foreach (var farm in farms)
            {
                if (PetAnimals)
                {
                    var allAnimals =
                        farm.animals.Values.Concat(
                            farm.buildings.Where(b => b.indoors is AnimalHouse)
                            .SelectMany(i => ((AnimalHouse)i.indoors).animals.Values));
                    foreach (var animal in allAnimals)
                    {
                        PetAnimal(animal);
                    }
                    Log.Info("All animals have been petted.");
                }
                foreach (var building in farm.buildings)
                {
                    var chest = ItemFinder.FindChestInLocation(building.indoors);
                    if (chest == null)
                    {
                        continue;
                    }
                    if (building is Coop)
                    {
                        // collect eggs
                        CollectItemsFromBuilding(building, chest, _coopCollectibles);
                    }
                    if (building is Barn)
                    {
                        int outsideAnimalCount = 0;
                        foreach (
                            var outsideAnimal in farm.animals.Values.Where(a => a.home is Barn && a.home == building))
                        {
                            CollectBarnAnimalProduce(outsideAnimal, chest);
                            ++outsideAnimalCount;
                        }
                        if (outsideAnimalCount > 0)
                        {
                            Log.Debug(
                                $"Found {outsideAnimalCount} animals wandering outside. collected their milk or wool and put it in the chest in their {building.buildingType}");
                        }
                        int insideAnimalCount = 0;
                        foreach (var animal in ((AnimalHouse)building.indoors).animals.Values)
                        {
                            CollectBarnAnimalProduce(animal, chest);
                            ++insideAnimalCount;
                        }
                        if (insideAnimalCount > 0)
                        {
                            Log.Debug(
                                $"Found {insideAnimalCount} animals in the {building.buildingType}. Collected their milk or wool and put it in the chest in their home.");
                        }
                    }
                    if (building.indoors is SlimeHutch)
                    {
                        // collect goop
                        foreach (var pair in building.indoors.objects.Where(o => o.Value.Name == "Slime Ball").ToList())
                        {
                            var    item   = pair.Value;
                            Random random =
                                new Random(
                                    (int)
                                    (Game1.stats.daysPlayed + (uint)((int)Game1.uniqueIDForThisGame) +
                                     (uint)((int)item.tileLocation.X * 77) + (uint)((int)item.tileLocation.Y * 777) +
                                     2u));
                            var number     = random.Next(10, 21);
                            var slimeStack = new Object(SlimeParentSheetIndex, number)
                            {
                                scale           = Vector2.Zero,
                                quality         = 0,
                                isSpawnedObject = false,
                                isRecipe        = false,
                                questItem       = false,
                                name            = "Slime",
                                specialVariable = 0,
                                price           = 5
                            };
                            if (chest.addItem(slimeStack) == null)
                            {
                                building.indoors.objects.Remove(pair.Key);
                                Log.Info($"Collected {number} Slimes from your Slime Hutch");
                            }
                        }
                    }
                }
            }
            _dailiesDone = true;
        }
예제 #26
0
        public override void Entry(params object[] objects)
        {
            base.Entry(objects);
            GameEvents.GameLoaded += (s, e) => { _gameLoaded = true; };

            TimeEvents.DayOfMonthChanged += (s, e) =>
            {
                if (_config.EnableMod)
                {
                    Log.Debug("It's a new day. Resetting the Item Collector mod");
                    _machinesProcessor.ValidateGameLocations();
                    _animalHouseProcessor.DailyReset();
                    _machinesProcessor.DailyReset();
                }
            };
            TimeEvents.TimeOfDayChanged += (s, e) =>
            {
                if (_gameLoaded && _config.EnableMod)
                {
                    try
                    {
                        _animalHouseProcessor.ProcessAnimalBuildings();
                        _machinesProcessor.ProcessMachines();
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"an error occured with the automation mod: {ex}");
                        _machinesProcessor.DailyReset();
                    }
                }
            };
            PlayerEvents.InventoryChanged += (s, c) =>
            {
                if (_gameLoaded && ItemFinder.HaveConnectorsInInventoryChanged(c))
                {
                    try
                    {
                        _animalHouseProcessor.DailyReset();
                        _machinesProcessor.InvalidateCacheForLocation(Game1.player.currentLocation);
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"an error occured with the automation mod: {ex}");
                        _machinesProcessor.DailyReset();
                    }
                }
            };
#if DEBUG
            // allow keypresses to initiate events for easier debugging.
            ControlEvents.KeyPressed += (s, c) =>
            {
                if (_gameLoaded && c.KeyPressed == Keys.K)
                {
                    _animalHouseProcessor.ProcessAnimalBuildings();
                    _machinesProcessor.ProcessMachines();
                }
                if (_gameLoaded && c.KeyPressed == Keys.P)
                {
                    _animalHouseProcessor.DailyReset();
                    _machinesProcessor.DailyReset();
                }
            };
#endif
        }
예제 #27
0
        private void LoadItemFinder()
        {
            var itemFinder = new ItemFinder();
            itemFinder.ShowDialog();
            if (itemFinder.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                var item = itemFinder.Tag as ItemDto;
                if (item != null)
                {
                    gridViewBudgetRequestDetails.EditingValue = item.Name;
                    // gridViewBudgetRequestDetails.SetRowCellValue(gridViewBudgetRequestDetails.FocusedRowHandle, gridViewBudgetRequestDetails.FocusedColumn, item.Name);

                    var currentDetail = gridViewBudgetRequestDetails.GetFocusedRow() as BudgetRequestDetailDto;
                    if (currentDetail != null) currentDetail.Item = item;
                }
            }
        }
예제 #28
0
        private bool SetStatus(bool status)
        {
            if (status == true)
            {
                try
                {
                    if (Settings.OverrideProcessID != 0)
                        finder = new ItemFinder(Settings.OverrideProcessID);
                    else
                        finder = new ItemFinder();
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not find the diablo process!");
                    return false;
                }
                timer.Enabled = true;
            }

            if (status == false)
            {
                try
                {
                    finder.Dispose();
                }
                catch (Exception)
                {
                }
                timer.Enabled = false;
            }

            return true;
        }
 internal EntityFinder(MusicSessionImpl ism)
 {
     _IMS = ism;
     AlbumFinder = new ItemFinder<IAlbum>(_IMS.AllAlbums, a => a.Name);
     TrackFinder = new ItemFinder<ITrack>(_IMS.AllTracks, (t) => t.Name);
 }
예제 #30
0
        internal static void Setup(out ContentPersister persister, FakeSessionProvider sessionProvider, ItemFinder finder, SchemaExport schemaCreator)
        {
            IRepository <int, ContentItem>     itemRepository = new ContentItemRepository(sessionProvider);
            INHRepository <int, ContentDetail> linkRepository = new NHRepository <int, ContentDetail>(sessionProvider);

            Setup(out persister, sessionProvider, itemRepository, linkRepository, finder, schemaCreator);
        }
예제 #31
0
 public override bool ArePreconditionsMet()
 {
     return(ItemFinder.IsItemAvailible(this.ItemID, this.Dimension, this.SearchLocation));
 }