Example #1
0
    def handle_failed_result(self, task_id):
        """save the failed status result

        Args:
            task_id (str): the result under this task_id
        """
        from job_manager import JobManager
        logger = Logger().get()
        logger.debug(
            f"save_result: task_id: {task_id} status: {Status.Failed}")
        ResourceManager().save_result(task_id, [])
        ResourceManager().update_task_status(task_id, Status.Failed)
        JobManager().finish_task(task_id)
        try:
            container = self.id_to_task_container[task_id][1]
        except Exception as e:
            logger.info(
                f"exception for finding container correspoding to {task_id}, status:{Status.Failed}, maybe the container is forced killed before, {e}"
            )
        else:
            self.id_to_task_container.pop(task_id, None)
            container.stop()
            container.remove()
            logger.debug(
                f"for task:{task_id}, can't run cmd normally, exit normally")
Example #2
0
def test_string_input():
    rm = ResourceManager()
    rm.string_input('''
a = [1,2,3]
b = sum(a)
''')
    assert rm.b == 6
Example #3
0
def get_stderr(task_id):
    print(task_id)
    stderr = ResourceManager().get_stderr(task_id)
    if stderr is None:
        abort(404)
    else:
        status_str = ResourceManager().get_status(task_id)
        return {"Status": status_str, "Content": stderr}
Example #4
0
def setup_pharos_tools(app):
    # Remove the check for non-debug mode
    # It means "Only run when app has been loaded"
    # Flask will run it twice to enable the "reload" feature in debug mode
    is_initialized = ResourceManager().setup()
    if is_initialized == False:
        ResourceManager().initialize_pharos_tools()
        t = Thread(target=thread_update_kernel)
        t.start()
Example #5
0
    def __init__(self, root):
        self.resource_manager = ResourceManager(Bank(self))
        self.wave_count = 1
        self._root = root
        self._gameRunning = False
        self._currWaveNumber = 0
        self._currWave = None

        self._canv = Canvas(root, width=CANVAS_DIM, height=CANVAS_DIM)

        self._bottom_panel = Frame(root)
        self._bottom_panel.pack()
        self._canv.pack()

        self._btStartGame = Button(self._bottom_panel,
                                   text="Start Game",
                                   command=self.startGame)
        self._btStartGame.pack(side=LEFT)

        Label(self._bottom_panel, text="Gold: ").pack(side=LEFT)
        self._goldAmtVar = IntVar()
        self._goldAmtVar.set(self.resource_manager.getMoney())
        self._goldLbl = Label(self._bottom_panel,
                              textvariable=self._goldAmtVar)
        self._goldLbl.pack(side=LEFT)

        self._btNextWave = Button(self._bottom_panel,
                                  text="Start Wave",
                                  command=self.startNextWave)
        self._btNextWave.pack(side=LEFT)

        Label(self._bottom_panel,
              text="Time till next wave starts: ").pack(side=LEFT)
        self._timeLeftTilWave = IntVar()
        self._timeLeftTilWave.set(TIME_BETWEEN_WAVES)
        self._timeLeftLbl = Label(self._bottom_panel,
                                  textvariable=self._timeLeftTilWave)
        self._timeLeftLbl.pack(side=LEFT)

        # A 2-d grid of locations
        self._grid = []
        for row in range(NUM_CELLS_PER_DIM):
            rowlist = []
            for col in range(NUM_CELLS_PER_DIM):
                cell = Cell(self._canv, col, row, SQUARE_SIZE,
                            self.resource_manager)
                rowlist.append(cell)
            self._grid.append(rowlist)

        # Follow the mouse everywhere and highlight the cell it is in.
        # self._canv.bind("<Motion>", self.highlight_cell)

        # Read path info from a file and highlight the path on the screen.
        self.readPathInfo()
        self.wave = Wave(self.resource_manager, self._canv, self._path)
    def _sliceSpriteSheet (self, sheet, width, height):
        images = []

        masterImage = ResourceManager().getImage(sheet, self._reuse)

        masterWidth, masterHeight = masterImage.get_size ()

        for i in range (int (masterWidth / width)):
            images.append (masterImage.subsurface ((i * width, 0, width, height)))

        return images
