Beispiel #1
0
 def build(self):
     return Controller()
Beispiel #2
0
import numpy

from controller.controller import Controller
import matplotlib.pyplot as plt

mean = []
stdDeviation = []
variance = []
fitness = []

for i in range(30):
    c = Controller(40, 4)
    c.evolutionaryAlgorithm(1000)
    result = c._problem.evaluateLastPopulationEA()
    mean.append(result[0])
    variance.append(result[1])
    stdDeviation.append(result[2])
    fitness.append(result[4])
plt.plot(fitness, 'ro')
plt.show()

print("Mean: " + str(numpy.mean(mean)))
print("Variance: " + str(numpy.mean(variance)))
print("StdDeviance: " + str(numpy.mean(stdDeviation)))
print("Fitness: " + str(numpy.mean(fitness)))
Beispiel #3
0
    for controller in controllers:
        controller.send(message)


def run_processor(processor):
    message = Message.IDLE

    while message is not Message.EXIT:
        # print("Processing...")
        message = processor.process()


if __name__ == '__main__':
    # VARIABLES-----------------------------------------------------------------
    manager = PluginManager() # Load the plugins from the plugin directory.
    main_controller = Controller()
    # biosignal = PrintBiosignal()
    biosignal = Tagger("./test_results/data.csv")
    processor = Processor([biosignal])

    # SET UP GUI----------------------------------------------------------------
    gui_thread = threading.Thread(target=make_gui, args=[main_controller])
    gui_thread.daemon = True
    gui_thread.start()

    # SET UP BOARD--------------------------------------------------------------
    parser = setup_parser()
    args = parser.parse_args()

    if not(args.add):
        print ("WARNING: no plugin selected, you will only be able to communicate with the board. You should select at least one plugin with '--add [plugin_name]'. Use '--list' to show available plugins or '--info [plugin_name]' to get more information.")
Beispiel #4
0
def control():
    return Controller()
Beispiel #5
0
from controller.controller import Controller

c = Controller()

c.start()



Beispiel #6
0
import sys

from PyQt5.QtWidgets import QApplication

from controller.controller import Controller
from model.main import Model

import sys
from PyQt5.QtWidgets import *

# from view.MainWindow import MainWindow
from view.MainWindow import MainWindow



if __name__ == '__main__':
    app = QApplication(sys.argv)

    view = MainWindow()
    view.show()

    controller = Controller(model=Model(), view = view)
    sys.exit(app.exec_())
Beispiel #7
0
def main():
    ui = OrderUI()
    dao = Dao()
    Controller(ui, dao)
Beispiel #8
0
def main():
    setlog()
    # pid = daemon()
    # if pid:
    #     return pid
    Controller().start()
Beispiel #9
0
# need to add logging aggregator request

analytics_impl = os.getenv("ANALYTICS_IMPL", "mock")
analyticsController = None

if analytics_impl == "azure":

    endpoint = os.environ["AZURE_TEXT_ANALYTICS_ENDPOINT"]
    key = os.environ["COGNITIVE_SERVICE_KEY"]
    text_analytics_client = None
    try:
        text_analytics_client = AzureAnalytics(
            TextAnalyticsClient(endpoint=endpoint,
                                credential=AzureKeyCredential(key)))
        analyticsController = Controller(text_analytics_client)

        print("authenticated azure", file=sys.stderr)
    except Exception as e:
        print(e, file=sys.stderr)
        print("Couldn't authenticate to Azure Text Analytics", file=sys.stderr)

if analytics_impl == "mock":
    analyticsController = Controller(MockAnalytics())
    print("Mock analytics")

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


@app.route(f'{VERSION_BASE}/key-phrase', methods=['POST'])
Beispiel #10
0
def main():
    # create_play_list("dusseldorf_000049", "C:/Users/RENT/Desktop/dissuldorf_49",6)
    control = Controller("./dusseldorf_000049.pls")
    control.run()
Beispiel #11
0
# -*- coding: utf-8 -*-

from model.model import Model
from controller.controller import Controller

if __name__ == '__main__':
    ip = 'localhost'
    db = 'Pronondb'
    #  user = '******'
    #  pswd = 'olescki'

    c = Controller(ip, db)
