def stat1(self): sql_users = "SELECT UserName, DNum FROM USER" self.sesh.cursor.execute(sql_users) result = self.sesh.cursor.fetchall() if (univutil.table_format(result) == 0): print("No users") input() return choice = input("Select index number: ") while (True): try: username, dnum = result[int(choice) - 1]["UserName"], result[int(choice) - 1]["DNum"] break except: print("Invalid index") input() return self.sesh.cursor.execute("DROP VIEW IF EXISTS FRIENDS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS SUBS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS FRIENDS_SUBS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS COMMON_INTS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS COMMON_SGS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS SgUrls;") self.sesh.cursor.execute("DROP VIEW IF EXISTS FRIENDS_SG;") self.sesh.cursor.execute( "CREATE VIEW FRIENDS AS (SELECT Friend2Name, Friend2DNum FROM FRIENDS_WITH WHERE Friend1Name = %s AND Friend2DNum = %s);", (username, dnum)) self.sesh.cursor.execute( "CREATE VIEW SUBS AS (SELECT UserName, DNum, SubName FROM HAS_INTEREST_IN WHERE UserName = %s AND DNum = %s);", (username, dnum)) self.sesh.cursor.execute( "CREATE VIEW SgUrls AS (SELECT UserName, DNum, SgUrl FROM PARTICIPATES_IN WHERE UserName = %s AND DNum = %s);", (username, dnum)) self.sesh.cursor.execute( "CREATE VIEW FRIENDS_SUBS AS (SELECT UserName, DNum, SubName from HAS_INTEREST_IN JOIN FRIENDS ON UserName = Friend2Name and DNum = Friend2DNum);" ) self.sesh.cursor.execute( "CREATE VIEW FRIENDS_SG AS (SELECT UserName, DNum, SgUrl from PARTICIPATES_IN JOIN FRIENDS ON UserName = Friend2Name and DNum = Friend2DNum);" ) self.sesh.cursor.execute( "CREATE VIEW COMMON_INTS AS (SELECT UserName, DNum, Count(*) as CommonInterests FROM FRIENDS_SUBS WHERE SubName in (SELECT SubName FROM SUBS) GROUP BY UserName, DNum);" ) self.sesh.cursor.execute( "CREATE VIEW COMMON_SGS AS (SELECT UserName, DNum, Count(*) as CommonStudyGroups FROM FRIENDS_SG WHERE SgUrl in (SELECT SgUrl FROM SgUrls) GROUP BY UserName, DNum);" ) self.sesh.cursor.execute( "SELECT COMMON_INTS.UserName, COMMON_INTS.DNum, CommonInterests, CommonStudyGroups from COMMON_INTS JOIN COMMON_SGS ON COMMON_INTS.UserName = COMMON_SGS.UserName and COMMON_INTS.DNum = COMMON_SGS.DNum;" ) result = self.sesh.cursor.fetchall() if (univutil.table_format(result) == 0): print("Nothing found.") input()
def view_user_posts(self): try: username = input("Enter UserName: "******"Enter DNum: ")) query = "SELECT PostTitle, PostContent, TimeStamp FROM POST WHERE UserName = '******' AND DNum = %d" % (username, dnum) self.sesh.cursor.execute(query) result = self.sesh.cursor.fetchall() univutil.table_format(result) input() except Exception as e: #print(e) univutil.ask_user_action(self.view_user_posts)
def update_usercontrib(self, sg_url): try: os.system("clear") print("User List: ") userquery = "SELECT UserName, DNum, UserSgRole FROM MEMBER_OF WHERE SgUrl = '%s'" % (sg_url) self.sesh.cursor.execute(userquery) result = self.sesh.cursor.fetchall() univutil.table_format(result) roles = ["Member", "Admin"] roleidx = 0 flag = 0 while(flag==0): username = input("Enter username: "******"Enter dnum")) for r in result: if(r["UserName"] == username and r["DNum"] == dnum): flag = 1 if(r["UserSgRole"] == "Admin"): roleidx = 1 if(flag==0): print("No such user in study group, try again!") contrib = -1 while(contrib < 0 or contrib > 10): contrib = int(input("Contribution rating of user [1-10]: ")) contribquery = "UPDATE MEMBER_OF SET UserSgContrib = %s WHERE SgUrl = %s AND UserName = %s AND DNum = %s;" self.sesh.cursor.execute(contribquery, (contrib, sg_url, username, dnum)) selection = 'X' while(selection != 'Y' and selection != 'N'): selection = input(f'Flip user role from {roles[roleidx]} to {roles[1-roleidx]} [Y/N]: ') if(selection == 'Y'): rolequery = "UPDATE MEMBER_OF SET UserSgRole = %s WHERE SgUrl = %s AND UserName = %s AND DNum = %s;" self.sesh.cursor.execute(rolequery, (roles[1-roleidx], sg_url, username, dnum)) self.sesh.cursor.connection.commit() except Exception as e: #print(e) univutil.ask_user_action(self.update_usercontrib) else: print("Contribution updated succesfully!") input() return
def show_friends_details(self): try: name = input("Enter friends name: ") all_users = f'SELECT CONCAT_WS(" ",FName, MName, SName) as Name, UserName, DNum FROM USER WHERE CONCAT(FName, MName, SName) like \'%{name}%\';' self.sesh.cursor.execute(all_users) result = self.sesh.cursor.fetchall() if(univutil.table_format(result) == 0): print("No user with that name") input() except Exception as e: univutil.ask_user_action(self.show_friends_details)
def update_post(self): try: query = "SELECT `PostNumber`, `PostTitle`, `PostContent` FROM `POST` WHERE `UserName` = '%s' AND `DNum` = %d" % (self.current_user[0], self.current_user[1]) self.sesh.cursor.execute(query) result = self.sesh.cursor.fetchall() num_posts = self.sesh.cursor.rowcount if(num_posts == 0): print("Sorry, no posts exist to be updated!") return print(num_posts, "posts currently exist!") post_num = num_posts univutil.table_format(result) while(post_num >= num_posts): post_num = int(input("Enter the post number: ")) print("Post Title: ", result[post_num]["PostTitle"]) print("Post Content: ", result[post_num]["PostContent"]) print("Now, please enter your edited post details") attrP = { "Post Title" : "", "Post Content" : "" } for attribute in attrP: while(attrP[attribute]==""): attrP[attribute] = input(attribute+": ") attrP["Post Title"] += " [edited]" update = "UPDATE `POST` SET `PostTitle` = %s, `PostContent` = %s WHERE `UserName` = %s AND `DNum` = '%s' AND `PostNumber` = '%s'" self.sesh.cursor.execute(update, (attrP["Post Title"], attrP["Post Content"], self.current_user[0], self.current_user[1], post_num)) self.sesh.connection.commit() input() except Exception as e: #print(e) univutil.ask_user_action(self.update_post) return
def delete_post(self): try: query = "SELECT `PostNumber`, `PostTitle`, `PostContent` FROM `POST` WHERE `UserName` = '%s' AND `DNum` = %d" % (self.current_user[0], self.current_user[1]) self.sesh.cursor.execute(query) result = self.sesh.cursor.fetchall() num_posts = self.sesh.cursor.rowcount if(num_posts == 0): print("Sorry, no posts exist to be deleted!") return print(num_posts, "posts currently exist!") univutil.table_format(result) post_num = num_posts while(post_num >= num_posts): post_num = int(input("Enter the post number to delete: ")) print("Are you sure you want to delete the following post: ") print("Post Title: ", result[post_num]["PostTitle"]) print("Post Content: ", result[post_num]["PostContent"]) confirm = 'X' while(confirm != 'Y' and confirm != 'N'): confirm = input("I'm sure, delete [Y/N]: ") if(confirm == 'N'): return sql = "DELETE FROM `POST` " sql += "WHERE UserName = '******' AND DNum = '%s' AND PostNumber = '%s'" % (self.current_user[0], self.current_user[1], post_num) self.sesh.cursor.execute(sql) self.sesh.connection.commit() input() except Exception as e: #print(e) univutil.ask_user_action(self.delete_post) return
def showSgForCourse(self, courseid): self.sesh.cursor.execute("DROP VIEW IF EXISTS `REQ_SG`;") self.sesh.cursor.execute("CREATE VIEW `REQ_SG` AS (SELECT DISTINCT SgUrl FROM `PARTICIPATES_IN` WHERE CourseID = %s);", courseid); self.sesh.cursor.execute("DROP VIEW IF EXISTS `POSS_SG`;") self.sesh.cursor.execute("CREATE VIEW `POSS_SG` AS (SELECT DISTINCT SgUrl FROM `REQ_SG` NATURAL JOIN `STUDY_GROUP` WHERE SgStatus = 'Active' OR SgStatus = 'Planned');") # sg_query = "SELECT SgUrl, AVG(UserSgRating), COUNT(EventNum), COUNT(DISTINCT (UserName, DNum)) \ # FROM `POSS_SG` NATURAL JOIN `MEMBER_OF` NATURAL JOIN `SG_EVENT` \ # GROUP BY SgUrl \ # ORDER BY SgUpdated DESC;" sg_query = "SELECT MEMBER_OF.SgUrl, AVG(UserSgRating), COUNT(EventNum), COUNT(concat(UserName, DNum)) as Members \ FROM `POSS_SG` NATURAL JOIN `MEMBER_OF` LEFT JOIN `SG_EVENT` ON `MEMBER_OF`.SgUrl = `SG_EVENT`.SgUrl \ group by SgUrl;" self.sesh.cursor.execute(sg_query) result = self.sesh.cursor.fetchall() if(univutil.table_format(result) == 0): return 0 input() return result
def enroll(self): # This would be a insertion into the quarternary relationship along with creating study_group if reqd. try: print("You can enroll in a new course (and a study group) or a new study group for a course already being taken.") result = self.sesh.see_all("COURSE") courseid = int(input("CourseID: ")) while(courseid not in [(lambda x: result[x]["CourseID"])(i) for i in range(len(result))]): courseid = int(input("CourseID: ")) coursequery = "INSERT IGNORE INTO `TAKES` (UserName, DNum, CourseID) VALUES (%s, %s, %s);" self.sesh.cursor.execute(coursequery, (self.current_user[0], self.current_user[1], courseid)) # This ignores if entry in TAKES already exists^ print("Available study groups for this course:") values = self.showSgForCourse(courseid) new_sg = 'X' if(values == 0): print("No study groups for this course.") while(True): new_sg = input("Create new study group? [Y/N]") if(new_sg == "N"): return elif(new_sg == "Y"): new_sg = "N" break while(new_sg != 'N' and new_sg != 'E'): new_sg = input("Do you want to create your own study group (N) or join an existing one [E]: ") if(new_sg == "E"): sg = input("Study Group URL: ") while(sg not in [(lambda x: values[x]["SgUrl"])(i) for i in range(len(values))]): sg = input("Enter valid study group URL: ") if(new_sg == 'N'): sg = input("Study Group URL: ") while(True): try: sgcreate = "INSERT INTO STUDY_GROUP (`SgUrl`) VALUES (%s);" except: print("Invalid study group URL. It might already exist.") input() break self.sesh.cursor.execute(sgcreate, sg) sgquery = "INSERT IGNORE INTO `MEMBER_OF` (UserName, DNum, SgUrl, UserSgRole) VALUES (%s, %s, %s, %s);" self.sesh.cursor.execute(sgquery, (self.current_user[0], self.current_user[1], sg, "Admin")) print("Created a new study group succesfully!") print("Available languages for this study group") langquery = "SELECT DISTINCT LangCode FROM PARTICIPATES_IN WHERE SgUrl = '%s'" % (sg) self.sesh.cursor.execute(langquery) result = self.sesh.cursor.fetchall() lfound = 0 if(univutil.table_format(result) == 0): values = self.sesh.see_all("LANGUAGE") while(True): choice = input("Pick language index: ") try: choice = int(choice) langcode = values[choice-1]['LangCode'] lfound = 1 break except: print("Error. Invalid index") while(lfound==0): langcode = input("Language to participate in study_group (langcode) [N for none]: ") if(langcode == "N"): print("Let's find a new study group.") input() return for i in range(self.sesh.cursor.rowcount): if(result[i]["LangCode"]==langcode): lfound=1 query = "INSERT INTO PARTICIPATES_IN VALUES (%s, %s, %s, %s, %s);" self.sesh.cursor.execute(query, (self.current_user[0], self.current_user[1], sg, langcode, courseid)) self.sesh.connection.commit() print("Enrolled in Course: %d as a member of Study Group: %s in language: %s succesfully!" % (courseid, sg, langcode)) input() except Exception as e: #print(e) univutil.ask_user_action(self.enroll) return
def add_course(self): try: os.system("clear") print("ADD NEW COURSE") attributes = { "Course Name: ": "", "Course Org: ": "", "Course Platform: ": "", "Weekly Course Hours: ": "", "Course Duration: ": "" } courseid_sql = "SELECT LAST_INSERT_ID();" coursedifficulty = "" for attribute in attributes: while (attributes[attribute] == ""): attributes[attribute] = input(attribute) while (True): coursedifficulty = input( "Course Difficulty [1. Beginner/2. Intermediate/3. Expert]: " ) if (coursedifficulty in ["1", "2", "3"]): coursedifficulty = ["Beginner", "Intermediate", "Expert"][int(coursedifficulty) - 1] break sql_difficulty = "INSERT INTO `COURSE_DIFFICULTY` (`CourseName`, `CourseOrg`, `CoursePlatform`, `CourseDifficulty`) values (%s, %s, %s, %s);" sql_course = "INSERT INTO `COURSE` (`CourseName`, `CourseOrg`, `CoursePlatform`, `CourseHours`, `CourseDuration`) values (%s, %s, %s, %s, %s);" self.sesh.cursor.execute( sql_difficulty, tuple(attributes.values())[:3] + (coursedifficulty, )) self.sesh.cursor.execute(sql_course, tuple(attributes.values())) self.sesh.cursor.execute(courseid_sql) courseid = self.sesh.cursor.fetchone()['LAST_INSERT_ID()'] while (True): subdub = "" values = self.sesh.see_all("LANGUAGE") choice = input("Pick language index: ") while (True): try: choice = int(choice) lang = values[choice - 1]['LangCode'] break except: print("Error. Invalid index") while (subdub not in ["Native", "Sub", "Dub"]): subdub = input("Language support [Native/Sub/Dub]: ") if (subdub == "Native"): subdub = None sql_lang = "INSERT INTO `USED_FOR` values (%s, %s, %s)" self.sesh.cursor.execute(sql_lang, (lang, courseid, subdub)) cont = input("More languages? [y/n]: ") if (cont == "n"): break while (True): values = self.sesh.see_all("SUBJECT") choice = input("Pick subject index: ") while (True): try: choice = int(choice) subject = values[choice - 1]['SubName'] break except: print("Error. Invalid index") sql_sub = "INSERT INTO `CONTAINS` values(%s, %s)" self.sesh.cursor.execute(sql_sub, (subject, courseid)) cont = input("More subjects? [y/n]: ") if (cont == "n"): break instructor = input("Add course instructor? [y/n]: ") while (instructor == "y"): courseinstructor = "" while (courseinstructor == ""): courseinstructor = input("Instructor Name: ") sql_instructor = "INSERT INTO `COURSE_INSTRUCTOR` values (%s, %s)" self.sesh.cursor.execute(sql_instructor, (courseinstructor, courseid)) if (input("More instructors? [y/n]: ") == "n"): break prereq = input("Add course prerequisites? [y/n]: ") while (prereq == "y"): sql_query = f'SELECT CourseID, CourseName FROM `COURSE`;' self.sesh.cursor.execute(sql_query) result = self.sesh.cursor.fetchall() univutil.table_format(result) choice = input("Select course index: ") while (True): try: choice = int(choice) courseprerequisite = values[choice - 1]['CourseID'] break except: print("Error. Invalid index") courseprerequisite_importance = "" while (courseprerequisite_importance not in ["Helpful", "Essential"]): courseprerequisite_importance = input( "Prequisite importance [Helpful/Essential]: ") sql_instructor = "INSERT INTO `PREREQUISITE` values (%s, %s, %s)" self.sesh.cursor.execute(sql_instructor, (courseid, courseprerequisite, courseprerequisite_importance)) if (input("More preqrequisites? [y/n]: ") == "n"): break self.sesh.connection.commit() except Exception as e: #print(e) univutil.ask_user_action(self.add_course)
def learning_analysis(self, courseid): # define score as: (mean of course rating, performance) # get top and bottom half of TAKES based on this score. # print studygroup information for users in these halves, avg (no. of study groups), avg (no. of users), avg (no. of friends) # print interactivity information for users in these halves, average(usersgrating) average(usersgcontrib) print( "Analysis of Study Group correlation with user satisfaction in course ", courseid) self.sesh.cursor.execute("DROP VIEW IF EXISTS PERFORMANCE;") self.sesh.cursor.execute("DROP VIEW IF EXISTS RATING;") self.sesh.cursor.execute("DROP VIEW IF EXISTS SCORE;") self.sesh.cursor.execute("DROP VIEW IF EXISTS SGUSERS;") self.sesh.cursor.execute("DROP VIEW IF EXISTS SG;") self.sesh.cursor.execute("DROP VIEW IF EXISTS UserSG;") self.sesh.cursor.execute("DROP VIEW IF EXISTS FinUserSG;") self.sesh.cursor.execute("DROP VIEW IF EXISTS UserTaken;") self.sesh.cursor.execute("DROP VIEW IF EXISTS UFrenz;") self.sesh.cursor.execute("DROP VIEW IF EXISTS USgFrenz;") self.sesh.cursor.execute("DROP VIEW IF EXISTS Final;") self.sesh.cursor.execute("DROP VIEW IF EXISTS TempTOP;") self.sesh.cursor.execute("DROP VIEW IF EXISTS TempBOTTOM;") self.sesh.cursor.execute("DROP VIEW IF EXISTS FinalTOP;") self.sesh.cursor.execute("DROP VIEW IF EXISTS FinalBOTTOM;") cc = self.sesh.cursor perfq = "CREATE VIEW PERFORMANCE AS \ (SELECT UserName, DNum, UserPerformance, CourseID FROM TAKES WHERE CourseID = %s); " rateq = "CREATE VIEW RATING AS \ (SELECT UserName, DNum, ReviewRating, CourseID FROM POST WHERE CourseID = %s AND ReviewRating IS NOT NULL);" scoreq = "CREATE VIEW SCORE AS \ (SELECT UserName, DNum, (UserPerformance + ReviewRating)/2 as Points FROM RATING NATURAL JOIN PERFORMANCE WHERE CourseID = %s);" \ #scoreq1 = "SELECT * FROM SCORE;" sguserq = "CREATE VIEW SGUSERS AS \ (SELECT SgUrl, Count(DISTINCT(CONCAT(UserName, DNum))) AS NumUsers FROM MEMBER_OF GROUP BY SgUrl);" sgq = "CREATE VIEW SG AS \ (SELECT UserName, DNum, SgUrl, Points FROM SCORE NATURAL JOIN PARTICIPATES_IN WHERE CourseID = %s); " USGq = "CREATE VIEW UserSG AS \ (SELECT UserName, DNum, SgUrl, Points, UserSgContrib, UserSgRating FROM SG NATURAL JOIN MEMBER_OF);" FinUSGq = "CREATE VIEW FinUserSG AS \ (SELECT UserName, DNum, SgUrl, Points, NumUsers, UserSgContrib, UserSgRating FROM UserSG NATURAL JOIN SGUSERS);" Uq = "CREATE VIEW UserTaken AS \ (SELECT UserName, DNum FROM FinUserSG);" UFrenq = "CREATE VIEW UFrenz AS \ (SELECT UserName, DNum, Friend2Name AS FrName, Friend2DNum AS FrDNum FROM UserTaken JOIN FRIENDS_WITH \ WHERE Friend1Name = UserName AND Friend1DNum = DNum);" USgFrenq = "CREATE VIEW USgFrenz AS \ (SELECT UserName, DNum, SgUrl, AVG(Points) AS Points, NumUsers, UserSgContrib, UserSgRating, COUNT(DISTINCT(CONCAT(FrName, FrDNum))) AS NumFrenz \ FROM UFrenz NATURAL JOIN FinUserSG \ GROUP BY UserName, DNum, SgUrl);" Finalq = "CREATE VIEW Final AS \ (SELECT UserName, DNum, COUNT(SgUrl) AS CountGroups, AVG(Points) as Points, AVG(UserSgContrib) AS AvgContrib, AVG(UserSgRating) AS AvgSgRating, Avg(NumFrenz) AS AvgFrenz \ FROM USgFrenz GROUP BY UserName, DNum);" cc.execute(perfq, courseid) cc.execute(rateq, courseid) cc.execute(scoreq, courseid) cc.execute(sguserq) cc.execute(sgq, courseid) cc.execute(USGq) cc.execute(FinUSGq) cc.execute(Uq) cc.execute(UFrenq) cc.execute(USgFrenq) cc.execute(Finalq) cc.execute("SELECT * FROM Final") result = cc.fetchall() print("Overall Analysis Table:") univutil.table_format(result) num_users = cc.rowcount num_top = int(num_users / 2) num_bottom = num_users - num_top print("Top Half Stats") toptempq = "CREATE VIEW TempTOP AS \ (SELECT * FROM Final ORDER BY Points DESC LIMIT %s);" topq = "CREATE VIEW FinalTOP AS \ (SELECT AVG(CountGroups) AS AvgGroupsT, AVG(Points) AS AvgPointsT, \ AVG(AvgContrib) AS AvgContribT, AVG(AvgSgRating) AS AvgRatingT, AVG(AvgFrenz) AS AvgFrenzT \ FROM TempTOP);" cc.execute(toptempq, num_top) cc.execute(topq) cc.execute("SELECT * FROM FinalTOP") resulttop = cc.fetchall() univutil.table_format(resulttop) print("Bottom Half Stats") bottomtempq = "CREATE VIEW TempBOTTOM AS \ (SELECT * FROM Final ORDER BY Points LIMIT %s);" bottomq = "CREATE VIEW FinalBOTTOM AS \ (SELECT AVG(CountGroups) AS AvgGroupsB, AVG(Points) AS AvgPointsB, \ AVG(AvgContrib) AS AvgContribB, AVG(AvgSgRating) AS AvgRatingB, AVG(AvgFrenz) AS AvgFrenzB \ FROM TempBOTTOM);" cc.execute(bottomtempq, num_bottom) cc.execute(bottomq) cc.execute("SELECT * FROM FinalBOTTOM") resultbottom = cc.fetchall() univutil.table_format(resultbottom) input() return ""
def see_all(self, table): sql_query = f'SELECT * FROM {table};' self.cursor.execute(sql_query) result = self.cursor.fetchall() table_format(result) return result
def see_available(self, table): refine = False while (True): os.system("clear") print("1. See all") print("2. Search by") print("3. Back") choice = input() if (choice == "1"): break elif (choice == "2"): os.system("clear") print("1. Language") print("2. Subject") print("3. Name") print("4. Back") refine = input() if (refine not in ["1", "2", "3", "4"]): print("Invalid choice") input() continue if (refine == "4"): continue break elif (choice == "3"): return elif (choice == "4"): return else: print("Invalid choice") if (not (refine)): self.see_all("COURSE") elif (refine == "1"): values = self.see_all("LANGUAGE") choice = input("Pick language index: ") while True: try: choice = int(choice) lang_code = values[choice - 1]['LangCode'] break except: print("Invalid index.") sql_query = "SELECT CourseName, LangCode FROM `COURSE` NATURAL JOIN `USED_FOR` WHERE LangCode = %s" self.cursor.execute(sql_query, lang_code) result = self.cursor.fetchall() table_format(result) elif (refine == "2"): values = self.see_all("SUBJECT") choice = input("Pick subject index: ") try: choice = int(choice) subname = values[choice - 1]['SubName'] sql_query = "SELECT CourseName, SubName FROM `COURSE` NATURAL JOIN `CONTAINS` WHERE SubName = %s" self.cursor.execute(sql_query, subname) result = self.cursor.fetchall() table_format(result) except: print("Error") elif (refine == "3"): choice = input("Enter course name: ") sql_query = "SELECT * FROM `COURSE` WHERE CourseName LIKE '%{}%'" self.cursor.execute(sql_query.format(choice)) result = self.cursor.fetchall() if (result == 0): print("None found.") table_format(result)