Example #7
0
    def __init__(self, *args, **kwargs):
        log.info("Initializing MapReduceMaster")
        self.rm = ResourceManager()

        self.KV_STORE_HOST = self.rm.find_kvstore()
        self.kvstore = KeyValueStoreClient(self.KV_STORE_HOST)

        self.workers = Queue()
        self.workers_mutex = threading.Lock()

        log.info("Initializing MapReduceMaster is complete, KV_STORE_HOST: {}".
                 format(self.KV_STORE_HOST))
Example #8
0
    def __init__(self, game_opts, *menu_opts):
        # create a programmer friendly mapping stucture of the menu options
        self.options = [{'label': x[0], 'callable': x[1]} for x in menu_opts]
        self.game_opts = game_opts

        # set the default menu dimensions (these dimensions
        # are calculated depending on the font and its size)
        self.width = 0
        self.height = 0

        # set up the default coordinates of the menu
        self.x = 0
        self.y = 0

        # the topleft corner of the screen
        self.screen_topleft_offset = (0, 0)
        # set the default focused option
        self.option = 0

        # set the default previous focused option
        self.option_previous = self.option

        # set the default normal color of the menu font
        self.normal_color = pygame.Color('black')

        # set the default focused color of the menu font
        self.focus_color = pygame.Color('red')

        # default is to enable support of menu image on focused options
        self.image_enabled = True

        # default is to enable support mouse on menu
        self.mouse_enabled = True

        # set mouse focusing at unknown by default
        self.mouse_focus = None
        self._font = None

        # set a default font and its size (also fix size)
        self.font = pygame.font.Font(None, FONT_SIZE)
        self._fix_size()

        # set the default sound to play when an option is focused
        self.focus_sound = load_sound(
            constants.FILES['sounds']['menu']['share']['focus'][0])

        # set the default sound to play when an option is entered
        self.select_sound = load_sound(
            constants.FILES['sounds']['menu']['share']['sel'][0])

        # set the default graphic to display before the option label
        self.focus_graphic = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['share']['focus'][0])
Example #9
0
def submit_job():
    """Test command: curl -H "Content-Type: application/json" --request POST -d @/vagrant/tests/sample_output/input.json http://localhost:5000/job"
    """
    if ResourceManager().get_updating_kernel() is True:
        return {
            "Status":
            "Currently the Pharos toolset is updating. Try later please."
        }

    request_json = request.get_json()
    # print(request.get_json())
    job = ResourceManager().save_new_job_and_tasks(request_json)
    thread = Thread(target=submit_job_through_job_manager, args=(job, ))
    thread.start()
    return {"Status": "ok"}
Example #10
0
def test_bindings_clash():
    with pytest.raises(SemanticError):
        ResourceManager().string_input('''
def f(x):
    x = 1
    return 2
''')
Example #11
0
    def kill_job(self, job_id):
        """Kill all unfinished tasks of this job.

        Args:
            job_id (String): The id of the job
        """
        logger = Logger().get()
        logger.debug(f"Start killing the job({job_id})")

        try:
            job = self.job_metadata[job_id]
            if job.finished_count == len(job.tasks):
                self.job_metadata.pop(job_id, None)
                logger.debug(f"Job({job_id}) has finished. Skipped killing.")
                return

            killed_count = 0
            for task in job.tasks:
                if job.finished_map[task.task_id] == False:
                    ExecutionManager().kill_task(task.task_id)
                    killed_count += 1

            ResourceManager(self.db_name).update_job_status(
                job_id, Status.Killed)

            self.job_metadata.pop(job_id, None)

            logger.debug(f"Killed {killed_count} tasks of Job({job_id}).")

        except Exception as e:
            logger.error(
                f"Something wrong when killing job({job_id}). Exception: {e}")
Example #12
0
    def __init__(self):
        pygame.init()

        self.clock = pygame.time.Clock()
        self.fps = SETTINGS['default_fps']

        # fullscreen on/off
        if SETTINGS['fullscreen_mode']:
            self.screen = pygame.display.set_mode((
                                                    SETTINGS['window_x_size'],
                                                    SETTINGS['window_y_size']
                                                    ),
                                                    pygame.FULLSCREEN
                                                )
        else:
            self.screen = pygame.display.set_mode((
                                                    SETTINGS['window_x_size'],
                                                    SETTINGS['window_y_size']
                                                ))

        # load resource manager
        self.rm = ResourceManager()

        # load input manager
        self.im = InputManager()

        # state setup
        self.cur_state = BoardState(self.screen,self.rm)

        # gui
        self.gui = PGui(self)
