private bool CreateUser(MlContext ctx, out string msg) { if (!VerifyInput(out msg)) { return(false); } var user = ctx.Users.FirstOrDefault(t => t.Username.Equals(Username)); if (user != null) { msg = "User already exists"; return(false); } user = new User { Username = Username }; try { ctx.Users.Add(user); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "User created"; return(true); }
private bool DeleteUser(MlContext ctx, out string msg) { var user = ctx.Users.FirstOrDefault(t => t.Id.Equals(Id)); if (user == null) { msg = "No such user"; return(false); } if (user.IsAdmin) { msg = "Cannot delete an administrative user"; return(false); } try { ctx.Users.Remove(user); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "User deleted"; return(true); }
public void GetWatchedSubmissions(MlContext ctx) { WatchedSubmissions = ctx.Submissions .Where(t => t.IsWatched) .Include(t => t.User) .ToList(); }
public void GetPlannedSubmissions(MlContext ctx, string username) { PlannedSubmissions = ctx.Submissions .Where(t => !t.IsWatched) .Include(t => t.User) .Include(t => t.Votes) .ThenInclude(t => t.User) .ToList(); // Count votes PlannedSubmissions.ForEach(t => t.UpVotes = t.Votes.Count(u => u.Value == 1)); PlannedSubmissions.ForEach(t => t.DownVotes = t.Votes.Count(u => u.Value == -1)); PlannedSubmissions.ForEach(t => t.Seen = t.Votes.Count(u => u.Value == 0)); // Find submissions the current user has voted for if (username != null) { PlannedSubmissions.ForEach(t => t.UserHasVotedFor = t.Votes.Any(u => u.Value == 1 && u.User.Username.Equals(username))); PlannedSubmissions.ForEach(t => t.UserHasVotedAgainst = t.Votes.Any(u => u.Value == -1 && u.User.Username.Equals(username))); PlannedSubmissions.ForEach(t => t.UserHasSeen = t.Votes.Any(u => u.Value == 0 && u.User.Username.Equals(username))); } // Sort by total sum of votes PlannedSubmissions.Sort((j, i) => (i.UpVotes - i.DownVotes - i.Seen) .CompareTo(j.UpVotes - j.DownVotes - j.Seen)); }
private bool VoteSubmission(MlContext ctx, string username, int value, out string msg) { var userId = ctx.Users.First(t => t.Username.Equals(username)).Id; var vote = ctx.Votes.FirstOrDefault(t => t.UserId == userId && t.SubmissionId == Id); // Vote didn't exist if (vote == null) { vote = new Vote { SubmissionId = Id, Value = value, UserId = userId }; // Attempt to add to database try { ctx.Votes.Add(vote); ctx.SaveChanges(); } catch { msg = "An error occurred while adding the vote"; return(false); } msg = "Successfully added vote"; return(true); } // Remove vote from database if (vote.Value == value) { try { ctx.Votes.Remove(vote); ctx.SaveChanges(); msg = "Successfully removed the vote"; return(true); } catch { msg = "An error occurred while adding the vote"; return(false); } } // Attempt to update vote try { vote.Value = value; ctx.Votes.Update(vote); ctx.SaveChanges(); } catch { msg = "An error occurred while adding the vote"; return(false); } msg = "Successfully updated the vote"; return(true); }
public void Train(string trainingFileName, string testingFileName) { if (!File.Exists(trainingFileName)) { Console.WriteLine($"Failed to find training data file ({trainingFileName}"); return; } if (!File.Exists(testingFileName)) { Console.WriteLine($"Failed to find test data file ({testingFileName}"); return; } var trainingDataView = GetDataView(trainingFileName); var options = new MatrixFactorizationTrainer.Options { MatrixColumnIndexColumnName = UserIDEncoding, MatrixRowIndexColumnName = MusicIDEncoding, LabelColumnName = "Label", NumberOfIterations = 20, ApproximationRank = 10, Quiet = false }; var trainingPipeLine = trainingDataView.Transformer.Append(MlContext.Recommendation().Trainers.MatrixFactorization(options)); ITransformer trainedModel = trainingPipeLine.Fit(trainingDataView.DataView); MlContext.Model.Save(trainedModel, trainingDataView.DataView.Schema, ModelPath); Console.WriteLine($"Model saved to {ModelPath}{Environment.NewLine}"); var testingDataView = GetDataView(testingFileName, true); var testSetTransform = trainedModel.Transform(testingDataView.DataView); var modelMetrics = MlContext.Recommendation().Evaluate(testSetTransform); Console.WriteLine($"Matrix Factorization Evaluation:{Environment.NewLine}{Environment.NewLine}" + $"Loss Function: {modelMetrics.LossFunction:F3}{Environment.NewLine}" + $"Mean Absolute Error: {modelMetrics.MeanAbsoluteError:F3}{Environment.NewLine}" + $"Mean Squared Error: {modelMetrics.MeanSquaredError:F3}{Environment.NewLine}" + $"R Squared: {modelMetrics.RSquared:F3}{Environment.NewLine}" + $"Root Mean Squared Error: {modelMetrics.RootMeanSquaredError:F3}"); }
public bool DoAction(MlContext ctx, string username, out string msg) { switch (Action) { case "upvote": return(VoteSubmission(ctx, username, 1, out msg)); case "downvote": return(VoteSubmission(ctx, username, -1, out msg)); case "seen": return(VoteSubmission(ctx, username, 0, out msg)); default: msg = "Invalid action"; return(false); } }
public bool DoAction(MlContext ctx, out string msg) { switch (Action) { case "delete": return(DeleteUser(ctx, out msg)); case "reset": return(ResetPassword(ctx, out msg)); case "create": return(CreateUser(ctx, out msg)); default: msg = "Invalid action"; return(false); } }
public bool DoAction(MlContext ctx, out string msg) { switch (Action) { case "delete": return(DeleteSubmission(ctx, out msg)); case "reset": return(ResetVotes(ctx, out msg)); case "watched": return(ToggleWatched(ctx, out msg)); default: msg = "Invalid action"; return(false); } }
public bool Login(MlContext ctx, out User user, out string msg) { user = null; if (!VerifyInput(out msg)) { return(false); } user = ctx.Users.FirstOrDefault(t => t.Username.Equals(Username)); if (user == null) { msg = "No user by that name"; return(false); } // If user has no password set, treat is as registration if (string.IsNullOrEmpty(user.Secret)) { user.Secret = Utility.Security.HashPassword(Password); try { ctx.Users.Update(user); ctx.SaveChanges(); } catch (Exception ex) { msg = ex.Message; return(false); } msg = "Account created"; return(true); } if (!Utility.Security.VerifyHashedPassword(user.Secret, Password)) { msg = "Invalid login credentials"; return(false); } msg = "Successfully logged in"; return(true); }
private bool ResetVotes(MlContext ctx, out string msg) { var submission = ctx.Submissions.FirstOrDefault(t => t.Id.Equals(Id)); if (submission == null) { msg = "No such submission"; return(false); } try { ctx.Votes.RemoveRange(ctx.Votes.Where(t => t.SubmissionId.Equals(submission.Id))); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "Successfully reset votes"; return(true); }
private bool DeleteSubmission(MlContext ctx, out string msg) { var submission = ctx.Submissions.FirstOrDefault(t => t.Id.Equals(Id)); if (submission == null) { msg = "No such submission"; return(false); } try { ctx.Submissions.Remove(submission); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "Submission deleted"; return(true); }
private bool ResetPassword(MlContext ctx, out string msg) { var user = ctx.Users.FirstOrDefault(t => t.Id.Equals(Id)); if (user == null) { msg = "No such user"; return(false); } try { user.Secret = null; ctx.Users.Update(user); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "User's password reset"; return(true); }
private bool ToggleWatched(MlContext ctx, out string msg) { var submission = ctx.Submissions.FirstOrDefault(t => t.Id.Equals(Id)); if (submission == null) { msg = "No such submission"; return(false); } submission.IsWatched = !submission.IsWatched; try { ctx.Submissions.Update(submission); ctx.SaveChanges(); } catch (Exception e) { msg = e.Message; return(false); } msg = "Successfully toggled watched state"; return(true); }
public void GetSubmissions(MlContext ctx) { Submissions = ctx.Submissions .Include(t => t.User) .ToList(); }
public void GetUsers(MlContext ctx) { Users = ctx.Users.ToList(); }
public bool AddToDb(MlContext ctx, string username, out string msg) { // Extract id from user-provided url int id; try { id = int.Parse(UrlRegex.Match(Url).Groups[2].Value); } catch { msg = "Invalid URL"; return(false); } // Check if the submission already exists. Prevents api spam // I'd use .Any() but it's throwing a lot of `InvalidOperationException: No coercion operator is defined // between types 'System.Int16' and 'System.Boolean'.` exceptions so I went with the gimmicky option due to // time constraints if (ctx.Submissions.Where(t => t.Id == id).ToList().Any()) { msg = "Movie already exists"; return(false); } // Attempt to get movie details from external API Entry entry; try { entry = ApiConnector.AsyncGet(id).Result; if (entry == null) { throw new Exception(); } } catch { msg = "An error occurred while fetching the data"; return(false); } // Attempt to add to database try { ctx.Submissions.Add(new Submission { Id = entry.MalId, UserId = ctx.Users.First(t => t.Username.Equals(username)).Id, Url = Url, Title = entry.Title, Duration = entry.Duration, Episodes = entry.Episodes, ImageUrl = entry.ImageUrl, Score = entry.Score, Type = entry.Type, TrailerUrl = entry.TrailerUrl, Rating = entry.Rating, Synopsis = entry.Synopsis, Genres = entry.Genres.Select(t => t.Name).Aggregate((i, j) => i + ", " + j) }); ctx.SaveChanges(); } catch (Exception ex) { msg = ex.Message; msg = "An exception occurred while processing the request"; return(false); } msg = "Successfully added"; return(true); }