def main():

    # Print versions
    print('The nltk version is {}.'.format(nltk.__version__))
    print('The scikit-learn version is {}.'.format(sklearn.__version__))

    # Initialise label class
    Label.initialise_class()

    # Functionality based on settings in Main class

    if Main.LOAD_FORMATTED_FILES:
        Main.load_formatted_files()

    elif Main.LOAD_UNFORMATTED_FILES:
        Main.load_unformatted_files()

    # Print info
    if Main.PRINT_EXCEPTION_DATA:
        LegalDoc.print_exception_data()

    if Main.PRINT_JUDGE_DATA:
        Judge.print_all()

    # Labels
    if Main.AUTO_REGEX_LABEL_FILES:
        Label.auto_regex_label_all_files()

    if Main.ADD_MANUAL_LABELS:
        ManualLabels.add_manual_labels()

    if Main.SPLIT_AND_WRITE[0]:
        Label.split_and_write(Main.SPLIT_AND_WRITE[1], Main.SPLIT_AND_WRITE[2],
                              Main.SPLIT_AND_WRITE[3], Main.SPLIT_AND_WRITE[4],
                              Main.SPLIT_AND_WRITE[5])

    if Main.WRITE_LABELS[0]:
        Label.write_labels(Main.WRITE_LABELS[1], Main.WRITE_LABELS[2])

    if Main.PRINT_ALL_LABELS:
        Label.print_all_tree()

    if Main.PRINT_DOCS_BY_REGEX[0]:
        LegalDoc.get_docs_by_regex(Main.REGEX, Main.PRINT_DOCS_BY_REGEX[1])

    # Test code
    if Main.RUN_TEST:
        Main.test()

    if Main.RUN_TEST_A_LEGAL_DOC:
        Main.test_a_legal_doc()

    if Main.RUN_TEST_ALL_LEGAL_DOCS:
        Main.test_all_legal_docs()

    # Print timers
    if Main.PRINT_TIMERS:
        Timer.print_all()

    print("Done!")
Exemple #2
0
    def showdown(self):
        public = self.flop + [self.turn, self.river]
        list1 = self.player1.cards + public
        list2 = self.player2.cards + public
        judge = Judge(list1, list2)
        judge.show()
        winner = judge.compare()

        return winner
Exemple #3
0
    def __init__(self, player=None, computer=None):
        """

        :rtype: object
        """
        self.tokens = [' '] * 9
        self.player_token = player
        self.computer_token = computer
        self.judge = Judge(self)
Exemple #4
0
class Brain(object):
    """This is our min max guy"""
    def __init__(self, scratch_board, token):
        self.scratch_board = scratch_board
        self.scratch_judge = Judge(self.scratch_board)
        self.opponent = { 'O':'X', 'X':'O' }
        self.token = token
        self.best_move = None


    def evaluateMove(self, p=None, board=None, depth=10):
        """Do the min max evaluation"""
        if board is None:
            board = [' '] * 9
        depth += 1
        scores = []
        moves = []
        #First off are we at the endgame state?
        #if ' ' not in board: #The board is full the game must be done.
        self.scratch_judge.board.tokens = board
        winner, state = self.scratch_judge.evalGame()
        if winner is None and state == 'done':
            return 0
        elif winner == self.token:
            return 10 + depth
        elif winner == self.opponent[self.token]:
            return 10 - depth
        #winner and state are both None

        #Now we build up our moves
        for next_move in self.scratch_judge.board.getPossibleMoves():
            #do the move
            self.scratch_judge.board.addToken(p, next_move)
            #get the new game state

            new_board = self.scratch_judge.board.getBoard()
            #re-evaluate
            score = self.evaluateMove(p=self.opponent[p], board=new_board, depth=depth)
            scores.append(score)
            moves.append(next_move)
            self.scratch_judge.board.tokens[next_move] = ' '

        #now fix the messed up min max that cannot work.
        if p == self.token: #Calc the max.
            max_score = max(scores)
            idx = scores.index(max_score)
            self.best_move = moves[idx]
            return scores[idx]
        else: #Calc the min
            min_score = min(scores)
            idx = scores.index(min_score)
            self.best_move = moves[idx]
            return scores[idx]