Example #13
0
    def __read_file(self, file_path):
        """
        :param file_path: absolute path of the file.
        :return: entity name and value as list inside config file.
        """
        try:
            val = []
            name = []

            with open(file_path, 'r') as f:

                for l in f:
                    l = l.strip()

                    if l != "\n" and l:

                        if l.startswith("#"):
                            continue

                        line = l.split("=")
                        left_side_val = line[0].strip().lower()
                        right_side_val = line[1].strip()
                        name.append(left_side_val)

                        if right_side_val.lower() == 'true':
                            val.append(True)
                        elif right_side_val.lower() == 'false':
                            val.append(False)
                        elif right_side_val.lstrip("+-").isdigit():
                            val.append(int(right_side_val))
                        elif (len(right_side_val.lower())
                              == 0) or (right_side_val.lower() == "n/a"):
                            val.append(None)
                        else:
                            if left_side_val.lower() in [
                                    "gcs_credential_directory_path",
                                    "local_upload_path", "local_download_path",
                                    "local_log_path"
                            ]:
                                ResourceManager.create_dir(right_side_val)
                            val.append(right_side_val)
                f.close()
            return name, val
        except:
            trace_err = StackTrace.get_stack_trace()
            msg = "Config (__read_file()) : %s%s" % ("\n", trace_err)
            raise Exception(msg)
Example #14
0
def save_realtime_stderr():
    Thread(target=lambda task_id, stderr: ResourceManager().update_stderr(
        task_id, stderr),
           args=(
               request.form['task_id'],
               request.form['stderr'],
           )).start()
    return {"status": "ok"}
class Listener(mapreduce_pb2_grpc.MapReduceWorkerServicer):
    def __init__(self, *args, **kwargs):
        self.rm = ResourceManager()
        self.kvstore = KeyValueStoreClient(self.rm.find_kvstore())

    def Execute(self, task, context):
        print('Execute request. code_id:{}, chunk_id:{}, type:{}'.format(
            task.code_id, task.input_chunk_id, task.type))
        log.info('Execute request. code_id:{}, chunk_id:{}, type:{}'.format(
            task.code_id, task.input_chunk_id, task.type))

        # download code and chunk
        log.info('Downloadin chunk')
        workplace = os.path.join(INTERMEDIATE_OUTPUTS_DIR, task.output_doc_id)
        self.kvstore.download_directory(task.code_id, workplace, flatten=True)

        log.info('Downloading code')
        module_name = generateId()
        os.rename(os.path.join(workplace, 'task.py'),
                  os.path.join(workplace, module_name + '.py'))

        try:
            sys.path.insert(1, workplace)
            py = __import__(module_name)

            output = []
            if task.type == 'map':
                chunk = self.kvstore.read_chunk(
                    task.input_chunk_id).decode(KV_STORE_ENCODING)
                for ch in py.mapper(task.input_doc_id, chunk):
                    output.append(ch)

                self.kvstore.upload_bytes(task.output_dir_id,
                                          task.output_doc_id,
                                          pickle.dumps(output))
            elif task.type == 'reduce':
                chunk = pickle.loads(
                    self.kvstore.read_bytes(task.input_dir_id,
                                            task.input_doc_id))
                for ch in py.reducer(chunk):
                    output.append('{} {}'.format(ch[0], ch[1]))

                self.kvstore.upload_file_str(task.output_dir_id,
                                             task.output_doc_id,
                                             '\n'.join(output))
            else:
                raise 'unknown operation'

            log.info('success')
            return mapreduce_pb2.ExecutionInfo(exec_id=task.output_dir_id,
                                               status='success')
        except BaseException as e:
            log.info('task failed {}'.format(e))
            return mapreduce_pb2.ExecutionInfo(exec_id=task.output_dir_id,
                                               status='failed')
        finally:
            shutil.rmtree(workplace)
Example #16
0
    def _run(self, resource_manager: ResourceManager, on_finish,
             sleep_during_loop):
        cmd = " ".join(self.command_line())
        if self.print_command_line:
            print("Start {} with cmd: {}".format(self.id, cmd))
        subprocess.Popen(cmd, shell=True)

        while not resource_manager.is_application_finished(self.id):
            if not self.is_running and resource_manager.is_application_running(
                    self.id):
                self.is_running = True

            time.sleep(sleep_during_loop)

        print("Application {} has finished".format(self))

        if callable(on_finish):
            on_finish(self)
