public bool SetRating(int userID, int productID, int rating) { try { ItemRating itemRating = Context.ItemRatings.Where(r => r.UserID == userID && r.ProductID == productID).FirstOrDefault(); if (itemRating == null) { Context.ItemRatings.Add( new ItemRating { UserID = userID, ProductID = productID, Rating = rating }); Context.SaveChanges(); return(true); } else { itemRating.Rating = rating; Context.SaveChanges(); return(true); } } catch { return(false); } }
public async Task<IHttpActionResult> PutItemRating(int id, ItemRating itemRating) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != itemRating.Id) { return BadRequest(); } db.Entry(itemRating).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ItemRatingExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public async Task <IHttpActionResult> PutItemRating(int id, ItemRating itemRating) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != itemRating.Id) { return(BadRequest()); } db.Entry(itemRating).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ItemRatingExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private void LoadRelations(CrowdRecDataContainer container) { Console.WriteLine("Importing relations..."); foreach (var line in File.ReadAllLines(_relationsFile)) { var tokens = line.Split('\t'); if (tokens.Length < 5) { throw new Exception("Expect 5 tab seperated fields."); } string relationType = tokens[0]; string relationId = tokens[1]; double temp; double?timestamp; if (double.TryParse(tokens[2], out temp)) { timestamp = temp; } else { timestamp = null; } ItemRating ir = container.CreateItemRating(relationId, timestamp, tokens[3], tokens[4]); container.Ratings.Add(ir); } }
private void CalculateRatings(List <Menu> menus) { string UserId = User.Identity.GetUserId(); //TODO: rewrite to sql foreach (var menu in menus) { menu.Items = menu.Items.OrderBy(i => i.Order).ToList(); foreach (var item in menu.Items) { // if ratings not calculated (present raiting with id = -1) if (!item.Ratings.Where(ir => ir.Id < 0).Any()) { var AllRatings = item.Ratings.ToList(); item.Ratings.Clear(); // [0] - average rating if (AllRatings.Count > 0) { var avg = AllRatings.Average(r => r.Rate); item.Ratings.Add(new ItemRating() { Id = -1, ItemId = item.Id, Rate = (int)avg }); } else { ItemRating rate = new ItemRating() { Id = -1, ItemId = item.Id, Rate = 0 }; item.Ratings.Add(rate); } // [1] - user rating, undefined if not logined if (UserId != null) { var rate = AllRatings.Where(r => r.UserId == UserId); if (rate.Any()) { item.Ratings.Add(rate.First()); } else { item.Ratings.Add(new ItemRating() { Id = 0, ItemId = item.Id, UserId = UserId, Rate = 0, Date = DateTime.Today }); } } } } } }
public async Task <IHttpActionResult> GetItemRating(int id) { ItemRating itemRating = await db.ItemRatings.FindAsync(id); if (itemRating == null) { return(NotFound()); } return(Ok(itemRating)); }
public IHttpActionResult PostItemRating(ItemRating itemrating) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.ItemRatings.Add(itemrating); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = itemrating.ID }, itemrating)); }
public async Task <IHttpActionResult> PostItemRating(ItemRating itemRating) { string UserId = User.Identity.GetUserId(); if (!ModelState.IsValid || itemRating.UserId != UserId) { return(BadRequest(ModelState)); } db.ItemRatings.Add(itemRating); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = itemRating.Id }, itemRating)); }
public async Task <IHttpActionResult> DeleteItemRating(int id) { ItemRating itemRating = await db.ItemRatings.FindAsync(id); if (itemRating == null) { return(NotFound()); } db.ItemRatings.Remove(itemRating); await db.SaveChangesAsync(); return(Ok(itemRating)); }
public async Task<IHttpActionResult> PostItemRating(ItemRating itemRating) { string UserId = User.Identity.GetUserId(); if (!ModelState.IsValid || itemRating.UserId != UserId) { return BadRequest(ModelState); } db.ItemRatings.Add(itemRating); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = itemRating.Id }, itemRating); }
private void CalculateRatings(List<Menu> menus) { string UserId = User.Identity.GetUserId(); //TODO: rewrite to sql foreach (var menu in menus) { menu.Items = menu.Items.OrderBy(i => i.Order).ToList(); foreach (var item in menu.Items) { // if ratings not calculated (present raiting with id = -1) if (!item.Ratings.Where(ir=> ir.Id < 0).Any()) { var AllRatings = item.Ratings.ToList(); item.Ratings.Clear(); // [0] - average rating if (AllRatings.Count > 0) { var avg = AllRatings.Average(r => r.Rate); item.Ratings.Add(new ItemRating() { Id = -1, ItemId = item.Id, Rate = (int)avg }); } else { ItemRating rate = new ItemRating() { Id = -1, ItemId = item.Id, Rate = 0 }; item.Ratings.Add(rate); } // [1] - user rating, undefined if not logined if (UserId != null) { var rate = AllRatings.Where(r => r.UserId == UserId); if (rate.Any()) { item.Ratings.Add(rate.First()); } else { item.Ratings.Add(new ItemRating() { Id = 0, ItemId = item.Id, UserId = UserId, Rate = 0, Date = DateTime.Today }); } } } } } }
public virtual ItemRating AddRating(string userId, string itemId, float rating, bool isTest = false) { // In case we want to make sure userId and itemIds are not the same we should enable the following lines of code // User u = AddUser(userId + "u"); // Item i = AddItem(itemId + "i"); User u = AddUser(userId); Item i = AddItem(itemId); var ir = new ItemRating(u, i, rating); ir.IsTest = isTest; Ratings.Add(ir); u.Ratings.Add(ir); i.Ratings.Add(ir); return ir; }
public virtual ItemRating AddRating(string userId, string itemId, float rating, bool isTest = false) { // In case we want to make sure userId and itemIds are not the same we should enable the following lines of code // User u = AddUser(userId + "u"); // Item i = AddItem(itemId + "i"); User u = AddUser(userId); Item i = AddItem(itemId); var ir = new ItemRating(u, i, rating); ir.IsTest = isTest; Ratings.Add(ir); u.Ratings.Add(ir); i.Ratings.Add(ir); return(ir); }
public override LibSvm.SvmNode[] GetSvmNode(ItemRating rating) { int followersCount = _container.Tweets[rating].FollowersCount; double followersFeature = followersCount > 1000 ? 1.0 : (double)followersCount / 1000; int friendsCount = _container.Tweets[rating].FriendsCount; double friendsFeature = friendsCount > 1000 ? 1.0 : (double)friendsCount / 1000; var svmNode = new SvmNode[6] { //new SvmNode(Mapper.ToInternalID("RetweetCount"), _container.Tweets[rating].RetweetCount), new SvmNode(Mapper.ToInternalID("Rating"), rating.Rating), new SvmNode(Mapper.ToInternalID("FollowersCount"), followersFeature), new SvmNode(Mapper.ToInternalID("FriendsCount"), friendsFeature), new SvmNode(Mapper.ToInternalID(rating.User.Id), 1), new SvmNode(Mapper.ToInternalID(rating.Item.Id + rating.Domain.Id), 1), new SvmNode(Mapper.ToInternalID(_container.Tweets[rating].MovieUrl), 1), }; return(svmNode); }
private static async Task RunExample() { var apiClient = new CrossingMindsApiClient(); await apiClient.LoginRootAsync(XMindsApiRootEmail, XMindsApiRootPassword); var createdIndividualAccount = await apiClient.CreateIndividualAccountAsync( XMindsApiIndividualAccountEmail, XMindsApiIndividualAccountPassword, Role.Manager, "John", "Doe"); await apiClient.ResendVerificationCodeAsync(XMindsApiIndividualAccountEmail); try { await apiClient.VerifyAsync(XMindsApiIndividualAccountEmail, // Invalid verification code. "00000000"); } catch (AuthErrorException) { // This is expected as we provided invalid verification code. } var createdServiceAccount = await apiClient.CreateServiceAccountAsync( XMindsApiServiceAccountName, XMindsApiServiceAccountPassword, Role.Manager); var listAllAccountsResult = await apiClient.ListAllAccountsAsync(); var createdDatabase = await apiClient.CreateDatabaseAsync( "ExampleDatabase", "Example Database created by .NET SDK Example", "uuid", "uint32"); await apiClient.LoginServiceAsync( XMindsApiServiceAccountName, XMindsApiServiceAccountPassword, createdDatabase.Id); var allDatabases = await apiClient.ListAllDatabasesAsync(1, 10); var currentDatabase = await apiClient.GetCurrentDatabaseAsync(); var currentDatabaseStatus = await apiClient.GetCurrentDatabaseStatusAsync(); #region Users Data and Properties await apiClient.CreateUserPropertyAsync(AgeUserProp, "uint8", false); await apiClient.CreateUserPropertyAsync(SubscriptionsUserProp, "unicode30", true); await apiClient.CreateUserPropertyAsync(ToBeDeletedUserProp, "float", false); var subsciptionsUserProperty = await apiClient.GetUserPropertyAsync(SubscriptionsUserProp); await apiClient.DeleteUserPropertyAsync(ToBeDeletedUserProp); var listAllUserPropertiesResult = await apiClient.ListAllUserPropertiesAsync(); var user1 = new User(new Dictionary <string, object> { { User.UserIdPropName, 1 }, { AgeUserProp, 25 }, { SubscriptionsUserProp, new List <string> { "chanel1", "chanel2" } } }); await apiClient.CreateOrUpdateUserAsync(user1); var getUserResult = await apiClient.GetUserAsync(user1.UserId); user1[AgeUserProp] = 26; var user2 = new User(new Dictionary <string, object> { { User.UserIdPropName, 2 }, { AgeUserProp, 45 }, { SubscriptionsUserProp, new List <string> { "chanel1", "chanel3" } } }); await apiClient.CreateOrUpdateUsersBulkAsync(new List <User> { user1, user2 }); var listAllUsersBulkResult = await apiClient.ListAllUsersBulkAsync(); var listUsersByIdsResult = await apiClient.ListUsersByIdsAsync(new List <object>() { user1.UserId, user2.UserId }); #endregion #region Items Data and Properties await apiClient.CreateItemPropertyAsync(PriceItemProp, "float32", false); await apiClient.CreateItemPropertyAsync(TagsItemProp, "unicode32", true); await apiClient.CreateItemPropertyAsync(ToBeDeletedItemProp, "float", false); var tagsItemProperty = await apiClient.GetItemPropertyAsync(TagsItemProp); await apiClient.DeleteItemPropertyAsync(ToBeDeletedItemProp); var listAllItemPropertiesResult = await apiClient.ListAllItemPropertiesAsync(); var item1 = new Item(new Dictionary <string, object> { { Item.ItemIdPropName, Guid.NewGuid() }, { PriceItemProp, 9.99 }, { TagsItemProp, new List <string> { "family", "sci-fi" } } }); await apiClient.CreateOrUpdateItemAsync(item1); var getItemResult = await apiClient.GetItemAsync(item1.ItemId); item1[PriceItemProp] = 10.99; var item2 = new Item(new Dictionary <string, object> { { Item.ItemIdPropName, Guid.NewGuid() }, { PriceItemProp, 4.49 }, { TagsItemProp, new List <string> { "family" } } }); await apiClient.CreateOrUpdateItemsBulkAsync(new List <Item> { item1, item2 }); var listAllItemsBulkResult = await apiClient.ListAllItemsBulkAsync(); var listItemsByIdsResult = await apiClient.ListItemsByIdsAsync(new List <object>() { item1.ItemId, item2.ItemId }); #endregion #region User Ratings await apiClient.CreateOrUpdateRatingAsync(user1.UserId, item1.ItemId, 5); await apiClient.CreateOrUpdateRatingAsync(user1.UserId, item2.ItemId, 7); await apiClient.CreateOrUpdateRatingAsync(user2.UserId, item1.ItemId, 8); await apiClient.CreateOrUpdateRatingAsync(user2.UserId, item2.ItemId, 9); await apiClient.CreateOrUpdateRatingAsync(user1.UserId, item1.ItemId, 6); var listAllRatingsBulk = await apiClient.ListAllRatingsBulkAsync(); await apiClient.DeleteRatingAsync(user1.UserId, item1.ItemId); var listUserRatingsResult = await apiClient.ListUserRatingsAsync(user1.UserId); await apiClient.CreateOrUpdateUserRatingsBulkAsync(user1.UserId, new List <ItemRating> { new ItemRating(item1.ItemId, 3, DateTime.Now), new ItemRating(item2.ItemId, 4, DateTime.Now), }); var listAllRatingsBulk2 = await apiClient.ListAllRatingsBulkAsync(); await apiClient.DeleteRatingAsync(user1.UserId); var listAllRatingsBulk3 = await apiClient.ListAllRatingsBulkAsync(); await apiClient.CreateOrUpdateRatingsBulkAsync(new List <UserItemRating> { new UserItemRating(user1.UserId, item1.ItemId, 3, DateTime.Now), new UserItemRating(user1.UserId, item2.ItemId, 4, DateTime.Now), new UserItemRating(user2.UserId, item2.ItemId, 1, DateTime.Now), }); var listAllRatingsBulk4 = await apiClient.ListAllRatingsBulkAsync(); await apiClient.CreateOrUpdateRatingsBulkAsync(new List <UserItemRating> { new UserItemRating(user1.UserId, item1.ItemId, 3, DateTime.Now), new UserItemRating(user1.UserId, item2.ItemId, 4, DateTime.Now), new UserItemRating(user2.UserId, item2.ItemId, 1, DateTime.Now), }); #endregion #region Recommendation and Background Tasks var random = new Random(); var items = new List <Item>(); var itemsRatings = new List <ItemRating>(); for (int i = 0; i < 20; ++i) { var item = new Item(new Dictionary <string, object> { { Item.ItemIdPropName, Guid.NewGuid() }, { PriceItemProp, random.NextDouble() * 10.0 }, { TagsItemProp, new List <string> { "family" } } }); items.Add(item); var itemRating = new ItemRating(item.ItemId, random.Next(1, 10), DateTime.Now); itemsRatings.Add(itemRating); } await apiClient.CreateOrUpdateItemsBulkAsync(items); await apiClient.CreateOrUpdateUserRatingsBulkAsync(user1.UserId, itemsRatings); await apiClient.TriggerBackgroundTaskAsync(BackgroundTaskName.MlModelRetrain); // Just required to wait while training task completes to be able to continue the example. await Task.Delay(40000); var listRecentBackgroundTasks = await apiClient.ListRecentBackgroundTasksAsync(BackgroundTaskName.MlModelRetrain); var filters = new List <string> { $"{PriceItemProp}:{RecoFilterOperator.Gt}:5" }; var getRecoItemToItemsResult = await apiClient.GetRecoItemToItemsAsync(item1.ItemId, filters : filters); var getRecoSessionToItemsResult = await apiClient.GetRecoSessionToItemsAsync(filters : filters); var getRecoUserToItemsResult = await apiClient.GetRecoUserToItemsAsync(user1.UserId, filters : filters); #endregion await apiClient.DeleteCurrentDatabaseAsync(); await apiClient.LoginRootAsync(XMindsApiRootEmail, XMindsApiRootPassword); await apiClient.DeleteIndividualAccountAsync(XMindsApiIndividualAccountEmail); await apiClient.DeleteServiceAccountAsync(XMindsApiServiceAccountName); //await apiClient.DeleteCurrentAccountAsync(); apiClient.Dispose(); }
public ItemRatingWithRelations(ItemRating itemRating, Dictionary <string, List <string> > relations) : base(itemRating.User, itemRating.Item, itemRating.Rating) { _relations = relations; }
public XDEnabledItemRating(ItemRating itemRating, Domain targetDomain) : this(itemRating, targetDomain, new List<XDEnabledItemRating>()) { }
public XDEnabledItemRating(ItemRating itemRating, Domain targetDomain, IList<XDEnabledItemRating> auxDomainItemRatings) : base(itemRating.User, itemRating.Item, itemRating.Rating) { TargetDomain = targetDomain; AuxDomainsItemRatings = auxDomainItemRatings; }
public XDEnabledItemRating(ItemRating itemRating, Domain targetDomain) : this(itemRating, targetDomain, new List <XDEnabledItemRating>()) { }
public ItemRatingWithRelations(ItemRating itemRating, Dictionary<string, List<string>> relations) : base(itemRating.User, itemRating.Item, itemRating.Rating) { _relations = relations; }
public ItemRating CreateItemRating(string relationId, double?timestamp, string properties, string linkedEntities) { var ir = new ItemRating(); ir.Id = relationId; ir.Timestamp = timestamp; var jProperties = JObject.Parse(properties); // add general properties jProperties.Properties().ToList().ForEach(p => ir.AddProperty(p.Name, p.Value.ToString())); // try to extract rating from properties try { ir.Rating = float.Parse(jProperties["rating"].ToString()); } catch (Exception) { throw new Exception("Can not find / parse rating in the relation."); } // parse linked entities var jLinkedEntities = JObject.Parse(linkedEntities); // user string user = jLinkedEntities["subject"].ToString(); if (!user.Contains("user")) { throw new Exception("Expect subject of type user in the linked entities."); } string userId = user.Substring(user.IndexOf(':') + 1); User u; if (!Users.TryGetValue(userId, out u)) { Console.WriteLine(string.Format("User with id {0} is not defined in the entities file.", userId)); u = new User(userId); } u.Ratings.Add(ir); // item string item = jLinkedEntities["object"].ToString(); if (!item.Contains("movie") && !item.Contains("item")) { throw new Exception("Expect object of type movie or item in the linked entities."); } string itemId = item.Substring(item.IndexOf(':') + 1); Item i; if (!Items.TryGetValue(itemId, out i)) { Console.WriteLine(string.Format("Item with id {0} is not defined in the entities file.", itemId)); i = new Item(itemId); } i.Ratings.Add(ir); ir.User = u; ir.Item = i; return(ir); }
public XDEnabledItemRating(ItemRating itemRating, Domain domain) : base(itemRating.User, itemRating.Item, itemRating.Rating) { Domain = domain; }
public List <RecommendedItems> RecommendNotPurchased(IList <SequenceSupport> sequenceSupports2Items, IList <UserSequence> userSequences, int recommendationNumber) { /*************************************************************************************/ // Fill User Item Matrix based on support of each rule /*************************************************************************************/ List <string> preRule = sequenceSupports2Items.SelectMany(a => a.sequence[0]).ToList(); List <UserItemRating> userItemRatingMatrix = new List <UserItemRating>(); foreach (UserSequence userSequence in userSequences) { List <string> userPurchasedItems = userSequence.Sequence.SelectMany(a => a).Distinct().ToList(); foreach (string item in userPurchasedItems) { if (preRule.Contains(item)) { IList <SequenceSupport> sequenceSupports = sequenceSupports2Items .Where(a => string.Equals(a.sequence[0][0], item)).ToList(); foreach (SequenceSupport sequenceSupport in sequenceSupports) { string descendantRule = sequenceSupport.sequence[1][0]; //select rules which user has not purchased the rule's descendant if (!userPurchasedItems.Contains(descendantRule)) { if (userItemRatingMatrix.Any(a => a.UserId == userSequence.User && a.ItemId == string.Copy(sequenceSupport.sequence[1][0]))) { userItemRatingMatrix.FirstOrDefault(a => a.UserId == userSequence.User && a.ItemId == string.Copy(sequenceSupport.sequence[1][0])).Rating += sequenceSupport.support; } else { UserItemRating userItemRating = new UserItemRating(); userItemRating.UserId = userSequence.User; userItemRating.ItemId = string.Copy(sequenceSupport.sequence[1][0]); userItemRating.Rating = sequenceSupport.support; userItemRatingMatrix.Add(userItemRating); } } } } } } System.Diagnostics.Debug.WriteLine("Step 1: " + DateTime.Now.TimeOfDay + " - UserItemMatrix created"); /*************************************************************************************/ // Normalized UserItemRatingMatrix with unit vector method /*************************************************************************************/ IEnumerable <int> users = userItemRatingMatrix.Select(a => a.UserId).Distinct(); List <UserItemRating> userItemRatingMatrixNormalized = new List <UserItemRating>(); List <UserVector> userVectors = new List <UserVector>(); //Find average rating of each user foreach (int user1 in users) { UserVector userVector = new UserVector() { }; userVector.User = user1; IEnumerable <float> ratings = userItemRatingMatrix.Where(a => a.UserId == user1).Select(a => a.Rating); float ratingsPower2 = 0; foreach (float rating in ratings) { ratingsPower2 += (float)Math.Pow(rating, 2.0); } userVector.Vector = (float)Math.Sqrt(ratingsPower2); userVectors.Add(userVector); } //fillup adjusted UserItem matrix foreach (UserItemRating userItemRating in userItemRatingMatrix) { float NormalziedRating = userItemRating.Rating / userVectors.Where(a => a.User == userItemRating.UserId).First().Vector; UserItemRating userItemRatingAdjusted = new UserItemRating(userItemRating.UserId, userItemRating.ItemId, NormalziedRating); userItemRatingMatrixNormalized.Add(userItemRatingAdjusted); } System.Diagnostics.Debug.WriteLine("Step 2: " + DateTime.Now.TimeOfDay + " - UserItemMatrix normalized"); /*************************************************************************************/ // Step 5: Recommend products /*************************************************************************************/ List <RecommendedItems> recomendations = new List <RecommendedItems>() { }; foreach (int user in users) { RecommendedItems recomendation = new RecommendedItems() { }; recomendation.User = user; recomendation.Items = new List <ItemRating>(); IEnumerable <UserItemRating> userItemRatings = userItemRatingMatrixNormalized.Where(a => a.UserId == user).OrderByDescending(a => a.Rating); for (int i = 0; i < recommendationNumber; i++) { UserItemRating userItemRating = userItemRatings.Skip(i).FirstOrDefault(); if (userItemRating != null) { ItemRating itemRating = new ItemRating(userItemRating.ItemId, userItemRating.Rating); recomendation.Items.Add(itemRating); } else { break; } } recomendations.Add(recomendation); } Console.WriteLine("Step 3: " + DateTime.Now.TimeOfDay + " - Recommend products"); return(recomendations); }
public XDEnabledItemRating(ItemRating itemRating, Domain targetDomain, IList <XDEnabledItemRating> auxDomainItemRatings) : base(itemRating.User, itemRating.Item, itemRating.Rating) { TargetDomain = targetDomain; AuxDomainsItemRatings = auxDomainItemRatings; }