Exemple #5
0
	def __init__(self,output='sv_output.txt',level=0):
		super().__init__()
		self.intro = '\nStyle🗜Vise\nType "play" to start a new game.\nType "help" or "?" to list commands.\n'
		self.prompt = '>'
		self.file = None
		started = False
		dead = False
		self.space = "      "
		self.nice_comments = ["Nice!","Impressive.","Solid.","Right on.","Now THAT'S typing.","Yes, make it new!"]
		self.mean_comments = ["*Yawn*","Same old same old.","Is that all you got?","...zzzzz..."]
		self.level2name = {
			0:"EASY",
			1:"MEDIUM",
			2:"HARD",
			3:"EXPERT",
			4:"EVIL"
		}
		self.judge = Judge()
		self.started = False
		##
		##adjustable
		self.output_file = open(output,'a+')
		self.starting_level=level
Exemple #6
0
class LeetcodeTest(unittest.TestCase):
    def setUp(self):
        self.judge = Judge()

    def testAllProblems(self):
        leetcodePath = "problems/leetcode/"
        allPyFiles = filter(lambda f: f.endswith(".py"), listdir(leetcodePath))
        pCount = 0
        for f in allPyFiles:
            problemModule = imp.load_source(f[:-3], join(leetcodePath, f))  # filename without .py
            problem = getattr(problemModule, "problem", None)
            if problem:
                self.assertTrue(self.judge.judge(problem()))
                pCount += 1
        print "%i problems verified." % pCount
Exemple #7
0
class LeetcodeTest(unittest.TestCase):
    def setUp(self):
        self.judge = Judge()

    def testAllProblems(self):
        leetcodePath = 'problems/leetcode/'
        allPyFiles = filter(lambda f: f.endswith('.py'), listdir(leetcodePath))
        pCount = 0
        for f in allPyFiles:
            problemModule = imp.load_source(
                f[:-3],  # filename without .py
                join(leetcodePath, f))
            problem = getattr(problemModule, 'problem', None)
            if problem:
                self.assertTrue(self.judge.judge(problem()))
                pCount += 1
        print '%i problems verified.' % pCount
Exemple #8
0
    def initialise(self, a_path, load_state):
        """"
        Initialises a LegalDoc instance from a file
        Separated from __init__ to avoid exceptions in the constructor
        This method must be executed after construction
        :param str a_path: The path to a legal document
        :param bool load_state: Whether the provided path points to a formatted file (true) or an unformatted file (false)
        :rtype: bool
        :return: Whether an instance was successfully generated from file at the provided path
        """

        # Initialise path
        self.__f_path = a_path

        # Get file name
        head, tail = ntpath.split(self.path)
        self.__f_file_name = (tail or ntpath.basename(head))

        # Read in file
        l_file = None
        try:
            l_file = open(self.path)
            l_file_content = l_file.read()
            l_file.close()

        # Handle file error
        except IOError:
            LegalDoc.__note_exception(self.path,
                                      "MAJOR ERROR: Unable to read file", True)
            l_file.close()
            return False

        # Load state from a formatted file
        if load_state:

            # TODO - Timer start
            Timers.s_init_load_state_timer.start()

            l_succeeded = self.__initialise_load_state(l_file_content)

            # TODO - Timer stop
            Timers.s_init_load_state_timer.stop()

            if not l_succeeded:
                LegalDoc.s_file_error += 1
                return False

        # Generate state from an unformatted file
        else:

            # TODO - Timer start
            Timers.s_init_gen_state_timer.start()

            l_succeeded = self.__initialise_generate_state(l_file_content)

            # TODO - Timer stop
            Timers.s_init_gen_state_timer.stop()

            if not l_succeeded:
                return False
            self.__f_punctuation_removed = LegalDoc.REMOVE_PUNCTUATION
            self.__f_lower_case = LegalDoc.TO_LOWER_CASE
            self.__f_stop_words_removed = LegalDoc.REMOVE_STOP_WORDS
            self.__f_stemmed = LegalDoc.APPLY_STEMMING
            self.__f_lemmatized = LegalDoc.APPLY_LEMMATIZATION

        # Note successful initialisation
        LegalDoc.s_successful_init_count += 1

        # Add current LegalDoc to static dictionary of LegalDocs
        LegalDoc.s_legal_doc_dict[self.file_name] = self

        # Create judge and add it to static dictionary of judges
        Judge.add_legal_doc(self)

        return True