Example #17
0
    def __init__(self, manager, slides):
        self.event_manager = manager
        self.event_manager.register_listener(self)

        self.screen = pygame.display.get_surface()

        if not len(slides):
            raise SlideLenError('Incorrect slide length: {0}'.format(sl))

        self.slides = slides

        parser = ConfigParser(constants.MAIN_CFG, constants.CFG_XMLNS)
        dir_name = parser.first_match('intro').attrib
        file_path = path.join(dir_name['dir'],
                              parser.first_match('blank').text)

        self.blank = ResourceManager().getImage(file_path)
        self.alphavalue = MAX_ALPHA
Example #18
0
    def __init__(self, ev_manager):
        self._rm = ResourceManager.instance()
        self._font = self._rm.get_font(FONT, FONT_SIZE)
        self._default_font = self._rm.get_font(FONT_ITALIC, FONT_SIZE)
        self._text_inputs = None
        self._connection_failed_warning = None
        self._username_taken_warning = None

        bg_widget = self._create_widgets()
        super(LoginView, self).__init__(ev_manager, bg_widget)
Example #19
0
    def __init__(self, ev_manager):
        self._rm = ResourceManager.instance()
        self._font = self._rm.get_font(FONT, FONT_SIZE)
        self._default_font = self._rm.get_font(FONT_ITALIC, FONT_SIZE)
        self._text_inputs = None
        self._connection_failed_warning = None
        self._username_taken_warning = None

        bg_widget = self._create_widgets()
        super(LoginView, self).__init__(ev_manager, bg_widget)
Example #20
0
    def __init__(self):
        try:
            os.environ['SDL_VIDEO_WINDOW_POS'] = str(44) + "," + str(44)

            self.commandQueue_l = []
            self.projectionMatrix = None

            self.configs = Configs()
            self.globalStates = GlobalStates()
            self.commander = Commander(self)

            self.globalStates.winWidth_i = self.configs.initScreenSizeWidth_i
            self.globalStates.winHeight_i = self.configs.initScreenSizeHeight_i

            p.init()
            winSize_t = ( self.globalStates.winWidth_i, self.globalStates.winHeight_i )
            if self.configs.fullScreen_b:
                p.display.set_mode(winSize_t, pl.DOUBLEBUF | pl.OPENGL | pl.FULLSCREEN)
            else:
                p.display.set_mode(winSize_t, pl.DOUBLEBUF | pl.OPENGL | pl.RESIZABLE)

            self.player = Player()
            self.camera = Camera("main_camera", self.player, (0.0, 1.6, 0.0))
            self.controller = Controller(self, self.player)

            self.resourceManager = ResourceManager(self.globalStates)
            self.resourceManager.runProcesses()
            self.resourceManager.requestLevelLoad("entry", 5.0)

            self.console = self.resourceManager.overlayUiMan.consoleWin

            self.fMan = FrameManager( False, self.resourceManager.overlayUiMan.frameDisplay.update, 0 )

            self.renderDude = RenderingDude(self.player, self.resourceManager, self.camera, self.configs)
            self.logicalDude = LogicalDude(self.resourceManager, self.player, self.commandQueue_l, self.globalStates)

            self.globalStates.menuPopUp_b = True
            self.controller.enableMouseControl(False)

            self.initGL()
        except:
            self.terminate()
            raise
    def __init__(self, kvstore_host):
        log.info("Initializing KeyValueStoreClient")

        self.rm = ResourceManager()
        self.KV_STORE_HOST = kvstore_host
        self.KV_STORE_DB_PATH = 'mysql+pymysql://root:P@ssword123@{}:3306/kvstore'.format(
            kvstore_host)
        self.db = DataBaseHandler(self.KV_STORE_DB_PATH)

        log.info("Initializing KeyValueStoreClient is successful")
Example #22
0
    def __init__(self, hyper_params, max_num=9999, random=True):
        self.hp_name = list(hyper_params.keys())
        self.hp = self.get_hp(hyper_params)
        self.max_num = max_num
        self.random = random

        self.resource_manager = ResourceManager(mem_limit=1,
                                                cpu_limit=0.1,
                                                gpu_limit=0.5,
                                                max_instances=self.max_num)

        self.waiting_pool = [item for item in self.hp]
        self.finished_pool = []
        self.working_pool = []
        self.working_process = []

        self.lock_list = []
        self.shared_eps_num_list = []
        self.shared_eps_reward_list = []
