public void Should_advance_it_to_a_valid_state_with_that_value() { Guid serviceId = Guid.NewGuid(); Learner<string> learner = new Learner<string>(serviceId) { Bus = MockRepository.GenerateMock<IServiceBus>() }; Accepted<string> message = new Accepted<string> { BallotId = 1, CorrelationId = serviceId, IsFinal = false, Value = "Chris", ValueBallotId = 1, }; learner.RaiseEvent(Learner<string>.ValueAccepted, message); learner.CurrentState.ShouldEqual(Learner<string>.Active); learner.Value.ShouldEqual(message.Value); learner.BallotId.ShouldEqual(message.BallotId); }
public async Task LearnerLearnsOfResult() { string result; var learner = new Learner(3); Assert.IsFalse(learner.TryGetResult("round", out result)); learner.SendMessage("", "AcceptorA", NetworkMessage.Commit("round", new SequenceNumber("[1:ProposerA]"), "foo").Accept()); learner.SendMessage("", "AcceptorA", NetworkMessage.Commit("round", new SequenceNumber("[1:ProposerA]"), "foo").Accept()); learner.SendMessage("", "AcceptorA", NetworkMessage.Commit("round", new SequenceNumber("[1:ProposerA]"), "foo").Accept()); Assert.IsFalse(learner.TryGetResult("round", out result)); learner.SendMessage("", "AcceptorB", NetworkMessage.Commit("round", new SequenceNumber("[2:ProposerB]"), "bar").Accept()); learner.SendMessage("", "AcceptorC", NetworkMessage.Commit("round", new SequenceNumber("[2:ProposerB]"), "bar").Accept()); Assert.AreEqual("bar", await learner.GetResult("round")); Assert.IsTrue(learner.TryGetResult("round", out result)); Assert.AreEqual("bar", result); }
public IActionResult UpdateLeanerEnrollment(long learnerId, long sessionId, Learner request) { try { var output = _learnerRepository.UpdateLeanerEnrollment(learnerId, sessionId, request); if (output == true) { return(Ok(new GenericResult { Response = true, Message = "Learner has been successfully updated" })); } else { return(NotFound(_NotFound)); } } catch (Exception e) { return(BadRequest(e)); } }
public void Action(Learner learner) { double metric_now = double.MaxValue; try { metric_now = learner.metrics_values[metric]; } catch { Console.WriteLine("Не могу прочитать метрику {0}", metric); return; } if (metric_val > metric_now) { metric_val = metric_now; File.WriteAllText(metric_val + ".neural", learner.optimizer.network.SaveJSON()); Console.WriteLine("нейросеть созранена в {0}", metric_val + ".neural"); } }
public void Arrange() { _fixture = new Fixture(); _sutModel = _fixture .Build <LearnerModel>() .Create(); _collectionPeriod = _fixture.Create <CollectionPeriod>(); _daysInLearning = new DaysInLearning(_collectionPeriod, _fixture.Create <int>()); _sutModel.DaysInLearnings = new List <DaysInLearning>() { new DaysInLearning(new CollectionPeriod((byte)(_collectionPeriod.PeriodNumber - 1), (short)(_collectionPeriod.AcademicYear - 1)), _fixture.Create <int>()), _daysInLearning, new DaysInLearning(new CollectionPeriod((byte)(_collectionPeriod.PeriodNumber + 1), (short)(_collectionPeriod.AcademicYear + 1)), _fixture.Create <int>()), }; _sut = Sut(_sutModel); }
public async Task <IActionResult> Create([Bind("LearnerId,PersonId,SchoolId,SchoolGradeId,MotivationText,YearSchoolCompleted,CreatedBy,DateCreated,LastUpdatedBy,DateUpdated")] Learner learner) { if (ModelState.IsValid) { learner.CreatedBy = "admin"; learner.DateCreated = DateTime.Now; learner.LastUpdatedBy = "admin"; learner.DateUpdated = DateTime.Now; _context.Add(learner); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["PersonId"] = new SelectList(_context.Person, "PersonId", "PersonId", learner.PersonId); ViewData["SchoolId"] = new SelectList(_context.School, "SchoolId", "SchoolId", learner.SchoolId); ViewData["SchoolGradeId"] = new SelectList(_context.SchoolGrade, "SchoolGradeId", "SchoolGradeId", learner.SchoolGradeId); return(PartialView(learner)); }
protected virtual void SelectNewMasterOnTopologyChanged(object sender, NodeMetadata nodeMetadata) { if (nodeMetadata.ChangeType == TopologyChangeType.MasterSelected) { return; //nothing to do here } MasterSelectedByQuorum = null; // Who is the master is in doubt, because the topology changed var others = topologyState.Keys.ToArray(); var acceptor = new Acceptor(this, myAddress, others); var proposer = new Proposer(this, acceptor, myAddress, others); var learner = new Learner(this, others); learner.OnAcceptedValue += LearnerOnOnAcceptedValue; agents = new Agent[] { acceptor, proposer, learner }; proposer.StartProposing(new SwitchMasterCommand { NewMaster = others.OrderBy(x => x.AbsoluteUri).First() }); }
public static LearnerModel ToModel(this Learner model) { return(new LearnerModel { LearnerId = model.LearnerId, FirstName = model.FirstName, LastName = model.LastName, DateOfBirth = model.DateOfBirth, Gender = model.Gender, IDNumber = model.IDNumber, Grade = model.Grade, Race = model.Race, SchoolName = model.SchoolName, Section = model.Section, CreateUserId = model.CreateUserId, CreateDate = model.CreateDate, ModifyUserId = model.ModifyUserId, ModifyDate = model.ModifyDate, StatusId = model.StatusId }); }
public IActionResult CourseReview(long learnerId, Learner request) { try { var output = _learnerRepository.AddCourseReview(learnerId, request); if (output == true) { return(Ok(new GenericResult { Response = true, Message = "Review posted" })); } else { return(NotFound(_NotFound)); } } catch (Exception e) { return(BadRequest(e)); } }
const int SIZE_IN_NB_LAYER = 2; // 1 layer for Coins - Player public Agent2D() { int inputSize = SIZE_IN; int outputSize = SIZE_OUT; model = CNTKHelper.CNTKHelper.CreateMLPModel1D(device, inputSize, SIZE_IN_NB_LAYER, outputSize); inputVariable = model.Arguments.First(a => a.IsInput); inputDataMap = new Dictionary <Variable, Value>() { { inputVariable, null } }; outputDataMap = new Dictionary <Variable, Value>() { { model.Output, null } }; inputTrainBatch = new Dictionary <Variable, Value>() { { inputVariable, null } }; outputTrainBatch = new Dictionary <Variable, Value>() { { model.Output, null } }; // Set per sample learning rate CNTK.TrainingParameterScheduleDouble learningRatePerSample = new CNTK.TrainingParameterScheduleDouble(0.001, 1); actionVariable = CNTKLib.InputVariable(new int[] { SIZE_OUT }, DataType.Float, "Actions"); var trainingLoss = CNTKLib.CrossEntropyWithSoftmax(new Variable(model), actionVariable, "lossFunction"); var prediction = CNTKLib.ClassificationError(new Variable(model), actionVariable, "classificationError"); IList <Learner> parameterLearners = new List <Learner>() { Learner.SGDLearner(model.Parameters(), learningRatePerSample) }; trainer = Trainer.CreateTrainer(model, trainingLoss, prediction, parameterLearners); }
/// <summary> /// Implementation method that executes a simple numl workflow, /// easily swapping generators/models, etc. This is primarily to /// keep things DRY, even though this is just example code. /// </summary> /// <typeparam name="TData">The type of your data</typeparam> /// <param name="getData">func to retrieve data, e.g. <c>() => SampleData.GetTennisData()</c></param> /// <param name="getDescriptor">func to describe your type of data, e.g. <c>() => Descriptor.Create<Tennis>()</c></param> /// <param name="getGenerator">func to create/initialize your generator. See example methods.</param> /// <param name="getToPredict">func to get/create the data you want to predict. See example methods.</param> /// <param name="getPredictionDesc">logging func for displaying prediction output on console.</param> static void SimpleNumlWorkflowImpl <TData>( Func <IEnumerable <TData> > getData, Func <Descriptor> getDescriptor, Func <Descriptor, IGenerator> getGenerator, Func <TData> getToPredict, Func <TData, string> getPredictionDesc, double trainingPercentage, int repeat ) where TData : class { // Start with descriptor var descriptor = getDescriptor(); // Choose our generator var generator = getGenerator(descriptor); Console.WriteLine($"Starting {generator.GetType().Name}\n"); // Load our data var data = getData(); // Create the model by learning from the data using the generator var learningModel = Learner.Learn(data, trainingPercentage, repeat, generator); Console.WriteLine(learningModel); // Now we could predict using the learning info's Model. var toPredict = getToPredict(); var prediction = learningModel.Model.Predict(toPredict); //var tennisPrediciton = learningModel.Model.Predict(areWeGonnaPlayTennis); Console.WriteLine($"To Predict: {toPredict})"); Console.WriteLine($"Prediction: {getPredictionDesc(prediction)}\n"); Console.WriteLine("Press any key...\n"); Console.ReadKey(); }
public void Train(string[] trainData) { int n = trainData.Length; Variable yt = Variable.InputVariable(new int[] { outputSize }, DataType.Float, "yt"); Function loss = CNTKLib.BinaryCrossEntropy(y, yt, "loss"); Function y_rounded = CNTKLib.Round(y); Function y_yt_equal = CNTKLib.Equal(y_rounded, yt); Learner learner = CNTKLib.SGDLearner(new ParameterVector(y.Parameters().ToArray()), new TrainingParameterScheduleDouble(0.01, 1)); Trainer trainer = Trainer.CreateTrainer(y, loss, y_yt_equal, new List <Learner>() { learner }); for (int i = 1; i <= 100; i++) { double sumLoss = 0; double sumEval = 0; foreach (string line in trainData) { float[] values = line.Split('\t').Select(x => float.Parse(x)).ToArray(); var inputDataMap = new Dictionary <Variable, Value>() { { x, LoadInput(values[0], values[1], values[2], values[3]) }, { yt, Value.CreateBatch(yt.Shape, new float[] { values[4] }, DeviceDescriptor.CPUDevice) } }; var outputDataMap = new Dictionary <Variable, Value>() { { loss, null } }; trainer.TrainMinibatch(inputDataMap, false, DeviceDescriptor.CPUDevice); sumLoss += trainer.PreviousMinibatchLossAverage(); sumEval += trainer.PreviousMinibatchEvaluationAverage(); } Console.WriteLine(String.Format("{0}\tloss:{1}\teval:{2}", i, sumLoss / n, sumEval / n)); } }
private void AddLearner_Click(object sender, RoutedEventArgs e) { //if (LearnerItemsCV != null && LearnerItemsCV.CurrentItem != null) //{ // foreach (Learner learner in LearnerItemsCV) // { // if (!string.IsNullOrWhiteSpace(learner.IncompleteMessage)) // { // MessageBox.Show($"Please complete all mandatory fields for learner {learner.LearnRefNumber} before proceeding" // , "Cannot proceed" // , MessageBoxButton.OK // , MessageBoxImage.Error // , MessageBoxResult.OK); // return; // } // } //} Learner newLr = App.ILRMessage.CreateLearner(); App.ILRMessage.Save(); if (App.ILRMessage.LearnerList.Count == 1) { SetupListData(); } foreach (Learner l in LearnerItemsCV) { //if (l != newLr) l.IsSelected = false; } newLr.IsSelected = true; DataItemListBox.SelectedItem = newLr; //LearnerItemsCV.MoveCurrentTo(newLr); LearnerItemsCV.Refresh(); OnPropertyChanged("LearnerItemsCV"); newLr.RefreshData(); }
public void Then_days_in_learning_is_zero_if_there_are_no_LearningPeriods() { // arrange _sutModel = _fixture .Build <LearnerModel>() .With(l => l.LearningPeriods, new List <LearningPeriod>()) .With(l => l.DaysInLearnings, new List <DaysInLearning>()) .Create(); int expectedDays = 0; _sut = Sut(_sutModel); // act _sut.SetDaysInLearning(_collectionCalendarPeriod); // assert var daysInLearning = _sut.GetModel().DaysInLearnings.Single(); daysInLearning.CollectionPeriod.Should().Be(_collectionCalendarPeriod.CollectionPeriod); daysInLearning.NumberOfDays.Should().Be(expectedDays); }
public async Task <LearnerDTO> CreateLearner(LearnerDTO _LearnerDTO) { var UserId = Guid.Parse(_httpContextAccessor.HttpContext.User.GetLoggedInUserId <string>()); var learner = new Learner() { FullName = _LearnerDTO.FullName, CountyLearner = _LearnerDTO.CountyLearner, CityLeaner = _LearnerDTO.CityLeaner, StreetLearner = _LearnerDTO.StreetLearner, NumberLearner = _LearnerDTO.NumberLearner, FinancialStateApproved = false, Introduction = _LearnerDTO.Introduction, UserID = UserId, }; _context.Learners.Add(learner); await _context.SaveChangesAsync(); return(new LearnerDTO()); }
public void ShouldSortStandardPaymentToBeLast() { var expectedFirstEventId = Guid.NewGuid(); var expectedSecondEventId = Guid.NewGuid(); var expectedThirdEventId = Guid.NewGuid(); var expectedSequence = new List <Guid> { expectedFirstEventId, expectedSecondEventId, expectedThirdEventId }; var learner = new Learner { Uln = 10000002 }; var amounts = new List <CalculatedRequiredLevyAmount> { new CalculatedRequiredLevyAmount { EventId = expectedThirdEventId, AmountDue = 1000, AgreedOnDate = DateTime.UtcNow, Learner = new Learner() { Uln = 1 }, AccountId = 112 }, new CalculatedRequiredLevyAmount { EventId = expectedFirstEventId, AmountDue = -1000, AgreedOnDate = DateTime.UtcNow, Learner = new Learner() { Uln = 1 }, AccountId = 112 }, new CalculatedRequiredLevyAmount { EventId = expectedSecondEventId, TransferSenderAccountId = 100000001, AgreedOnDate = DateTime.UtcNow, Learner = learner, AccountId = 112 }, }; var result = calculatedRequiredLevyAmountPrioritisationService.Prioritise(amounts, new List <(long, int)>()); Assert.IsTrue(expectedSequence.SequenceEqual(result.Select(r => r.EventId))); }
/// <summary> /// create from saved model /// </summary> /// <param name="model"></param> /// <param name="deviceName"></param> public FCN7(byte[] modelBuffer, string deviceName) { device = NP.CNTKHelper.GetDeviceByName(deviceName); Function model = Function.Load(modelBuffer, device); inputVariable = model.Inputs.First(v => v.Name == "inputVariable"); outputVariable = Variable.InputVariable(model.Output.Shape, DataType.Float, "labelVariable"); classifierOutput = model; Function loss = CNTKLib.SquaredError(classifierOutput, outputVariable); Function pred = CNTKLib.ClassificationError(classifierOutput, outputVariable); //adam leaner ParameterVector parameterVector = new ParameterVector(classifierOutput.Parameters().ToList()); TrainingParameterScheduleDouble learningRateSchedule = new TrainingParameterScheduleDouble(0.00178125, BatchSize); TrainingParameterScheduleDouble momentumRateSchedule = new TrainingParameterScheduleDouble(0.9, BatchSize); Learner leaner = CNTKLib.AdamLearner(parameterVector, learningRateSchedule, momentumRateSchedule, true); //构造leaner方法 trainer = Trainer.CreateTrainer(classifierOutput, loss, pred, new List <Learner>() { leaner }); }
public void WithNoDifferentFAMTypeReturnsTrue() { //arrange var ldObj = new Learner() { LearningDeliveries = new List <LearningDelivery>() { new LearningDelivery() { LearnAimRef = "", AimSeqNumber = 1, LearningDeliveryFAMs = new List <LearningDeliveryFAM>() { new LearningDeliveryFAM() { LearnDelFAMCode = "1", LearnDelFAMType = "XYZ", LearnDelFAMDateFrom = new DateTime(2017, 12, 10), LearnDelFAMDateTo = new DateTime(2017, 12, 21) }, new LearningDeliveryFAM() { LearnDelFAMCode = "2", LearnDelFAMType = "BCD", LearnDelFAMDateFrom = new DateTime(2017, 12, 10), LearnDelFAMDateTo = new DateTime(2017, 12, 21) } } } } }; //act var results = _r105RuleValidator.Validate(ldObj); //assert Assert.True(results.IsValid); }
public void WithOverlappingDatesButSameCodes() { //arrange var ldObj = new Learner() { LearningDeliveries = new List <LearningDelivery>() { new LearningDelivery() { LearnAimRef = "", AimSeqNumber = 1, LearningDeliveryFAMs = new List <LearningDeliveryFAM>() { new LearningDeliveryFAM() { LearnDelFAMCode = "1", LearnDelFAMType = "ACT", LearnDelFAMDateFrom = new DateTime(2017, 12, 10), LearnDelFAMDateTo = new DateTime(2017, 12, 21) }, new LearningDeliveryFAM() { LearnDelFAMCode = "1", LearnDelFAMType = "ACT", LearnDelFAMDateFrom = new DateTime(2017, 12, 10), LearnDelFAMDateTo = new DateTime(2017, 12, 21) } } } } }; //act var results = _r105RuleValidator.Validate(ldObj); //assert Assert.True(results.IsValid); }
public static void Go() { // Start with our data Tennis[] data = SampleData.GetTennisData(); // Create the corresponding descriptor var descriptor = Descriptor.Create <Tennis>(); // Choose our generator var generator = new DecisionTreeGenerator(descriptor); generator.SetHint(false); Console.WriteLine($"Using the {generator.GetType().Name}\n"); // Create the model by learning from the data using the generator LearningModel learningModel = Learner.Learn(data, 0.80, 1000, generator); Console.WriteLine(learningModel); // Now we could predict using the learning info's Model. var toPredict = new Tennis() { Outlook = Outlook.Rainy, Temperature = Temperature.Low, Windy = true, // Play = ? - This is what we will predict }; var prediction = learningModel.Model.Predict(toPredict); // And we're spent... Console.WriteLine($"ToPredict: {toPredict}"); Console.WriteLine($"Prediction: Play = {prediction.Play}\n"); Console.WriteLine("Press any key...\n"); Console.ReadKey(); }
public async Task <IActionResult> EnrollByLearner(long courseId, long sessionId) { try { if (courseId == 0) { return(BadRequest(new GenericResult { Response = false, Message = "No course selected" })); } long userId = 0; if (HttpContext.User.Identity is ClaimsIdentity identity) { userId = Convert.ToInt32(identity.FindFirst(ClaimTypes.Name).Value); } var enrollmentStatus = _context.Status.Where(x => x.category == "Enrollment" && x.name == "New").FirstOrDefault(); Learner request = new Learner(); request.courseId = courseId; request.userId = userId; request.enrollmentType = 0; // self enrolled request.isNotify = 0; request.statusId = enrollmentStatus.id; request.createdAt = DateTime.Now; request.updatedAt = DateTime.Now; _context.Learner.Add(request); await _context.SaveChangesAsync(); return(Ok(request)); } catch (Exception e) { return(BadRequest(e)); } }
public static List <Offer> getCurrentRequests(Learner learner) { using (BTProjectEntities db = new BTProjectEntities()) { //if the learner is a vulunteer if (learner.groupId != null) { //he can only watch his req //find the req id var group = ClosedGroup.cToDTO(db.closedGroup_tbl.Where(cg => cg.GroupId == learner.groupId).ToList()); var groupReqId = group[0].reqId; return(Offer.cToDTO(db.request_tbl .Where(r => r.reqId == groupReqId && r.RegisterEndDate > DateTime.Today) //ההרשמה עדייין פתוחה .ToList())); } //מחזיר את ההצעות שעדיין ניתן להרשם אליהם. List <Offer> currentLearning = (Offer.cToDTO(db.request_tbl .Where(r => //בדיקה שכל הפרמטרים של הבקשה מתאימים לתנאי הלומד r.genderid == learner.gender && //המין מתאים r.occuptionId == learner.occuptionId && //העיסוק מתאים r.RegisterEndDate > DateTime.Today && //ההרשמה עדייין פתוחה r.reqEndDate <learner.endDate && //זמן הלימוד המבוקש אינו מתארך מעבר למה שהלומד מעונין r.reqStartDate> learner.startDate//זמן הלימוד המבוקש אינו מתחיל לפני התאריך שממנו והלאה הלומד מעונין ללמוד ).ToList())); //if (currentLearning.Count > 0) // return currentLearning; //else // return return(currentLearning); } }
public async Task <UpsertResult <Guid> > UpsertLearnerAsync(Learner learner, CancellationToken cancellationToken) { bool created; Guid key; var existingLearner = await _dbContext.Learners .Where(x => x.Ukprn == learner.Ukprn && x.LearnRefNumber == learner.LearnRefNumber) .SingleOrDefaultAsync(cancellationToken); if (existingLearner == null) { if (learner.Id == Guid.Empty) { learner.Id = new Guid(); } _dbContext.Learners.Add(learner); key = learner.Id; created = true; } else { existingLearner.UpdateFrom(learner); key = existingLearner.Id; created = false; } await _dbContext.CommitAsync(cancellationToken); return(new UpsertResult <Guid> { Created = created, Key = key, }); }
public void FundModel35_Returns_OneItemList() { var parameter = new Learner() { LearningDeliveries = new List <LearningDelivery>() { new LearningDelivery() { FundModel = 36, LearnStartDate = new DateTime(2016, 05, 5) }, new LearningDelivery() { FundModel = 35, LearnStartDate = new DateTime(2017, 09, 5) } } }; var actual = _rule.Evaluate(parameter); Assert.Single(actual); }
public void FundModelNot35_Returns_ZeroList() { var parameter = new Learner() { LearningDeliveries = new List <LearningDelivery>() { new LearningDelivery() { FundModel = 36, LearnStartDate = new DateTime(2016, 05, 5) }, new LearningDelivery() { FundModel = 39, LearnStartDate = new DateTime(2017, 05, 5) } } }; var actual = _rule.Evaluate(parameter); Assert.Empty(actual); }
public ActionResult Index(Learner lc) { Learning_strategy_class obj = new Learning_strategy_class(); try { Learner l = obj.Get_all_learners().Where(x => x.learner_pass == lc.learner_pass.ToString() && x.learner_email == lc.learner_email).First(); if (!l.learner_id.Equals(null)) { Session["id"] = l.learner_id; Session["name"] = l.learner_name; return(RedirectToAction("Index", "Home")); } else { ViewData["Message"] = "Login failed!!! invalid credentials"; } } catch { ViewData["Message"] = "Login failed!!! invalid credentials"; } return(View()); }
internal static Learner Map(this LearnerModel model) { var learner = new Learner { Id = model.Id, ApprenticeshipIncentiveId = model.ApprenticeshipIncentiveId, ApprenticeshipId = model.ApprenticeshipId, Ukprn = model.Ukprn, ULN = model.UniqueLearnerNumber, LearningPeriods = model.LearningPeriods.Map(model.Id), DaysInLearnings = model.DaysInLearnings.Map(model.Id) }; learner.SubmissionFound = model.SubmissionData.SubmissionFound; learner.LearningFound = model.SubmissionData.LearningData.LearningFound; learner.SubmissionDate = model.SubmissionData.SubmissionDate; learner.StartDate = model.SubmissionData.LearningData.StartDate; learner.HasDataLock = model.SubmissionData.LearningData.HasDataLock; learner.InLearning = model.SubmissionData.LearningData.IsInlearning; learner.RawJSON = model.SubmissionData.RawJson; return(learner); }
public IActionResult AddUpdateLearnerAppraisal(long userId, Learner request) { try { var learner = _context.Learner.Where(x => x.userId == userId && x.courseId == request.courseId).FirstOrDefault(); if (learner == null) { return(BadRequest(_NotFound)); } learner.overallRating = request.overallRating; _context.SaveChanges(); var output = _learnerRepository.AddLearnerAppraisal(learner.id, request); var hey = JsonConvert.SerializeObject(output); return(Ok(output)); } catch (Exception e) { return(BadRequest(e)); } }
public IActionResult UpdateLearnerAssessment(long learnerId, Learner request) { try { var output = _learnerRepository.AssessLearner(learnerId, request); if (output == true) { return(Ok(new GenericResult { Response = true, Message = "Learner assessment completed" })); } else { return(NotFound(new GenericResult { Response = false, Message = "Learner not found" })); } } catch (Exception e) { return(BadRequest(e)); } }
public static async Task <IActionResult> RunHttp( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); LearnerRequest request = JsonConvert.DeserializeObject <LearnerRequest>(requestBody); BlobApi blobApi = await BlobApi.Instance; ContestResponse contest = await blobApi.GetContest(request.CustomerId, request.CollectionName); CloudSkillApi cloudSkillApi = await CloudSkillApi.Instance; Learner learnerReponse = await cloudSkillApi.AddLearnerAsync(contest.ContestId, request.LearnerId); return(new OkObjectResult(contest.CollectionUrl)); } catch (Exception ex) { log.LogError(string.Format("Error in AddLearnerToChallengeFromHttp: {0}", ex.Message)); return(new BadRequestObjectResult(ex.Message)); } }
private void LearnerTester(string input, string output, string rewards) { Learner learner = new Learner(); bool firstRun = true; // talk for (int i = 0; i < input.Length; i++) { if (firstRun) { firstRun = false; } else { learner.RegisterReward(rewards.Substring(i, 1)); } // reply string reply = learner.Answer(input.Substring(i, 1)); Assert.AreEqual(output.Substring(i, 1), reply, "Unexpected answer in step " + (i + 1)); } }
public void Linear_Regression_Learner_Test() { var datum = new[] { new { X = 1.0, Y = 1.0 }, new { X = 2.0, Y = 2.0 }, new { X = 3.0, Y = 1.3 }, new { X = 4.0, Y = 3.75 }, new { X = 5.0, Y = 5.25 } }; var d = Descriptor.New("DATUM") .With("X").As(typeof(double)) .Learn("Y").As(typeof(double)); var generator = new LinearRegressionGenerator() { Descriptor = d }; var model = Learner.Learn(datum, 0.9, 5, generator); Assert.True(0.8 >= model.Accuracy); }
private void treeList2_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e) { if (treeList2.FocusedNode != null) { mainFormLearner = new Learner((string)treeList2.FocusedNode[1], GlobalProperties.loggedOnUserDivison); txtName.Text = mainFormLearner.Name; txtSurname.Text = mainFormLearner.Surname; txtUpdateID.Text = mainFormLearner.Id; datDOB.DateTime = mainFormLearner.DateOfBirth; } }
public Enrolment Enrol(Learner student) { var enrolment = new Enrolment(student, this); Enrolments.Add(enrolment); return enrolment; }
public Enrolment(Learner learner, CourseDelivery courseRun) { Learner = learner; CourseRun = courseRun; }
private double calculateError(DataSet ds, Learner l) { double error = 0.0; for (int i = 0; i < ds.examples.Count; i++) { Example e = ds.getExample(i); if (!(l.predict(e).Equals(e.targetValue()))) { error = error + exampleWeights[i]; } } return error; }
private void adjustExampleWeights(DataSet ds, Learner l, double error) { double epsilon = error / (1.0 - error); for (int j = 0; j < ds.examples.Count; j++) { Example e = ds.getExample(j); if ((l.predict(e).Equals(e.targetValue()))) { exampleWeights[j] = exampleWeights[j] * epsilon; } } exampleWeights = Util.normalize(exampleWeights); }