Beispiel #12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
主函数
"""

import sys
from ui.gui import Ui_MainWindow
from ui.view import View
from controller.controller import Controller
from PyQt5 import QtWidgets

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    view = View(ui, MainWindow)  # View prep (gui)
    controller = Controller(
        view)  # Controller prep (communication between model and view)
    view.startConnections(controller)

    MainWindow.show()
    sys.exit(app.exec_())
Beispiel #13
0
def update():
    path = os.getcwd()
    c = Controller(path)

    return c.deploy(request.args, 'upgrade')
Beispiel #14
0
def deploy():
    path = os.getcwd()
    c = Controller(path)

    return c.deploy(request.args)
Beispiel #15
0
    def __init__(
            self,
            data_dir=None,
            model_dir=None,
            best_model_dir=None,
            # Training params
            max_epochs=100,
            max_num_stuck_epochs=15,
            eval=False,
            feedback=False,
            batch_size=32,
            seed=0,
            init_lr=1e-3,
            ent_loss=0.1,
            # Slurm params
            slurm_id=None,
            # Other params
            **kwargs):

        # Set training params
        self.max_epochs = max_epochs
        self.max_num_stuck_epochs = max_num_stuck_epochs
        self.feedback = feedback
        self.slurm_id = slurm_id
        self.ent_loss = ent_loss

        # Set random seeds
        np.random.seed(seed)
        torch.manual_seed(seed)

        # Prepare data info
        self.train_iter, self.valid_iter, self.test_iter, self.itos \
            = GAPDataset.iters(path=data_dir, batch_size=batch_size, feedback=feedback)

        # Get model paths
        self.model_dir = model_dir
        self.data_dir = data_dir
        self.model_path = path.join(model_dir, 'model.pth')
        self.best_model_path = path.join(best_model_dir, 'model.pth')

        # Initialize model and training metadata
        self.model_args = kwargs
        self.model = Controller(**kwargs)
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.model = self.model.to(device)

        self.optimizer = torch.optim.AdamW(self.model.parameters(),
                                           lr=init_lr,
                                           weight_decay=0)
        self.optim_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
            self.optimizer,
            mode='max',
            factor=0.5,
            patience=5,
            min_lr=0.1 * init_lr,
            verbose=True)

        self.train_info = {}
        self.train_info['epoch'] = 0
        self.train_info['val_perf'] = 0.0
        self.train_info['threshold'] = 0.0
        self.train_info['num_stuck_epochs'] = 0

        # Print model params
        utils.print_model_info(self.model)

        if not eval:
            if path.exists(self.model_path):
                logging.info('Loading previous model: %s' % (self.model_path))
                self.load_model(self.model_path)
            self.train()

        self.final_eval()
Beispiel #16
0
session = config['Telegram']['session']

mode = os.getenv("MODE")
api_id = os.getenv('api_id')
api_hash = os.getenv('api_hash')

proxy_ip = config['Telegram']['proxy_ip']
proxy_port = int(config['Telegram']['proxy_port'])
secret = config['Telegram']['secret']
proxy = (proxy_ip, proxy_port, secret)

if __name__ == '__main__':
    if mode == "dev":
        logger.info("Dev mode select, now creating controller")
        proxy_ip = config['Telegram']['proxy_ip']
        proxy_port = int(config['Telegram']['proxy_port'])
        secret = config['Telegram']['secret']
        proxy = (proxy_ip, proxy_port, secret)
        controller = Controller(session,
                                api_id,
                                api_hash,
                                mode="dev",
                                proxy=proxy)
    elif mode == "prod":
        logger.info("Prod mode select, now creating controller")
        controller = Controller(session,
                                api_id,
                                api_hash,
                                mode="prod",
                                proxy=None)
'''
Created on Dec 19, 2016

@author: Emy
'''
from repository.Repository import Repository
from controller.controller import Controller
from ui.console import UI
from domain.student import Student

repo = Repository()
ctrl = Controller(repo)
ui = UI(ctrl)

ui.run()
Beispiel #18
0
    default=False)
parser.add_argument("--send-strings",
                    help='Send strings instead of byte arrays',
                    action='store_true',
                    default=bool(
                        os.environ.get('CONTROLLER_SEND_STRINGS', False)))

args = parser.parse_args()

logging.setupLoggers(args.log_level, args.log_to_console)
logger = logging.getLogger('script')

logger.debug('Set hostname to %s with port %s', args.hostname, args.port)

# Process init
controller = Controller(logging.getLogger('controller'))
controller.prepareFloorPlan()
controller.setAlgorithm(algorithmManager.getAlgorithm(args.algorithm))


async def handleIncomingMessages(websocket, path):
    async for message in websocket:
        logger.info('Received message: %s', message)

        if message is str:
            data = json.loads(message)
        else:
            data = json.loads(message, encoding='utf-8')

        if type(data) is dict:
            if 'quit' in data:
Beispiel #19
0
def run():
    # This is used in case we want to use a freezing program to create an .exe
    #if getattr(sys, 'frozen', False):
    #    os.chdir(sys._MEIPASS)

    guiEnabled = int(input("Enable GUI?: (1 == yes)\n"))
    guiEnabled = (guiEnabled == 1)
    viewEnabled = False
    if guiEnabled:
        viewEnabled = int(input("Display view?: (1 == yes)\n"))
        viewEnabled = (viewEnabled == 1)

    modelName = None
    modelPath = None
    loadedModelName = None
    algorithm = None
    packageName = None
    parameters = None
    model_in_subfolder = False
    loadModel = int(input("Do you want to load a model? (1 == yes)\n"))
    loadModel = (loadModel == 1)
    if loadModel:
        while packageName is None:
            packageName = None
            print("#########################################")
            print("Saved Models: \n")
            for folder in [i for i in os.listdir("savedModels/")]:
                print(folder)
            modelName = input("Enter the model name (name of directory in savedModels): (Empty string == break)\n")
            # If user presses enter, quit model loading
            if str(modelName) == "":
                loadModel = False
                modelName = None
                break
            # If user inputs wrong model name, ask for input again
            modelPath = "savedModels/" + modelName + "/"
            if not os.path.exists(modelPath):
                print("Invalid model name, no model found under ", modelPath)
                continue
            # CHECK FOR SUBFOLDERS
            if str(modelName)[0] != "$":
                while packageName is None:
                    print("------------------------------------")
                    print("Folder Submodels: \n")
                    for folder in [i for i in os.listdir(modelPath) if os.path.isdir(modelPath + "/" + i)]:
                        print(folder)
                    subModelName = input("Enter the submodel name: (Empty string == break)\n")
                    # If user presses enter, leave model
                    if str(subModelName) == "":
                        break
                    subPath = modelPath + subModelName + "/"
                    if not os.path.exists(subPath):
                        print("Invalid model name, no model found under ", subPath)
                        continue
                    packageName = "savedModels." + modelName + "." + subModelName
                    loadedModelName = subPath
                    # modelName = path
                    model_in_subfolder = True
                if packageName is None:
                    continue

            if packageName is None:
                packageName = "savedModels." + modelName
                loadedModelName = modelPath
                # ModelName = None will autogenereate a name
                modelName = None
        if packageName is not None:
            parameters = importlib.import_module('.networkParameters', package=packageName)
            algorithm = algorithmNameToNumber(parameters.ALGORITHM)
            # model.setPath(modelName)

    if not loadModel:
        parameters = importlib.import_module('.networkParameters', package="model")

        algorithm = int(input("What learning algorithm do you want to use?\n" + \
                              "'Q-Learning' == 0, 'Actor-Critic' == 2,\n"))
    tweaking = int(input("Do you want to tweak parameters? (1 == yes)\n"))
    tweakedTotal = []
    if tweaking == 1:
        while True:
            tweakedParameter = str(input("Enter name of parameter to be tweaked:\n"))
            paramLineNumber = checkValidParameter(tweakedParameter)
            if paramLineNumber is not None:
                paramValue = str(input("Enter parameter value:\n"))
                tweakedTotal.append([tweakedParameter, paramValue, paramLineNumber])
            if 1 != int(input("Tweak another parameter? (1 == yes)\n")):
                break
        modelPath = "savedModels/" + nameSavedModelFolder(tweakedTotal)
        model_in_subfolder = True

    if int(input("Give saveModel folder a custom name? (1 == yes)\n")) == 1:
        modelPath = "savedModels/" + str(input("Input folder name:\n"))


    model = Model(guiEnabled, viewEnabled, parameters, True)
    if parameters.JOB_TRAINING_STEPS != 0 and parameters.JOB_STEP_START > 0:
        model.loadModel(loadedModelName)
        print("Loaded into load path: " + model.getPath())

    else:
        model.initModelFolder(modelPath, loadedModelName, model_in_subfolder)
        print("Created new path: " + model.getPath())

    if tweakedTotal:
        modifyParameterValue(tweakedTotal, model)

    numberOfHumans = 0
    mouseEnabled = True
    humanTraining = False
    if guiEnabled and viewEnabled:
        numberOfHumans = int(input("Please enter the number of human players: (" + str(MAXHUMANPLAYERS) + " max)\n"))
        if fitsLimitations(numberOfHumans, MAXHUMANPLAYERS):
            createHumans(numberOfHumans, model)
            if 2 >= numberOfHumans > 0:
                humanTraining = int(input("Do you want to train the network using human input? (1 == yes)\n"))
                mouseEnabled = not humanTraining
            if numberOfHumans > 0 and not humanTraining:
                mouseEnabled = int(input("Do you want control Player1 using the mouse? (1 == yes)\n"))


    enableTrainMode = humanTraining if humanTraining is not None else False
    if not humanTraining:
        enableTrainMode = int(input("Do you want to train the network?: (1 == yes)\n"))
    model.setTrainingEnabled(enableTrainMode == 1)

    parameters = importlib.import_module('.networkParameters', package=model.getPath().replace("/", ".")[:-1])
    numberOfNNBots = parameters.NUM_NN_BOTS
    numberOfGreedyBots = parameters.NUM_GREEDY_BOTS
    numberOfBots = numberOfNNBots + numberOfGreedyBots

    Bot.init_exp_replayer(parameters, loadedModelName)

    setSeedAccordingToFolderNumber(model_in_subfolder, loadModel, modelPath, enableTrainMode)

    createBots(numberOfNNBots, model, "NN", parameters, algorithm, loadModel)
    createBots(numberOfGreedyBots, model, "Greedy", parameters)
    createBots(parameters.NUM_RANDOM_BOTS, model, "Random", parameters)
    model.addDataFilesToDictionary()

    if guiEnabled and viewEnabled and not model.hasHuman():
        spectate = int(input("Do want to spectate an individual bot's FoV? (1 = yes)\n"))
        if spectate == 1:
            model.addPlayerSpectator()

    if numberOfNNBots == 0:
        model.setTrainingEnabled(False)

    if numberOfBots == 0 and not viewEnabled:
        modelMustHavePlayers()

    model.initialize(loadModel)

    screenWidth, screenHeight = defineScreenSize(numberOfHumans)

    testResults = None
    if guiEnabled:
        view = View(model, screenWidth, screenHeight, parameters)
        controller = Controller(model, viewEnabled, view, mouseEnabled)
        view.draw()
        while controller.running:
            controller.process_input()
            model.update()
    else:
        maxSteps = parameters.MAX_SIMULATION_STEPS
        jobSteps = maxSteps if parameters.JOB_SIMULATION_STEPS == 0 else parameters.JOB_SIMULATION_STEPS
        jobStart = parameters.JOB_STEP_START
        smallPart = max(int(maxSteps / 100), 1) # constitutes one percent of total training time
        testPercentage = smallPart * 5
        if jobStart == 0:
            testResults = []
        else:
            print("max:", maxSteps, "start:", jobStart, "steps:", jobSteps)
            with open(model.getPath() + 'testResults.pkl', 'rb') as inputFile:
                testResults = pkl.load(inputFile)
        for step in range(jobStart, jobStart + jobSteps):
            model.update()
            if step % smallPart == 0 and step != 0:
                print("Trained: ", round(step / maxSteps * 100, 1), "%")
                # Test every 5% of training
            if parameters.ENABLE_TESTING:
                if step % testPercentage == 0:
                    testResults = updateTestResults(testResults, model, round(step / maxSteps * 100, 1), parameters)

        jobStart_line = checkValidParameter("JOB_STEP_START")
        epsilon_line = checkValidParameter("EPSILON")
        endParams = []
        endParams.append(["JOB_STEP_START", jobStart + jobSteps, jobStart_line])
        endParams.append(["EPSILON", model.getBots()[0].getLearningAlg().getNoise(), epsilon_line])
        modifyParameterValue(endParams, model)

        if parameters.ENABLE_TESTING and parameters.JOB_TRAINING_STEPS == 0 or \
                parameters.JOB_SIMULATION_STEPS + parameters.JOB_STEP_START >= parameters.MAX_SIMULATION_STEPS:
            testResults = updateTestResults(testResults, model, 100, parameters)
            meanMassesOfTestResults = [val[0] for val in testResults]
            exportTestResults(meanMassesOfTestResults, model.getPath() + "data/", "testMassOverTime")
            meanMassesOfPelletResults = [val[2] for val in testResults]
            exportTestResults(meanMassesOfPelletResults, model.getPath() + "data/", "Pellet_CollectionMassOverTime")
            plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Test", 0)
            plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Pellet_Collection", 2)
            
            if parameters.MULTIPLE_BOTS_PRESENT:
                meanMassesOfGreedyResults = [val[4] for val in testResults]
                exportTestResults(meanMassesOfGreedyResults, model.getPath() + "data/", "VS_1_GreedyMassOverTime")
                plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Vs_Greedy", 4)
            if parameters.VIRUS_SPAWN:
                meanMassesOfPelletVirusResults = [val[6] for val in testResults]
                exportTestResults(meanMassesOfPelletVirusResults, model.getPath() + "data/", "Pellet_Collection_Virus_MassOverTime")
                plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Pellet_Collection_with_Viruses", 6)
                if parameters.MULTIPLE_BOTS_PRESENT:
                    meanMassesOfGreedyVirusResults = [val[8] for val in testResults]
                    exportTestResults(meanMassesOfGreedyVirusResults, model.getPath() + "data/", "VS_1_Greedy_Virus_MassOverTime")
                    plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Vs_Greedy_with_Viruses", 8)


            print("Training done.")
            print("")

    if model.getTrainingEnabled():
        model.save(True)
        model.saveModels()
        if parameters.JOB_TRAINING_STEPS == 0 or \
                parameters.JOB_SIMULATION_STEPS + parameters.JOB_STEP_START >= parameters.MAX_SIMULATION_STEPS:

            runTests(model, parameters)
            if model_in_subfolder:
                print(os.path.join(modelPath))
                createCombinedModelGraphs(os.path.join(modelPath))

            print("Total average time per update: ", round(numpy.mean(model.timings), 5))

            bots = model.getBots()
            for bot_idx, bot in enumerate([bot for bot in model.getBots() if bot.getType() == "NN"]):
                player = bot.getPlayer()
                print("")
                print("Network parameters for ", player, ":")
                attributes = dir(parameters)
                for attribute in attributes:
                    if not attribute.startswith('__'):
                        print(attribute, " = ", getattr(parameters, attribute))
                print("")
                print("Mass Info for ", player, ":")
                massListPath = model.getPath() + "/data/" +  model.getDataFiles()["NN" + str(bot_idx) + "_mass"]
                with open(massListPath, 'r') as f:
                    massList = list(map(float, f))
                mean = numpy.mean(massList)
                median = numpy.median(massList)
                variance = numpy.std(massList)
                print("Median = ", median, " Mean = ", mean, " Std = ", variance)
                print("")
        elif testResults is not None:
            with open(model.getPath() + "replay_buffer.pkl", 'wb') as output:
                print(len(model.getBots()[0].getExpReplayer()), "buffLength")
                pkl.dump(model.getBots()[0].getExpReplayer(), output, pkl.HIGHEST_PROTOCOL)
            with open(model.getPath() + "testResults.pkl", 'wb') as output:
                pkl.dump(testResults, output, pkl.HIGHEST_PROTOCOL)

            submitNewJob(model.getPath())
Beispiel #20
0
import parameters
from controller.controller import Controller

parameters.config()
params = parameters.parameters()

control = Controller()
control.exec(params)
Beispiel #21
0
def main():
    ui = UI()
    dao = Dao()
    controller = Controller(ui, dao)
def open_chrome(context):
    context.controller = Controller(driver=None)
    context.controller.open_chrome()
Beispiel #23
0
def main():
    controller = Controller()
    controller.run()
Beispiel #24
0
setup_view.set_size(320, 240)

setup_clock_view = RadioSetupClockView(screen, images, framebuilder, fonts, sizes, colors)
setup_clock_view.set_size(320, 240)

screensaver_view = ScreensaverView(screen, images, cursor_cross, cursor_empty)
screensaver_view.set_size(320, 240)

ui.get_root().add(play_view)
ui.get_root().add(select_view)
ui.get_root().add(select_music_view)
ui.get_root().add(setup_view)
ui.get_root().add(setup_clock_view)
ui.set_screensaver(screensaver_view)

controller = Controller(play_view, select_view, select_music_view, setup_view, setup_clock_view, radio_service, audio_player, network_service, audiofile_service)

ui.get_root().show()
ui.refresh()

input_device = MouseDevice()
pygame.mouse.set_visible(True)
pygame.mouse.set_cursor((16, 16), (7, 7), *cursor_cross)

#pygame.mouse.set_visible(False)
#input_device = TouchDevice()
#input_device.calibration_load('calibration.ini')

while True:
    input_device.poll(ui)
    ui.refresh()
Beispiel #25
0

# citas = m.mostrar_citas()
# contactos = m.mostrar_contactos()
# for i in citas:
#     print(i.asunto)
# for i in contactos:
#     print(i.nombre)

# print("------")
# m.borrar_contacto(1)

# citas = m.mostrar_citas()
# contactos = m.mostrar_contactos()
# for i in citas:
#     print(i.asunto)
# for i in contactos:
#     print(i.nombre)

# v = View()
# s  = m.mostrar_contactos()
# v.mostrar_contactos(s)

# f, c = m.borrar_contacto(1)
# if f:
#     v.borrar_contacto(c)
# else:
#     v.contacto_no_existe(1)

cont = Controller()
cont.start()
Beispiel #26
0
class Menu:
    controller = Controller()
    create()

    @classmethod
    def test(cls):

        cls.controller.create_movie("Home Alone", 5.6)
        cls.controller.create_movie("Taxy", 7.6)

        cls.controller.create_movie_projection(1, "3D", '2018-05-23', '19:10')
        cls.controller.create_movie_projection(1, "2D", '2018-05-23', '19:00')
        cls.controller.create_movie_projection(1, "3D", '2018-05-24', '22:15')

        cls.controller.create_movie_projection(2, "2D", '2018-05-23', '18:00')
        cls.controller.create_movie_projection(2, "3D", '2018-05-24', '21:15')

        # cls.controller.show_movies()
        # cls.controller.show_movie_projections(1, '2018-05-23')

        # tickets = 2
        # movie_id = 1
        projection_id = 1
        username = "******"
        password = "******"

        cls.controller.log_user(username, password)

        # cls.controller.show_movie_projections_with_avaliable_seats(movie_id)
        # print(cls.controller.check_movie_projection(projection_id, tickets))

        cls.controller.create_reservation(projection_id, 2, 3)
        cls.controller.create_reservation(projection_id, 2, 4)

        # cls.controller.show_projection_spots(projection_id)
        # cls.controller.show_projection_info(projection_id, seats)

        cls.controller.finalize()
        cls.controller.exit()

        # tickets = 2
        # movie_id = 1
        # projection_id = 1
        # username = "******"
        # password = "******"

        # cls.controller.log_user(username, password)

        # cls.controller.show_movie_projections_with_avaliable_seats(movie_id)

        # print(cls.controller.check_movie_projection(projection_id, tickets))
        # seats = ['(7, 3)', '(7, 4)']
        # cls.controller.create_reservation(projection_id, seats[0])
        # cls.controller.create_reservation(projection_id, seats[1])

        # cls.controller.show_projection_spots(projection_id)
        # cls.controller.show_projection_info(projection_id, seats)

        # cls.controller.finalize()
        # cls.controller.exit()

    @classmethod
    def show_movies(cls):
        cls.controller.show_movies()

    @classmethod
    def show_movie_projections(cls, command):
        movie_id = command.split(' ')[3]
        try:
            date = command.split(' ')[4]
        except IndexError:
            cls.controller.show_movie_projections(movie_id)
        else:
            cls.controller.show_movie_projections(movie_id, date)

    @classmethod
    def log_user(cls):
        print("You need to a user in the system to make reservations!")
        username = custom_input("Username: "******"Password: "******"Minimum 8 symbols and number, symbol, capital leter!")
            password = custom_input("Password: "******"Hello, {username}")

    @classmethod
    def get_tickets(cls):
        tickets = custom_input("Step 1 (User): Choose number of tickets> ")

        print("Current movies: \n")
        cls.controller.show_movies()
        return tickets

    @classmethod
    def get_movie(cls):
        movie_id = custom_input("Step 2 (Movie): Choose a movie> ")

        print("Projections for movie: \n")
        cls.controller.show_movie_projections_with_avaliable_seats(movie_id)
        return movie_id

    @classmethod
    def get_projection(cls, tickets):
        projection_id = custom_input(
            "Step 3 (Projection): Choose a projection> ")
        while (not cls.controller.check_movie_projection(
                projection_id, tickets)):
            projection_id = custom_input(
                "Step 3 (Projection): Choose a projection> ")

        print("Available seats (marked with a dot): \n")
        cls.controller.show_projection_spots(projection_id)
        return projection_id

    @classmethod
    def get_seats(cls, tickets, projection_id):
        count = 0
        seats = []
        while count < int(tickets):
            seat = custom_input(f"Step 4 (Seats): Choose seat {count + 1}> ")
            if seat == "give up":
                cls.controller.give_up()
                break

            s = (int(seat.split(', ')[0]), int(seat.split(', ')[1]))
            try:
                cls.controller.create_reservation(projection_id, s[0], s[1])
            except (NotValidSeat, SeatNotInRange) as e:
                print(e)
            else:
                seats.append(seat)
                count += 1

        print("This is your reservation: ")
        cls.controller.show_projection_info(projection_id, seats)

    @classmethod
    def finalize(cls):
        finalize = input("Step 5 (Confirm - type 'finalize')> ")
        if finalize == "give up":
            cls.controller.give_up()
        if finalize == "finalize":
            cls.controller.finalize()

    @classmethod
    def cancel_reservation(cls, command):
        username = command.split(' ')[2]
        cls.controller.cancel_reservation(username)

    @classmethod
    def help(cls):
        print(help_command)

    @classmethod
    def exit(cls):
        cls.controller.exit()
        exit()

    @classmethod
    def start(cls):
        print("Welcome to Krisky Cinema!")

        while True:
            command = input("> ")

            if command == 'show movies':
                cls.show_movies()

            elif command.startswith('show movie projections'):
                cls.show_movie_projections()

            elif command == 'make reservation':
                try:
                    cls.log_user()
                    tickets = cls.get_tickets()
                    cls.get_movie()
                    projection_id = cls.get_projection(tickets)
                    cls.get_seats(tickets, projection_id)
                    cls.finalize()
                except GiveUpException:
                    break
            # TO DO make it with name
            elif command.startswith('cancel reservation'):
                cls.cancel_reservation()

            elif command == 'help':
                cls.help()

            elif command == 'exit':
                cls.exit()
            else:
                print("Not a valid command")
Beispiel #27
0
from controller.controller import Controller
from entities.sentance import Hangman
from repository.FileRepository import TextFile
from repository.PickleFile import PickleRepository

#controller = Controller(TextFile("entities/Hangman.txt"))
controller = Controller(PickleRepository("entities/Hangman.pickle"))


def run():
    while True:
        print("Choose a command: 1.Add sentance'\n'2.Play'\n'3.Exit'\n'")
        cmd = int(input("Insert command: "))
        if cmd == 1:
            sentance = input("Insereaza noua propozitie: ")
            controller.addSentance(sentance)
        elif cmd == 2:
            controller.play()
            while controller.get_dead():
                print(controller.get_hangman())
                letter = input("Alege litera: ")
                controller.guess(letter)
        elif cmd == 0:
            break


run()
Beispiel #28
0
from tester.tester import Tester

from ui.application import Application

from controller.controller import Controller

from repository.repository import Repository

with open("database.txt", "r") as f:

    t = Tester()
    repo = Repository()
    controller = Controller(repo, f)
    app = Application(controller, repo)
    app.run()
Beispiel #29
0
from controller.controller import Controller
from model.types import Base
from model.engine import engine
import os

if __name__ == '__main__':
    # 모든 테이블을 만듭니다. 처음에 한 번 실행하고 주석처리 하면 됩니다.
    # Base.metadata.create_all(engine)

    controller = Controller()
    try:
        for year in [2017, 2018, 2019]:
            for month in [i for i in range(1, 13)]:
                controller.save_all_in_month(year, month)
                controller.commit()
                print(f'{year} {month} 저장 완료')
    except:
        os.system('afplay /System/Library/Sounds/Sosumi.aiff')
Beispiel #30
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 14:37:57 2020

@author: Mark
"""
from controller.controller import Controller

if __name__ == "__main__":
    app = Controller()
    app.root.mainloop()