def menu_comment(user, q_n, language): """Displays a menu to interact with the comment(s) of the given question/new. Args: language (dict): The language in which the information will be given. q_n (Question/New): The question/new's comment. user (User): The user that interacts with the comment(s). """ break_while = 0 EXIT = 1 while break_while != EXIT: print(language.get("separator")) print(language.get("coms")) print(q_n.show_comments(language)) print(language.get("selectc")) option = input(language.get("inputtabs")) if option == "1": comment = Client.in_id(language, q_n) break_while1 = 0 while break_while1 != EXIT: print(language.get("separator1")) print(language.get("comse")) print(comment.to_string(language)) print(language.get("commento")) option1 = input(language.get("inputtabs")) if option1 == "1": Rating(user, comment, "like") elif option1 == "2": Rating(user, comment, "dislike") elif option1 == "3": print(language.get("l")) print(comment.watch_users_reactions(language, "like")) elif option1 == "4": print(language.get("dl")) print(comment.watch_users_reactions(language, "dislike")) elif option1 == "5": if user.repeated_fav(comment): print(language.get("fhs")) else: print(language.get("fs")) elif option1 == "6": Client.edit_comment(language, comment, user) elif option1 == "7": if comment.check_user(user): comment.delete_comment() Client.delete_favorite(comment) print(language.get("cod")) break_while1 = EXIT else: print(language.get("np")) elif option1 == "@": #To go to the previous menu break_while1 = EXIT else: print(language.get("i")) print(language.get("separator")) elif option == "@": break_while = EXIT else: print(language.get("i"))
def ladder(self): s = sorted(self.scores, key=self.scores.get) rat = Rating() newR = rat.rate(s) for i in range(4): s[i].rating = round(newR[i]) s[i].games += 1 s[i].points += self.scores[s[i]] s[i].place[i] += 1
def edit_rating(id): if request.method == 'GET': rating = Rating.find(id) return render_template('edit.html', rating=rating) elif request.method == 'POST': rating = Rating.find(id) rating.rating = request.form['edit_rating'] rating.update() logging.info('%s edited rating with id = %d!', rating.movie, rating.id) return redirect('/all')
def fetchRating(user_id, product_id): rating = Rating.get(user_id, product_id) if not rating: rating = 0 avg_rating = Rating.get_avg_rating(product_id) count_rating = Rating.count_individual_rating(user_id) return flask.jsonify({ "rating": rating, "avgRating": avg_rating, "countRating": count_rating }), 200
def __init__( self, name, suburb, service_type, description, ): self._name = name self._suburb = suburb self._service_type = service_type self._description = description self._doctors = [] self._rating = Rating()
def insert_rating(): # 1. check for session & user # 2. check for date, subject, sem, user combo before insert to prevent duplicates # 3. insert # 4. response subject_name = bottle.request.forms.get("subject") date = bottle.request.forms.get("date") sem = bottle.request.forms.get("sem") star = bottle.request.forms.get("star") batch = bottle.request.forms.get("batch") cookie = bottle.request.get_cookie("session") username = sessions.get_username(cookie) # see if user is logged in response_obj = None if username is None: # print "welcome: can't identify user...redirecting to signup" response_obj = { "error":True, "data": "Cannot identify user" } else: isDuplicate = ratings.check_entry(date, subject_name, int(sem), username) if not isDuplicate: subject_rating = Rating(subject_name,date,batch,username,sem,star) subject_rating.set_date(date) result = ratings.insert_Rating(subject_rating) if result == None: response_obj = { "error":True, "data": "Error inserting document" } else: print "inserted document ", result response_obj = { "error":False, "data": "Success" } else: response_obj = { "error":True, "data": "Duplicate entry. Check data" } return json.dumps(response_obj)
def addDummyData(): try: tempData = createDummyData() for user_id, product_id, rating in tempData: User.create(user_id, "*****@*****.**", product_id) Product.create(product_id, '10') Rating.create(user_id, product_id, rating) # add more records for user_id in range(20, 25): User.create(user_id, '*****@*****.**', '12') Rating.create(user_id, '12', random.randint(0, 5)) return "dummy Data has been created", 200 except Exception as e: print(e) return "exception while adding data, check the logs", 403
class HealthCentre(): def __init__( self, name, suburb, service_type, description, ): self._name = name self._suburb = suburb self._service_type = service_type self._description = description self._doctors = [] self._rating = Rating() def get_name(self): return self._name def get_suburb(self): return self._suburb def get_service_type(self): return self._service_type def get_description(self): return self._description def get_doctors(self): return self._doctors # draft 1 def get_average_rating(self): return self._rating.get_average() def record_rating(self, customer, score): self._rating.makeRating(customer, score) def isRated(self, customer): if self._rating.get_previous_rating(customer): return True return False def __str__(self): return 'name:' + self._name + '-suburb:' + self._suburb + '-service_type:' + self._service_type def add_doctor(self, doctor): #print(doctor) if doctor not in self._doctors: self._doctors.append(doctor)
def main(): args = parser.parse_args() print("\nWelcome to BioMonitor!\n\nUse Ctrl+C to quit\nStarting...") CameraConfig.simulation_source = args.source_file CameraConfig.index = args.cam_index IsolatorConfig.debug = args.debug if args.dontwait: args.fps = 99999999 cam = camera.CameraInput(args.fps, MainConfig.buffer_size, bool(args.source_file)) ai = Classifier() ai.load() buffer = cam.get() while buffer: trajectories = ObjectIsolator.isolate(buffer) prepared = ai.prepare(trajectories) predictions = [] for one in prepared: predictions.append(ai.predict(one, args.predictions)) if args.verbose: print( f"\nDetected: \t{len(predictions)}\nContaminated: \t{sum([x.argmax() for x in predictions])}" ) print("Rating:\t\t", Rating.evaluate(predictions)) buffer = cam.get() cam.terminate()
def movie_rate(user): movie_idX = input('Podaj ID filmu: ') rate = int(input("Podaj ocene (1-10): ")) if (rate < 1 or rate > 10): print("Ocena ma byc od 1 do 10") rate = int(input("Podaj ocene (1-10): ")) inBase = False x = Rating(None, movie_idX, rate, user) #tworzenie obiektu klasy rating c.execute("SELECT movie_id, userName FROM rating") for userName, movie_id in c: if (user == userName and movie_idX == movie_id): print("Film juz oceniony") inBase = True if (inBase == False): c.execute( "INSERT INTO rating VALUES(:rate_id,:movie_id,:rate,:userName)", { 'rate_id': x.rate_id, 'movie_id': x.movie_id, 'rate': float(x.rate), 'userName': x.userName }) conn.commit() print("Film Oceniony") sleep(1) os.system('cls') menu(user)
class HealthProvider(HASUser): def __init__(self, username, password, name, profile): HASUser.__init__(self, username, password, 'health_provider', name) self._profile = profile self._healthCentre = [] self._rating = Rating() def make_appointment(self, patient, time, message): new_appointment = Appointment(patient, self, time, message) self._appointments.append(new_appointment) self._appointments.sort(key=lambda x: x.time, reverse=False) # sort appointments return new_appointment def get_avaliable_time_slot(self, date): avaliable_slots = [] for hour in range(0, 24): for minute in [00, 30]: slot = datetime.strptime( date + ' ' + str(hour) + ':' + str(minute), '%Y-%m-%d %H:%M') if slot.strftime("%Y-%m-%d %H:%M") not in [ x.time.strftime("%Y-%m-%d %H:%M") for x in self.get_appointment() ]: avaliable_slots.append(slot.strftime("%H:%M")) return avaliable_slots def get_health_centre(self): pass #todo def get_profile(self): return self._profile def get_average_rating(self): return self._rating.get_average() def record_rating(self, customer, score): self._rating.makeRating(customer, score) def isRated(self, customer): if self._rating.get_previous_rating(customer): return True return False def __str__(self): return HASUser.__str__(self) + ' ' + str(self._healthCentre)
def new_rating(): if request.method == 'GET': return render_template('index.html') elif request.method == 'POST': values = (None, request.form['movie'], request.form['rating']) rating = Rating(*values).create() logging.info('%s created new rating!', rating.movie) return redirect('/all')
def testRating(reader, similarity): dict = {} ratingList = [] for line in reader: ratingValue = int(line['Rating']) if ratingValue in dict: dict[ratingValue] += 1 else: dict[ratingValue] = 1 for ratingValue, count in dict.items(): rating = Rating() rating.ratingValue = ratingValue rating.count = count ratingList.append(rating) ratingCalculator = RatingCalculator() print ratingCalculator.calculateRating(ratingList, similarity)
def generate_f_data(): """Generates fictional data to load the program.""" ch = Channel("Life","This channel is made to talk about life") ch2 = Channel("None", "none") u = User.users[random.choice(list(User.users.keys()))] u2 = User.users[random.choice(list(User.users.keys()))] while u == u2: u2 = User.users[random.choice(list(User.users.keys()))] a = Admin("Valentina", "Vvasquez", "*****@*****.**", "V123") q = Question(u, ch, "What is life?") c = Comment(u2, q, "That is; in fact, a hard question, what would it be?") r = Rating(u2, q, "like") r1 = Rating(a, c, "dislike") q2 = Question(u2, ch, "What is love?") c2 = Comment(u, q2, "The affection you feel for someone; or even, something.") r2 = Rating(a, q2, "dislike") q3 = Question(a, ch, "What is Death?") n = New(a, "The hollow has come!", "That witch has taken my daughthers body.", "Niklaus.", "Drama")
def __init__(self, title='', director='', actors=[], rating_information={}): self.title = title self.director = director self.actors = actors self.rating = Rating(rating_information)
def set_rating(self, user_or_ip, rating): '''Record a user's rating of this package. The caller function is responsible for doing the commit. If a rating is outside the range MAX_RATING - MIN_RATING then a RatingValueException is raised. @param user_or_ip - user object or an IP address string ''' user = None from user import User from rating import Rating, MAX_RATING, MIN_RATING if isinstance(user_or_ip, User): user = user_or_ip rating_query = meta.Session.query(Rating)\ .filter_by(package=self, user=user) else: ip = user_or_ip rating_query = meta.Session.query(Rating)\ .filter_by(package=self, user_ip_address=ip) try: rating = float(rating) except TypeError: raise RatingValueException except ValueError: raise RatingValueException if rating > MAX_RATING or rating < MIN_RATING: raise RatingValueException if rating_query.count(): rating_obj = rating_query.first() rating_obj.rating = rating elif user: rating = Rating(package=self, user=user, rating=rating) meta.Session.add(rating) else: rating = Rating(package=self, user_ip_address=ip, rating=rating) meta.Session.add(rating)
def get_ratings(episode, next_rating_number): global current_scores ratings = {} for person, score in current_scores.items(): new_rating = Rating(episode.number, episode.date, episode.epoch, person, episode.restaurant, score) ratings["_" + str(next_rating_number)] = new_rating next_rating_number += 1 return ratings
def __init__(self, title="", votes="", date="", description="", genres="", released=False): self.title = title self.title_eng = "" self.votes = votes self.date = date self.description = description self.genres = genres self.year = 0 self.rating = Rating() self.url = None self.poster_imdb = None self.poster_fweb = None self.poster_imdb_full = None self.released = released self.runtime = 0
def identify_teams_and_players(self): f = open("Game_Lineup.txt", 'r') i = 0 for line in f: if i == 0: i += 1 else: tokens = line.split() game_id = tokens[0].strip('"') period = int(tokens[1]) player_id = tokens[2].strip('"') team_id = tokens[3].strip('"') status = tokens[4].strip('"') if game_id == self.game_id: if team_id not in self.team_ids: self.add_team(team_id) if period == 0: self.ratings[player_id] = Rating( game_id, team_id, player_id) f.close()
def get_user_ratings_by_sem(self, user, semno): collection = self.rating_collection ratings = collection.find({"user":user, "sem":int(semno)}) modelled_rating_arr = [] for rating in ratings: model_rating = Rating() model_rating.set_name(rating["subject_name"]) model_rating.set_star(rating["star"]) model_rating.set_date(rating["date"]) model_rating.set_batch(rating["batch"]) model_rating.set_username(rating["user"]) model_rating.set_sem(rating["sem"]) modelled_rating_arr.append(model_rating) print modelled_rating_arr return modelled_rating_arr
def test_finding_all_ratings_by_movie_id(): assert Rating.find_all_ratings_by_movie(242, rating_objects) == [3, 4, 2]
def __init__(self, level): """ Initialize the Move Rating """ Rating.__init__(self, level) self.moveCount = 0
def delete_rating(id): rating = Rating.find(id) rating.delete() logging.info('%s deleted rating with id = %d', rating.movie, id) return redirect('/all')
def get_all_ratings(self): collection = self.Rating_collection ratings = collection.find() modelled_rating_arr = [] for rating in ratings: # model data from Rating # print Rating model_rating = Rating() model_rating.set_name(rating["subject_name"]) model_rating.set_star(rating["star"]) model_rating.set_date(rating["date"]) model_rating.set_batch(rating["batch"]) model_rating.set_batch(rating["user"]) model_rating.set_batch(rating["sem"]) # append modelled Rating to array modelled_rating_arr.append(model_rating) return modelled_rating_arr
def menu_new(user, language): """Displays a menu to interact with the new(s). Args: language (dict): The language in which the information will be given. user (User): The user that interacts with the new(s). """ break_while = 0 EXIT = 1 while break_while != EXIT: print(language.get("separator1")) print(language.get("selectn")) option = input(language.get("inputtabs")) if option == "1": if isinstance(user, Admin): new = Client.upload_a_new(language, user) else: print(language.get("np")) break_while = EXIT elif option == "2": if len(New.news): Client.show_news(language) new = Client.in_id(language) new.increase_views() break_while1 = 0 while break_while1 != EXIT: print(language.get("separator1")) print(language.get("ns")) print(new.to_string(language)) print(language.get("newo")) option1 = input(language.get("inputtabs")) if option1 == "1": print(language.get("separator")) comment = Client.comment(language, user, new) print(comment.to_string(language)) elif option1 == "2": if len(new.show_comments(language)): Client.menu_comment(user, new, language) else: print(language.get("ncn")) elif option1 == "3": Rating(user, new, "like") elif option1 == "4": Rating(user, new, "dislike") elif option1 == "5": print(language.get("l")) print(new.watch_users_reactions(language, "like")) elif option1 == "6": print(language.get("dl")) print(new.watch_users_reactions(language, "dislike")) elif option1 == "7": if user.repeated_fav(new): print(language.get("fhs")) else: print(language.get("fs")) elif option1 == "8": Client.edit_new(language, new, user) elif option1 == "9": if new.check_user(user): new.delete_new() print(language.get("nd")) else: print(language.get("np")) break_while1 = EXIT elif option1 == "@": break_while1 = EXIT else: print(language.get("i")) else: print(language.get("nnews")) elif option == "3": print(language.get("separator")) print(language.get("topn")) print(Client.top_news(language)) break_while1 = 0 EXIT = 1 while break_while1 != EXIT: print(language.get("gbp")) option1 = input(language.get("inputtabs")) if option1 == "@": break_while1 = EXIT else: print(language.get("i")) elif option == "@": break_while = EXIT else: print(language.get("i"))
def readRatings(): with open(ratingsFileName, 'r') as ratingsFile: data = ratingsFile.readlines() for line in data: userId, movieId, rating, timestamp = line.split(delimiter) ratings.append(Rating(userId, movieId, rating, timestamp))
def __init__(self): self.rating = Rating() self.history = []
def __init__(self, power, level): """ Initialize the Power Rating """ Rating.__init__(self, level) self.power = power
ai = Classifier() ai.load() buffer = cam.get() timeline = [] ratings = [] while buffer: op = ObjectIsolator.isolate(buffer) preped = ai.prepare(op) predictions = [] for one in preped: predictions.append(ai.predict(one, False)) timeline.append(predictions) r = Rating.evaluate(predictions) ratings.append(r) buffer = cam.get() n = [len(x) for x in timeline] cont = [sum([y.argmax() for y in x]) for x in timeline] ok = np.array(n) - np.array(cont) df = pd.DataFrame({ 'n': n, 'clean': ok, 'contaminated': cont, 'rating': ratings }) df.plot.line() plt.grid()
def get_ratings_by_batch(self, batch): print "in get by batch" collection = self.rating_collection ratings = collection.find({"batchname":batch}) modelled_rating_arr = [] for rating in ratings: # model data from Rating # print Rating model_rating = Rating() model_rating.set_name(rating["subject_name"]) model_rating.set_star(rating["star"]) model_rating.set_date(rating["date"]) model_rating.set_batch(rating["batch"]) model_rating.set_batch(rating["user"]) model_rating.set_batch(rating["sem"]) # append modelled Rating to array modelled_rating_arr.append(model_rating) return modelled_Rating_arr
def get_user_ratings(self, user): collection = self.rating_collection ratings = collection.find({'user' : user}) modelled_rating_arr = [] for rating in ratings: model_rating = Rating() model_rating.set_name(rating["subject_name"]) model_rating.set_star(rating["star"]) model_rating.set_date(rating["date"]) model_rating.set_batch(rating["batch"]) model_rating.set_username(rating["user"]) model_rating.set_sem(rating["sem"]) modelled_rating_arr.append(model_rating) return modelled_rating_arr
def menu_question(user, channel, language): """Displays a menu to interact with the question(s) of the given channel. Args: language (dict): The language in which the information will be given. channel (Channel): The question's channel. user (User): The user that interacts with the question(s). """ break_while = 0 EXIT = 1 while break_while != EXIT: print(language.get("separator")) print (language.get("qs")) print(channel.to_string1(language)) print(language.get("selectq")) option = input(language.get("inputtabs")) if option == "1": question = Client.in_id(language, channel) question.increase_views() break_while1 = 0 while break_while1 != EXIT: print (language.get("separator1")) print (language.get("ps")) print(question.to_string(language)) print(language.get("questiono")) option1 = input(language.get("inputtabs")) if option1 == "1": comment = Client.comment(language, user, question) print(comment.to_string(language)) elif option1 == "2": if len(question.show_comments(language)): Client.menu_comment(user, question, language) else: print(language.get("ncq")) elif option1 == "3": Rating(user, question, "like") elif option1 == "4": Rating(user, question, "dislike") elif option1 == "5": print(language.get("l")) print(question.watch_users_reactions(language, "like")) elif option1 == "6": print(language.get("dl")) print(question.watch_users_reactions(language, "dislike")) elif option1 == "7": if user.repeated_fav(question): print(language.get("fhs")) else: print(language.get("fs")) elif option1 == "8": Client.edit_question(language, question, user) elif option1 == "9": if question.check_user(user): question.delete_question() Client.delete_favorite(question) print(language.get("qd")) else: print(language.get("np")) break_while1 = EXIT elif option1 == "@": break_while1 = EXIT else: print(language.get("i")) elif option == "@": #To go to the previous menu break_while = EXIT else: print(language.get("i"))
def test_finding_average_ratings(): assert Rating.find_average_ratings(242, ratings) == 3.0
def get_ratings(): return render_template('all.html', ratings=Rating.all_ratings())
def test_finding_all_ratings_by_user_id(): assert Rating.find_all_ratings_by_user(196, rating_objects) == [3, 4, 4, 3]
def __init__(self, Moves, playerIsWhite, maxDepth): self.Moves = Moves self.Rating = Rating(Moves) self.playerIsWhite = playerIsWhite self.maxDepth = maxDepth
def principalVariationSearch(self, alpha, beta, history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle, whiteTurn, depth): Moves = self.Moves Rating = self.Rating #if we reach our max search depth, return the best score for the board at that level if (depth == self.maxDepth): bestScore = Rating.evaluate( history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle, depth, self.playerIsWhite) return bestScore, "No Move" if (whiteTurn): moves = Moves.white_legalMoves( history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle) else: moves = Moves.black_legalMoves( history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle) #get the first legal move for the current player. After the moves have been sorted, we assume that the first move is always the best move. moves = self.sanitizeMove(moves, history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle, whiteTurn) #if no legal move for current player, then it must be checkmate or stalemate #if this is player's turn, this is really bad. return -5000 #if this is opponent's turn, this is good. we want this. return 5000 #TODO: Check this AND FIX THIS! if (len(moves) == 0): if (self.playerIsWhite == whiteTurn): return -5000, "No Move" else: return 5000, "No Move" moves = self.sortMoves(moves, history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle, whiteTurn, depth) firstLegalMoveIndex = 0 b = beta bestScore = -math.inf ####################################### throughroughly search firstLegalMove firstLegalMove = moves[firstLegalMoveIndex] try: originalX = int(firstLegalMove[0]) originalY = int(firstLegalMove[1]) newX = int(firstLegalMove[2]) newY = int(firstLegalMove[3]) except (ValueError): raise ValueError( "Error in principalVariationSearch: the first four character of firstLegalMove string must be integer." ) start = (originalX * 8) + originalY end = (newX * 8) + newY #white pieces tempWhiteKing = Moves.makeMove(whiteKing, firstLegalMove, "K") tempWhiteQueen = Moves.makeMove(whiteQueen, firstLegalMove, "Q") tempWhiteBishop = Moves.makeMove(whiteBishop, firstLegalMove, "B") tempWhiteKnight = Moves.makeMove(whiteKnight, firstLegalMove, "H") tempWhiteRook = Moves.makeMove(whiteRook, firstLegalMove, "R") tempWhitePawn = Moves.makeMove(whitePawn, firstLegalMove, "P") #if castling, make castling move if ("WL" in firstLegalMove or "WR" in firstLegalMove): tempWhiteKing, tempWhiteRook = Moves.makeCastlingMove( whiteKing, whiteRook, firstLegalMove) #black pieces tempBlackKing = Moves.makeMove(blackKing, firstLegalMove, "k") tempBlackQueen = Moves.makeMove(blackQueen, firstLegalMove, "q") tempBlackBishop = Moves.makeMove(blackBishop, firstLegalMove, "b") tempBlackKnight = Moves.makeMove(blackKnight, firstLegalMove, "h") tempBlackRook = Moves.makeMove(blackRook, firstLegalMove, "r") tempBlackPawn = Moves.makeMove(blackPawn, firstLegalMove, "p") if ("BL" in firstLegalMove or "BR" in firstLegalMove): tempBlackKing, tempBlackRook = Moves.makeCastlingMove( blackKing, blackRook, firstLegalMove) tempHistory = firstLegalMove ###update castling variables #copy castling variables from previous tempWhiteQueenCastle = whiteQueenCastle tempWhiteKingCastle = whiteKingCastle tempBlackQueenCastle = blackQueenCastle tempBlackKingCastle = blackKingCastle #update castling variable based on the firstLegalMove we made #if firstLegalMove is making white castling move, we can no longer castle again for white if ("WL" in firstLegalMove or "WR" in firstLegalMove): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if firstLegalMove is making black castling move, we can no longer castle again for black elif ("BL" in firstLegalMove or "BR" in firstLegalMove): tempBlackQueenCastle = False tempBlackKingCastle = False else: #if firstLegalMove is moving whiteKing, white queen and king side castle become False if (((1 << start) & whiteKing) != 0): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if firstLegalMove is moving blackKing, black queen and king side castle become False elif (((1 << start) & blackKing) != 0): tempBlackQueenCastle = False tempBlackKingCastle = False #if firstLegalMove is moving white left rook, white queenside castling become False elif (((1 << start) & whiteRook & (1 << 56)) != 0): tempWhiteQueenCastle = False #if firstLegalMove is moving white right rook, white kingside castling become False elif (((1 << start) & whiteRook & (1 << 63)) != 0): tempWhiteKingCastle = False elif (((1 << start) & blackRook & (1 << 0)) != 0): tempBlackQueenCastle = False elif (((1 << start) & blackRook & (1 << 7)) != 0): tempBlackKingCastle = False """ # original algorithm score,bestMove=-self.principalVariationSearch(-b,-alpha,tempHistory,tempWhiteKing,tempWhiteQueen,tempWhiteBishop,tempWhiteKnight,tempWhiteRook,tempWhitePawn,tempBlackKing,tempBlackQueen,tempBlackBishop,tempBlackKnight,tempBlackRook,tempBlackPawn,tempWhiteQueenCastle,tempWhiteKingCastle,tempBlackQueenCastle,tempBlackKingCastle,not whiteTurn,depth+1) """ #Alternate way of writing to original algorithm score, bestMove = self.principalVariationSearch( -b, -alpha, tempHistory, tempWhiteKing, tempWhiteQueen, tempWhiteBishop, tempWhiteKnight, tempWhiteRook, tempWhitePawn, tempBlackKing, tempBlackQueen, tempBlackBishop, tempBlackKnight, tempBlackRook, tempBlackPawn, tempWhiteQueenCastle, tempWhiteKingCastle, tempBlackQueenCastle, tempBlackKingCastle, not whiteTurn, depth + 1) score = -score #In principal variation search, we assume that our first move is the best move, and thus yield the best score. bestScore = self.max(bestScore, score) #can also write bestScore=score alpha = self.max(alpha, score) bestMoveIndex = firstLegalMoveIndex if (alpha >= beta): return alpha, moves[bestMoveIndex] b = alpha + 1 ####################################### simply and quickly search through remaining move to confirm our assumption that firstLegalMove is the best move for i in range(len(moves)): #if current iteration is firstLegalMoveIndex, skip, since we already thoroughly searched this move. if (i == firstLegalMoveIndex): continue #if current iteration is not firstLegalMoveIndex, simply and quickly search through current move. currentMove = moves[i] try: originalX = int(currentMove[0]) originalY = int(currentMove[1]) newX = int(currentMove[2]) newY = int(currentMove[3]) except (ValueError): raise ValueError( "Error in principalVariationSearch: the first four character of currentMove string must be integer." ) start = (originalX * 8) + originalY end = (newX * 8) + newY #white pieces tempWhiteKing = Moves.makeMove(whiteKing, currentMove, "K") tempWhiteQueen = Moves.makeMove(whiteQueen, currentMove, "Q") tempWhiteBishop = Moves.makeMove(whiteBishop, currentMove, "B") tempWhiteKnight = Moves.makeMove(whiteKnight, currentMove, "H") tempWhiteRook = Moves.makeMove(whiteRook, currentMove, "R") tempWhitePawn = Moves.makeMove(whitePawn, currentMove, "P") #if castling, make castling move if ("WL" in currentMove or "WR" in currentMove): tempWhiteKing, tempWhiteRook = Moves.makeCastlingMove( whiteKing, whiteRook, currentMove) #black pieces tempBlackKing = Moves.makeMove(blackKing, currentMove, "k") tempBlackQueen = Moves.makeMove(blackQueen, currentMove, "q") tempBlackBishop = Moves.makeMove(blackBishop, currentMove, "b") tempBlackKnight = Moves.makeMove(blackKnight, currentMove, "h") tempBlackRook = Moves.makeMove(blackRook, currentMove, "r") tempBlackPawn = Moves.makeMove(blackPawn, currentMove, "p") if ("BL" in currentMove or "BR" in currentMove): tempBlackKing, tempBlackRook = Moves.makeCastlingMove( blackKing, blackRook, currentMove) tempHistory = currentMove ###update castling variables #copy castling variables from previous tempWhiteQueenCastle = whiteQueenCastle tempWhiteKingCastle = whiteKingCastle tempBlackQueenCastle = blackQueenCastle tempBlackKingCastle = blackKingCastle #update castling variable based on the currentMove we made #if currentMove is making white castling move, we can no longer castle again for white if ("WL" in currentMove or "WR" in currentMove): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if currentMove is making black castling move, we can no longer castle again for black elif ("BL" in currentMove or "BR" in currentMove): tempBlackQueenCastle = False tempBlackKingCastle = False else: #if currentMove is moving whiteKing, white queen and king side castle become False if (((1 << start) & whiteKing) != 0): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if currentMove is moving blackKing, black queen and king side castle become False elif (((1 << start) & blackKing) != 0): tempBlackQueenCastle = False tempBlackKingCastle = False #if currentMove is moving white left rook, white queenside castling become False elif (((1 << start) & whiteRook & (1 << 56)) != 0): tempWhiteQueenCastle = False #if currentMove is moving white right rook, white kingside castling become False elif (((1 << start) & whiteRook & (1 << 63)) != 0): tempWhiteKingCastle = False elif (((1 << start) & blackRook & (1 << 0)) != 0): tempBlackQueenCastle = False elif (((1 << start) & blackRook & (1 << 7)) != 0): tempBlackKingCastle = False #TODO: check this! """ # original algorithm score,bestMove=-self.principalVariationSearch(-b,-alpha,tempHistory,tempWhiteKing,tempWhiteQueen,tempWhiteBishop,tempWhiteKnight,tempWhiteRook,tempWhitePawn,tempBlackKing,tempBlackQueen,tempBlackBishop,tempBlackKnight,tempBlackRook,tempBlackPawn,tempWhiteQueenCastle,tempWhiteKingCastle,tempBlackQueenCastle,tempBlackKingCastle,not whiteTurn,depth+1) """ #Alternate way of writing to original algorithm score, bestMove = self.principalVariationSearch( -b, -alpha, tempHistory, tempWhiteKing, tempWhiteQueen, tempWhiteBishop, tempWhiteKnight, tempWhiteRook, tempWhitePawn, tempBlackKing, tempBlackQueen, tempBlackBishop, tempBlackKnight, tempBlackRook, tempBlackPawn, tempWhiteQueenCastle, tempWhiteKingCastle, tempBlackQueenCastle, tempBlackKingCastle, not whiteTurn, depth + 1) score = -score if (score > alpha and score < beta): """ # original algorithm score,bestMove=-self.principalVariationSearch(-beta,-score,tempHistory,tempWhiteKing,tempWhiteQueen,tempWhiteBishop,tempWhiteKnight,tempWhiteRook,tempWhitePawn,tempBlackKing,tempBlackQueen,tempBlackBishop,tempBlackKnight,tempBlackRook,tempBlackPawn,tempWhiteQueenCastle,tempWhiteKingCastle,tempBlackQueenCastle,tempBlackKingCastle,not whiteTurn,depth+1) """ #alternate way of writing to original algorithm score, bestMove = self.principalVariationSearch( -beta, -score, tempHistory, tempWhiteKing, tempWhiteQueen, tempWhiteBishop, tempWhiteKnight, tempWhiteRook, tempWhitePawn, tempBlackKing, tempBlackQueen, tempBlackBishop, tempBlackKnight, tempBlackRook, tempBlackPawn, tempWhiteQueenCastle, tempWhiteKingCastle, tempBlackQueenCastle, tempBlackKingCastle, not whiteTurn, depth + 1) score = -score ##For debugging # print("researched") if (score > bestScore): bestMoveIndex = i bestScore = score alpha = self.max(alpha, score) if (alpha >= beta): return alpha, moves[bestMoveIndex] b = alpha + 1 return bestScore, moves[bestMoveIndex]
from cityCode_process import CityProcess from lda import LDAProcess from rating import Rating import numpy as np import matplotlib.pyplot as plt city = CityProcess() rate = Rating() cities = city.loadData() lda = LDAProcess() lda.loadData() n_groups = 5 res1 = rate.rate("topic/topic0.txt") res2 = rate.rate("topic/topic1.txt") res3 = rate.rate("topic/topic2.txt") res4 = rate.rate("topic/topic3.txt") res5 = rate.rate("topic/topic4.txt") res6 = rate.rate("topic/topic5.txt") res7 = rate.rate("topic/topic6.txt") res8 = rate.rate("topic/topic7.txt") res9 = rate.rate("topic/topic8.txt") res10 = rate.rate("topic/topic9.txt") fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.15 opacity = 0.4 res11 = []
def sortMoves(self, moves, history, whiteKing, whiteQueen, whiteBishop, whiteKnight, whiteRook, whitePawn, blackKing, blackQueen, blackBishop, blackKnight, blackRook, blackPawn, whiteQueenCastle, whiteKingCastle, blackQueenCastle, blackKingCastle, whiteTurn, depth): Moves = self.Moves Rating = self.Rating MoveAndScoreList = [] li = [] for i in range(len(moves)): currentMove = moves[i] try: originalX = int(currentMove[0]) originalY = int(currentMove[1]) newX = int(currentMove[2]) newY = int(currentMove[3]) except (ValueError): raise ValueError( "Error in sortMoves: the first four character of currentMove string must be integer." ) start = (originalX * 8) + originalY end = (newX * 8) + newY ##make currentMove #white pieces tempWhiteKing = Moves.makeMove(whiteKing, currentMove, "K") tempWhiteQueen = Moves.makeMove(whiteQueen, currentMove, "Q") tempWhiteBishop = Moves.makeMove(whiteBishop, currentMove, "B") tempWhiteKnight = Moves.makeMove(whiteKnight, currentMove, "H") tempWhiteRook = Moves.makeMove(whiteRook, currentMove, "R") tempWhitePawn = Moves.makeMove(whitePawn, currentMove, "P") #if castling, make castling move if ("WL" in currentMove or "WR" in currentMove): tempWhiteKing, tempWhiteRook = Moves.makeCastlingMove( whiteKing, whiteRook, currentMove) #black pieces tempBlackKing = Moves.makeMove(blackKing, currentMove, "k") tempBlackQueen = Moves.makeMove(blackQueen, currentMove, "q") tempBlackBishop = Moves.makeMove(blackBishop, currentMove, "b") tempBlackKnight = Moves.makeMove(blackKnight, currentMove, "h") tempBlackRook = Moves.makeMove(blackRook, currentMove, "r") tempBlackPawn = Moves.makeMove(blackPawn, currentMove, "p") if ("BL" in currentMove or "BR" in currentMove): tempBlackKing, tempBlackRook = Moves.makeCastlingMove( blackKing, blackRook, currentMove) tempHistory = currentMove ###update castling variables #copy castling variables from previous tempWhiteQueenCastle = whiteQueenCastle tempWhiteKingCastle = whiteKingCastle tempBlackQueenCastle = blackQueenCastle tempBlackKingCastle = blackKingCastle #update castling variable based on the currentMove we made #if currentMove is making white castling move, we can no longer castle again for white if ("WL" in currentMove or "WR" in currentMove): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if currentMove is making black castling move, we can no longer castle again for black elif ("BL" in currentMove or "BR" in currentMove): tempBlackQueenCastle = False tempBlackKingCastle = False else: #if currentMove is moving whiteKing, white queen and king side castle become False if (((1 << start) & whiteKing) != 0): tempWhiteQueenCastle = False tempWhiteKingCastle = False #if currentMove is moving blackKing, black queen and king side castle become False elif (((1 << start) & blackKing) != 0): tempBlackQueenCastle = False tempBlackKingCastle = False #if currentMove is moving white left rook, white queenside castling become False elif (((1 << start) & whiteRook & (1 << 56)) != 0): tempWhiteQueenCastle = False #if currentMove is moving white right rook, white kingside castling become False elif (((1 << start) & whiteRook & (1 << 63)) != 0): tempWhiteKingCastle = False elif (((1 << start) & blackRook & (1 << 0)) != 0): tempBlackQueenCastle = False elif (((1 << start) & blackRook & (1 << 7)) != 0): tempBlackKingCastle = False currentScore = Rating.quickEvaluate( tempHistory, tempWhiteKing, tempWhiteQueen, tempWhiteBishop, tempWhiteKnight, tempWhiteRook, tempWhitePawn, tempBlackKing, tempBlackQueen, tempBlackBishop, tempBlackKnight, tempBlackRook, tempBlackPawn, tempWhiteQueenCastle, tempWhiteKingCastle, tempBlackQueenCastle, tempBlackKingCastle, depth + 1, self.playerIsWhite) moveAndScore = MoveAndScore(currentMove, currentScore) MoveAndScoreList.append(moveAndScore) #Idea: #if this is player's turn, we need to return list sorted in descending order. Because player want to choose the most maximum score move. #If this is opponent's turn, we need to return list sorted in ascending order. Because opponent want to choose the most minimum score move. #if this is player's turn, sort in descending order if (self.playerIsWhite == whiteTurn): MoveAndScoreList.sort(key=self.getScore, reverse=True) #if this is opponent's turn, sort in ascending order else: MoveAndScoreList.sort(key=self.getScore, reverse=False) for i in range(len(MoveAndScoreList)): li.append(MoveAndScoreList[i].move) return li