Exemple #9
0
class Game(cmd.Cmd):


	def __init__(self,output='sv_output.txt',level=0):
		super().__init__()
		self.intro = '\nStyle🗜Vise\nType "play" to start a new game.\nType "help" or "?" to list commands.\n'
		self.prompt = '>'
		self.file = None
		started = False
		dead = False
		self.space = "      "
		self.nice_comments = ["Nice!","Impressive.","Solid.","Right on.","Now THAT'S typing.","Yes, make it new!"]
		self.mean_comments = ["*Yawn*","Same old same old.","Is that all you got?","...zzzzz..."]
		self.level2name = {
			0:"EASY",
			1:"MEDIUM",
			2:"HARD",
			3:"EXPERT",
			4:"EVIL"
		}
		self.judge = Judge()
		self.started = False
		##
		##adjustable
		self.output_file = open(output,'a+')
		self.starting_level=level


	## internal events

	def special_print(self,text):
		"duplicates input---print and add to file"
		self.output_file.write(text+"\n")
		print(text)


	def restart(self):
		"set a bunch of variables for one attempt of the game. record time."
		self.level = self.starting_level
		#self.old_sents = []
		self.total_points = 0
		self.level_points = 0
		self.points_to_next_level = 10
		self.life = 10
		self.started = False
		self.life_warned = False
		self.dead = False
		## time
		time_string = time.asctime( time.localtime(time.time()) )
		self.output_file.write("\n"+time_string+"\n") 

		## get the old sentences stored in a text file
		try:
			with open('old_sents.txt','r') as f:
				self.old_sents = [s.rstrip("\n") for s in f.readlines()]
		except FileNotFoundError: ## no file yet
			self.old_sents = []
		## now open append
		self.old_sents_file = open('old_sents.txt','a+') 


	def level_banner(self):
		banner="\u001b[32m*****************\u001b[0m\n"
		banner+="\u001b[32mLevel  %d: %s\u001b[0m\n" % (self.level+1,self.level2name[self.level])
		banner+="\u001b[32m*****************\u001b[0m\n"
		return banner


	def scratch_out(self,listoftokens):
		"return a string version with the 'boring' language crossed out"
		newstring = ""
		for token in listoftokens:
			if token.startswith("<"):
				inside = token[1:-1] ## get inside without brackets
				inside = "\u001b[9m%s\u001b[0m" % inside
				newstring+=(" "+inside)
			else:
				newstring+=(" "+token)
		return newstring


	def update_based_on_judgment(self,judgment):
		"""
		update state based on judgement and tell the player about it
		uniqueness is judged before interestingness
		cue other functions to reply to the player's input
		"""
		to_print = ""
		## not interesting
		if judgment['unique']==False:
			to_print+=self.space+"*Yawn*---you have already written:\n"
			to_print+=self.space+'"'+judgment['prevSent']+'"\n'
			to_print+=self.space+"💖-1\n"
			self.life-=1
		## not interesting
		elif judgment['interesting']==False:
			to_print+=self.space+self.scratch_out(judgment['markedUp'])+"\n"
			to_print+=self.space+random.choice(self.mean_comments)+"\n"
			to_print+=self.space+"💖-1\n"
			self.life-=1
		## interesting & unique
		else:
			if random.choice([True,True,True,False]):
				to_print+=self.space+"👍+1\n"
			else:
				to_print+=self.space+"👍"+random.choice(self.nice_comments)+"\n"
			## add to current list of old_sents but also to file
			self.old_sents.append(judgment['originalLine'])
			self.old_sents_file.write(judgment['originalLine']+"\n")
			self.total_points+=1
			self.level_points+=1
		### now maybe change level
		if self.life==0:
			self.dead = True
			to_print += "%sOut of 💖s.\n%sGAME OVER\n%sYou earned %d point%s this time.\n%sType 'play' to start again\n".replace('1 points','1 point') % (self.space,self.space,self.space,self.total_points,"s" if self.total_points!=1 else "",self.space)
		elif self.life==1:
			if self.life_warned==False:
				self.life_warned==True
			to_print+="%s\u001b[38;5;40;5;7m(Warning...only one 💖 left!)\u001b[0m\n" % self.space
		elif self.level_points==self.points_to_next_level:
			if self.level<self.judge.max_level: ## should be 5
				self.level+=1
				to_print+=self.level_banner()
				self.level_points = 0
		return to_print


	def win(self):
		"print celebration once player wins"
		self.special_print("%sYOU WIN\n%s~~~~~~~\n" % (self.space, self.space))
		elite_sentence = "elite sentence generator!".split()
		celebrations = list("       💫💫💫💫💯💯💯🙌🙌💪🧠🤟🎆🎉🎉")
		for i in range(9):
			self.special_print("%s%s%s" % (self.space," "*random.randrange(4),elite_sentence[0]))
			elite_sentence.append(elite_sentence.pop(0))
			self.special_print("%s%s" % (self.space," ".join(random.sample(celebrations,4))))



	## interpreted commands (using cmd)


	def do_quit(self,args):
		"Quit the game"
		try:
			self.special_print("%sYou earned %d point%s this time.\n" % (self.space,self.total_points,"s" if self.total_points!=1 else ""))
			print("%sSession data saved to %s.\n" % (self.space,self.output_file.name)) ## don't record
			self.output_file.close()
		except:
			print("Goodbye.")  ## if not played
		return True


	def do_info(self,args):
		"Learn about the game"
		with open('readme.md','r') as f:
			readme = f.read()
		to_print = readme.split("***")[0].rstrip()
		self.special_print(to_print)


	def do_score(self,args):
		"Check your score"
		try:
			"print the player's current score and health"
			to_print = "%s👍 = %d\n%s💖 = %d\n" % (self.space*2,self.total_points,self.space*2,self.life)
		except:
			to_print = self.intro
		self.special_print(to_print)


	def do_play(self,args):
		"Start (or restart) the game"
		self.restart()
		self.started = True
		to_print=self.level_banner()
		to_print+="%sType 'score' to see your current points (👍) and your remaining life (💖).\n" % self.space
		to_print+="%sSee how many points you can get before you run out of life!\n" % self.space
		self.special_print(to_print)


	def default(self,args):
		"""
		handle any non-parsable input
		assume it is a sentence to be judged
		"""
		if self.started==True and self.dead==False:
			if args[-1] in ".?!":  ## make sure input ends in punctuation
				self.output_file.write(args+"\n") ## write user line to file
				judgment = self.judge.input_and_test_new_sent(args,self.level,self.old_sents)
				to_print = self.update_based_on_judgment(judgment)
			else:
				if len(args.split(" "))==1: ## if it looks like a special command
					to_print = "%sAre you trying to enter a command?\n%sIf so, type 'help' or '?'.\n" % (self.space,self.space)
				else: ## if no puntuation
					to_print = "%sPlease make sure to end your sentence with punctuation ('.', '?', or '!')\n" % self.space
		else:
			to_print = self.intro
		self.special_print(to_print)
