def __init__(self): """Inicjalizacja gry""" self._current_player = Player("Adam", Color.White) self._next_player = Player("Eve", Color.Black) self._console = Console() self._board = Chessboard() self._board.init()
def explore(fpath): _, ext = splitext(fpath) ftype = 'data' if ext in ('.h5', '.hdf5') else 'simulation' print("Using %s file: '%s'" % (ftype, fpath)) if ftype == 'data': globals_def, entities = entities_from_h5(fpath) data_source = H5Data(None, fpath) h5in, _, globals_data = data_source.load(globals_def, entities) h5out = None simulation = Simulation(globals_def, None, None, None, None, entities.values(), None) period, entity_name = None, None else: simulation = Simulation.from_yaml(fpath) h5in, h5out, globals_data = simulation.load() period = simulation.start_period + simulation.periods - 1 entity_name = simulation.default_entity entities = simulation.entities_map if entity_name is None and len(entities) == 1: entity_name = entities.keys()[0] if period is None and entity_name is not None: entity = entities[entity_name] period = max(entity.output_index.keys()) eval_ctx = EvaluationContext(simulation, entities, globals_data, period, entity_name) try: c = Console(eval_ctx) c.run() finally: h5in.close() if h5out is not None: h5out.close()
def __init__(self): self.width = getWidth() self.height = getHeight() self.fps = getFPS() self.bubbleCount = int(getWidth() / 160) self.drawBubbles = True self.drawBG = True pygame.init() self.fpsClock = pygame.time.Clock() if fullscreen(): self.windowSurfaceObj = pygame.display.set_mode( (self.width, self.height), pygame.FULLSCREEN) else: self.windowSurfaceObj = pygame.display.set_mode( (self.width, self.height)) pygame.display.set_caption('Anim') pygame.mouse.set_visible(cursor()) for i in range(0, self.bubbleCount): self.entitylist[2].append(Bubble(True)) self.entitylist[0].append(Bubble(False)) self.player = Player() self.entitylist[1].append(self.player) self.background = Background() print('Init...') self.console = Console(getWidth(), getHeight()) Console.host = self self.DrawPosVector = False
def start_console(): print("Welcome to the Shadowrun Combat Manager") print("type \"exit\" to close. Type \"help\" for a list of commands for for details on a specific command") print() console = Console() add_default_commands(console) console.run_console()
def write_cfg(self): """ Schrijf settings naar config bestand. """ with open(SETTINGSFILE, 'wb') as f: pickle.dump([self.music, self.sound], f) Console.write_settings()
def write_cfg(self): """ Schrijf settings naar config bestand. """ with open(SETTINGSFILE, 'wb') as f: pickle.dump([self.fullscreen, self.window_frame], f) Console.write_settings()
def _add_console(self): """ Adds a widget to the bottom pane for command output. """ self._console = Console() self._console.set_font(self._settings.get_string("console-font")) panel = self.window.get_bottom_panel() panel.add_item_with_stock_icon(self._console, "AndroidConsole", "Console", STOCK_CONSOLE)
def __init__(self): self.console = Console() self.landscape = Landscape() self.display = Display(self.landscape, self.console) self.control = Controller(self.console) self.cursorX = 2 self.cursorY = 2
def play(cls): cls.__set_players() cls.__set_deck() for player in cls.__players: cls.__table_deck.assign_cards_player(player, 2, cls.__table_deck.deck) cls.__number_of_players = len(cls.__players) #We let everybody see their cards by turns print( "\nOn this first round every player will get to SEE THEIR CARDS.") for player in cls.__players: player.status = "Playing" print("PASS computer to {}".format(player)) input("PLAYER {} PRESS ANY KEY to see your cards".format(player)) player.see_cards() input("PRESS ANY KEY to continue") Console.clear() player.status = None #To not begin first round inmediately: print("Pass the computer to {}".format(cls.__players[0])) input("NOW THE GAME BEGINS: press enter ") while len(cls.__players) > 1: for player in cls.__players: if (player == cls.__current_player): continue cls.__current_player = player cls.__player_play() cls.__remove_player() print("{} there are NO MORE PLAYERS left, YOU WON!!".format( cls.__players[0]))
def send_over_communication_network(self): if not self.processWeightDataQueue.empty(): process_data = self.processWeightDataQueue.get() if 'data' in process_data: Console.customPrint( self.logFile, 'PLC receives: ' + str(process_data['data'])) self.communicationNetwork.put({'data': process_data['data']})
def __set_players(cls): for i in range(1, cls.NUMBER_OF_PLAYERS + 1): name = Console.get_str_input_with_args( '\nWrite player\'s {} name: ', [i]) cls.__players.append(Player(name, i)) cls.__actual_player = cls.__players[0] Console.clear()
def __init__(self): self._cursor = (1, 1) self._start = (1, 1) self._goal = (33, 8) self._console = Console() self._map = Map() self._astar = AStar(self._map.cost)
def render(self, screen): """ Surface tekent layer, de rest gaat op de layer, en screen tekent de surface. :param screen: self.screen van partyscreen """ self.surface.blit(self.layer, (0, self.lay_rect.y - self.rect.y)) self.layer.blit(self.background, (0, 0)) # zwarte background achter de titel. is voor scrollen. pygame.draw.rect(self.surface, COLORKEY, pygame.Rect(TITLERECT)) self.surface.blit(self.title, (self.title_x, self.title_y)) # zwarte omranding ná de titel, omdat de titel uitsteekt. pygame.draw.rect(self.surface, self.linecolor, self.surface.get_rect(), 1) for index, row in enumerate(self.view_matrix): for row_nr, columnx in enumerate(self.total_columns): if columnx[0] == ColumnType.icon: self.layer.blit( row[row_nr], (columnx[1], self.columnsy + self.iconoffset + index * self.rowheight)) elif columnx[0] == ColumnType.text: self.layer.blit( row[row_nr], (columnx[1], self.columnsy + index * self.rowheight)) else: Console.error_unknown_column_key() raise KeyError if self.lay_rect.y - self.rect.y < 0: self.surface.blit(self.up_arrow, (self.box_width + ARROWRIGHT, ARROWTOP)) if self.lay_rect.y - self.rect.y - BOTTOMSPACER > self.rect.height - self.layer_height: self.surface.blit(self.down_arrow, (self.box_width + ARROWRIGHT, self.box_height + ARROWBOTTOM)) screen.blit(self.surface, self.rect.topleft)
def __init__(self, isChat): self.speech_domain = '' self.isChat = isChat if isChat: self.console = Console() self.answerer = Answerer() self.default_response = ['是嗎?', '有道理', '我認同', '我不太明白你的意思', '原來如此']
class ManagerMenu(Menu): def __init__(self, master=None): super().__init__(master) self.master = master self.file = Menu(self) self.add_cascade(menu=self.file, label='File') self.file.add_command(label='New Console', command=self.new_console) self.file.add_command(label='Console Settings', command=self.new_settings) self.settings = None self.console = None master['menu'] = self def new_console(self): if self.console != None: self.console.destroy() self.console = Console(master=self.master) self.console.focus_force() def new_settings(self): if self.settings == None: self.settings = ConsoleSettings(master=self.master) if not self.settings.winfo_exists(): self.settings = ConsoleSettings(master=self.master) self.settings.focus_force()
class Widget(QDialog): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.View = View(config.enosPath) self.console = Console() self.View.setFocusPolicy(Qt.StrongFocus) lt = QVBoxLayout() lt.addWidget(self.View) lt.addWidget(self.console) self.setLayout(lt) self.View.focusOut.connect(self.switchFocus) # fake View's focus out self.View.focusOutEvent('') self.console.setFocus() self.focus = 'console' self.console.focusOut.connect(self.switchFocus) def keyPressEvent(self, ev): ch = ev.text() super(Widget, self).keyPressEvent(ev) def switchFocus(self): if self.focus == 'console': self.View.setFocus() self.focus = 'View' else: self.console.setFocus() self.focus = 'console'
class CalculatorEngine: def __init__(self) -> None: super().__init__() self.display = CalculatorDisplay() self.computer = CalculatorComputer() self.console = Console() def perform_add(self): first_value = self.console.get_double_input( "Enter your first value to be added") second_value = self.console.get_double_input( "Enter your second value to be added") sum = self.computer.add(first_value, second_value) self.display.current_value = sum def perform_subtract(self): return None # TODO - Implement method def perform_multiply(self): return None # TODO - Implement method def perform_divide(self): return None # TODO - Implement method def display(self): self.display.display()
def server(cx=0, cy=0, tx=0, ty=0, angle=0, saved_file="model.pickle"): cx = request.args.get('cx', "CX") cy = request.args.get('cy', "CY") tx = request.args.get('tx', "TX") ty = request.args.get('ty', "TY") angle = request.args.get('angle', "ANG") if (cx == "CX" or cy == "CY" or tx == "TX" or ty == "TY" or angle == "ANG"): return render_template('index.html') cx = float(cx) tx = float(tx) cy = float(cy) ty = float(ty) angle = float(angle) g = None with open(saved_file, 'rb') as f: g = pickle.load(f) if g is None: return "Error - couldn't load model" #return ('{} | {} | {} | {}'.format(cx, angle, type(cx), type(angle))) result = g.predict([cx,cy,tx,ty,angle]) res= {'model':'miss', 'actual':'miss'} if result[0]>result[1]: res['model']='hit'; game = Console(Canon(x=cx, y=cy, angle=angle), Target(x=tx, y=ty, radius=3)) result = game.shoot() game.display2f() if result: res['actual']='hit' valid = 'MODEL PREDICTION IS CORRECT!' if res['actual'] != res['model']: valid = 'MODEL PREDICTION IS INCORRECT.' figID = '/static/capt.png?{}{}{}{}{}'.format(cx,cy,tx,ty,angle) return render_template('index.html', answer=str(res), validation=str(valid), cx=str(cx), cy=cy, tx=tx, ty=ty, angle=angle, figure=figID)
def __init__(self): """ Start up the game window and initialize game resources """ pygame.init() # Get game settings self.settings = Settings() # Set up the display self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Mission X") self.console = Console(self) # Start storing game statistics self.stats = GameStats(self) # Attach appropriate groups to respective variables self.ship = Ship(self) self.rockets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.stars = pygame.sprite.Group() # Make play button self.play_button = Button(self, 'Play')
def __init__(self, hints_file="../resource/hints.json"): self.problem_template = ProblemTemplate() self.io_helper = IOHelper() self.console = Console() self.problem_metadata = problem_metadata with open(hints_file, "r", encoding="utf-8") as f: self.hints_json = json.load(f)
def __see_coins_and_cards(cls): print("\nGAME STATUS: [ {}'s turn ]".format(cls.__current_player)) print("----------------------------------------") for i in cls.__players: Console.coins_and_cards_display(i.name, i.coins, i.cards[0], i.cards[1]) print("----------------------------------------")
def __init__(self): self.titulo = '' self.recursosMaximos = [] self.recursosAlocados = [] self.recursosNecessarios = [] self.__console = Console() self.__finalizado = False
def explore(fpath): _, ext = splitext(fpath) ftype = 'data' if ext in ('.h5', '.hdf5') else 'simulation' print("Using {} file: '{}'".format(ftype, fpath)) if ftype == 'data': globals_def, entities = entities_from_h5(fpath) simulation = Simulation(globals_def, None, None, None, None, entities.values(), 'h5', fpath, None) period, entity_name = None, None else: simulation = Simulation.from_yaml(fpath) # use output as input simulation.data_source = H5Source(simulation.data_sink.output_path) period = simulation.start_period + simulation.periods - 1 entity_name = simulation.default_entity dataset = simulation.load() data_source = simulation.data_source data_source.as_fake_output(dataset, simulation.entities_map) data_sink = simulation.data_sink entities = simulation.entities_map if entity_name is None and len(entities) == 1: entity_name = entities.keys()[0] if period is None and entity_name is not None: entity = entities[entity_name] period = max(entity.output_index.keys()) eval_ctx = EvaluationContext(simulation, entities, dataset['globals'], period, entity_name) try: c = Console(eval_ctx) c.run() finally: data_source.close() if data_sink is not None: data_sink.close()
def __init__(self): self.rng = RNG() self.entities = [] self.active_entities = [] self.dungeon = None self.message_log = None self.menu = None self.overlay = None self.tile_types = {} self.materials = {} self.words = {} self.status_effects = {} self.traits = {} self.abilities = {} self.breeds = {} self.prefabs = {} self.active_region = [] self.player = None self.fps=0 self.map_con = Console("Dungeon Map",MAP_X,MAP_Y,MAP_W,MAP_H) self.panel_con = Console("Side Panel",PANEL_X,PANEL_Y,PANEL_W,PANEL_H) self.log_con = Console("Message Log",LOG_X,LOG_Y,LOG_W,LOG_H) self.state = STATE_PLAYING self.input_state = INPUT_NORMAL self.key = libtcod.Key() self.mouse = libtcod.Mouse()
class Sandy: _settings = {} def __init__(self): self.console = Console() def start_console(self): self.console.run()
def __init__(self): """ Pull all variables from config.py file. """ self.player = Player() self.database = config.database self.Max_point_tournament = config.Max_point_tournament self.BotNet_update = config.BotNet_update self.joinTournament = config.joinTournament self.tournament_potator = config.tournament_potator self.booster = config.booster self.Use_netcoins = config.Use_netcoins self.attacks_normal = config.attacks_normal self.updates = config.updates self.updatecount = config.updatecount self.maxanti_normal = config.maxanti_normal self.active_cluster_protection = config.active_cluster_protection self.mode = config.mode self.number_task = config.number_task self.min_energy_botnet = config.minimal_energy_botnet_upgrade self.stat = "0" self.wait_load = config.wait_load self.c = Console(self.player) self.u = Update(self.player) # disable botnet for > api v13 self.b = Botnet(self.player) self.ddos = ddos.Ddos(self.player) self.m = Mails(self.player) self.init()
def murder(self, player, list_of_players): if len(list_of_players) == 1: print("SORRY there are no other players with influences to murder") return 0 player.coins = -3 choose_person = [] counter = 0 for person in (list_of_players): if person.status != "Playing": choose_person.append(person) print( "You can MURDER an INFLUENCE of {} by pressing {}".format( person, counter)) counter += 1 print( "Enter the number of the person's influence you want to murder: ") murder_person = Console.cast(0, counter) print("PASS the computer to {}".format( choose_person[murder_person].name)) input("PRESS ANY KEY to continue") Console.clear() choose_person[murder_person].resign_card() print("Player {} now has {} coins".format(player.name, player.coins))
def get_answer(data, part2=False): c = Console(data) if part2: return brute_force(c) else: return c.run()
def setUp(self): self.credentials_json = json.dumps({ 'sessionId': 'id', 'sessionKey': 'key', 'sessionToken': 'token' }) self.c = Console()
def __init__(self): """ Pull all variables from config.py file. """ self.player = Player() self.database = config.database self.Max_point_tournament = config.Max_point_tournament self.BotNet_update = config.BotNet_update self.joinTournament = config.joinTournament self.tournament_potator = config.tournament_potator self.booster = config.booster self.Use_netcoins = config.Use_netcoins self.attacks_normal = config.attacks_normal self.updates = config.updates self.updatecount = config.updatecount self.maxanti_normal = config.maxanti_normal self.active_cluster_protection = config.active_cluster_protection self.mode = config.mode self.stat = "0" self.wait_load = config.wait_load self.c = Console(self.player.username, self.player.password) self.u = Update(self.player.username, self.player.password) self.b = Botnet(self.player) self.ddos = ddos.Ddos() self.init()
class ConsoleTests(unittest.TestCase): def setUp(self): self.console = Console("Test", "Test Console") def test_console_lookup(self): """ Console lookup should do a few things: 1) It should return the object from supported_consoles 2) It should return the same instance every time 3) It should return None when the console of that name is not found """ # 1 self.assertTrue(console_lookup("GBA") in supported_consoles) # 2 self.assertEqual(console_lookup("GBA"), gba) self.assertEqual(console_lookup("GBA"), gba) # 3 self.assertTrue(console_lookup("Random String") == None) # @unittest.skip("Not yet implemented") # def test_find_all_roms(self): # pass # # @unittest.skip("Not yet implemented") # def test_find_all_roms_for_console(self): # pass def test_roms_directory(self): """ The ROMs directory for a console should be the ROMs directory from filesystem_helper, except the directory name should be equal to the shortname for the console """ gba_dir = self.console.roms_directory() self.assertEqual(os.path.dirname(gba_dir), filesystem_helper.roms_directory()) self.assertEqual(os.path.basename(gba_dir), self.console.shortname) def test_executables_directory(self): """ The executables directory for a console should be a directory located in the main executables directory, and the consoles directory should be named the same as the shortname of the console """ gba_dir = self.console.executables_directory() self.assertEqual(os.path.dirname(gba_dir), filesystem_helper.executables_directory()) self.assertEqual(os.path.basename(gba_dir), self.console.shortname) def test_icon_path(self): """ The icon path for a console should be in the icons directory, and the file should be named the shortname of the console with a .png extension """ gba_path = self.console.icon_path() self.assertEqual(os.path.dirname(gba_path), filesystem_helper.icons_directory()) self.assertEqual(os.path.basename(gba_path), self.console.shortname + ".png")
def delete(filename): """ Delete een opgeslagen spelbestand. :param filename: het gekozen bestandsnaam uit de lijst """ Console.delete_gamedata() filename = os.path.join(SAVEPATH, filename) os.remove(filename)
def __init__(self): """ Constructor """ self.console = Console() self.logger = logging.getLogger(self.__class__.__name__) self.timestamp = None self.devices = {}
def cli(): kwargs = docopt(__doc__) title = kwargs.get('<title>', None).replace('+', ' ') if kwargs.get( '<title>', None) else None author = kwargs.get('<author>', None).replace('+', ' ') if kwargs.get( '<author>', None) else None console = Console() console.search_book(title, author)
def postExploit(self, credential): con = Console() message = con.getTimeString() message += con.format(" Login was Successful!!! ", ['green', 'bold']) message += "username: %s password: %s " % ( con.format(credential.username, ['green', 'bold']), con.format(credential.password, ['green', 'bold'])) print(message) exit()
class ConsoleTests(unittest.TestCase): def setUp(self): self.console = Console("Test","Test Console") def test_console_lookup(self): """ Console lookup should do a few things: 1) It should return the object from supported_consoles 2) It should return the same instance every time 3) It should return None when the console of that name is not found """ # 1 self.assertTrue(console_lookup("GBA") in supported_consoles) # 2 self.assertEqual(console_lookup("GBA"),gba) self.assertEqual(console_lookup("GBA"),gba) # 3 self.assertTrue(console_lookup("Random String") == None) # @unittest.skip("Not yet implemented") # def test_find_all_roms(self): # pass # # @unittest.skip("Not yet implemented") # def test_find_all_roms_for_console(self): # pass def test_roms_directory(self): """ The ROMs directory for a console should be the ROMs directory from filesystem_helper, except the directory name should be equal to the shortname for the console """ gba_dir = self.console.roms_directory() self.assertEqual(os.path.dirname(gba_dir),filesystem_helper.roms_directory()) self.assertEqual(os.path.basename(gba_dir),self.console.shortname) def test_executables_directory(self): """ The executables directory for a console should be a directory located in the main executables directory, and the consoles directory should be named the same as the shortname of the console """ gba_dir = self.console.executables_directory() self.assertEqual(os.path.dirname(gba_dir),filesystem_helper.executables_directory()) self.assertEqual(os.path.basename(gba_dir),self.console.shortname) def test_icon_path(self): """ The icon path for a console should be in the icons directory, and the file should be named the shortname of the console with a .png extension """ gba_path = self.console.icon_path() self.assertEqual(os.path.dirname(gba_path),filesystem_helper.icons_directory()) self.assertEqual(os.path.basename(gba_path),self.console.shortname + ".png")
def setup_console(self): #setup dock dockWidget = QtGui.QDockWidget('console', self) dockWidget.setAllowedAreas(Qt.BottomDockWidgetArea) self.addDockWidget(Qt.BottomDockWidgetArea, dockWidget) #setup console in it console = Console() console.setFixedHeight(100) dockWidget.setWidget(console) self.console = console
def do_help(self, arg): if arg in ('status', 'query', 'result', 'config', 'exit'): Console.do_help(self, arg) else: print "\n".join(['These are the accepted commands.', 'Type help <command> to get help on a specific command.', '', 'status Show summary of system status.', 'query Manipulate and run query.', 'result Show result of a query.', 'config Set config variables.', 'exit Exit application.'])
def execute_script(script, test_code, extra_locals, files): soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (10, hard)) checker = Console(locals_=extra_locals, files=files) feedback = checker.run_tests(script, test_code) output = checker.output return_code = 0 if feedback: return_code = 1 new_locals = checker.get_locals() resource.setrlimit(resource.RLIMIT_CPU, (soft, hard)) return return_code, output, feedback, new_locals
def load_all_maps(self): """...""" map_path = 'resources/maps/' Console.load_all_maps() try: # noinspection PyTypeChecker for map_name in MapTitle: map_name.value.append(pytmx.load_pygame(map_path + map_name.name + '.tmx')) except pygame.error: # bij het sluiten van het spel voordat alle kaarten geladen zijn. pass self.all_maps_loaded = True Console.maps_loaded()
def load(filename): """ Laad een opgeslagen spelbestand. :param filename: het gekozen bestandsnaam uit de lijst """ filename = os.path.join(SAVEPATH, filename) try: Console.load_gamedata() with open(filename, 'rb') as f: data = pickle.load(f) return data except (pickle.UnpicklingError, EOFError, AttributeError): Console.corrupt_gamedata()
def remove(self, hero): """ Haal heroes weg uit de party :param hero: Hero Object """ if hero.RAW == 'alagos': Console.error_leader_not_leave_party() raise AttributeError elif hero.RAW in self: del self[hero.RAW] else: Console.error_hero_not_in_party(hero.NAM, self.NAM) raise AttributeError
def test_works_with_csv_files(self): files = {'dummy.csv': 'foo,bar\nbob,alice'} console = Console(files=files) code = """ import csv fd = open('dummy.csv') data = csv.reader(fd.readlines()) print data.next() print data.next() """.strip() console.run_tests(code, TEST_CODE) expected_output = "['foo', 'bar']\n['bob', 'alice']\n" self.assertEqual(expected_output, console.output)
def save(data, filename): """ Save de voortgang naar een bestand. Maak bij voorbaat een pad aan. :param data: self.engine.data :param filename: het gekozen bestandsnaam uit de lijst of ingetypt. """ if not os.path.exists(SAVEPATH): os.makedirs(SAVEPATH) Console.save_gamedata() filename = os.path.join(SAVEPATH, filename) with open(filename, 'wb') as f: pickle.dump(data, f)
def remove(self, pouch_item, cost, verbose=True, force=False): """ Verwijdert quantity uit de pouch. Als je iets koopt bijv. :param pouch_item: :param cost: :param verbose: :param force: als hij er 0 uit de pouch moet nemen vanwege polymorph, dan zou hij crashen, gebruik force om qty 0 uit de pouch te nemen. """ if cost < 1 and force is False: Console.error_quantity_less_than_one(cost) raise ValueError if pouch_item.RAW not in self: Console.quantity_not_enough(pouch_item.NAM, cost, 0) return False elif self[pouch_item.RAW].qty < cost: Console.quantity_not_enough(pouch_item.NAM, cost, self[pouch_item.RAW].qty) return False elif self[pouch_item.RAW].qty == cost and pouch_item.RAW != 'gold': # goud is de enige uitzondering, del self[pouch_item.RAW] # die moet in de pouch blijven, ook met 0. return True else: self[pouch_item.RAW].qty -= cost if verbose: Console.remove_item_from_container(cost, pouch_item.NAM, self.NAM) return True
def _load_cfg(self): """ Laad settings uit config bestand. """ if not os.path.exists(SETTINGSPATH): os.makedirs(SETTINGSPATH) try: with open(SETTINGSFILE, 'rb') as f: self.music, self.sound = pickle.load(f) Console.load_settings() except (pickle.UnpicklingError, FileNotFoundError, EOFError): Console.corrupt_settings() self.music, self.sound = True, True self.write_cfg()
def _load_cfg(self): """ Laad settings uit config bestand. """ if not os.path.exists(SETTINGSPATH): os.makedirs(SETTINGSPATH) try: with open(SETTINGSFILE, 'rb') as f: self.fullscreen, self.window_frame = pickle.load(f) Console.load_settings() except (pickle.UnpicklingError, FileNotFoundError, EOFError, TypeError): Console.corrupt_settings() self.fullscreen = False self.window_frame = True self.write_cfg()
def add(self, hero, verbose=True): """ Voeg heroes toe aan de party. :param hero: Hero Object :param verbose: als False meegegeven wordt, print dan niets in de console """ if hero.RAW in self: Console.error_hero_double_join(hero.NAM, self.NAM) raise ValueError elif len(self) < self.MAX: self[hero.RAW] = hero if verbose: Console.hero_join_party(hero.NAM, self.NAM) return True else: return False
def __init__(self): self.width = getWidth() self.height = getHeight() self.fps = getFPS() self.bubbleCount = int(getWidth() / 160) self.drawBubbles = True self.drawBG = True pygame.init() self.fpsClock = pygame.time.Clock() if fullscreen(): self.windowSurfaceObj = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN) else: self.windowSurfaceObj = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption('Anim') pygame.mouse.set_visible(cursor()) for i in range(0, self.bubbleCount): self.entitylist[2].append(Bubble(True)) self.entitylist[0].append(Bubble(False)) self.player = Player() self.entitylist[1].append(self.player) self.background = Background() print('Init...') self.console = Console(getWidth(), getHeight()) Console.host = self self.DrawPosVector = False
def _construct_widget(self): self.ubuntuMonoFont = QFont("Ubuntu Mono", 10) self.edit.setFont(self.ubuntuMonoFont) self.console = Console(self.edit) self.edit.keyPressEvent = self.console.keyPressEvent self.edit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.console.quit.connect(self.quit)
def __init__(self, matcher): Console.__init__(self) self.config = self._default_config self.prompt = ">> " self.intro = "Welcome to the CBR system. Type 'help' for a list of commands." self.matcher = matcher if not self.matcher.cases: self.intro += "\nNOTE: Currently no cases loaded (you may want to run parser.py to generate some)!" self.query = Case() self.result = [] if not sys.stdin.isatty(): self.prompt = self.intro = "" self.interactive = False self.config['auto_run'] = False else: self.interactive = True
class ConsoleTab(UmitView): name = "PythonShellTab" label_text = _("Python Shell") tab_position = gtk.POS_BOTTOM icon_name = "python_small" def __create_widgets(self): self.console = Console() self.console.banner() def __pack_widgets(self): self._main_widget.add(self.console) self._main_widget.show_all() def create_ui(self): self.__create_widgets() self.__pack_widgets()
def start(self): Console.write("fireherd starting up", Console.Style.Important) try: self._start() except KeyboardInterrupt as e: Console.write("Interrupted by user.", Console.Style.Error) except Exception as e: msg = e.message if e.message!="" else "Unknown error!" Console.write(msg, Console.Style.Error) Console.write(traceback.format_exc(), Console.Style.Error)
def _analyzeFile(self, filename): Console.write("Analyzing '{}'".format(filename), Console.Style.Important) # prepare a packet data source source = OfflineSource(filename) # init the PacketProcessor, which will dissect each packet and retrieve # some information from them. pproc = PacketProcessor() pproc.show_packets = Settings.options['debug.show_packets'] # init the TCPManager, which will reconstruct TCP connections from # previously dissected TCP packets tcpman = TCPManager() # this tells the TCPManager which analyzers should create for # each TCP thread that is opened tcpman.analyzer_classes = [HTTPAnalyzer] # init some counters that will be later used for statistics count = 0 last_count = 0 msg_period = 3.0 start_time = time.time() # start obtaining and processing network packets for packet in source: # dissect this packet, then use this packet # to reassemble tcp threads pproc.run(packet) tcpman.run(packet) count += 1 # if count > 100000: # Console.write("Packet limit has been reached") # break; # show a message if msg_period has passed so that the user # does not get bored to death if Console.timeSinceLast()>msg_period: speed = (count - last_count)/msg_period last_count = count Console.write("Analyzed {} packets at {:.2f} p/sec.".format(count, speed)) # after completion show elapsed time, number of packets and number of threads stop_time = time.time() Console.write("Analyzed {} packets in {:.2f} seconds".format(count, stop_time - start_time)) Console.write("Found {} TCP threads".format(tcpman.total_count))