예제 #1
0
파일: client.py 프로젝트: smithma01/runner
def callback(ch, method, properties, body):
    # Create temp file containing the script
    temp = tempfile.NamedTemporaryFile(delete=False)
    body = json.loads(body)
    temp.write(body['script'])
    temp.close()
    # Make sure the file is executable and fix perms if it isn't
    if not os.access(temp.name, os.X_OK):
        print("%s is not executable attempting to make it executable now" %
              (temp.name))
        # Not 100% sure how I can make this work across different OSes yet.
        try:
            # May want to change this to using octal as I think it would save me the stat import\
            # but I'm leaving it until I get a chance to test if this works in Windows (doubt it will though).
            os.chmod(temp.name, stat.S_IRUSR | stat.S_IXUSR)
        except Exception as E:
            print("ERROR: Unable to make %s executable. Exiting" % (temp.name))
            print("Exception: %s" % (E))
            # Instead of exiting here I should probably report back a failure in the future
            os.__exit(1)

    # Need to add timeout options so a script can't hang forever

    # Run the script
    process = subprocess.Popen(temp.name)
    process.wait()
    # Need to save this output to a var and pass it back through rabbitmq
    process.communicate()

    # Remove temp file as its no-longer needed
    temp.unlink(temp.name)
예제 #2
0
def pred_batch_iter(sourceData,
                    labelData,
                    batch_size,
                    num_epochs,
                    shuffle=False):
    data = np.array(sourceData)  # 将sourceData转换为array存储
    data_size = len(sourceData)
    num_batches_per_epoch = int(len(sourceData) / batch_size) + 1
    for epoch in range(num_epochs):
        # Shuffle the data at each epoch
        if shuffle:
            os.__exit()
            shuffle_indices = np.random.permutation(np.arange(data_size))
            shuffled_data = sourceData[shuffle_indices]
        else:
            input_data = sourceData
            label_data = labelData

        for batch_num in range(num_batches_per_epoch):
            start_index = batch_num * batch_size
            end_index = min((batch_num + 1) * batch_size, data_size)
            if (
                    end_index - start_index
            ) < batch_size:  # Padding! In case that the last size of batch < batch_size
                start_index = end_index - batch_size

            yield input_data[start_index:end_index], label_data[
                start_index:end_index]
예제 #3
0
파일: client.py 프로젝트: krasmussen/runner
def callback(ch, method, properties, body):
	# Create temp file containing the script
	temp = tempfile.NamedTemporaryFile(delete=False)
	body = json.loads(body)
	temp.write(body['script'])
	temp.close()
	# Make sure the file is executable and fix perms if it isn't
	if not os.access(temp.name, os.X_OK):
		print("%s is not executable attempting to make it executable now" %(temp.name))
		# Not 100% sure how I can make this work across different OSes yet.
		try:
			# May want to change this to using octal as I think it would save me the stat import\
			# but I'm leaving it until I get a chance to test if this works in Windows (doubt it will though).
			os.chmod(temp.name, stat.S_IRUSR | stat.S_IXUSR)
		except Exception as E:
			print("ERROR: Unable to make %s executable. Exiting" %(temp.name))
			print("Exception: %s" %(E))
			# Instead of exiting here I should probably report back a failure in the future
			os.__exit(1)

	# Need to add timeout options so a script can't hang forever

	# Run the script
	process = subprocess.Popen(temp.name)
	process.wait()
	# Need to save this output to a var and pass it back through rabbitmq
	process.communicate()

	# Remove temp file as its no-longer needed
	temp.unlink(temp.name)
예제 #4
0
def handleClient(connection):
	time.sleep(5)
	while True:
		data = connection.recv(1024)
		if not data:break
		reply = 'Echo => %s at %s' %(data,now())
		connection.send(reply.encode())
		connection.close()
		os.__exit(0)
