/// <summary> /// main CC loop (I dont see a need to unit test it) /// </summary> public override void Run() { while (true) { //this thing will grow on second stage of project: core.GetProblem(); //could be in another thread: solvingWatch.Reset(); log.Debug("Sending problem"); SolveRequestResponse response = SendProblem(); ulong problemId = response.Id; log.DebugFormat("Response received. Id of the problem in cluster: {0}", problemId); solvingWatch.Start(); SolutionRequest request = new SolutionRequest() { Id = problemId }; SolutionsSolution solution = this.WorkProblem(request); if (solution == null) { log.Debug("Solving timeout. Aborting."); continue; } else { log.DebugFormat("\n*** SOLUTION FOUND ({0}) ***\n", problemId); } core.PrintSolutionResult(solution); } }
public void SerializeSolutionRequest() { SolutionRequest d = new SolutionRequest(); string xml = d.SerializeToXML(); Assert.IsNotNull(xml); }
/// <summary> /// checks computations - sends solutionRequest msg /// </summary> /// <param name="request"></param> /// <returns>complete solution if cluster finished task</returns> public virtual Solutions CheckComputations(SolutionRequest request) { Message[] requests = creator.Create(request); Message[] responses = this.SendMessages(clusterClient, requests); Solutions solutionReponse = null; foreach (var response in responses) { switch (response.MessageType) { case MessageType.NoOperationMessage: log.Debug("NoOperation acquired: updating backups"); this.UpdateBackups(response.Cast <NoOperation>()); break; case MessageType.SolutionsMessage: log.Debug("Solutions acquired: checking..."); if (solutionReponse != null) { throw new Exception("Multiple solutions msg from CS to CC"); } solutionReponse = response.Cast <Solutions>(); break; default: throw new Exception("Wrong msg type delivered to CC: " + response.ToString()); } } if (solutionReponse == null) { throw new Exception("No Solutions message from server delivered (it always should do that)"); } //could (or couldn't?) be null: return(solutionReponse); }
public ActionResult CreateSolution([FromBody] SolutionRequest item) { if (item == null || !ModelState.IsValid) { return(BadRequest("Model state not valid.")); } if (_solutionService.SolutionExists(item.Title)) { return(BadRequest("Solution already exists.")); } var now = DateTime.UtcNow; var solution = new Solution { Title = item.Title, UpdatedBy = "Oscar Negrete", LastUpdate = now }; try { _solutionService.AddSolution(solution); } catch (Exception) { return(BadRequest("Could not create solution")); } return(Ok($"Solution created: {item.Title}")); }
private async void SendAsync() { bool isValid = await ValidateData2Async(); if (!isValid) { return; } SolutionRequest solutionrequest = new SolutionRequest { username = User.username, solution = Solution }; string url = App.Current.Resources["UrlAPI"].ToString(); bool status = await _apiService.PutAsync(url, "/Account", "/SendSolution", solutionrequest, "bearer", Problem.token); if (status) { await App.Current.MainPage.DisplayAlert("Congratulation!", "The answer was registered successfully!", "Accept"); } else { await App.Current.MainPage.DisplayAlert("Error", "The answer was not registered successfully", "Accept"); } }
public async Task <ActionResult <SudokuSolution> > Solve( [FromBody] SolutionRequest request) { var result = await solutionService.Solve(request); if (result.Success) { if (result.Solution != null) { result.Message = ControllerMessages.StatusCode200(result.Message); return(Ok(result)); } else { result.Message = ControllerMessages.StatusCode200(result.Message); return(Ok(result)); } } else { result.Message = ControllerMessages.StatusCode404(result.Message); return(NotFound(result)); } }
public void DeserializeSolutionRequest() { SolutionRequest d = new SolutionRequest(); string xml = d.SerializeToXML(); d = (SolutionRequest)xml.DeserializeXML(); Assert.IsNotNull(d); }
/// <summary> /// Method used to send request to check whether cluster has succesfully computed the solution /// </summary> /// <param name="_id"></param> private void SolutionRequest(ulong _id) { SolutionRequest solutionRequest = new SolutionRequest() { Id = _id }; Send(SerializeMessage <SolutionRequest>(solutionRequest)); ReceiveSolutionInfo(_id); }
/// <summary> /// gets computation stage as reponse for client node /// </summary> /// <param name="request">request with proper info</param> /// <param name="dataSets">data sets in server's memory</param> /// <returns></returns> public static Solutions GetSolutionState (SolutionRequest request, IDictionary <int, ProblemDataSet> dataSets) { var key = (int)request.Id; //something can go very very wrong: if (!dataSets.ContainsKey(key)) { return(null); } //template of response indicating that the problem is "ongoing" //this is very inconsistent, but i did not write the specification var response = new Solutions() { CommonData = dataSets[key].CommonData, Id = (ulong)key, ProblemType = dataSets[key].ProblemType, SolutionsList = new[] { new SolutionsSolution() { ComputationsTime = 0, Data = null, TaskIdSpecified = false, Type = SolutionsSolutionType.Ongoing } } }; if (dataSets[key].PartialSets == null || dataSets[key].PartialSets.Length == 0 || dataSets[key].PartialSets[0].PartialSolution == null) { return(response); } //response will be the status of first partial solution in problem memory (will be final //when TM would link it) if (dataSets[key].PartialSets[0].PartialSolution != null) { response = new Solutions() { CommonData = dataSets[key].CommonData, Id = (ulong)key, ProblemType = dataSets[key].ProblemType, SolutionsList = new[] { dataSets[key].PartialSets[0].PartialSolution } }; } return(response); }
public async Task <IActionResult> SubmitSolution(SolutionRequest request) { var task = await _context.Tasks.FirstOrDefaultAsync(t => t.Id == request.TaskId); if (task == null) { ModelState.AddModelError(nameof(request.TaskId), $"Task with id {request.TaskId} does not exist"); return(BadRequest(ModelState)); } var codingLanguage = await _context.CodingLanguages.FirstOrDefaultAsync(l => l.Id == request.CodingLanguageId); if (codingLanguage == null) { ModelState.AddModelError(nameof(request.CodingLanguageId), $"Coding language with id {request.CodingLanguageId} does not exist"); return(BadRequest(ModelState)); } var solution = await _context.Solutions.FirstOrDefaultAsync(s => s.User == request.User && s.Task == task); if (solution != null) { ModelState.AddModelError(nameof(request.TaskId), $"User has already submitted a solution for task {request.TaskId}"); return(BadRequest(ModelState)); } var verificationResult = await _solutionVerifier.Verify(request.Code, task.Input, task.ExpectedOutput); if (!verificationResult.IsSuccessful) { ModelState.AddModelError(nameof(request.Code), verificationResult.Error); return(BadRequest(ModelState)); } var entry = await _context.Solutions.AddAsync(new Solution { User = request.User, Code = request.Code, CodingLanguage = codingLanguage, Task = task }); await _context.SaveChangesAsync(); return(Ok(entry.Entity.Id)); }
public void CheckComputationsNoSolutionsExceptionTest() { var mockcore = new Mock <ClientNodeProcessingModule>(); var mockcreator = new Mock <IMessageArrayCreator>(); var solutionRequest = new SolutionRequest(); Message[] request = new[] { solutionRequest }; mockcreator.Setup(u => u.Create(solutionRequest)).Returns(request); var mockclient = new Mock <IClusterClient>(); var response = new NoOperation(); var responses = new Message[] { response }; mockclient.Setup(u => u.SendRequests(request)).Returns(responses); var clientNode = new ClientNode(mockclient.Object, mockcore.Object, mockcreator.Object); var ret = clientNode.CheckComputations(solutionRequest); }
private void SendSolutionInfo(Socket _handler, SolutionRequest _solutionRequestMessage) { m_memoryLock.WaitOne(); Problem problem = m_problems.Find(e => e.Id == _solutionRequestMessage.Id); Solutions solutionInfo = new Solutions() { Id = _solutionRequestMessage.Id, Solutions1 = null }; if (problem != null) { solutionInfo.CommonData = problem.Data; solutionInfo.ProblemType = problem.ProblemType; solutionInfo.Solutions1 = problem.solutions; //solutionInfo.Solutions1[0].TimeoutOccured = problem.timeoutOccured; } m_memoryLock.Release(); Send(SerializeMessage(solutionInfo), _handler); }
public async Task SolveSudokuMatrices() { // Arrange var solutionRequest = new SolutionRequest() { FirstRow = new List <int> { 0, 2, 0, 5, 0, 0, 8, 7, 6 }, SecondRow = new List <int> { 7, 0, 0, 1, 8, 0, 0, 5, 0 }, ThirdRow = new List <int> { 8, 5, 9, 7, 0, 0, 0, 4, 0 }, FourthRow = new List <int> { 5, 9, 0, 0, 0, 4, 6, 8, 1 }, FifthRow = new List <int> { 0, 1, 0, 0, 3, 0, 0, 0, 0 }, SixthRow = new List <int> { 0, 0, 0, 8, 6, 0, 0, 9, 5 }, SeventhRow = new List <int> { 2, 0, 7, 0, 0, 8, 0, 0, 9 }, EighthRow = new List <int> { 9, 0, 4, 0, 0, 7, 2, 0, 8 }, NinthRow = new List <int> { 0, 0, 0, 0, 0, 2, 4, 6, 0 } }; // Act var result = await sut.Solve((ISolutionRequest)solutionRequest); // Assert Assert.That(result.Success, Is.True); Assert.That(result.Message, Is.EqualTo("Sudoku Solution Found")); Assert.That(result.Solution, Is.TypeOf <SudokuSolution>()); }
protected override Message[] RespondSolutionRequestMessage(SolutionRequest message, IDictionary <int, ProblemDataSet> dataSets, IDictionary <int, ActiveComponent> activeComponents, List <BackupServerInfo> backups) { //sent by client node. send NoOperation + CaseExtractor.GetSolutionState var solutionState = DataSetOps.GetSolutionState(message, dataSets); if (solutionState == null) { return(new Message[] { new NoOperation() { BackupServersInfo = backups.ToArray() } }); } return(new Message[] { solutionState, new NoOperation() { BackupServersInfo = backups.ToArray() } }); }
public void ResponseIfProblemIsSolved() { DvrpProblem.Problems.Clear(); DvrpProblem.ProblemSolutions.Clear(); SolveRequest solveRequest = new SolveRequest() {Data = new byte[1]}; DvrpProblem.Problems.Add(1, solveRequest); Solutions solution = new Solutions() { CommonData = new byte[1], Solutions1 = new SolutionsSolution[] {new SolutionsSolution() {Data = new byte[1]}} }; SolutionRequest request = new SolutionRequest() {Id = 1}; DvrpProblem.ProblemSolutions.Add(request.Id, solution); string msg = MessageSerialization.Serialize(request); SolutionRequestStrategy solutionRequestStrategy = new SolutionRequestStrategy(); solutionRequestStrategy.HandleMessage(networkAdapterMock.Object, msg, MessageType.SolutionRequestMessage, new TimeSpan(0,1,0)); networkAdapterMock.Verify(p => p.Send(It.IsAny<Solutions>()), Times.Once); //Assert.AreEqual(DvrpProblem.ProblemSolutions.Count, 0); }
public ActionResult UpdateSolution(int id, [FromBody] SolutionRequest item) { if (item == null || !ModelState.IsValid) { return(BadRequest("Model state not valid.")); } if (id != item.ID) { return(BadRequest("ID not valid.")); } var now = DateTime.UtcNow; var solution = new Solution { ID = id, Title = item.Title, UpdatedBy = "Oscar Negrete", LastUpdate = now }; try { _solutionService.UpdateSolution(solution); } catch (Exception e) { if (!_solutionService.SolutionExists(id)) { return(NotFound()); } else { return(BadRequest(e.Message)); } } return(Ok($"Solution updated: {solution.ID} - {solution.Title}")); }
protected override string ReceivedSolutionRequest(SolutionRequest solutionRequest) { /* Solution Request message is sent from the CC in order to check whether the cluster has successfully * computed the solution. It allows CC to be shut down and disconnected from server during computations. */ Solutions solution = new Solutions(); List <Solutions> solutions = this.serverQueues.FinalSolutions.ToList(); foreach (Solutions s in solutions) { if (s.Id == solutionRequest.Id) { solution = s; break; } } if (!this.BackupMode) { Console.WriteLine("Sending Solutions"); } return(solution.SerializeToXML()); }
public void WorkProblemTimeoutTest() { var mock = new Mock <ClientNode>(MockBehavior.Default, new ClusterClient("-1", -1, TcpClientAdapterFactory.Factory)); mock.CallBase = true; SolutionRequest solutionRequest = new SolutionRequest(); SolutionsSolution solution = new SolutionsSolution() { TimeoutOccured = true }; mock.Setup(u => u.CheckComputations(solutionRequest)).Returns( new Solutions() { SolutionsList = new SolutionsSolution[] { solution } }); var clientNode = mock.Object; var ret = clientNode.WorkProblem(solutionRequest); Assert.IsNull(ret); }
public void WorkProblemGetFinalSolutionTest() { var mock = new Mock <ClientNode>(MockBehavior.Default, new ClusterClient("-1", -1, TcpClientAdapterFactory.Factory)); mock.CallBase = true; SolutionRequest solutionRequest = new SolutionRequest(); SolutionsSolution finalSolution = new SolutionsSolution() { Type = SolutionsSolutionType.Final }; mock.Setup(u => u.CheckComputations(solutionRequest)).Returns( new Solutions() { SolutionsList = new SolutionsSolution[] { finalSolution } }); var clientNode = mock.Object; var ret = clientNode.WorkProblem(solutionRequest); Assert.AreEqual(ret, finalSolution); }
/// <summary> /// main communication loop concerning actual problem context /// </summary> /// <returns>final solution (or none if something crashed)</returns> public virtual SolutionsSolution WorkProblem(SolutionRequest request) { while (true) { Thread.Sleep((int)Properties.Settings.Default.SolutionCheckingInterval); log.DebugFormat("Sending solutionRequest ({0})", request.Id); Solutions solution = CheckComputations(request); //assuming that final solution has one element with type==final if (solution.SolutionsList[0].Type == SolutionsSolutionType.Final) { return(solution.SolutionsList[0]); } //assuming only one timeout is enough to end waiting for an answer if (solution.SolutionsList[0].TimeoutOccured) { break; } // ~~ else continue log.DebugFormat("No solution yet ({0})", request.Id); } return(null); }
private void SolutionRequestMessage(ulong id) { var solutionRequestMessage = new SolutionRequest() {Id = id}; _networkAdapter.StartConnection(); _networkAdapter.Send(solutionRequestMessage, false); var solutions = _networkAdapter.Receive<Solutions>(false); _networkAdapter.CloseConnection(); if (solutions == null || solutions.Solutions1 == null) { Thread.Sleep(SleepTime); return; } try { foreach (var e in solutions.Solutions1) { switch (e.Type) { case SolutionsSolutionType.Final: Console.WriteLine( "Final Solutions in da hause - \n" + "Id: {0} \n" + "Problem type: {1} \n" + "It's computations time: {2}\n" + "\nSolution: {3}\n\n" + "Closing connection... \n\n", solutions.Id, solutions.ProblemType, e.ComputationsTime, DataSerialization.BinaryDeserializeObject<double>(e.Data)); _working = false; break; case SolutionsSolutionType.Partial: Console.WriteLine( "Partial Solutions in da hause - \n" + "Id: {0} \n" + "Problem type: {1} \n" + "It's computations time: {2}\n" + "Continue to processing... \n\n", solutions.Id, solutions.ProblemType, e.ComputationsTime); Console.WriteLine(@"Partial solution for problem {0} is {1}", id, DataSerialization.BinaryDeserializeObject<double>(e.Data)); break; default: Console.WriteLine( "Id: {0} \n" + "Problem type: {1} \n" + "It's status: {2}, so still waiting for final or partial solutions... \n\n", solutions.Id, solutions.ProblemType, e.Type); break; } if (!_solutionsList.Contains(e.Data)) _solutionsList.Add(e.Data); if (e.TimeoutOccured) throw new TimeoutException(); } } catch (Exception) { Console.WriteLine(@"Exception thrown while reading solutions."); } Thread.Sleep(SleepTime); }
protected abstract string ReceivedSolutionRequest(SolutionRequest solutionRequest);
public async Task Setup() { context = await TestDatabase.GetDatabaseContext(); mockSolutionsService = new MockSolutionsService(context); mockAppsService = new MockAppsService(context); baseRequest = new BaseRequest(); solutionRequest = new SolutionRequest() { FirstRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, SecondRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, ThirdRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, FourthRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, FifthRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, SixthRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, SeventhRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, EighthRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, NinthRow = new List <int> { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; addSolutionRequest = new AddSolutionRequest() { Limit = 1000 }; invalidAddSolutionRequest = new AddSolutionRequest() { Limit = 1001 }; sutSuccess = new SolutionsController( mockSolutionsService.SolutionsServiceSuccessfulRequest.Object, mockAppsService.AppsServiceSuccessfulRequest.Object); sutFailure = new SolutionsController( mockSolutionsService.SolutionsServiceFailedRequest.Object, mockAppsService.AppsServiceSuccessfulRequest.Object); sutSolvedFailure = new SolutionsController( mockSolutionsService.SolutionsServiceSolveFailedRequest.Object, mockAppsService.AppsServiceSuccessfulRequest.Object); }
protected virtual Message[] RespondSolutionRequestMessage(SolutionRequest message, IDictionary <int, ProblemDataSet> dataSets, IDictionary <int, ActiveComponent> activeComponents, List <BackupServerInfo> backups) { return(null); }
protected override string ReceivedSolutionRequest(SolutionRequest solutionRequest) { Debug.Assert(false, "Should not be here"); return(null); }
public Task <SolutionResponse> GetSolutionAsync(SolutionRequest SolutionRequest) { throw new NotImplementedException(); }
public SolutionResponse GetSolution(SolutionRequest SolutionRequest) { throw new NotImplementedException(); }
public async Task <bool> PutAsync(string urlBase, string servicePrefix, string controller, SolutionRequest solution, string tokenType, string accessToken) { try { string request = JsonConvert.SerializeObject(solution); StringContent content = new StringContent(request, Encoding.UTF8, "application/json"); HttpClient client = new HttpClient { BaseAddress = new Uri(urlBase) }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken); string url = $"{servicePrefix}{controller}"; HttpResponseMessage response = await client.PutAsync(url, content); string answer = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return(false); } return(true); } catch (Exception ex) { return(false); } }
private MessagePackage AskForSolution(ulong problemId) { var request = new SolutionRequest { Id = problemId }; return SendMessageSingleResponse(request); }