Exemple #10
0
 def __init__(self, scratch_board, token):
     self.scratch_board = scratch_board
     self.scratch_judge = Judge(self.scratch_board)
     self.opponent = { 'O':'X', 'X':'O' }
     self.token = token
     self.best_move = None
Exemple #11
0
    fileE = Genera(options.Numbers, options.Range)
    fileStand = Verify(fileE.filename)
    print('next: is time:')
    t = int(round(time.time() * 1000)) - t
    print(t)
    print('ms')  # 微秒级时间戳
if options.Numbers and options.Range and options.ProExFile and options.AnsFile:
    '生成Numbers条有负数结果的算式, 再将其标准化(去除中间过程有负数结果的算式以及/后面有0的非法算式), 输出文件是StandExercises.txt'
    t = time.time()
    fileE = Genera(options.Numbers, options.Range)
    t -= t
    fileStand = Verify(fileE.filename)
    fileA = Answer(options.AnsFile)
    print(str(t) + 'ms')

if options.AnsFile and not options.Numbers:
    '回答-a后面的filename题目文件,并输出结果到Answers.txt文件'
    fileA = Answer(options.AnsFile)

if options.ProExFile and options.Numbers and options.Range and not options.AnsFile:
    '生成Numbers条有负数结果的算式, 生成文件是Exercises.txt'
    fileE = Genera(options.Numbers, options.Range)