예제 #5
0
파일: latis.py 프로젝트: minhsqtruong/LaTIS
 def __get_call(self):
     try:
         interface(
             """How would a program calls your new macro? For example: my_macro(var1, var2, var3) """
         )
         user_string = checkinput()
         self.call = user_string.split('(')[0]
         self.numinput = len(user_string.split(','))
     except:
         interface(
             "Oops...your format is wrong, return to menu now. Idiot proof needed for better feature"
         )
         time.sleep(2)
         os.__exit(0)
예제 #6
0
파일: latis.py 프로젝트: minhsqtruong/LaTIS
 def __get_variable(self):  #TODO make it idiot proof
     try:
         interface(
             "Ok so your macro name is \'" + self.call + "\' with " +
             str(self.numinput) +
             " arguments. List first from last arguments in <type> | <name> | <value> | format."
         )
         self.inputname = []
         self.inputtype = []
         self.inputval = []
         self.test_call = ''
         for i in range(self.numinput):
             user_string = checkinput().split('|')
             self.inputtype.append(user_string[0].replace(' ', ''))
             self.inputname.append(user_string[1].replace(' ', ''))
             self.inputval.append(user_string[2].replace(' ', ''))
             self.test_call += user_string[0] + ' ' + user_string[
                 1] + '=' + user_string[2] + ';'
     except:
         interface(
             "Oops...your format is wrong, return to menu now. Idiot proof needed for better feature"
         )
         time.sleep(2)
         os.__exit(0)
예제 #7
0
 def control_c(self):
     try:
         while True:
             pass
     except KeyboardInterrupt as e:
         os.__exit(0)
예제 #8
0
def exit_with_usage():
	print globals()['__doc__']
	os.__exit(1)