def main():
    # change the current directory to the one of the game
    # this is to allow executions like ``python src/tct.py''
    try:
        os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
    except IOError as e:
        print(e)
        exit(constants.FILE_ERR)

    # create the resource manager and initialize it.
    resourceManager = ResourceManager()
    resourceManager.setResourcesPath(constants.RESOURCES_DIR)
    resourceManager.setImagesPath(constants.GRAPHICS_DIR)

    # get the command line options; return the option flags
    game_opts = get_parsed_opts()

    # MVC stuff
    event_manager = EventManager()
    gui_view = MainGUIView(event_manager, game_opts)

    # the game manager
    game_manager = GameManager(game_opts)

    # controller which handles the main game loop
    main_controller = MainController(event_manager, gui_view, game_manager)

    # keep running the game until a quit event occurs
    main_controller.run()

    # if control somehow reaches this point close all the pygame subsystems
    pygame.quit()
    safe_exit()
Example #24
0
    def __init__(self, analysis_config, train_configs, datasets, split_names, base_models=[], output_dir=None, search_name=None, monitor_cpu=True, monitor_gpu=True, cpu_cores=[], gpu_devices=[]):
        self._analysis_cfg = analysis_config
        
        # create trial output dir if not specified
        if search_name is None:
            search_name = 'gqcnn_hyperparam_search_{}'.format(gen_timestamp())  
        if output_dir is None:
            output_dir = 'models'
        self._trial_output_dir = os.path.join(output_dir, search_name)
        if not os.path.exists(self._trial_output_dir):
            os.makedirs(self._trial_output_dir)

        # set up logger
        self._logger = Logger.get_logger(self.__class__.__name__, log_file=os.path.join(self._trial_output_dir, 'search.log'), global_log_file=True)

        # init resource manager
        self._resource_manager = ResourceManager(TrialConstants.TRIAL_CPU_LOAD, TrialConstants.TRIAL_GPU_LOAD, TrialConstants.TRIAL_GPU_MEM, monitor_cpu=monitor_cpu, monitor_gpu=monitor_gpu, cpu_cores=cpu_cores, gpu_devices=gpu_devices)
        
        # parse train configs and generate individual trial parameters
        if len(base_models) > 0:
            assert len(train_configs) == len(datasets) == len(split_names) == len(base_models), 'Must have equal number of training configs, datasets, split_names, and base models!'
        else:
            assert len(train_configs) == len(datasets) == len(split_names), 'Must have equal number of training configs, datasets, and split_names!'
        self._logger.info('Generating trial parameters...')
        trial_params = gen_trial_params(train_configs, datasets, split_names, base_models=base_models)

        # create pending trial queue
        self._trials_pending_queue = Queue()
        if len(base_models) > 0:
            for trial_name, hyperparam_summary, train_cfg, dataset, base_model, split_name in trial_params:
                self._trials_pending_queue.put(GQCNNFineTuningAndAnalysisTrial(self._analysis_cfg, train_cfg, dataset, base_model, split_name, self._trial_output_dir, trial_name, hyperparam_summary))
        else:
            for trial_name, hyperparam_summary, train_cfg, dataset, split_name in trial_params:
                self._trials_pending_queue.put(GQCNNTrainingAndAnalysisTrial(self._analysis_cfg, train_cfg, dataset, split_name, self._trial_output_dir, trial_name, hyperparam_summary))

        # create containers to hold running, finished, and errored-out trials
        self._trials_running = []
        self._trials_finished = []
        self._trials_errored = []
Example #25
0
    def __init__(self):

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.display = DisplaySystem()

        self.key = Keyboard()
        self.mouse = Mouse()
        self.resman = ResourceManager()
