private async Task <IEnumerable <Player> > GetPlayersByElementTypeAsync(ElementType elementType) { var fplApiClient = new WebApiClient(); StaticResponse staticResponse = await fplApiClient.GetStaticAsync(); var pickedElementIds = new HashSet <int>(); if (staticResponse.CurrentEvent > 0) { TeamResponse teamResponse = await fplApiClient.GetTeamAsync(MyTeamId, staticResponse.CurrentEvent); pickedElementIds = new HashSet <int>(teamResponse.Picks.Select(p => p.ElementId)); } double minimumMinutesRatio = 0.2d; double totalMinutes = staticResponse.CurrentEvent * 90; double minimumMinutesPlayed = totalMinutes * minimumMinutesRatio; Dictionary <int, string> teamNamesById = staticResponse.Teams.ToDictionary( t => t.Id, t => t.Name); IEnumerable <Element> elements = staticResponse.Elements .Where(e => e.ElementType == (int)elementType) .Where(e => e.Minutes >= minimumMinutesPlayed); IEnumerable <Player> players = elements.Select( e => Player.FromElement(e, teamNamesById, pickedElementIds.Contains(e.Id))); return(players); }
public virtual void Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { IEnumerable <string> findTokens = StaticResponse.FindTokens(); string textToSend = ReplaceTokens(StaticResponse, findTokens, eventArgs); chatClient.SendMessage(textToSend); }
static async Task PrintAllExpectedPointsAsync(StaticResponse staticResponse) { var expectedPointsService = new ExpectedPointsService(); // Start with Rondon Element rondon = staticResponse.Elements.Single(e => e.Id == 493); float expectedPoints = await expectedPointsService.CalculateExpectedPointsAsync(rondon); Console.WriteLine($"Expected points: {expectedPoints:N2}"); }
public CommandUsage Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { _timeCommandLastInvoked = DateTimeOffset.UtcNow; IEnumerable <string> findTokens = StaticResponse.FindTokens(); string textToSend = ReplaceTokens(StaticResponse, findTokens, eventArgs); chatClient.SendMessage(textToSend); return(new CommandUsage(eventArgs.ChatUser.DisplayName, DateTimeOffset.UtcNow, this)); }
public StaticPage GetPostByID(int id) { StaticResponse response = new StaticResponse(); var repo = StaticFactory.CreateStaticPageRepository(); var page = repo.GetPageByID(id); if (page != null) { response.Success = true; response.Message = "It worked!"; response.StaticPage = page; } else { response.Success = false; response.Message = "Post not found!"; } return(page); }
public CommandUsage Process(IChatClient chatClient, CommandReceivedEventArgs eventArgs) { TimeSpan timePassedSinceInvoke = DateTimeOffset.UtcNow - _timeCommandLastInvoked; bool userCanBypassCooldown = eventArgs.ChatUser.Role?.EqualsAny(UserRole.Streamer, UserRole.Mod) ?? false; if (userCanBypassCooldown || timePassedSinceInvoke >= Cooldown) { _timeCommandLastInvoked = DateTimeOffset.UtcNow; IEnumerable <string> findTokens = StaticResponse.FindTokens(); string textToSend = ReplaceTokens(StaticResponse, findTokens, eventArgs); chatClient.SendMessage(textToSend); } else { string timeRemaining = (Cooldown - timePassedSinceInvoke).ToExpandingString(); string cooldownMessage = $"That command is currently on cooldown - Remaining time: {timeRemaining}"; chatClient.SendDirectMessage(eventArgs.ChatUser.DisplayName, cooldownMessage); } return(new CommandUsage(eventArgs.ChatUser.DisplayName, DateTimeOffset.UtcNow, this)); }
public async Task <IEnumerable <Player> > GetPickedPlayersAsync() { var fplApiClient = new WebApiClient(); StaticResponse staticResponse = await fplApiClient.GetStaticAsync(); var pickedElementIds = new HashSet <int>(); if (staticResponse.CurrentEvent > 0) { TeamResponse teamResponse = await fplApiClient.GetTeamAsync(MyTeamId, staticResponse.CurrentEvent); pickedElementIds = new HashSet <int>(teamResponse.Picks.Select(p => p.ElementId)); } Dictionary <int, string> teamNamesById = staticResponse.Teams.ToDictionary( t => t.Id, t => t.Name); IEnumerable <Element> pickedElements = staticResponse.Elements.Where(e => pickedElementIds.Contains(e.Id)); IEnumerable <Player> players = pickedElements.Select( e => Player.FromElement(e, teamNamesById, true)); return(players); }
public async Task Make(WebApiClient fplWebApiClient, StaticResponse staticResponse, string path) { IEnumerable <Fixture> fixtures = await fplWebApiClient.GetFixturesAsync(); using (StreamWriter writer = new StreamWriter(File.Create(path))) { writer.WriteLine("event_id,player_id,player_name,difficulty,home,points"); int progress = 0; int max = staticResponse.Elements.Count(); foreach (Element element in staticResponse.Elements) { Console.WriteLine($"Predicting {++progress} of {max}"); ElementSummaryResponse elementResponse = await fplWebApiClient.GetElementSummaryAsync(element.Id); if (elementResponse == null) { continue; } ElementHistoryPast history2017 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2017/18"); ElementHistoryPast history2018 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2018/19"); ElementHistoryPast history2019 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2019/20"); ModelInput fixtureData = new ModelInput() { Isvalid2017 = (history2017 == null) ? 0 : 1, Minutes2017 = (history2017 == null) ? 0 : history2017.Minutes, Points2017 = (history2017 == null) ? 0 : history2017.TotalPoints, Influence2017 = (history2017 == null) ? 0 : float.Parse(history2017.Influence), Creativity2017 = (history2017 == null) ? 0 : float.Parse(history2017.Creativity), Threat2017 = (history2017 == null) ? 0 : float.Parse(history2017.Threat), Isvalid2018 = (history2018 == null) ? 0 : 1, Minutes2018 = (history2018 == null) ? 0 : history2018.Minutes, Points2018 = (history2018 == null) ? 0 : history2018.TotalPoints, Influence2018 = (history2018 == null) ? 0 : float.Parse(history2018.Influence), Creativity2018 = (history2018 == null) ? 0 : float.Parse(history2018.Creativity), Threat2018 = (history2018 == null) ? 0 : float.Parse(history2018.Threat), Isvalid2019 = (history2019 == null) ? 0 : 1, Minutes2019 = (history2019 == null) ? 0 : history2019.Minutes, Points2019 = (history2019 == null) ? 0 : history2019.TotalPoints, Influence2019 = (history2019 == null) ? 0 : float.Parse(history2019.Influence), Creativity2019 = (history2019 == null) ? 0 : float.Parse(history2019.Creativity), Threat2019 = (history2019 == null) ? 0 : float.Parse(history2019.Threat), Playerid = element.Id, Teamid = element.Team, Position = element.ElementType, Selectedby = float.Parse(element.SelectedByPercent), Transfersin = element.TransfersInEvent, Transfersout = element.TransfersOutEvent, Diff = 2F, Home = "0", Value = element.NowCost }; foreach (ElementHistory history in elementResponse.History) { Fixture gwFixture = fixtures.Single(f => f.Id == history.FixtureId); AddPreviousGameweekToInput(fixtureData, history, gwFixture, staticResponse.CurrentEvent); } foreach (ElementFixture fixture in elementResponse.Fixtures.Take(5)) { fixtureData.Diff = fixture.Difficulty; fixtureData.Home = fixture.IsHome ? "1" : "0"; var predictionResult = ConsumeModel.Predict(fixtureData); writer.WriteLine($"{fixture.EventId},{element.Id},{element.FirstName} {element.SecondName},{fixtureData.Diff},{fixtureData.Home},{predictionResult.Score}"); } } } }
public async Task Build(WebApiClient fplWebApiClient, StaticResponse staticResponse, string path) { IEnumerable <Fixture> fixtures = await fplWebApiClient.GetFixturesAsync(); using (StreamWriter writer = new StreamWriter(File.Create(path))) { Event currentEvent = staticResponse.Events.Single(e => e.IsCurrent); int numPreviousGameweeks = currentEvent.Id - 1; string gameweeksHeader = BuildGameweeksHeader(currentEvent.Id); writer.WriteLine($"{PreviousSeason.GetHeaderRow("2017")},{PreviousSeason.GetHeaderRow("2018")},{PreviousSeason.GetHeaderRow("2019")},{gameweeksHeader},playerid,teamid,position,selectedby,transfersin,transfersout,diff,home,value,points"); int progress = 0; //IEnumerable<Element> elementsToProcess = staticResponse.Elements.Take(50); IEnumerable <Element> elementsToProcess = staticResponse.Elements; int max = elementsToProcess.Count(); foreach (Element element in elementsToProcess) { Console.WriteLine($"Processing {++progress} of {max}"); ElementSummaryResponse elementResponse = await fplWebApiClient.GetElementSummaryAsync(element.Id); if (elementResponse == null) { continue; } ElementHistoryPast history2017 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2017/18"); ElementHistoryPast history2018 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2018/19"); ElementHistoryPast history2019 = elementResponse.HistoryPast.SingleOrDefault(hp => hp.SeasonName == "2019/20"); PreviousSeason season2017 = BuildPreviousSeason(history2017); PreviousSeason season2018 = BuildPreviousSeason(history2018); PreviousSeason season2019 = BuildPreviousSeason(history2019); // First pass to build all previous match data by gameweek var previousMatchesByGameweek = new Dictionary <int, PreviousMatch>(); foreach (ElementHistory history in elementResponse.History) { // TODO: add support for multi-match weeks if (previousMatchesByGameweek.ContainsKey(history.Round)) { continue; } Fixture fixture = fixtures.Single(f => f.Id == history.FixtureId); PreviousMatch gameweek = BuildPreviousMatch(history, fixture); previousMatchesByGameweek.Add(history.Round, gameweek); } PreviousMatch gameweekNull = BuildPreviousMatch(null, null); foreach (ElementHistory history in elementResponse.History) { TrainingDataRow row = new TrainingDataRow(); row.Season2017 = season2017; row.Season2018 = season2018; row.Season2019 = season2019; row.PreviousGameweeks = new PreviousMatch[numPreviousGameweeks]; int previousRound = history.Round - 1; for (int round = 0; round < numPreviousGameweeks; ++round) { if (previousMatchesByGameweek.ContainsKey(previousRound)) { row.PreviousGameweeks[round] = previousMatchesByGameweek[previousRound]; } else { row.PreviousGameweeks[round] = gameweekNull; } --previousRound; } Fixture fixture = fixtures.Single(f => f.Id == history.FixtureId); row.AtHome = history.WasHome ? 1 : 0; if (history.WasHome) { row.Difficulty = fixture.HomeTeamDifficulty; } else { row.Difficulty = fixture.AwayTeamDifficulty; } row.Value = history.Value; row.TotalPoints = history.TotalPoints; string seasonsData = $"{row.Season2017},{row.Season2018},{row.Season2019}"; var previousGameweeksBuilder = new StringBuilder(); for (int round = 0; round < numPreviousGameweeks; ++round) { previousGameweeksBuilder.Append(row.PreviousGameweeks[round]); if (round < (numPreviousGameweeks - 1)) { previousGameweeksBuilder.Append(","); } } string gameweeksData = previousGameweeksBuilder.ToString(); string otherData = $"{element.Id},{element.Team},{element.ElementType},{element.SelectedByPercent:F1},{history.TransfersIn:F1},{history.TransfersOut:F1},{row.Difficulty},{row.AtHome},{row.Value:F1},{row.TotalPoints:F1}"; writer.WriteLine($"{seasonsData},{gameweeksData},{otherData}"); } } } }
static async Task Main(string[] args) { var fplWebApiClient = new WebApiClient(); StaticResponse staticResponse = await fplWebApiClient.GetStaticAsync(); //int myTeamId = 1231491; //TeamResponse teamResponse = await fplWebApiClient.GetTeamAsync( // myTeamId, // staticResponse.CurrentEvent); var players = new List <Player>(); foreach (Element element in staticResponse.Elements) { var player = new Player { Name = $"{element.FirstName} {element.SecondName}", MinutesPlayed = element.Minutes, TotalPoints = element.TotalPoints, IctIndex = double.Parse(element.IctIndex), Threat = double.Parse(element.Threat), Goals = element.GoalsScored, Creativity = double.Parse(element.Creativity), Assists = element.Assists, Influence = double.Parse(element.Influence), Bonus = element.Bonus, NowCost = element.NowCost / 10d, Position = (Position)element.ElementType, Team = staticResponse.Teams.Single(t => t.Id == element.Team) }; players.Add(player); } string command = args.Length >= 1 ? args[0] : String.Empty; if (command == "ict-rankings") { PrintIctRankings(players, staticResponse.CurrentEvent); } else if (command == "team-ict-rankings") { PrintTeamIctRankings(players, staticResponse.Teams); } else if (command == "by-position-table") { PrintByPositionTable(players, staticResponse.CurrentEvent); } else if (command == "expected-points") { await PrintAllExpectedPointsAsync(staticResponse); } else if (command == "build-training-data") { string path = args[1]; await BuildTrainingDataAsync(fplWebApiClient, staticResponse, path); } else if (command == "make-predictions") { string path = args[1]; await MakePredictionsAsync(fplWebApiClient, staticResponse, path); } }
static async Task MakePredictionsAsync(WebApiClient fplWebApiClient, StaticResponse staticResponse, string path) { var predictionsMaker = new PredictionsMaker(); await predictionsMaker.Make(fplWebApiClient, staticResponse, path); }
static async Task BuildTrainingDataAsync(WebApiClient fplWebApiClient, StaticResponse staticResponse, string path) { var trainingDataBuilder = new TrainingDataBuilder(); await trainingDataBuilder.Build(fplWebApiClient, staticResponse, path); }
public static BadrResponse ServeStaticFiles(BadrRequest request, UrlArgs args = null) { string resourcePath = null; if (args != null && (resourcePath = args[STATIC_RESOURCE_GROUP_NAME]) != null) { bool reloadFile = true; bool conditionalGet = request.Headers[HttpRequestHeaders.IfModifiedSince] != null; DateTime resourceLastModificationDate = StaticFilesManager.GetLastModificationTimeUtc(resourcePath); DateTime clientLastModificationDate; if(conditionalGet) { if(DateTime.TryParse(request.Headers[Badr.Net.Http.Request.HttpRequestHeaders.IfModifiedSince], out clientLastModificationDate)) { reloadFile = resourceLastModificationDate.CompareTo(clientLastModificationDate) > 0; } } BadrResponse response; if (reloadFile){ response = new StaticResponse(request, MimeMapping.GetMimeMapping(resourcePath)) { Status = HttpResponseStatus._200, BodyBytes = StaticFilesManager.GetFileBytes(resourcePath) }; } else { response = new BadrResponse(request) { Status = HttpResponseStatus._304 }; } response.Headers.Add(HttpResponseHeaders.LastModified, resourceLastModificationDate.ToString("r")); return response; } return null; }