public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "countrylist/{country}")] HttpRequest req, ILogger log, string country) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); string input = country.ToUpper(); List <string> path = null; log.LogInformation("C# HTTP trigger function processed a request."); // This computes the path and catches the two main error cases try { path = CountrySearch.shortestPath(input); } catch (KeyNotFoundException) { log.LogInformation($"Key {input} not contained in the map."); return(new BadRequestObjectResult($"The destination {input} is not contained in North America")); } if (path.Count == 0) { log.LogInformation($"No path from USA to {input} found in the map."); return(new BadRequestObjectResult($"No path from USA to {input} found in the map")); } // format and return succesful response PathResponse okPathResponce = new PathResponse { Start = "USA", Destination = input, Path = path }; var okJsonResponse = JsonConvert.SerializeObject(okPathResponce); return(new JsonResult(okPathResponce)); }
private void ProcessCalculationResult(PathResponse result, bool wasCanceled) { if (wasCanceled) { OpenOpenerUi(); return; } if (result == null || result.Items.Count <= 0) { Debug.Log($"Got no result to display. Result count was: {result?.Items.Count}"); OpenOpenerUi(); return; } CloseAllUis(); resultPanel.SetResult(result.Items); resultPanel.gameObject.SetActive(true); statisticsUI.StopTimerAndDisplay(); statisticsUI.UpdateCalcDistance(result.Distance); if (!customer.onlyBeeLine) { statisticsUI.UpdateRealDistance(NodeModel.GetVector3List(result.Items)); } }
private void ProcessIntermediateResult(PathResponse intermediateRes) { if (intermediateRes == null || intermediateRes.DemoItems.Count <= 0) { return; } statisticsUI.UpdateCalcDistance(intermediateRes.Distance); pathDisplayer.DisplayStraightPath(NodeModel.GetVector3List(intermediateRes.DemoItems)); }
public IActionResult Path([FromQuery(Name = "source")] string source, [FromQuery(Name = "target")] string target) { if (source == String.Empty || target == String.Empty || source == null || target == null) { return(BadRequest()); } PathResponse pathResponse = pathFinding.FindPath(source, target); if (pathResponse.stops.Count == 0) { return(BadRequest()); } return(Json(pathResponse)); }
public void FinishProcessing(PathResponse pathResponse) { if (multiThreading) { //Add New Result To Queue Result To Call Back it lock (_results) { _results.Enqueue(pathResponse); } } else { pathResponse.callBack(pathResponse.path, pathResponse.succes); } }
// Call back The Result to Each Agent Request void CallBackTheResult() { if (_results.Count > 0) { lock (_results) { for (int i = 0; i < _results.Count; i++) { PathResponse pathResponse = _results.Dequeue(); pathResponse.callBack(pathResponse.path, pathResponse.succes); } } } }
private IEnumerator QueryCalculationResult(string hostUrl, Action <PathResponse> intAction, Action <PathResponse, bool> actionOnResult) { Debug.Log("Checking for result..."); PathResponse result = null; int numNetErrors = 0; while (!cancelCalculation) { var request = CreateGetCalculatedWaypointsRequest(hostUrl); yield return(request.SendWebRequest()); if (!request.isNetworkError && request.responseCode == 200) { Debug.Log("Got result."); var response = Encoding.UTF8.GetString(request.downloadHandler.data); result = JsonUtility.FromJson <PathResponse>(response); if (result != null) { if (result.Items != null && result.Items.Count > 0) { break; } intAction(result); } } else if (request.isNetworkError) { numNetErrors++; Debug.LogWarning($"Network-Error, cant get result. Response-Code is: {request.responseCode}. \nNumber of failed attempts: {numNetErrors}"); if (numNetErrors > 10) { Debug.LogWarning("Cancel result fetching. There were more then a total of ten network errors!"); break; } } yield return(new WaitForSeconds(delayBetweenRequests)); } calculationActive = false; Debug.Log("Displaying result..."); actionOnResult(result, cancelCalculation); cancelCalculation = false; }
public static List <PathResponse> ScanFolderService(string pathString, bool showFolder) { List <string> files = Directory.GetFiles(pathString).ToList(); var pathRespList = new List <PathResponse>(); foreach (var s in files) { FileInfo fileInf = new FileInfo(s); //Использовать var и простой инициализатор var pathResp = new PathResponse { FullName = fileInf.FullName, CreationTime = fileInf.CreationTime, LastWriteTime = fileInf.LastWriteTime, Length = fileInf.Length, IsDirectory = false }; pathRespList.Add(pathResp); } //если пользователь отметил и папки if (showFolder) { List <string> dirs = Directory.GetDirectories(pathString).ToList(); foreach (var s in dirs) { DirectoryInfo dirInfo = new DirectoryInfo(s); //Использовать var и простой инициализатор var pathResp = new PathResponse { FullName = dirInfo.FullName, CreationTime = dirInfo.CreationTime, LastWriteTime = dirInfo.LastWriteTime, Length = FolderSizeService(s), IsDirectory = true }; pathRespList.Add(pathResp); } } return(pathRespList); }
public void FindingPath(PathRequest request, Action <PathResponse> callBack) { if (_pointGrid.grid == null) { return; } Heap <PointNode> openList = new Heap <PointNode>(); List <PointNode> closeList = new List <PointNode>(); PointNode agentNode = _pointGrid.GetPointNodeFromGridByPosition(request.startNode); PointNode targetNode = _pointGrid.GetPointNodeFromGridByPosition(request.targetNode); if (targetNode == null) { return; } openList.Add(agentNode); while (openList.Count > 0) { PointNode currentNode = openList.Pop(); if (currentNode == null) { return; } //Check If Reach The Goal if (_pointGrid.CheckIfPointsLinkedTogether(currentNode, targetNode)) { targetNode.parent = currentNode; break; } closeList.Add(currentNode); List <PointNode> neighboursNode = currentNode.neighbors; for (int i = 0; i < neighboursNode.Count; i++) { if (closeList.Contains(neighboursNode[i])) { continue; } else { float gCost = currentNode.gCost + CalculateMovementCostToTargetNode(currentNode, neighboursNode[i]); float hCost = CalculateMovementCostToTargetNode(neighboursNode[i], targetNode); if (openList.Contains(neighboursNode[i]) == false) { //Set fValue neighboursNode[i].fCost = hCost + gCost; neighboursNode[i].parent = currentNode; openList.Add(neighboursNode[i]); } else { float new_fCost = gCost + hCost; //Check if new fvalue is best than the older if (neighboursNode[i].fCost > new_fCost) { //Update fValue neighboursNode[i].fCost = new_fCost; neighboursNode[i].parent = currentNode; } } } } } // Create The Path Vector3[] path = CreatePath(agentNode, targetNode); //Create Response To Call Back it PathResponse pathResponse = new PathResponse(path, true, request.callBack); //Call Back callBack(pathResponse); return; }
/// <summary> /// Метод для упрощенного создания объектов ответа и токена. /// </summary> public static void New(out PathRequestToken <TPoint> token, out PathResponse <TPoint> response) { token = new PathRequestToken <TPoint>(); response = new PathResponse <TPoint>(token); }
/// <summary> /// Find path between two stops using graph structure /// </summary> /// <param name="source">Node name where path should start</param> /// <param name="destination">Node name where path should end</param> /// <returns>Path response: List of nodes for found path and length of path</returns> public PathResponse FindPath(string source, string destination) { SolvroCityGraphNode sourceNode = Nodes.Find((node) => node.stop_name == source); //first node SolvroCityGraphNode destinationNode = Nodes.Find((node) => node.stop_name == destination); //last node if (sourceNode == null || destinationNode == null) // check if nodes exists before attempting to find path { return(new PathResponse()); } List <SolvroCityGraphNode> nodesCpy = new List <SolvroCityGraphNode>(Nodes); // create copy of nodes on which we can operate List <SolvroCityGraphNode> nodesChecked = new List <SolvroCityGraphNode>(); // create empty list for visited nodes for (int i = 0; i < nodesCpy.Count; i++) // init weigth of nodes { nodesCpy[i].weightSum = uint.MaxValue; nodesCpy[i].prevNode = null; } sourceNode.weightSum = 0; while (nodesCpy.Count > 0) // proceed with algorithm { SolvroCityGraphNode minNode = null; foreach (SolvroCityGraphNode node in nodesCpy) { if (minNode == null || minNode.weightSum > node.weightSum) { minNode = node; } } nodesChecked.Add(minNode); nodesCpy.RemoveAll((node) => node.id == minNode.id); for (int i = 0; i < minNode.Links.Count; i++) { if (minNode.Links[i].Available) { SolvroCityGraphNode neighbor = minNode.Links[i].TargetNode; if (minNode.weightSum != uint.MaxValue && neighbor.weightSum > minNode.weightSum + minNode.Links[i].distance) { neighbor.weightSum = minNode.weightSum + minNode.Links[i].distance; neighbor.prevNode = minNode; } } } } //best path have been found, proceed to generating "nice" data destinationNode = nodesChecked.Find((node) => node == destinationNode); PathResponse pathResponse = new PathResponse() { distance = destinationNode.weightSum }; List <SolvroCityNode> foundNodes = new List <SolvroCityNode>(); while (destinationNode.prevNode != null) // follow path from target to source (backwards) { foundNodes.Add(new SolvroCityNode() { id = destinationNode.id, stop_name = destinationNode.stop_name }); destinationNode = destinationNode.prevNode; } if (destinationNode != sourceNode) { pathResponse = new PathResponse(); } else { foundNodes.Add(new SolvroCityNode() { id = destinationNode.id, stop_name = destinationNode.stop_name }); foundNodes.Reverse(); //path is reversed so we need to call reverse to have it in correct order pathResponse.stops = foundNodes; } return(pathResponse); }