Example #26
0
class IntroCutSceneGUIView:
    '''This class is responsible for initialising all the intro cut scene 
    GUI-related stuff and handling the related events.
    '''
    def __init__(self, manager, slides):
        self.event_manager = manager
        self.event_manager.register_listener(self)

        self.screen = pygame.display.get_surface()

        if not len(slides):
            raise SlideLenError('Incorrect slide length: {0}'.format(sl))

        self.slides = slides

        parser = ConfigParser(constants.MAIN_CFG, constants.CFG_XMLNS)
        dir_name = parser.first_match('intro').attrib
        file_path = path.join(dir_name['dir'],
                              parser.first_match('blank').text)

        self.blank = ResourceManager().getImage(file_path)
        self.alphavalue = MAX_ALPHA

    def notify(self, event):
        '''Handle the related events.'''

    def next_slide(self, slide):
        '''Blit the given slide on screen.'''
        self.blank.set_alpha(self.alphavalue)

        # blit the slide
        s = self.screen.blit(slide, (0, 0))
        # blit the blank slide
        bs = self.screen.blit(self.blank, (0, 0))

        # pass only the changes to update
        up_l = (s, bs)
        pygame.display.update(up_l)
Example #27
0
def get_job(id):
    """Test command: curl --request GET http://localhost:5000/job-info/<id>/json

    Test steps:
        1. Modify line 14 & 15 of this file to use database "test"
        2. Run "curl --request GET http://localhost:5000/clean-all"
        3. Submit jobs through browser
        4. Run "curl --request GET http://localhost:5000/job-list/json" to get the list
        5. Run "curl --request GET http://localhost:5000/job-info/<id>/json" where the id is of the first job in the list
        6. Run "curl --request GET http://localhost:5000/clean-all" after use
        7. Remember to modify the name of the database
    """
    job_dict = ResourceManager().get_job_info(id)
    return job_dict
Example #28
0
def update_kernel():
    """update backend Pharos tool from docker hub
    The form of the POST format: {Content: seipharos/pharos:latest}
    Test command: curl http://localhost:5000/pharos -X POST -d "Content=seipharos/pharos:latest"
                  curl http://localhost:5000/pharos -X POST -d "Content=ubuntu"
    """
    if ResourceManager().get_updating_kernel() is True:
        return {
            "Status":
            "Currently the Pharos toolset is updating. Try later please."
        }
    BASE_IMAGE = request.get_json()['Content']
    t = Thread(target=thread_update_kernel, args=(BASE_IMAGE, ))
    t.start()
    return {"Status": "ok"}
Example #29
0
    def initialize_job(self, new_job):
        """Initialize additional metadata of the new job.

        Args:
            new_job (Job): The job object
        """
        new_job.finished_count = 0
        new_job.finished_map = {}
        for task in new_job.tasks:
            new_job.finished_map[task.task_id] = False
        self.job_metadata[new_job.job_id] = new_job
        for task in new_job.tasks:
            self.task_id_to_job_id[task.task_id] = new_job.job_id
        ResourceManager(self.db_name).update_job_status(
            new_job.job_id, Status.Running)
    def start(self, resource_manager: ResourceManager, on_finish=None, sleep_during_loop=5):
        self.id = resource_manager.next_application_id()
        print("Start Application {}".format(self))

        for task in self.tasks:
            if task.node is None:
                raise NotCorrectlyScheduledError(
                    "A task of the application {} is not scheduled on a node".format(self.name)
                )
            self.nodes.add(task.node.address)

        # print(self.nodes)
        print(datetime.datetime.utcnow().strftime('%Y-%m-%d"T"%H:%M:%S"Z"'))

        self.thread = Thread(target=self._run, args=[resource_manager, on_finish, sleep_during_loop])
        self.thread.start()
Example #31
0
    def start(self,
              resource_manager: ResourceManager,
              on_finish=None,
              sleep_during_loop=5):
        self.id = resource_manager.next_application_id()
        print("Start Application {}".format(self))

        for task in self.tasks:
            if task.node is None:
                raise NotCorrectlyScheduledError(
                    "A task of the application {} is not scheduled on a node".
                    format(self.name))

        self.thread = Thread(
            target=self._run,
            args=[resource_manager, on_finish, sleep_during_loop])
        self.thread.start()
    def __init__(self, manager, game_opts):
        self.event_manager = manager
        self.event_manager.register_listener(self)
        self.game_opts = game_opts
        GAME_WINDOW_TITLE = constants.GAME_PACKAGE

        # make the window of the game always centered
        os.environ["SDL_VIDEO_CENTERED"] = "1"

        pygame.init()

        pygame.display.set_mode(
            (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT),
            pygame.FULLSCREEN if self.game_opts.fullscreen else 0)
        pygame.display.set_caption(GAME_WINDOW_TITLE)
        pygame.display.set_icon(ResourceManager().getImage(
            constants.FILES['graphics']['window']['icon'][0]))

        pygame.mouse.set_visible(False)