if options.JudgeFile and not options.Numbers and not options.Range and not options.ProExFile:
    '-e 接一个用户的答案文件, 并将其和标准答案文件Answers.txt比较'
    FileA = Judge(options.JudgeFile, "Answers.txt")
if options.Numbers:
    print('asdads')

if __name__ == '__main__':
    pass
Exemple #12
0
 def setUp(self):
     self.judge = Judge()
Exemple #13
0
class Board(object):

    def __init__(self, player=None, computer=None):
        """

        :rtype: object
        """
        self.tokens = [' '] * 9
        self.player_token = player
        self.computer_token = computer
        self.judge = Judge(self)

    def playAgain(self):
        """Find out if we want another go"""
        print('Do you want to play again? (yes or no)')
        return self._raw_input().lower().startswith('y')

    def isWinner(self):
        """Did a win just happen?"""
        result = self.judge.evalGame()
        if result[0] is not None:
            return 'win'
        elif result == [None, None]:
           return False
        else:
            return 'draw'

    def makeComputerMove(self, brain):
        """Make the computer's move"""
        results = []
        tokens = copy.copy(self.tokens)
        if self.take_center():
            best = 4
        else:
            brain.evaluateMove(p=self.computer_token, board=tokens)
            best = brain.best_move
        self.addToken(self.computer_token, int(best))
        print(self.drawBoard())

    def take_center(self):
        """figure out if we can have the center square
        rather than calculating the whole tree our first
        move"""
        token_count = self.tokens.count(' ')
        if token_count == 9:
            return True
        elif token_count == 8 and self.tokens[4] == ' ':
            return True
        return False

    def getPlayerMove(self):
        """Get the player's move"""
        move = ' '
        while move not in self.getPossibleMoves():
            print('What is your next move? (1-9)')
            move = self._raw_input()
            try:
                int(move)
            except:
                print("Please enter a digit")
                print(self.drawBoard())
                continue
            try:
                self.addToken(self.player_token, int(move) - 1)#make the move into an index of the board
                print(self.drawBoard())
                break
            except TokenPlacementException:
                print("please select an empty spot")
                print(self.drawBoard())


    def firstMove(self):
        """Computer goes first"""
        which = random.randint(1, 2)
        if which == 1:
            return 'computer'
        else:
            return 'player'

    def drawBoard(self):
        """Draw a tic-tac-toe board"""

        b = '\n\n%s|%s|%s\n' % tuple(self.tokens[:3])
        b += '_____\n'
        b += '%s|%s|%s\n' % tuple(self.tokens[3:6])
        b += '_____\n'
        b += '%s|%s|%s\n\n' % tuple(self.tokens[6:])

        return b

    def addToken(self, token, idx):
        """Add a token to the board or raise an exception

        str token  "x" or "o"
        int idx    0-8"""

        idx = int(idx)
        if  idx > 8 or idx < 0:
            msg = "Invalid index %s " % idx
            raise TokenPlacementException(msg)

        if self.tokens[idx] == ' ':
            self.tokens[idx] = token
        else:
            msg = "Token at %s" % idx
            raise TokenPlacementException(msg)

    def getBoard(self):
        return copy.copy(self.tokens)

    def getPossibleMoves(self):
        """Return the indexes of possible moves"""
        result = list()
        for i in range(9):
            if self.tokens[i] == ' ':
                result.append(i)
        return result

    def inputPlayerLetter(self):
        """Allow the player to choose a letter"""
        letter = ''
        while not (letter == 'X' or letter == 'O'):
            print('Do you want to be X or O?')
            letter = self._raw_input()
            letter = letter.upper()
            if letter == 'X':
                self.player_token = letter
                self.computer_token = 'O'
                break
            elif letter == 'O':
                self.player_token = letter
                self.computer_token = 'X'
                break

    def _raw_input(self):
        return input()
Exemple #14
0
 def setUp(self):
     self.judge = Judge()