async Task SendMessage() { TradeInfo tradeInfo; bool ok; string msgFormat = "@{0} Hi, I'd like to buy your {1} {2} for {3} {4} in {5}."; if (TradesQueue.Count > 0) { ok = TradesQueue.TryDequeue(out tradeInfo); if (ok) { string msg1 = string.Format(msgFormat, tradeInfo.IGN, tradeInfo.ActualAmountToBuy, tradeInfo.ItemName, tradeInfo.TotalPrice, tradeInfo.CurrencyName, tradeInfo.LeagueName); System.Windows.Forms.Clipboard.SetText(msg1); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.CONTROL); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.VK_V); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.VK_V); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.CONTROL); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN); frmItemLists.RemoveItemFromGrid(tradeInfo.Id, false); } } }
private async Task StartProcessingRefreshQueue() { Tuple <Guid, MetadataRefreshOptions> refreshItem; var libraryManager = _libraryManagerFactory(); if (_disposed) { return; } var cancellationToken = _disposeCancellationTokenSource.Token; while (_refreshQueue.TryDequeue(out refreshItem)) { if (_disposed) { return; } try { var item = libraryManager.GetItemById(refreshItem.Item1); if (item != null) { // Try to throttle this a little bit. await Task.Delay(100).ConfigureAwait(false); if (refreshItem.Item2.ValidateChildren) { var folder = item as Folder; if (folder != null) { await folder.ValidateChildren(new SimpleProgress <double>(), cancellationToken).ConfigureAwait(false); } } var artist = item as MusicArtist; var task = artist == null ? RefreshItem(item, refreshItem.Item2, cancellationToken) : RefreshArtist(artist, refreshItem.Item2, cancellationToken); await task.ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.ErrorException("Error refreshing item", ex); } } lock (_refreshQueueLock) { _isProcessingRefreshQueue = false; } }
private void HookManager_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == ClearListsKey) { BulkTradeQueue.Clear(); TradesQueue.Clear(); frmItemLists.ClearLists(); } if (e.KeyCode == this.LiveSearchMsgKey) { Task t = this.SendMessage(); } if (e.KeyCode == this.BulkSearchMsgKey) { if (BulkTradeQueue.Count > 0) { BulkTradeInfo item; bool ok = BulkTradeQueue.TryDequeue(out item); if (ok) { frmItemLists.RemoveItemFromGrid(item.Id, true); if (item.dblStock >= item.AmountYouGetD) { string msgFormat = "@{0} Hi, I'd like to buy your {1} {2} for my {3} {4} in {5}."; string msg1 = string.Format(msgFormat, item.IGN, item.TotalAmountYouCanBuy, item.ItemYouGet, item.BuyAllPrice, item.ItemYouPay, item.LeagueName); bool clipSet = false; int i = 0; while (clipSet != true) { i++; try { if (i < 3) { System.Windows.Forms.Clipboard.SetText(msg1); clipSet = true; } else { clipSet = true; } } catch { } } inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.CONTROL); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.VK_V); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.VK_V); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.CONTROL); inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN); inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN); } } } } }
public bool Pop(out IJob job) { lock (queue) { var result = queue.TryDequeue(out job); if (result) { Trace.WriteLine($"VSFake: Popping job {{queueSize:{queue.Count}, " + $"type=\"{job.GetType()}\"}}"); } return(result); } }
private async Task StartProcessingRefreshQueue() { var libraryManager = _libraryManager; if (_disposed) { return; } var cancellationToken = _disposeCancellationTokenSource.Token; while (_refreshQueue.TryDequeue(out Tuple <Guid, MetadataRefreshOptions> refreshItem)) { if (_disposed) { return; } try { var item = libraryManager.GetItemById(refreshItem.Item1); if (item != null) { // Try to throttle this a little bit. await Task.Delay(100, cancellationToken).ConfigureAwait(false); var task = item is MusicArtist artist ? RefreshArtist(artist, refreshItem.Item2, cancellationToken) : RefreshItem(item, refreshItem.Item2, cancellationToken); await task.ConfigureAwait(false); } } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "Error refreshing item"); } } lock (_refreshQueueLock) { _isProcessingRefreshQueue = false; } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { LookupRequest request; while (!stoppingToken.IsCancellationRequested) { if (_queue.TryDequeue(out request)) { var response = new LookUpResponse { LookUpId = request.LookUpId }; IPricingService service; if (string.IsNullOrEmpty(request.ApiKey)) { service = _defaultService; } else { service = new AlphaVantageClient(new AlphaVantageSettings { ApiKey = request.ApiKey }); } response.Price = await service.GetPriceAsync(request.Symbol); var result = _writers.Remove(response.LookUpId, out var writer); if (!result) { throw new NotSupportedException(); } await writer.WriteAsync(response); writer.Complete(); } else { await Task.Delay(100, stoppingToken); } } }
QueueStatus SendSome(Action <IList <TraceMessage> > sendTraceMessagesTask) { TraceMessage tm; while ((totalEstimatedSize < Fonlow.TraceHub.Constants.TransportBufferSize) && pendingQueue.TryPeek(out tm)) { var estimatedSize = GetTraceMessageSize(tm); if (totalEstimatedSize + estimatedSize >= Fonlow.TraceHub.Constants.TransportBufferSize) { break; } pendingQueue.TryDequeue(out tm); sendingBuffer.Add(tm); totalEstimatedSize += GetTraceMessageSize(tm); } if (sendingBuffer.Count > 0) { try { sendTraceMessagesTask(sendingBuffer); sendingBuffer.Clear(); } catch (AggregateException ex) { Console.WriteLine(ex.ToString()); return(QueueStatus.Failed); } } else { return(QueueStatus.Empty); } totalEstimatedSize = 0; return(QueueStatus.Sent); }
public static List <GraphEdge> PrimSearch(GraphBase graph, int start) { List <GraphEdge> shortestPathPredecessors = new List <GraphEdge>(); HashSet <int> visitedNodes = new HashSet <int>(); SimplePriorityQueue <GraphEdge> nodeQueue = new SimplePriorityQueue <GraphEdge>(); GraphNode node = graph[start]; //把该节点的作为父节点标记为已访问 while (node != null) { //把该节点标记为已访问 visitedNodes.Add(node.index); //插入所有连接该节点的边 foreach (GraphEdge edge in node.edges) { nodeQueue.Enqueue(edge, edge.cost); } nodeQueue.TryDequeue(out GraphEdge edage); //获取消费最小的边 while (edage != null && visitedNodes.Contains(edage.to)) //是否和访问过的节点形成闭合回路 { nodeQueue.TryDequeue(out edage); //是的话跳过该边 } //当剩下的边和访问过的边能组合成闭合回路时搜索完成 if (edage == null) { break; } //此时该边已是有效的最小消费边 shortestPathPredecessors.Add(edage); node = graph[edage.to]; } return(shortestPathPredecessors); }
public List <TickInput> DequeueInputsForTick(uint worldTick) { var ret = new List <TickInput>(); TickInput entry; while (queue.TryDequeue(out entry)) { if (entry.WorldTick < worldTick) { } else if (entry.WorldTick == worldTick) { ret.Add(entry); } else { // We dequeued a future input, put it back in. queue.Enqueue(entry, entry.WorldTick); break; } } return(ret); }
public List <Vector2> GetPath(Vector2 from, Vector2 to) { List <Vector2> returnList = new List <Vector2>() { from }; Vector2 vectorFrom = TranslateToNavGrid(from); NavigationGridCell cellFrom = GetCell((short)vectorFrom.X, (short)vectorFrom.Y); Vector2 vectorTo = TranslateToNavGrid(to); NavigationGridCell goal = GetCell((short)vectorTo.X, (short)vectorTo.Y); if (cellFrom != null && goal != null) { SimplePriorityQueue <Stack <NavigationGridCell> > priorityQueue = new SimplePriorityQueue <Stack <NavigationGridCell> >(); Stack <NavigationGridCell> start = new Stack <NavigationGridCell>(); Dictionary <int, NavigationGridCell> closedList = new Dictionary <int, NavigationGridCell>(); Stack <NavigationGridCell> path = null; start.Push(cellFrom); priorityQueue.Enqueue(start, NavigationGridCell.Distance(cellFrom, goal)); closedList.Add(cellFrom.ID, cellFrom); // while there are still paths to explore while (true) { if (!priorityQueue.TryFirst(out _)) { // no solution return(null); } float currentCost = priorityQueue.GetPriority(priorityQueue.First); priorityQueue.TryDequeue(out path); NavigationGridCell cell = path.Peek(); currentCost -= (NavigationGridCell.Distance(cell, goal) + cell.Heuristic); // decrease the heuristic to get the cost // found the min solution return it (path) if (cell.ID == goal.ID) { break; } foreach (NavigationGridCell neighborCell in GetCellNeighbors(cell)) { // if the neighbor in the closed list - skip if (closedList.TryGetValue(neighborCell.ID, out _)) { continue; } // not walkable - skip if (neighborCell.HasFlag(NavigationGridCellFlags.NOT_PASSABLE) || neighborCell.HasFlag(NavigationGridCellFlags.SEE_THROUGH)) { closedList.Add(neighborCell.ID, neighborCell); continue; } // calculate the new path and cost +heuristic and add to the priority queue Stack <NavigationGridCell> npath = new Stack <NavigationGridCell>(new Stack <NavigationGridCell>(path)); npath.Push(neighborCell); // add 1 for every cell used priorityQueue.Enqueue(npath, currentCost + 1 + neighborCell.Heuristic + neighborCell.ArrivalCost + neighborCell.AdditionalCost + NavigationGridCell.Distance(neighborCell, goal)); closedList.Add(neighborCell.ID, neighborCell); } } NavigationGridCell[] pathArray = path.ToArray(); Array.Reverse(pathArray); List <NavigationGridCell> pathList = SmoothPath(new List <NavigationGridCell>(pathArray)); pathList.RemoveAt(0); // removes the first point foreach (NavigationGridCell navGridCell in pathList.ToArray()) { returnList.Add(TranslateFrmNavigationGrid(navGridCell.Locator)); } return(returnList); } return(null); }
public static void Main(string[] args) { var query = from line in File.ReadLines(@"C:\Users\undoall\source\repos\BananagramsAI\BananagramsAI\shortwords.txt") where line.All(c => "abcdefghijklmnopqrstuvwxyz".Contains(c)) select line; List <string> wordList = query.ToList(); Gaddag words = new Gaddag(false); foreach (string word in wordList) { words.InsertWord(word); } float Heuristic(SearchNode node) { return((float)node.State.Bank.Size); //return (1 - node.State.Bank.CalculateValue(wordList)) * node.State.Bank.Size; } List <char> pile = new List <char>(); for (int i = 0; i < 2; ++i) { pile.AddRange("J, K, Q, X, Z".ToLower().Split(',').Select(w => w.Trim()[0])); } for (int i = 0; i < 3; ++i) { pile.AddRange("B, C, F, H, M, P, V, W, Y".ToLower().Split(',').Select(w => w.Trim()[0])); } pile.AddRange(Enumerable.Repeat('g', 4)); pile.AddRange(Enumerable.Repeat('l', 5)); for (int i = 0; i < 6; ++i) { pile.AddRange("D, S, U".ToLower().Split(',').Select(w => w.Trim()[0])); } pile.AddRange(Enumerable.Repeat('n', 8)); pile.AddRange(Enumerable.Repeat('t', 9)); pile.AddRange(Enumerable.Repeat('r', 9)); pile.AddRange(Enumerable.Repeat('o', 11)); pile.AddRange(Enumerable.Repeat('i', 12)); pile.AddRange(Enumerable.Repeat('a', 13)); pile.AddRange(Enumerable.Repeat('e', 18)); int num_taking = 40; Random rng = new Random(); int[] temp = new int[26]; for (int i = 0; i < num_taking; ++i) { int index = rng.Next(0, pile.Count); temp[pile[index] - 'a'] += 1; pile.RemoveAt(index); } Bank bank = new Bank(temp); Grid grid = new Grid(); SimplePriorityQueue <SearchNode> queue = new SimplePriorityQueue <SearchNode>(); SearchNode root = new SearchNode(new PlayerState(bank, grid), 0); queue.Enqueue(root, num_taking); int count = 0; PlayerState BestFirstSearch(PlayerState start) { for (; ;) { SearchNode node; while (!queue.TryDequeue(out node)) { ; } //SearchNode node = queue.Dequeue(); Interlocked.Increment(ref count); //Console.Clear(); //node.State.Grid.Display(); if (count % 1000 == 0) { Console.WriteLine("({0}) got node with bank size {1}", count, node.State.Bank.Size); } foreach (SearchNode child in node.FindChildren(words)) { if (child.State.Bank.Size == 0) { Console.WriteLine("Solution found!"); child.State.Grid.Display(); Console.WriteLine("Total number of nodes examined: {0}", count); Environment.Exit(Environment.ExitCode); return(child.State); } queue.Enqueue(child, Heuristic(child)); } } } Console.Write("Bank: "); for (char c = 'a'; c <= 'z'; ++c) { for (int i = 0; i < bank.letters[c - 'a']; ++i) { Console.Write(c); } } Console.WriteLine(); Console.WriteLine("Searching for solution..."); int num_threads = 1; Task[] tasks = new Task[num_threads]; for (int i = 0; i < num_threads; ++i) { tasks[i] = Task.Run(() => BestFirstSearch(new PlayerState(bank, grid))); } tasks[0].Wait(); /* * PlayerState state = new PlayerState(bank, grid); * List<Placement> placements; * for (int i = 0; i < 20; ++i) { * Console.WriteLine(); * placements = state.FindPlacements(wordsBlock); * Console.Write("From " + placements.Count + " possible moves, placing: "); * Placement placement = placements[rng.Next(0, placements.Count)]; * * * Console.WriteLine(placement.word); * state.PlaceWord(placement); * state.Grid.Display(); * for (char c = 'a'; c <= 'z'; ++c) { * if (state.Bank.HasLetter(c)) { * Console.Write(c); * } * } * Console.WriteLine(); * } */ }
private async Task PerformTaskExecutionWorkerIterationAsync(int workerIndex, CancellationToken cancellationToken) { while (_tasksQueue.Count > 0) { if (cancellationToken.IsCancellationRequested) { return; } if (IsHighPriorityOnlyWorker(workerIndex)) { _tasksQueue.TryFirst(out var possibleTask); if (possibleTask == null || possibleTask.Priority != _highestPriority) { break; } } HttpRequestScheduledTaskBase task = null; lock (_perPriorityQueue) { _tasksQueue.TryDequeue(out task); if (task != null) { _perPriorityQueue[task.Priority].TryRemove(task); } } if (task == null) { break; } _taskIdToTaskMap.TryRemove(task.Id, out var _); _priorityToTasksCountMap.AddOrUpdate(task.Priority, 0, (key, value) => value - 1); await Executor.ExecuteSilentlyAsync( async() => { if (task is CompleteHttpRequestScheduledTask scheduledTask) { await ExecuteAsync(scheduledTask).ConfigureAwait(false); } else { await ExecuteAsync(task as RedirectHttpRequestScheduledTask).ConfigureAwait(false); } }).ConfigureAwait(false); task.Deferral.CompleteIfInProgress(); } await Task.Delay( IsHighPriorityOnlyWorker(workerIndex) ?HighPriorityWorkerTaskExecutionIterationDelayInMilliseconds : WorkerTaskExecutionIterationDelayInMilliseconds).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { return; } PerformTaskExecutionWorkerIterationAsync(workerIndex, cancellationToken); }