예제 #9
0
def main():

    game1 = Game()
    player1 = Player("X")
    player2 = Player("O")
    game1.initialize()
    array_of_players = [player1, player2]
    turn = None
    depth = None
    while turn != "1" and turn != "2":
        turn = input("AI is player 1 or 2?")
    game1.set_AI_turn(int(turn) - 1)
    while depth != "1" and depth != "2":
        depth = input("Minimax Depth is  1 or 2?")
    # Game loop, continuous until draw or winner
    while game1.get_move_counter() != 30 or player1.get_pieces_counter(
    ) != 15 or player2.get_pieces_counter() != 15:
        turn_counter = (game1.get_turn_counter()) % 2
        print("Player " + str(turn_counter + 1) + " turn")
        if game1.get_move_counter(
        ) == 15 and array_of_players[turn_counter] == 15:
            print("No more options left")
            game1.set_turn_counter(game1.get_turn_counter() + 1)
            continue

        while True:
            # AI turn
            if game1.get_turn_counter() % 2 == game1.get_AI_turn():
                sys.stdout = open(os.devnull, 'w')
                column_holder, row_holder, move_column_holder, move_row_holder, score, movetype = game1.minimax_function(
                    array_of_players, int(depth), -1001)
                sys.stdout = sys.__stdout__
                print(column_holder, row_holder, move_column_holder,
                      move_row_holder, score, movetype)
                if movetype == "Put":
                    array_of_players[turn_counter].put_piece(
                        game1, column_holder, row_holder)
                    print("Put token " + column_holder + str(row_holder))
                    if game1.check_winning_conditions(
                            array_of_players[turn_counter], column_holder,
                            row_holder):
                        print(game1.print_board())
                        print("Player " + str(turn_counter + 1) +
                              " is the Winner")
                        input("Enter any key to end program")
                        os._exit(0)
                    break
                if movetype == "Move":
                    array_of_players[turn_counter].move_piece(
                        game1, column_holder, row_holder, move_column_holder,
                        move_row_holder)
                    print("Moved token " + column_holder + str(row_holder) +
                          " to" + move_column_holder + str(move_row_holder))
                    if game1.check_winning_conditions(
                            array_of_players[turn_counter], move_column_holder,
                            move_row_holder):
                        print(game1.print_board())
                        print("Player " + str(turn_counter + 1) +
                              " is the Winner")
                        input("Enter any key to end program")
                        os._exit(0)
                    break
            else:
                move_choice = input(
                    "Choose your next move: \n1-Place a token \n"
                    "2-Move a token\n ")
                if move_choice == "1":
                    if array_of_players[turn_counter].get_pieces_counter(
                    ) == 15:
                        print("No more tokens to place")
                        continue

                    put_input = input(
                        "Input which grid to place coordinates(ie:A1):\n")
                    try:
                        if not array_of_players[turn_counter].put_piece(
                                game1, put_input[0], int(put_input[1:])):
                            print("Invalid Inputs, Please Try Again")
                            continue
                        elif game1.check_winning_conditions(
                                array_of_players[turn_counter], put_input[0],
                                int(put_input[1:])):
                            print(game1.print_board())
                            print("Player " + str(turn_counter + 1) +
                                  " is the Winner")
                            input("Enter any key to end program")
                            os._exit(0)
                    except:
                        print("Invalid Inputs, Please try again")
                        continue
                    break
                elif move_choice == "2":
                    if game1.get_move_counter() == 30:
                        print("No moves left for both players")
                        continue
                    if array_of_players[turn_counter].get_pieces_counter(
                    ) == 0:
                        print("No pieces available to be moved")
                        continue

                    old_move_input = input(
                        "Input which grid to move tokens(ie:A2)\n")
                    new_move_input = input(
                        "Input which grid to move the token to(ie:A3)\n")
                    try:
                        if not array_of_players[turn_counter].move_piece(
                                game1, old_move_input[0],
                                int(old_move_input[1:]), new_move_input[0],
                                int(new_move_input[1:])):
                            print("Invalid Input, Please Try Again")
                            continue
                        elif game1.check_winning_conditions(
                                array_of_players[turn_counter],
                                new_move_input[0], int(new_move_input[1:])):
                            print(game1.print_board())
                            print("Player " + str(turn_counter + 1) +
                                  " is the Winner")
                            input("Enter any key to end program")
                            os._exit(0)
                        elif game1.check_move_winning(
                                array_of_players[turn_counter],
                                old_move_input[0], int(old_move_input[1])):
                            print(game1.print_board())
                            print("Player " + str((turn_counter + 1) % 2 + 1) +
                                  " is the Winner")
                            input("Enter any key to end program")
                            os._exit(0)
                    except:
                        print("Invalid Input, Please try again")
                        continue
                    break
                else:
                    print("Invalid Input, please choose a valid option")
        game1.print_board()
        game1.set_move_counter(array_of_players[1].get_pieces_moved_counter() +
                               array_of_players[0].get_pieces_moved_counter())
        print(" \nCurrent move counter is " + str(game1.get_move_counter()))
        print("Player " + str(turn_counter + 1) + " Token counter is " +
              str(array_of_players[turn_counter].get_pieces_counter()))
        game1.set_turn_counter(game1.get_turn_counter() + 1)
    print("Game is a draw")
    input("Enter any key to end program")
    os.__exit(0)
예제 #10
0
def audit(name, args):
    if not audit.did_exec and name == 'exec':
        audit.did_exec = True
    else:
        __exit(1)
예제 #11
0

def audit(name, args):
    if not audit.did_exec and name == 'exec':
        audit.did_exec = True
    else:
        __exit(1)


audit.did_exec = False

sys.stdout.write('> ')
try:
    code = compile(sys.stdin.read(), '<user input>', 'exec')
except:
    __exit(1)
sys.stdin.close()

for module in set(sys.modules.keys()):
    if module in sys.modules:
        del sys.modules[module]

sys.addaudithook(audit)

namespace = {}
try:
    exec(code, namespace, namespace)
except:
    __exit(1)
__exit(0)