Example #33
0
 def __init__(self, ev_manager):
     self.elapsed_time = 0
     self.last_win_time = -5
     self._rm = ResourceManager.instance()
     self._font = self._rm.get_font(FONT, FONT_SIZE)
     self._warnings = {}
     self.username = None
     self._player_positions = {}
     self._card_widgets = {}
     self._trump_widgets = {}
     self._choose_trump_widget = None
     self._ask_tricks_widget = None
     self._user_move = False
     self._played_card_widgets = []
     self._said_tricks_widgets = {}
     self._user_move_widget = None
     self._player_order = None
     self.final_winners = None
     self.final_points = None
     bg_widget = self._create_widgets()
     super(CardGameView, self).__init__(ev_manager, bg_widget)
Example #34
0
class Game(object):
    def __init__(self):

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.display = DisplaySystem()

        self.key = Keyboard()
        self.mouse = Mouse()
        self.resman = ResourceManager()


    def on_start(self): pass
    def on_stop(self): pass

    def start(self):
        self.run()

    def stop(self):
        self.running = False

    def set_mode(self, mode):
        mode._attach_parent(self)
        if self.running:
            self.current_mode.stop()

        self.current_mode = mode

        if self.running:
            self.current_mode.start()

    def run(self):
        self.on_start()

        if self.current_mode == None: return

        self.current_mode.start()
        self.running = True

        while(self.running):
            time_elapsed = self.clock.tick(self.fps)

            self.check_events()

            #Run a frame of the current mode
            self.current_mode.run(time_elapsed) #For now let's just pretend the fps is perfect
            self.current_mode.scene.update(time_elapsed)
            self.current_mode.frame += 1 #Increment frame count of active mode

            self.current_mode.camera.render()

            self.display.blit(self.current_mode.camera.surface)

        self.current_mode.stop()
        self.on_stop()

        pygame.quit()

    def check_events(self):
        self.key._on_enter_frame()
        self.mouse._on_enter_frame()
        self.resman._on_enter_frame()
        self.display._on_enter_frame()

        for event in pygame.event.get():
            if   event.type == pygame.QUIT:
                self.running = False #No arguing

            elif event.type == pygame.KEYDOWN:
                #Some alt+key special hotkeys. TODO: Move this elsewhere
                if pygame.key.get_mods() & pygame.KMOD_ALT:
                    if event.key == pygame.K_ESCAPE:
                        self.running = False
                    if event.key == pygame.K_F12:
                        pygame.image.save(self.screen, utils.join_path("user", "screenshot.png"))

                self.key._on_key_down(event)

            elif event.type == pygame.KEYUP:
                self.key._on_key_up(event)

            elif event.type == pygame.MOUSEMOTION:
                self.mouse._on_mouse_motion(event)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.mouse._on_mouse_button_down(event)

            elif event.type == pygame.MOUSEBUTTONUP:
                self.mouse._on_mouse_button_up(event)
import time
from resource_manager import ResourceManager

#
# Resources required
#
resourcesA =  {'typevm':"m1.small"}
resourcesB =  { 'cpu':1, 'ram':128, 'disk':2, 'level':1 }
resourcesC =  { 'cpu':1, 'ram':256, 'disk':5, 'level':1 }
resourcesD =  {'cpu':1, 'ram':200, 'disk':4.5, 'level':0, 'percent':0.5}

resources = [ resourcesA, resourcesB, resourcesC, resourcesD ]
infra_deploy = ResourceManager()

#
# Getting Instances
#
instances, instances_ok, reservations = infra_deploy.get_instances(resources)
print "Instances(engine): %s" % instances
print "Num Instances to verify: %s" % instances_ok
print "New Instances(engine): %s" % reservations

#
# Rebooting Instances
#
print "\nGettint instances ids"
instances_ids = []
for instance in instances:
    instances_ids.append( instance[0].id.encode("latin-1") )

print "Instances Ids to Reboot: %s" % instances_ids
Example #36
0
'''
Created on Apr 11, 2013

@author: Suvodeep Pyne
'''
import pprint as pp
import json
from resource_manager import ResourceManager

rm = ResourceManager()

json_data = open(rm.get_resource('sample_data.json'))
data = json.load(json_data)
pp.pprint(data)