/// <summary> /// Serialize the current object to storage /// </summary> /// <param name="predictions">predictions</param> /// <param name="captureNum">integer to make the file unique</param> public void SaveHologram(int captureNum) { var texture = GetComponent <Renderer>().sharedMaterial.GetTexture("_MainTex") as Texture2D; var imageBytes = texture.GetRawTextureData(); var holoObj = new Holo() { confidences = Predictions.Select(p => p.Confidence).ToList(), labels = Predictions.Select(p => p.Label).ToList(), predictedRects = Predictions.Select(p => p.Rect).ToList(), image = imageBytes, cameraToWorldMatrix = camera2WorldFloat, projectionMatrix = projectionFloat, x = transform.position.x, y = transform.position.y, z = transform.position.z, qx = transform.rotation.x, qy = transform.rotation.y, qz = transform.rotation.z, qw = transform.rotation.w, width = texture.width, height = texture.height, headX = HeadPos.x, headY = HeadPos.y, headZ = HeadPos.z }; string path = Path.Combine(Application.persistentDataPath, $"{FilePrefix}{captureNum++}.json"); HoloSaver.Instance.SaveHologram(holoObj, path); }
private async static Task <int> Suns(Predictions predictions) { var querycount = 0; predictions.OnQuery += () => { querycount++; }; // this should cause a query var suns = await predictions.CurrentSuns(); foreach (var s in suns) { Console.WriteLine($"{s.Date} {s.Type}"); } if (suns.Count == 0 || querycount <= 0) { throw new Exception("Invalid query"); } var previousquerycount = querycount; // this round should not cause a query suns = await predictions.CurrentSuns(); if (suns.Count == 0 || querycount != previousquerycount) { throw new Exception("Invalid query"); } return(0); }
public Dictionary <string, double> GetVector(Predictions predictions) { var result = new Dictionary <string, double>(); for (int i = 0; i < predictions.Pictures.Count; i++) { for (var j = 0; j < keyWords.Count; j++) { double tfIdf = 0; ConceptModel model; if (predictions.Pictures[i].PictureData.TryGetValue(keyWords[j], out model)) { tfIdf = model.Value * GetIdf(keyWords[i]); if (!result.ContainsKey(model.Name)) { result.Add(model.Name, tfIdf); } else { result[model.Name] = (result[model.Name] + tfIdf) / 2; } } } } return(result); }
public PredictionResult Predict() { var _MLContext = new MLContext(); var PredictionResultList = new List <Predictions>(); var predictionFunction = _MLContext.Model.CreatePredictionEngine <EnergyUsage, EnergyUsagePrediction>(_trainedModel); var results = new PredictionResult { Center = _center.CenterAbbr, ModelUsed = _center.BestTrainer }; foreach (var fc in _forecast.Periods) { var test = new EnergyUsage() { Center = _center.CenterAbbr, DayOfWeek = (int)fc.startTime.DayOfWeek, Hour = fc.startTime.Hour, AvgTemp = fc.temperature, kWH = 0 }; var prediction = predictionFunction.Predict(test); var pr = new Predictions() { kWH_Usage = prediction.kWH, Hour = test.Hour }; results.Predictions.Add(pr); } return(results); }
public async Task <IActionResult> Edit(int id, [Bind("PredictionID,DayOfPrediction,DateOfPrediction,PlayerName,CasesOfPrediction")] Predictions predictions) { if (id != predictions.PredictionID) { return(NotFound()); } var DateOfRealCase = predictions.DateOfPrediction.DayOfWeek; var DayOfRealCase = predictions.DayOfPrediction; if (DateOfRealCase == DayOfRealCase) { if (ModelState.IsValid) { try { _context.Update(predictions); try { await _context.SaveChangesAsync(); } catch (Exception ex) { if (ex.InnerException.Message.Contains("IndexPredictionDate")) { return(View("UniquePredictionDate", predictions)); } } } catch (DbUpdateConcurrencyException) { if (!PredictionsExists(predictions.PredictionID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } } else { ModelState.AddModelError("DateOfPrediction", "Date of Prediction does not match with its date of week"); } var list = new List <User>(); var playerNames = _context.Players.OrderBy(y => y.Name).Select(x => x.Name).ToList(); foreach (var item in playerNames) { list.Add(new User { Key = item, Display = item }); } predictions.PlayersList = new SelectList(list, "Key", "Display"); return(View(predictions)); }
public NetworkTestingViewModel(NeuralNetwork network, PatternContainer patternContainer) { _network = network; _patternContainer = patternContainer; PredictCommand = new AsyncRelayCommand(async() => await Task.Run(() => Predict())); AddToTrainingSetCommand = new RelayCommand(() => { var dialog = new Views.SavePatternAsDialog { ResponseText = Predictions?.FirstOrDefault(p => p.IsHighest)?.Name ?? string.Empty }; if (dialog.ShowDialog() != true) { return; } var pattern = new Pattern { Name = dialog.ResponseText, Rows = 15, Columns = 10 }; // 0 - black, 1 - white pattern.FillUsing(Pixels.Cast <double>().Select(p => p < 0.5).ToArray()); _patternContainer.Add(pattern); }); }
public PredictionsTests() { var words = new[] { "any", "rage", "ragee", "sage", "raid", "raider" }; var dictionary = new Dictionary(words); _predictions = new Predictions(dictionary); }
private FrameStats ProceedPredictions(Predictions predictions) { var frameStats = new FrameStats(); foreach (var prediction in predictions.predictions) { if (prediction.probability > Threshold) { if (prediction.tagName.Equals("Car")) { frameStats.NbOfCars++; } else if (prediction.tagName.Equals("Person_BadMask")) { frameStats.NbOfPeopleWithOutMask++; frameStats.NbOfPeopleOnImage++; } else if (prediction.tagName.Equals("Person_GoodMask")) { frameStats.NbOfPeopleWithMask++; frameStats.NbOfPeopleOnImage++; } else if (prediction.tagName.Equals("Person_Rear")) { frameStats.NbOfPeopleOnImage++; } } } return(frameStats); }
private async static Task <int> WeatherStation(Predictions predictions) { var querycount = 0; predictions.OnQuery += () => { querycount++; }; // this should cause a query var weather = await predictions.CurrentWeatherStation(); foreach (var w in weather) { Console.WriteLine($"{w.Date} {w.Type} {w.StrValue} {w.Value}"); } if (weather.Count == 0 || querycount != 1) { throw new Exception($"Invalid query : {weather.Count} {querycount}"); } var previousquerycount = querycount; // this round should not cause a query weather = await predictions.CurrentWeatherStation(); if (weather.Count == 0 || querycount != previousquerycount) { throw new Exception($"Invalid query : {weather.Count} {querycount}"); } return(0); }
public IActionResult OnGet() { Predictions = _predictionData.GetAll(); var EntityGames = Predictions.Select(p => p.Game).Distinct().OrderBy(g => g.Order); Games = new List <GameEditModel>(); foreach (var game in EntityGames) { if (Games.All(g => g.Id != game.Id)) { Games.Add(_gameConverter.ToEditModel(game)); } } Users = _userData.GetAll(); TotalScores = new Dictionary <int, int>(); foreach (var user in Users) { var total = 0; foreach (var p in Predictions.Where(p => p.User.Id == user.Id)) { total += _scoreCalculator.Calculate(p.Game.HalftimeScore, p.Game.FulltimeScore, p.HalftimeScore, p.FulltimeScore); } TotalScores.Add(user.Id, total); } return(Page()); }
public void Tip( string league, int round) { Predictions.Clear(); var sched = Context.LeagueSchedule[league][round]; foreach (var game in sched) { var prediction = new PredictedResult(game); // just uses table position to predict var homeRank = GetRank(game.HomeTeam); var awayRank = GetRank(game.AwayTeam); if (homeRank < awayRank) { prediction.HomeWin = true; prediction.AwayWin = false; } else { prediction.HomeWin = false; prediction.AwayWin = true; } Predictions.Add(prediction); } }
public ActionResult PredictionCreator(string predictionType, string subRegionID, string inputPrecipitation, string inputTemperature, string inputCropProduction, string inputCropDestruction, string inputWaterConsumption) { OptagricEntities DB = new OptagricEntities(); List <Predictions> lst = DB.Predictions.ToList(); //ViewBag.SubRegion= DB.SubRegion.Select(x => new { x.ID , x.Name }).Distinct().ToList(); ViewBag.SubRegion = DB.SubRegion.ToList(); if (predictionType != "" && predictionType != null && subRegionID != "" && inputPrecipitation != "" && inputTemperature != "" && inputCropProduction != "" && inputCropDestruction != "" && inputWaterConsumption != "" && subRegionID != null && inputPrecipitation != null && inputTemperature != null && inputCropProduction != null && inputCropDestruction != null && inputWaterConsumption != null) { Predictions ekle = new Predictions { Type = predictionType, IDSubRegion = Convert.ToInt32(subRegionID), PA_Precipitatation = Convert.ToInt32(inputPrecipitation), PA_Temp = Convert.ToInt32(inputTemperature), PU_CropProduction = Convert.ToInt32(inputCropProduction), PK_Disaster = Convert.ToInt32(inputCropDestruction), PT_WaterConsumption = Convert.ToInt32(inputWaterConsumption), PredictionDate = DateTime.Now }; DB.Predictions.Add(ekle); DB.SaveChanges(); return(View()); } else { return(View(lst)); } }
private async void LoadDestinationPredictions(string pLocationText) { PlacesAutocomplete places = new PlacesAutocomplete("AIzaSyCFG2-DEKK7EnqzH_tiiKItD_CpaJYGCUg"); Predictions predictions = await places.GetAutocomplete(pLocationText); DestinationPredictions = predictions.predictions; }
public ActionResult ScalingPredictions() { //string staticSubs =["Satakum-1-2018", "Satakum-2-2018", "Satakum-3-2018", "Satakum-4-2018", "Satakum-5-2018", "Satakum-6-2018"]; string[] staticTypes = new string[] { "Irrigation", "Crop Destruction", "Croped Product" }; Random arr = new Random(); Random scaling = new Random(); //string tempP1 = staticSubs[arr.Next(0, 5)].ToString(); OptagricEntities DB = new OptagricEntities(); for (int i = 0; i < 100; i++) { Predictions eklenecek = new Predictions { IDSubRegion = arr.Next(2, 20), PA_Precipitatation = scaling.Next(0, 100), PA_Temp = scaling.Next(0, 100), PK_Disaster = scaling.Next(0, 100), PT_WaterConsumption = scaling.Next(0, 100), PU_CropProduction = scaling.Next(0, 100), Type = staticTypes[arr.Next(0, 2)].ToString(), PredictionDate = DateTime.Now }; DB.Predictions.Add(eklenecek); DB.SaveChanges(); } return(RedirectToAction("PredictionCreator")); }
private Attachment CreateThumbnailCard(string pictureUrl, Predictions playerInfo, bool includePosition) { List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: pictureUrl)); string title = ""; if (includePosition) { title = $"{playerInfo.Player} ({playerInfo.Age}) - {playerInfo.Position} on {playerInfo.Team}"; } else { title = $"{playerInfo.Player} ({playerInfo.Age}) - {playerInfo.Team}"; } ThumbnailCard plCard = new ThumbnailCard() { Title = title, Subtitle = $"{playerInfo.Season} projected PER: {Math.Round(playerInfo.PER.Value, 2)}", Images = cardImages }; Attachment attachment = plCard.ToAttachment(); return(attachment); }
private void OnSubmit() { var allMatches = this.MatchDays.SelectMany(matchDay => matchDay.Matches); var predictions = new Predictions(this.Name, allMatches, this.Groups); var directory = Path.Combine(GetExecutingAssemblyDirectory(), "Predictions"); Directory.CreateDirectory(directory); var filePath = Path.Combine(directory, $"{this.Name}.json"); var output = JsonConvert.SerializeObject(predictions, Formatting.Indented); try { File.WriteAllText(filePath, output); MessageBox.Show($"Well done {this.Name}, your submission was successful. \n\n" + $"You have successfully pressed the number keys on your computer in a seemingly random order. " + $"Good luck! Let's see if you can beat an octopus.\n\n" + $"Cem and Andy and any other members of the organising committee will be in touch in due course.\n\n" + $"The app will now close.", "All done"); } catch (Exception e) { MessageBox.Show( $"Unable to save your predictions, please contact technical support! (Andy Scott), exception info:\n\n{e.Message}" + $"\n\n The technical bit:\n\n{e.StackTrace}", "Catastrophic Failure!", MessageBoxButton.OK, MessageBoxImage.Error); } Environment.Exit(0); }
private void DrawChart(List <string[]> csvContent) { Dictionary <DateTime, double> csvDictionary = CsvConverter.ConvertToDictionary(csvContent); Predictions.Clear(); DiagrammPainter.UpdateSeries(csvDictionary); }
public async Task <IList <PredictionViewModel> > GetPredictionsForYearAsync(int year) { if (Predictions == null) { Predictions = await GetAllPredictionsAsync(); } return(Predictions.Where(p => p.Year == year).ToList()); }
public async Task <Predictions> GetPlayerInfoByName(string player) { await db.Database.Connection.OpenAsync(); Predictions result = db.PlayersInfo.Where(p => p.Player == player).FirstOrDefault(); db.Database.Connection.Close(); return(result); }
public async Task <ActionResult> DeleteConfirmed(int id) { Predictions predictions = await db.Predictions.FindAsync(id); db.Predictions.Remove(predictions); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public async Task <IList <int> > GetPredictionYearsAsync() { if (Predictions == null) { Predictions = await GetAllPredictionsAsync(); } return(Predictions.OrderByDescending(p => p.Year).Select(p => p.Year).Distinct().ToList()); }
public async Task MarkPlayerAsDraftedByName(string player) { Predictions p = await GetPlayerInfoByName(player); if (p != null) { p.Drafted = 1; db.SaveChanges(); } }
private void HandlePredictions(Dictionary <string, string> restoredPredictions) { if (!Predictions.Contains(restoredPredictions)) { Predictions.Add(restoredPredictions); } DrawPredictions(restoredPredictions); IsDataTransfering = false; }
private async static Task <int> Tides(Predictions predictions) { var querycount = 0; predictions.OnQuery += () => { querycount++; }; // this should cause a query var tides = await predictions.CurrentTides(); foreach (var tide in tides) { Console.WriteLine($"{tide.Date} {tide.Value}"); } if (tides.Count == 0 || querycount != 1) { throw new Exception("Invalid query"); } // this round should not cause a query tides = await predictions.CurrentTides(); if (tides.Count == 0 || querycount != 1) { throw new Exception("Invalid query"); } Console.WriteLine(); var extremes = await predictions.CurrentExtremes(); foreach (var e in extremes) { Console.WriteLine($"{e.Date} {e.Value} {e.Type}"); } if (extremes.Count == 0 || querycount != 2) { throw new Exception($"Invalid query : {extremes.Count} {querycount}"); } // this round should not cause a query extremes = await predictions.CurrentExtremes(); if (extremes.Count == 0 || querycount != 2) { throw new Exception("Invalid query"); } return(0); }
private void SaveFavourites() { PersistenceService.DeleteFavourites().Wait(); var favourites = Predictions.Where(x => x.Favourite) .Select(x => new FavouriteDTO { StockId = x.TrainingSession.Stock.GetUniqueId() }).ToList(); if (favourites.Any()) { PersistenceService.SaveFavourites(favourites).Wait(); } }
protected virtual void OnForecastChange() { ForecastChange.Raise(this); // If track forecasts is enabled, create a trade that we'll watch if (TrackForecasts && Forecast != null) { // Create a prediction with this forecast var trade = new Trade(Bot, Instrument, Forecast.Value, Name, CurrentIndex); var features = new List <Feature>(Features); Predictions.Add(new Prediction(trade, features)); } }
public static async Task <List <PredictionCorrection> > InitPredictions([ActivityTrigger] DataOpParameters pipe, ILogger log) { log.LogInformation($"InitPredictions: Starting"); List <PredictionCorrection> predictionList = new List <PredictionCorrection>(); Predictions predictions = new Predictions(pipe.StorageAccount); PredictionParameters parms = JObject.Parse(pipe.JsonParameters).ToObject <PredictionParameters>(); predictionList = await predictions.GetPredictions(parms.DataConnector); log.LogInformation($"Number of predictions are {predictionList.Count}"); log.LogInformation($"InitPredictions: Complete"); return(predictionList); }
public async Task <ActionResult> Edit([Bind(Include = "PredictionId,UserId,MatchId,LocalGoals,VisitorGoals,Points")] Predictions predictions) { if (ModelState.IsValid) { db.Entry(predictions).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.MatchId = new SelectList(db.Matches, "MatchId", "MatchId", predictions.MatchId); ViewBag.UserId = new SelectList(db.Users, "UserId", "FirstName", predictions.UserId); return(View(predictions)); }
public void SetAccountIDs(StreamReader ids, List <int> labels) { ids.DiscardBufferedData(); ids.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); int i = 0; string id; while ((id = ids.ReadLine()) != null) { Predictions.Add(new Prediction(Convert.ToInt32(id), labels[i])); i++; } }
// GET: Predictions/Details/5 public async Task <ActionResult> Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Predictions predictions = await db.Predictions.FindAsync(id); if (predictions == null) { return(HttpNotFound()); } return(View(predictions)); }
public static Predictions BuildPredictions(XElement predictionsElement) { var result = new Predictions { AgencyTitle = predictionsElement.GetAttributeValue(NextBusName.Title), RouteTag = predictionsElement.GetAttributeValue(NextBusName.RouteTag), RouteTitle = predictionsElement.GetAttributeValue(NextBusName.RouteTitle), RouteCode = predictionsElement.GetAttributeValue(NextBusName.RouteCode), StopTag = predictionsElement.GetAttributeValue(NextBusName.StopTag), StopTitle = predictionsElement.GetAttributeValue(NextBusName.StopTitle), DirectionTitleBecauseNoPredictions = predictionsElement.GetAttributeValue(NextBusName.DirTitleBecauseNoPredictions), }; var directionElements = predictionsElement.Elements(NextBusName.Direction); if (directionElements != Null.OrEmpty) { result.Directions = directionElements.Select(d => new Direction { Title = d.GetAttributeValue(NextBusName.Title), Predictions = d.Elements(NextBusName.Prediction) .Select(BuildPrediction).ToList() }).ToList(); } var messageElements = predictionsElement.Elements(NextBusName.Message); if (messageElements != Null.OrEmpty) { result.Messages = messageElements.Select(m => new Message { Text = m.GetAttributeValue(NextBusName.Text), Priority = m.GetAttributeValue(NextBusName.Priority) }) .ToList(); } return result; }