def __init__(self, topoWidget): View.__init__(self, topoWidget, "FlowTracer") # Buttons infoBtn = QtGui.QPushButton('What is FlowTracer?') self.connect(infoBtn, QtCore.SIGNAL('clicked()'), self.showInfo) traceBtn = QtGui.QPushButton('Trace!') self.connect(traceBtn, QtCore.SIGNAL('clicked()'), self.trace_flow) self.buttons.append(infoBtn) self.buttons.append(traceBtn) # Signals self.topologyInterface.flowtracer_received_signal.connect( \ self.got_json_msg ) # Subscribe to messages from backend msg = {} msg["_mux"] = "gui" msg["type"] = "flowtracer" msg["command"] = "subscribe" msg["msg_type"] = "highlight" self.topologyInterface.send( msg ) self.highlighted_path = [] self.querynode = None
def saveState(self): ''' Saves the view's settings to configuration. ''' View.saveState(self) config.set(self.NAME, self._CONFIG_SECTION_CONSOLE, "visible", self._widgetConsole.isVisible())
class Controller: def __init__(self): self.view = View() self.serialize = Serialize() def menu(self): while True: point = self.view.create_menu() if point == 1: self._calculate() elif point == 2: self.serialize.load() elif point == 3: data = self.view.change_serialization_file() self.serialize.change_config(data[0], data[1]) elif point == 4: break def _calculate(self): gender = self.view.read_gender() weight = self.view.read_weight() height = self.view.read_height() age = self.view.read_age() pa = self.view.read_pa() model = Model(gender, weight, height, age, pa) self.view.get_info(model.get_info()) data = (gender, weight, height, age, pa, model.calculate_calories()) input() if self.view.is_dump(): self.serialize.dump(data)
def view(self, header_names, lines, vertical_header=None, initial_sort=[], decimal_points=3): sub_views = [] conv_lines = [] # turn lines to html for line in lines: conv_line, sub_sub_views = convert_to_html(line) conv_lines.append(conv_line) sub_views += sub_sub_views conv_sort = [] for s in initial_sort: dir = 0 if s[1] == 'asc': dir = 0 elif s[1] == 'desc': dir = 1 else: raise Exception('Sort must either be asc or desc') conv_sort.append('[%d,%d]' % (header_names.index(s[0]), dir)) conv_sort = ', '.join(conv_sort) conv_sort = '[%s]' % conv_sort data = OrderedDict() for i in xrange(len(header_names)): data[header_names[i]] = [l[i] for l in conv_lines] html = render('table.html', { 'vertical_header' : vertical_header, 'data' : data, 'id' : self._get_unique_id(), 'header_names': header_names, 'lines': conv_lines, 'sort': conv_sort}) v = View(self, html, ['table.css'], ['jquery.tablesorter.js']) for sub in sub_views: v.append_view_files(sub) return v
def main(): if password_changed(): config = Configuration() indexView=View(config.system.actions) indexView.output() else: redirect()
class Infrastructure(): def __init__(self, resolution, frame_rate): self.frame_rate = frame_rate self.event_manager = EventManager() self.event_manager.register_listener(self) self.model = Model(self.event_manager) self.view = View(self.event_manager, resolution) self.controller = InputController(self.event_manager) self.main_loop = True def update_resolution(self, resolution): self.view.update_window(resolution) def update_frame_rate(self, frame_rate): self.frame_rate = frame_rate def run_main(self): while self.main_loop: clock = pygame.time.Clock() milliseconds = clock.tick(self.frame_rate) self.event_manager.post(TickEvent(milliseconds)) def get_event_manager(self): return self.event_manager def notify(self, event): if isinstance(event, QuitEvent): self.main_loop = False
def __init__(self, topoWidget): View.__init__(self, topoWidget, "Elastic Tree") self.logDisplay = self.topoWidget.parent.logWidget.logDisplay utilBtn = QtGui.QPushButton('Change Util Bound') infoBtn = QtGui.QPushButton('What is ElasticTree?') self.connect(utilBtn, QtCore.SIGNAL('clicked()'), self.changeUtil) self.connect(infoBtn, QtCore.SIGNAL('clicked()'), self.showInfo) # self.connect(powerBtn, QtCore.SIGNAL('clicked()'), # self.showPowerStats) # self.buttons.append(powerBtn) self.buttons.append(utilBtn) self.buttons.append(infoBtn) self.utilBound = 0.01 self.slider = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.slider.setMinimum(0) self.slider.setMaximum(100) self.buttons.append(self.slider) self.sliderValue = 0 self.stats = {} # maps tuples (dpid, port) to utilization self.powerSliderSignal.connect(self.changeSlider) self.indicator = QtGui.QLabel() self.buttons.append(self.indicator)
def __init__(self, topoWidget): View.__init__(self, topoWidget, "Monitoring") # Monitoring view buttons infoBtn = QtGui.QPushButton('What is Monitoring?') self.connect(infoBtn, QtCore.SIGNAL('clicked()'), self.showInfo) self.buttons.append(infoBtn) for b in self.buttons: b.setCheckable(True) # maps tuples (dpid, port) to utilization self.stats = {} self.topologyInterface.monitoring_received_signal.connect( \ self.got_monitoring_msg ) # Subscribe for linkutils msg = {} msg["_mux"] = "gui" msg ["type"] = "monitoring" msg ["command"] = "subscribe" msg ["msg_type"] = "linkutils" self.topologyInterface.send( msg )
class Mission: def __init__(self, description, actions, level): self.description = description self.actions = actions self.level = level self.view = View() def start(self, player): self.player = player self.view.mission_description(self.description) decision = self.view.input_mission_decision(self.actions) passed_mission = self.determine_outcome(decision) if passed_mission: battle = Battle(self.player, self.level) while battle.take_turn(): pass if battle.lost == False: return True return False #TODO make random decision def determine_outcome(self, action): if action not in self.actions: return None elif action == self.actions[0]: return True else: return False
class Application(QApplication): ''' The main application class where the main objects are set up and connected with each other. ''' def __init__(self, *args): QApplication.__init__(self, *args) # initialize logging logging.basicConfig(filename='log.txt', level=logging.INFO, filemode='w',format='%(asctime)s %(message)s') logging.info("Starting application.") # initialize user preferences preferences = Preferences() # initialize model market = GoxMarket(preferences) # initialize view self.view = View(preferences, market) self.connect(self, SIGNAL('lastWindowClosed()'), self.__quit) def __quit(self): self.view.stop()
def __init__(self, app): View.__init__(self, app) self.app_window.entrylist.listbox.connect('row-activated', self.show_entry_details) self.scrolled_window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER) self.overlay = Gtk.Overlay() self.web = WebKit.WebView() self.web.set_size_request(300, 200) scw = Gtk.ScrolledWindow() scw.add(self.web) self.overlay.add(scw) self.add(self.overlay) self.headline = "" self.plot = "" self.author = "" self.prev_listbox = None self.entry_id = None image = Gtk.Image.new_from_icon_name('edit-redo-symbolic', Gtk.IconSize.BUTTON) self.browse_button = Gtk.Button(label=" Show Article ", image=image) self.browse_button.set_valign(Gtk.Align.END) self.browse_button.set_halign(Gtk.Align.START) self.browse_button.set_margin_start(20) self.browse_button.set_margin_bottom(15) self.browse_button.set_relief(Gtk.ReliefStyle.NONE) self.browse_button.connect("clicked", self.browse_link) self.browse_button.set_always_show_image (True) self.overlay.add_overlay(self.browse_button) self.overlay.show()
def __init__(self, element, composition, timeline): goocanvas.Group.__init__(self) View.__init__(self) Zoomable.__init__(self) self.element = element self.comp = composition self.timeline = timeline self.bg = goocanvas.Rect( height=self.__HEIGHT__, fill_color_rgba=self.__NORMAL__, line_width=0) self.content = Preview(self.element) self.name = goocanvas.Text( x=10, text=os.path.basename(unquote(element.factory.name)), font="Sans 9", fill_color_rgba=0x000000FF, alignment=pango.ALIGN_LEFT) self.start_handle = StartHandle(element, timeline, height=self.__HEIGHT__) self.end_handle = EndHandle(element, timeline, height=self.__HEIGHT__) for thing in (self.bg, self.content, self.start_handle, self.end_handle, self.name): self.add_child(thing) if element: self.zoomChanged() self.normal()
class Controller: # Constructor def __init__(self, root): # Retrieve my model (or create) self.my_number = Model() self.my_number.add_callback(self.number_change) # Create the view self.view_number = View(root) # Link View elements to Controller self.view_number.inc_button.config(command=self.inc_number) self.view_number.dec_button.config(command=self.dec_number) self.number_change(self.my_number.get()) # Action to Model from View elements def inc_number(self): self.my_number.set(self.my_number.get() + 1) def dec_number(self): self.my_number.set(self.my_number.get() - 1) # Update View from Model def number_change(self, n): self.view_number.update_number(n)
class Application(QApplication): ''' The main application class where the main objects are set up and connected with each other. ''' def __init__(self, *args): self.logfile = open('log.txt', 'w') QApplication.__init__(self, *args) # initialize model (gox) #goxapi.FORCE_PROTOCOL = 'socketio' self.config = goxapi.GoxConfig("goxtool.ini") self.secret = goxapi.Secret(self.config) self.gox = goxapi.Gox(self.secret, self.config) self.strategy_object = stoploss.Strategy(self.gox) # initialize view self.view = View(self.gox, self.secret, self.logfile) self.view.log('Starting application.') # start connection to MtGox self.gox.start() self.connect(self, SIGNAL('lastWindowClosed()'), self.__quit) def __quit(self): self.gox.stop() self.logfile.close()
def tick(self): reported = set() while self.views_changed: v, buf = self.views_changed.pop() if not self.joined_workspace: msg.debug('Not connected. Discarding view change.') continue if 'patch' not in G.PERMS: continue if 'buf' not in buf: msg.debug('No data for buf ', buf['id'], ' ', buf['path'], ' yet. Skipping sending patch') continue view = View(v, buf) if view.is_loading(): msg.debug('View for buf ', buf['id'], ' is not ready. Ignoring change event') continue if view.native_id in reported: continue reported.add(view.native_id) patch = utils.FlooPatch(view.get_text(), buf) # Update the current copy of the buffer buf['buf'] = patch.current buf['md5'] = patch.md5_after self.send(patch.to_json()) reported = set() self._status_timeout += 1 if self._status_timeout > (2000 / G.TICK_TIME): self.update_status_msg()
def __init__(self, app): View.__init__(self, app) self.app_window.feedview.listbox.connect('row-activated', self.show_entries) self.app_window.feedhandler.connect("feed-updated", self.update_entryview) self.listbox = Gtk.ListBox() self.add(self.listbox)
def __init__(self, topoWidget): View.__init__(self, topoWidget) self.name = "Traffic Engineering" # TE view buttons TTBtn = QtGui.QPushButton('&Tunnel Table') TEDBtn = QtGui.QPushButton('Traffic Engineering &Database') NewTunBtn = QtGui.QPushButton('New Tunnel...') DelTunBtn = QtGui.QPushButton('Delete Tunnel...') self.connect(TTBtn, QtCore.SIGNAL('clicked()'), self.handle_TTBtnClick) self.connect(TEDBtn, QtCore.SIGNAL('clicked()'), self.request_TED) self.connect(NewTunBtn, QtCore.SIGNAL('clicked()'), self.new_tunnel) self.connect(DelTunBtn, QtCore.SIGNAL('clicked()'), self.remove_tunnel) self.buttons.append(TTBtn) self.buttons.append(TEDBtn) self.buttons.append(NewTunBtn) self.buttons.append(DelTunBtn) self.buttons[0].setCheckable(True) #self.buttons[2].setCheckable(True) #self.buttons[3].setCheckable(True) # tunnel descriptions, taken from te backend self.tunnels = [] # backup tables, string taken from te backend self.backup_tables = "" # unprotected hops per tunnel, string taken from te backend self.uprotected_hops = "" # unaccommodated tunnels, string taken from te backend self.unaccomodated_tunnels = "" # latest TED, string taken from te backend self.ted = "" # tunnel colors (tid:color) self.tunnel_colors = {'default':QtCore.Qt.blue,\ 1:QtGui.QColor(QtCore.Qt.red),\ 2:QtGui.QColor(QtCore.Qt.yellow)} # draw tunnel? (tid:true/false) self.tunnel_displays = {1:True, 2:True} #{0:False, 1:False} # connect signals to slots self.topologyInterface.tunnels_reply_received_signal.connect \ (self.show_tunnel_table) self.topologyInterface.ted_reply_received_signal.connect \ (self.show_TED) self.topologyInterface.link_status_change_signal.connect \ (self.update_tunnel_table) self.popupTT = False
def convertDate(self, dictionary): view = View() if "day" in dictionary.keys(): dictionary["day"] = view.days_str(dictionary["day"]) if "startTime" in dictionary.keys(): dictionary["startTime"] = view.time_str(dictionary["startTime"]) if "endTime" in dictionary.keys(): dictionary["endTime"] = view.time_str(dictionary["endTime"])
def _delayedRender(self, request, settings): try: properties, per_index = self.properties, self.per_index if request.path == "/properties/api.json": items = [] for i in xrange(30): item = self.model.get_item(i) items.append({'id': i, "title": "better " + item['title']}) request.setHeader("content-type", "application/json") request.write(json.dumps(items)) elif request.path.startswith("/properties/index_"): m = re.search(r'.*_(\d+)', request.path) if not m: raise Exception('expected number') page = int(m.group(1)) # Divide with roundup indices = (properties + per_index - 1) / per_index if page >= indices: raise Exception('invalid index number') np = "index_%05d.html" % (page+1) start = per_index * page end = min(per_index * (page + 1), properties) index = { 'page': page, 'nextp': None if page >= (indices-1) else np, 'items': self.model.get_items(xrange(start, end)) } request.write(View.render_index(index)) elif request.path.startswith("/properties/property_"): m = re.search(r'.*_(\d+)', request.path) if not m: raise Exception('expected number') pid = int(m.group(1)) if pid >= properties: raise Exception('invalid property number') item = self.model.get_item(pid) request.write(View.render_property(item)) else: raise Exception('unknown page') except: request.write('can\'t find page. sorry') request.finish()
def main(): ''' generates an error page ''' config=Configuration() fs=cgi.FieldStorage() view = View(config.system.actions) view.setContent('Page not found', 'The requested page was not found. Did you type the url manually?') view.output()
def __init__(self, *args): View.__init__(self, *args) # Recent files menu self._recentFiles = LastValues(self.NAME, self._CONFIG_SECTION_MENU, "recent", 5) self._actionClearMenu = self._elements["actionClearMenu"] self._menuRecentFiles = self._menuFile[1] self._actionClearMenu.triggered.connect(self._recentFiles.clear) self._actionClearMenu.triggered.connect(self._updateRecentFiles) # Widgets self._treeWidget = self._elements["treeWidgetInfo"] self._tabWidget = self._elements["tabWidgetResults"] self._tabWidget.setTabBar(ClosableTabBar()) self._widgetConsole = self._elements["widgetConsole"] self._buttonShowConsole = self._elements["buttonShowConsole"] self._buttonHideConsole = self._elements["buttonHideConsole"] self._splitterConsole = self._elements["splitterConsole"] self._buttonSaveOutput = self._elements["buttonSaveOutput"] self._textEdit = self._elements["textEditConsole"] self._tabs = {} self._treeWidget.setColumnCount(2) self._treeWidget.header().resizeSection(2, 0) self._treeWidget.header().setHorizontalScrollMode( QtGui.QAbstractItemView.ScrollPerPixel) self._treeWidget.header().setResizeMode(1, QtGui.QHeaderView.ResizeToContents) self._treeWidget.header().setResizeMode(2, QtGui.QHeaderView.Fixed) self._treeWidget.header().setStretchLastSection(True) self._widgetConsole.setVisible(False) self._buttonHideConsole.setVisible(False) self._tabWidget.currentChanged[int].connect(self._displaySelected) self._tabWidget.tabCloseRequested.connect(self._closeTabOfIndex) self._buttonShowConsole.clicked.connect(self._showConsole) self._buttonHideConsole.clicked.connect(self._hideConsole) self._buttonSaveOutput.clicked.connect(self._saveOutput) # Actions self._elements["actionOpen"].triggered.connect(self._openDialog) self._elements["actionClose"].triggered.connect(self._closeCurrentTab) self._actionExpand = self._elements["actionExpand"] self._actionExpandAll = self._elements["actionExpandAll"] self._actionCollapse = self._elements["actionCollapse"] self._actionCollapseAll = self._elements["actionCollapseAll"] # Console channel self._hideConsole() consoleChannelHelper = ConsoleChannelHelper(textEdit=self._textEdit) channels.add(ConsoleChannel, "_ui_console", console=consoleChannelHelper) self._splitterConsole.handle(1).setEnabled(False) # Tab channel self._resultChannelHelper = ResultChannelHelper(self) channels.add(ResultChannel, "_ui_result", result=self._resultChannelHelper)
def __init__(self, parent): View.__init__(self, parent) self._devices = TestDeviceList(self._elements["treeWidgetDevices"]) self._actionStart = self._elements["actionStart"] self._actionStop = self._elements["actionStop"] self._actionPause = self._elements["actionPause"] self._actionResume = self._elements["actionResume"] self._actionStart.triggered.connect(self._startTests) self._actionStop.triggered.connect(self._stopTests) self._actionPause.triggered.connect(self._pauseTests) self._actionResume.triggered.connect(self._resumeTests) self._actionStart.setVisible(True) self._actionStop.setVisible(False) self._actionPause.setVisible(False) self._actionResume.setVisible(False) # Summary channel channels.add("SummaryChannel", "_ui_summary") # Progress channel pBar = QtGui.QProgressBar() pBar.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) font = pBar.font() font.setBold(True) pBar.setFont(font) self._parent.getStatusBar().addPermanentWidget(pBar, 1) self._progress = ProgressChannelHelper(pBar) channels.add(ProgressChannel, "_ui_progress", progress=self._progress) self._progress.testStarted.connect(self._onTestStarted) self._progress.testStopped.connect(self._onTestStopped) self._progress.stopped.connect(self._onStopped) self._tests = Tests(self._elements["treeWidgetLocations"], self._elements["treeWidgetTests"], self._elements["treeWidgetModels"]) self._elements["actionAdd"].triggered.connect(self._tests.addLocation) self._elements["actionRemove"].triggered.connect( self._tests.removeLocation) self._elements["actionExpand"].triggered.connect( self._tests.expandSelected) self._elements["actionExpandAll"].triggered.connect( self._tests.expandAll) self._elements["actionCollapse"].triggered.connect( self._tests.collapseSelected) self._elements["actionCollapseAll"].triggered.connect( self._tests.collapseAll) self._elements["actionRefresh"].triggered.connect(self._tests.refresh) # Initialize private test variables self._suiteRuns = 0 self._todoSuites = 0 self._testResult = None self._testRunner = None
def view(self, center, left): html = render('leftpanel.html', { 'id' : self._get_unique_id(), 'center' : center.main_html, 'left' : left.main_html}) v = View(self, html, [], []) v.append_view_files(center) v.append_view_files(left) return v
class TestView(unittest.TestCase): def setUp(self): self.view = View() self.view.setController(mocks.MockController()) def test_do_foo(self): self.view.do_foo([]) self.assertEqual(1, 1)
def get_meta_info(self, data_path): ''' Get meta information for a requested data path. ''' if data_path not in self._views.keys(): path_type = self.check_path_type(data_path) # detect if this is a section or fov if path_type == 'FOV': # this is a FoV fov = FoV.from_directory(data_path, True) view = View.create( data_path, [fov], fov._width, fov._height, fov._tx, fov._ty, self) elif path_type == 'SECTION': section = Section.from_directory(data_path, True, True) view = View.create( data_path, section._fovs, section._width, section._height, section._tx, section._ty, self, section._luts64_map) # # and add to our views dictionary # self._views[data_path] = view else: view = self._views[data_path] meta_info = {} meta_info['width'] = view._width meta_info['height'] = view._height meta_info['layer'] = 0 meta_info['minLevel'] = 0 meta_info['maxLevel'] = 1 meta_info['tileSize'] = settings.CLIENT_TILE_SIZE meta_info['centers'] = view._centers return meta_info
def tick(self): reported = set() while self.views_changed: v, buf = self.views_changed.pop() if not G.JOINED_WORKSPACE: msg.debug('Not connected. Discarding view change.') continue if 'patch' not in G.PERMS: continue if 'buf' not in buf: msg.debug('No data for buf %s %s yet. Skipping sending patch' % (buf['id'], buf['path'])) continue view = View(v, buf) if view.is_loading(): msg.debug('View for buf %s is not ready. Ignoring change event' % buf['id']) continue if view.native_id in reported: continue reported.add(view.native_id) patch = utils.FlooPatch(view.get_text(), buf) # Update the current copy of the buffer buf['buf'] = patch.current buf['md5'] = hashlib.md5(patch.current.encode('utf-8')).hexdigest() self.send(patch.to_json()) reported = set() while self.selection_changed: v, buf, summon = self.selection_changed.pop() if not G.JOINED_WORKSPACE: msg.debug('Not connected. Discarding selection change.') continue # consume highlight events to avoid leak if 'highlight' not in G.PERMS: continue view = View(v, buf) vb_id = view.native_id if vb_id in reported: continue reported.add(vb_id) highlight_json = { 'id': buf['id'], 'name': 'highlight', 'ranges': view.get_selections(), 'ping': summon, 'summon': summon, } self.send(highlight_json) self._status_timeout += 1 if self._status_timeout > (2000 / G.TICK_TIME): editor.status_message('Connected to %s/%s' % (self.owner, self.workspace)) self._status_timeout = 0
def tick(self): reported = set() while self.views_changed: v, buf = self.views_changed.pop() if not G.JOINED_WORKSPACE: msg.debug("Not connected. Discarding view change.") continue if "patch" not in G.PERMS: continue if "buf" not in buf: msg.debug("No data for buf %s %s yet. Skipping sending patch" % (buf["id"], buf["path"])) continue view = View(v, buf) if view.is_loading(): msg.debug("View for buf %s is not ready. Ignoring change event" % buf["id"]) continue if view.native_id in reported: continue reported.add(view.native_id) patch = utils.FlooPatch(view.get_text(), buf) # Update the current copy of the buffer buf["buf"] = patch.current buf["md5"] = hashlib.md5(patch.current.encode("utf-8")).hexdigest() self.send(patch.to_json()) reported = set() while self.selection_changed: v, buf, summon = self.selection_changed.pop() if not G.JOINED_WORKSPACE: msg.debug("Not connected. Discarding selection change.") continue # consume highlight events to avoid leak if "highlight" not in G.PERMS: continue view = View(v, buf) vb_id = view.native_id if vb_id in reported: continue reported.add(vb_id) highlight_json = { "id": buf["id"], "name": "highlight", "ranges": view.get_selections(), "ping": summon, "summon": summon, } self.send(highlight_json) self._status_timeout += 1 if self._status_timeout > (2000 / G.TICK_TIME): editor.status_message("Connected to %s/%s" % (self.owner, self.workspace)) self._status_timeout = 0
class Game: def __init__(self): self.adventure.index = 0 self.adventure = [] self.player = None self.view= View() def begin(self): self.player = self.view.input_player_name() def create_player(self): name = self.view.input_player_name() job = self.view.input_player_job() return Player(name, job) def play(self): self.view.introduction_message() while self.adventure_index<len(self.adventure): if self.adventure[self.adventure_index].start(self.player): self.mission_index += 1 self.view.passed_adventure_message() else: self.view.failed_mission_message() break def load_adventure(self, adventure): self.adventure = passed_adventure_messageself.adventure_index = 0
def view(self, collapsed_view, expanded_view): html = render('miniexpander.html', { 'widget_id' : self.id, 'id' : self._get_unique_id(), 'collapsed' : collapsed_view.main_html, 'expanded' : expanded_view.main_html, 'shown' : self.values.shown == 'shown'}) v = View(self, html, [], []) v.append_view_files(collapsed_view) v.append_view_files(expanded_view) return v
def main(): if password_changed(): config = Configuration() view = View(config.system.actions) main_view_file = open(MAIN_VIEW) content = main_view_file.read() main_view_file.close() view.setContent("Welcome", content) view.output() else: redirect()
def main(screen): view = View(screen) controller = Controller() characterPressed = 0 while characterPressed != KeyConsts.EXIT: if (characterPressed == KeyConsts.DOWN) and not controller.listEmpty(): view.moveDown(controller.getNumberOfItems()) elif (characterPressed == KeyConsts.UP) and not controller.listEmpty(): view.moveUp(controller.getNumberOfItems()) elif (characterPressed == KeyConsts.RIGHT) and not controller.listEmpty(): view.moveScreenDown(controller.getNumberOfItems()) elif (characterPressed == KeyConsts.LEFT) and not controller.listEmpty(): view.moveScreenUp() elif characterPressed == KeyConsts.RELOAD_DATABASE: if controller.isDirectory(view.getLibraryPath()): view.showReloadLibraryDialog() [addedItems, removedItems, movedItems] = controller.loadItems(view.getLibraryPath()) view.hideReloadLibraryDialog() view.showReloadSummaryDialog(addedItems, removedItems, movedItems) else: view.showLibraryPathIsNotDirectoryDialog() elif characterPressed == KeyConsts.SELECT_LIBRARY_PATH: view.showLibrarySelectionDialog() if controller.isDirectory(view.getLibraryPath()): controller.loadItemsFromDatabase(view.getLibraryPath()) else: view.showLibraryPathIsNotDirectoryDialog() elif characterPressed == KeyConsts.CHANGE_READ_STATE: controller.changeReadState(view.getPosition()) elif characterPressed == KeyConsts.APPLY_EXTENSION_FILTER: selectedExtensions = view.showExtensionsDialog( controller.getExtensions()) controller.processExtensionsFilter(selectedExtensions) view.drawScreen(controller.getItems(), controller.getReadItems()) characterPressed = view.getPressedCharacter()
import os import mimetypes from view import View from manager import Manager from response import Response, default_responses from model import Entry from utils import get_first_element import config from utils import get_file_contents, get_file_path home_view = View('home.html') messages_view = View('messages.html') upload_view = View('upload.html') manager = Manager('data.db') def static_controller(request): if config.DEBUG: print('Static file requested: {}'.format(request.URI_PATH)) requested_uri = os.path.join( config.STATIC_BASE_DIR, request.URI_PATH[len(config.STATIC_BASE_URI):]) try: requested_path = get_file_path(requested_uri, config.STATIC_BASE_DIR) content = get_file_contents(requested_path) except IOError: return default_responses[403] mime_type, encoding = mimetypes.guess_type(requested_path) status = '200 OK' headers = [('Content-type', mime_type or 'application/octet-stream')] if encoding: headers.append(('Content-encoding', encoding))
def __init__(self, rows, cols): self.rows, self.cols = rows, cols self._model = Model(rows, cols) self._view = View(rows, cols, open_browser=True)
def run(self, maze, startState, docksPos, heuristic): log = Log() log.startTiming() # Creates an initial node using the initial state startNode = Node(None, startState, None) # Initializes the search frontier openList = [] closedList = [] # Adds the initial node in the open list openList.append(startNode) # Loop until the finder finds the end state (target) while len(openList) > 0: currentNode = openList[0] currentIndex = 0 for i, node in enumerate( openList): # Finding the node with smallest cost f if node.f < currentNode.f: currentNode = node currentIndex = i openList.pop( currentIndex ) # Removing the node with the smallest cost from the open list closedList.append( currentNode ) # Putting the node with the smallest cost in the closed list # Getting information about the current state of the game playerPos = currentNode.state.playerPos boxesPos = currentNode.state.boxesPos View.updateMaze(playerPos, boxesPos, maze) # View.draw(maze) # Enable this line to see the temporary mazes on the screen if self.__isEndState(maze, boxesPos): path = [] auxNode = currentNode while auxNode is not None: path.append(auxNode) auxNode = auxNode.parent log.finishTiming() log.showReport() return path[::-1] # If the target wasn't find, explore the neighborhood (4-connected) for direction in [(0, -1), (0, 1), (-1, 0), (1, 0)]: newPosition = (playerPos[0] + direction[0], playerPos[1] + direction[1]) # Validation of obstacles if newPosition[0] < maze.numberOfRows and newPosition[ 1] < maze.numberOfColumns: content = maze.matrix[newPosition[0]][newPosition[1]] if content in [' ', '.']: newNode = currentNode.addChild( State(newPosition, copy.deepcopy(boxesPos)), Action.getAction(direction, False)) log.updateData(newNode) elif content in ['*', '$']: nextPosition = (newPosition[0] + direction[0], newPosition[1] + direction[1]) nextContent = maze.matrix[nextPosition[0]][ nextPosition[1]] if nextContent in [' ', '.']: boxIndex = self.__findBoxByPosition( newPosition, boxesPos) if self.__findBoxByPosition(newPosition, boxesPos) == -1: raise RuntimeError( "failure to find the box on the position:" + str(newPosition)) newBoxesPos = copy.deepcopy(boxesPos) newBoxesPos[boxIndex] = nextPosition newNode = currentNode.addChild( State(newPosition, newBoxesPos), Action.getAction(direction, True)) log.updateData(newNode) # Checks if the node has already been visited for child in currentNode.children: isClosed = False for node in closedList: if child == node: isClosed = True break if not isClosed: if heuristic == SearchType.NO_HEURISTIC: child.h = 0 child.g = currentNode.g + 1 elif heuristic == SearchType.MANHATTAN: child.h = self.__computeH(child.state.playerPos, child.state.boxesPos, docksPos, SearchType.MANHATTAN) child.g = currentNode.g + 1 elif heuristic == SearchType.PYTHAGOREAN: child.h = self.__computeH(child.state.playerPos, child.state.boxesPos, docksPos, SearchType.PYTHAGOREAN) child.g = currentNode.g + 1 elif heuristic == SearchType.GREEDY: child.h = self.__computeH(child.state.playerPos, child.state.boxesPos, docksPos, SearchType.GREEDY) child.g = 0 child.f = child.g + child.h # If there is a better path until the node, this path has priority isBetter = True for node in openList: if (child == node and child.g > node.g): isBetter = False break if isBetter: openList.append(child)
class Controller: #-- # Attributes #-- # @property def result_id(self): return self._result_id #-- # Operational Methods #-- # def __init__(self): self.__simulation = Simulation() self.__view = View(self.__simulation) # Result identification self._result_id = { "code": None,\ "name": None,\ "group": None,\ "subgroup": None } # def get_group(self): group_data = pd.read_csv("controller/active_group.csv", index_col=0, header=None, squeeze=True) self.result_id["group"] = group_data["group"] self.result_id["subgroup"] = group_data["subgroup"] if len(group_data["subgroup"]) > 0 else None self.__view.set_result_id(self.result_id) #-- # Methods to manage the interface #-- # def main_menu(self): # Get group and subgroup self.get_group() # Initial menu level menu_level = 1 # Message msg = None # Loop menu while True: # Options if menu_level == 1: # Options opts = { 1: "Run simulation",\ 2: "Plot/get results",\ 3: "Change group/subgroup" } # Description desc = "Choose an option:" # Get group chosen_opt, back_menu, msg = self.__call_menu(opts, desc, msg=msg) # Simulate a new dataset if chosen_opt == 1: self.simulation_menu() # Plot/get results elif chosen_opt == 2: self.results_menu() # Change group/subgroup elif chosen_opt == 3: self.group_menu() # Change menu level menu_level += -2*back_menu # Leave menu else: print("Exiting ...") exit(0) # Set the parameters and run a new simulation def simulation_menu(self): # Message msg = None # Menu level menu_level = 1 # Loop menu while True: # Result short name if menu_level == 1: # Description desc = "Run simulation / Short Name" # Get shortname shortname, back_menu = self.__call_input(desc) menu_level += -2*back_menu + 1 # Simulation option elif menu_level == 2: # Description desc = "Run simulation / " if shortname is not None: desc += "(Short Name) " + shortname + " / " desc += "Simulation option" # Simulation options sim_opts = { 1: "Marginal distributions",\ 2: "Complete 3D distribution",\ 3: "Analysis of trapped atoms" } # Get group sim_opt, back_menu, msg = self.__call_menu(sim_opts, desc, msg) # Set menu level menu_level += -2*back_menu + 1 # Execute simulation elif menu_level == 3: # Create a new simulation self.__simulation.new(self.result_id["group"], self.result_id["subgroup"], shortname, sim_opt) # Print simulation status self.__view.simulation_status(sim_opt=sim_opts[sim_opt]) # Check looping loop_num = self.__simulation.results.loop["length"] if loop_num == 0: loop_num = 1 # Set progress bars pbars = [] for i in range(loop_num): if loop_num == 1: desc = None else: desc = self.__simulation.results.loop["var"] desc += " " + str(self.__simulation.results.loop["values"][i]) pbars.append(tqdm(total=self.__simulation.results.perform["num_sim"], desc=desc, position=i)) # Run simulation #-- for i in range(loop_num): # Change loop self.__simulation.change_loop(i) # Simulate atoms #-- while self.__simulation.atoms_simulated < self.__simulation.results.perform["num_sim"]: # Simulate atoms times = self.__simulation.run() pbars[i].update(times) #-- # Save simulation self.__simulation.save() #-- # Close progress bars for i in range(loop_num): pbars[i].close() # # Release memory gc.collect() # Information about the simulation self.__view.print_msg("\nThe simulation has finished!", clear_screen=False) menu_level = 0 # Leave menu else: break ''' # Create a new simulation self.__simulation.new(shortname, opt, results_group) # Check looping loop_num = len(self.__simulation.results.loop["values"]) if loop_num == 0: loop_num = 1 # Update time check_time = dt.now().timestamp() # Print simulation status self.__view.simulation_header(group=available_groups[results_group], sim_opt=opts[opt], clear_screen=True) # Set progress bars pbars = [] for i in range(loop_num): desc = "Atoms simulated" if loop_num == 1 else self.__simulation.results.loop["var"] + " = " + ("%.2f" % self.__simulation.results.loop["values"][i]) pbars.append(tqdm(total=self.__simulation.results.perform["num_sim"], desc=desc, position=i)) # # Run simulation #-- for i in range(loop_num): # Open new simulation for each looping value if i > 0: self.__simulation.open(self.__simulation.results.code, i, opt) # # Simulate atoms #-- while self.__simulation.atoms_simulated < self.__simulation.results.perform["num_sim"]: # Simulate atoms times = self.__simulation.run() pbars[i].update(times) #-- # Save simulation self.__simulation.save() #-- # Close progress bars for i in range(loop_num): pbars[i].close() # # Release memory gc.collect() # Information about the simulation #self.__view.simulation_header(group=available_groups[results_group], sim_opt=opts[opt], clear_screen=True) input("Enter any key to continue ... ") # # Set menu level self._menu_level = 0 ''' # Plot/Get results def results_menu(self): # Message msg = None # Set menu level menu_level = 1 # Loop menu while True: # Check collective or individual results option #-- if menu_level == 1: # Description desc = "Plot/Get Results / Choose an option:" # Options opts = { 1: "Individual results",\ 2: "Collective results" } # Get group collective_results, back_menu, msg = self.__call_menu(opts, desc, msg) collective_results -= 1 # Set menu level menu_level += -2*back_menu + 1 #-- # Results option elif menu_level > 1: # Collective results if collective_results: # Get result option if menu_level == 2: # Description desc = "Collective Results / Choose an option:" # Options #-- opts = { 1: "Trap depth" } #-- # Get group view_opt, back_menu, msg = self.__call_menu(opts, desc, msg) menu_level += -2*back_menu + 1 # Graph or CSV file option elif menu_level == 3: # Description #-- desc = "... / " + opts[view_opt] desc += " / Choose an option" #-- # Options #-- opts = { 1: "Visualization",\ 2: "Get CSV file" } #-- # Get group view_or_CSV, back_menu, msg = self.__call_menu(opts, desc, msg) # Set menu level menu_level += -2*back_menu + 1 # Visualization elif menu_level == 4: # Trap depth if view_opt == 1: if view_or_CSV == 1: results = self.__simulation.available_results(self.result_id) self.__view.trap_depth(results) menu_level -= 1 else: self.__view.print_msg("Creating CSV file ...", press_button = False) X, Y = results.escape_flux_atoms() # Save CSV file #-- data = { results.loop["var"]: X,\ "escape_flux_atoms": Y } path = "temp/" path += str(self.result_id["code"]) path += "_escape_flux_atoms.csv" pd.DataFrame(data).to_csv(path, index=False) #-- self.__view.print_msg("The CSV file has been created! Path: %s" % path) # Set menu level menu_level -= 2 # Individual results else: # Get code of a simulated data if menu_level == 2: # Description desc = "Individual Results / Choose a set of simulated data:" # Available results #-- results_opts = self.__simulation.available_results(self.result_id) #-- # Get result object results_code, back_menu, msg = self.__call_menu(results_opts, desc, msg, enumerated_list=True) if results_code > 0: self.__view.print_msg("Loading result ...", press_button=False) results = Results(results_code, self.result_id["group"], self.result_id["subgroup"]) self._result_id['code'] = results.id["code"] self.result_id["name"] = results.id["name"] self.__view.set_result_id(self.result_id) # Set menu level menu_level += -2*back_menu + 1 # Get view option elif menu_level == 3: # Description #-- desc = "... / Individual results / Choose an option" #-- # Options available_view_opts, all_view_opts = self.__view.available_views(results) opts = {(k+1):all_view_opts[v] for (k,v) in enumerate(available_view_opts)} # Get visualization view_opt, back_menu, msg = self.__call_menu(opts, desc, msg) view_opt = available_view_opts[view_opt-1] menu_level += -2*back_menu + 1 # Get view option 2 elif menu_level == 4: # Set view as default view_or_CSV = 1 # Check loop if results.loop["length"] > 0: # Description #-- desc = "... / " + all_view_opts[view_opt] desc += " / Choose an option" #-- # Options #-- opts = { 1: "Visualization",\ 2: "Get CSV file" } #-- # Get group view_or_CSV, back_menu, msg = self.__call_menu(opts, desc, msg) # Set menu level menu_level += -2*back_menu + 1 # Visualization else: menu_level += 1 # View data elif menu_level == 5: # Histogram of positions (choose axis or looping value) if view_opt == 1: # Plot graph if view_or_CSV == 1: self.__view.centre_of_mass(results) menu_level -= 2 # Get CSV file elif view_or_CSV == 2: self.__view.print_msg("Creating CSV file ...", press_button = False) X, Y = results.escape_flux_atoms() # Save CSV file #-- data = { results.loop["var"]: X,\ "escape_flux_atoms": Y } path = "temp/" path += str(self.result_id["code"]) path += "_escape_flux_atoms.csv" pd.DataFrame(data).to_csv(path, index=False) #-- self.__view.print_msg("The CSV file has been created! Path: %s" % path) # Set menu level menu_level -= 2 # Centre of mass elif view_opt == 2: # Plot graph if view_or_CSV == 1: self.__view.centre_of_mass(results) menu_level -= 2 # Get CSV file elif view_or_CSV == 2: self.__view.print_msg("Creating CSV file ...", press_button = False) X, Y = results.escape_flux_atoms() # Save CSV file #-- data = { results.loop["var"]: X,\ "escape_flux_atoms": Y } path = "temp/" path += str(self.result_id["code"]) path += "_escape_flux_atoms.csv" pd.DataFrame(data).to_csv(path, index=False) #-- self.__view.print_msg("The CSV file has been created! Path: %s" % path) # Set menu level menu_level -= 2 # Cloud size elif view_opt == 3: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Histogram of velocities (choose axis or looping value) elif view_opt == 4: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Temperature elif view_opt == 5: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Heat map elif view_opt == 6: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Escape flux of atoms elif view_opt == 7: # Plot graph if view_or_CSV == 1: self.__view.escape_flux_atoms(results) menu_level -= 2 # Get CSV file elif view_or_CSV == 2: self.__view.print_msg("Creating CSV file ...", press_button = False) X, Y = results.escape_flux_atoms() # Save CSV file #-- data = { results.loop["var"]: X,\ "escape_flux_atoms": Y } path = "temp/" path += str(self.result_id["code"]) path += "_escape_flux_atoms.csv" pd.DataFrame(data).to_csv(path, index=False) #-- self.__view.print_msg("The CSV file has been created! Path: %s" % path) # Set menu level menu_level -= 2 # Trapped atoms elif view_opt == 8: # Plot graph if view_or_CSV == 1: self.__view.trapped_atoms(results, fit_func="erf") menu_level -= 2 # Get CSV file elif view_or_CSV == 2: self.__view.print_msg("Creating CSV file ...", press_button = False) X, Y = results.normalized_trapped_atoms() # Save CSV file #-- data = { results.loop["var"]: X,\ "trapped_atoms": Y } path = "temp/" path += str(self.result_id["code"]) path += "_trapped_atoms.csv" pd.DataFrame(data).to_csv(path, index=False) #-- self.__view.print_msg("The CSV file has been created! Path: %s" % path) # Set menu level menu_level -= 2 # Trapped atoms (Escape velocity) elif view_opt == 9: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Escape velocity elif view_opt == 10: self.__view.print_msg("Function has not implemented!") menu_level -= 2 # Leave menu else: print("Exiting ...") exit(0) # Leave menu else: break # Set the active group and subgroup def group_menu(self): # Message msg = None # Set menu level menu_level = 1 # Loop menu while True: # Get group if menu_level == 1: # Available groups opts = self.__simulation.available_groups() desc = "Choose a group:" # Get group chosen_opt, back_menu, msg = self.__call_menu(opts, desc, msg) if back_menu == 0: self._result_id["group"] = opts[chosen_opt] # Change menu level menu_level += -2*back_menu + 1 # Get subgroup: elif menu_level == 2: # Available subgroups opts = self.__simulation.available_subgroups(self.result_id["group"]) # Check available subgroups if len(opts) > 0: # Get subgroup desc = ("(Group) %s / Choose a subgroup:" % self.result_id["group"]) chosen_opt, back_menu, msg = self.__call_menu(opts, desc, msg) if back_menu == 0: self._result_id["subgroup"] = opts[chosen_opt] # Change menu level menu_level += -2*back_menu + 1 # Leave looping else: menu_level = 0 # Leave looping else: break # Change CSV file #-- group_data = { "group":self.result_id["group"],\ "subgroup":self.result_id["subgroup"] } pd.Series(group_data, name="active_group").to_csv("controller/active_group.csv") #-- # Change view self.__view.set_result_id(self.result_id) # def __call_menu(self, opts, desc = None, msg = None, clear_screen = True, enumerated_list = False): # Variables back_menu = 0 # Call menu #-- while True: # Get option opt = self.__view.terminal_menu(opts, desc=desc, msg=msg, clear_screen=clear_screen, enumerated_list = enumerated_list) msg = None # Exit if opt == '0': print('\nExiting ...', end='\n\n') exit(0) # Back elif opt == "-1": opt = int(opt) back_menu = 1 break # Get in order elif opt[:2] == "_o" and len(opt) > 2 and opt[2:].isdigit(): opts_keys = list(opts.keys()) if ((int(opt[2:]) - 1) < len(opts_keys)) and int(opt[2:]) > 0: opt = opts_keys[int(opt[2:]) - 1] break else: msg = "Option not found" # Check value elif len(opt) > 0 and (opt.isdigit() or (opt[0] == "-" and opt[1:].isdigit())): opt = int(opt) if (opt in opts.keys()): break else: msg = "Invalid option" else: msg = "Invalid option" #-- return opt, back_menu, msg # def __call_input(self, desc, validation=None, back_opt=True): # Variables back_menu = 0 msg = None # Get value opt = self.__view.terminal_input(desc) # Exit if opt == '0': print('\nExiting ...\n') exit(0) # Back elif opt == "-1" and back_opt: back_menu = 1 # Validation elif (validation is not None) and (opt != "-1"): while (not validation(opt)) and (opt != "-1"): msg = "Invalid value!" opt = self.__view.terminal_input(description, header=header, clear_screen=clear_screen, footer=msg) # Exit if opt == '0': print('\nExiting ...\n') exit(0) # Back elif opt == "-1": opt = int(opt) back_menu = 1 break # Empty elif len(opt.strip()) == 0: opt = None return opt, back_menu
def __init__(self): self.model = Model() self.view = View()
def __init__(self): self.chess = Chess() self.view = View()
def __init__(self, env_name, **kwargs): """Initializes the environment. Args: env_name: The name of the environment to display. This should have a corresponding PNG image and YAML file with the same name in the maps folder. Keyword Args: render: Whether the environment should be rendered. Defaults to True. vision: Whether to return raw pixel values as observations. Defaults to False. obstacle: Whether to use the special Obstacle NPC. Defaults to False. decimals: Number of decimals in the observations. Defaults to None (no rounding). reward_function: The reward funtion to use. Defaults to internal reward. feature_function: A function to transform observations to a feature vector. tick: Whether to tick the clock at the desired frequency when stepping the env. Defaults to False. flip: Whether to flip the display so that the user can control the car more easily. Defaults to False. scroll: Whether to follow the view of the agent or generate the whole environment. Defaults to True. """ self.max_angle = global_var.MAX_ANGLE self.max_acc = global_var.MAX_ACC self.max_speed = global_var.MAX_SPEED set_env(env_name) # KEYWORD ARGS self.render = kwargs["render"] if "render" in kwargs else True self.vision = kwargs["vision"] if "vision" in kwargs else False self.obstacle = kwargs["obstacle"] if "obstacle" in kwargs else False self.decimals = kwargs["decimals"] if "decimals" in kwargs else None self.reward = kwargs[ "reward_function"] if "reward_function" in kwargs else self._default_reward self.feature_fn = kwargs[ "feature_function"] if "feature_function" in kwargs else self._default_feature_fn self.tick = kwargs["tick"] if "tick" in kwargs else False self.flip = kwargs["flip"] if "flip" in kwargs else False self.scroll = kwargs["scroll"] if "scroll" in kwargs else True # ZONES self.lanes = [] self.intersections = [] self.lane_markers = [] with open(os.path.join(global_var.PATH, "maps", env_name + ".yaml")) as f: description = yaml.load(f) # Width and height of the actual environment. self.width = description["width"] self.height = description["height"] self._create_zones(description) # Choose whether to use the pos from the config or the default pos from the map. if agent.USE_POS: self.agent = Agent() else: pos = description["agent_start"] self.agent = Agent(pos["x"], pos["y"], pos["theta"]) self._keep_agent_in_map() self.npc_manager = NPCManager(description["starts"], (self.width, self.height), self.obstacle) # Number of elements in the action and the observation vectors. self.observation_n = len(self._get_observation()) self.action_n = 2 self.clock = None self.display_surface = None # The PNG image of the map. if self.scroll: self.view = View(env_name, description["width"], description["height"], screen.WIDTH, screen.HEIGHT, self.flip) else: self.view = View(env_name, description["width"], description["height"]) self.setup()
class Controller: def __init__(self): self.model = Model() self.view = View() def run_menu(self, message=''): selectionMenu = SelectionMenu( TABLES_NAMES + ['Search players by level name with set health and nickname', 'Find skins by player health, last online and level', 'Count players who own skin by skin name, level title and health', 'Fill table "level" by random data'], title='Menu:', subtitle=message) selectionMenu.show() index = selectionMenu.selected_option if index < len(TABLES_NAMES): tableName = TABLES_NAMES[index] self.show_entity_menu(tableName) elif index == 4: self.search_players_on_level_by_levelname_health_nickname() elif index == 5: self.search_skin_by_playerhealth_online_levelname() elif index == 6: self.count_players_with_skin_by_skin_name_levelname_health() elif index == 7: self.fill_level_by_random_data() else: print('Closing...') def show_entity_menu(self, tableName, msg=''): options = ['Get', 'Delete', 'Update', 'Insert'] functions = [self.get, self.delete, self.update, self.insert] selectionMenu = SelectionMenu(options, f'{tableName}', exit_option_text='Back', subtitle=msg) selectionMenu.show() try: function = functions[selectionMenu.selected_option] function(tableName) except IndexError: self.run_menu() def get(self, tableName): try: condition = getInput( f'GET {tableName}\nEnter search criteria:', tableName) start_time = time.time() data = self.model.get(tableName, condition) self.view.print(data) print("\nQuery time:", time.time() - start_time) input() self.show_entity_menu(tableName) except Exception: self.show_entity_menu(tableName, 'Invalid search criteria') def insert(self, tableName): try: columns, values = getInsertInput( f"INSERT {tableName}\nEnter columns, then values", tableName) self.model.insert(tableName, columns, values) self.show_entity_menu(tableName, 'Insert is successful!') except Exception as err: self.show_entity_menu(tableName, 'Invalid insert arguments') def delete(self, tableName): try: condition = getInput( f'DELETE {tableName}\n Enter criteria for deletion:', tableName) self.model.delete(tableName, condition) self.show_entity_menu(tableName, 'Delete is successful') except Exception: self.show_entity_menu(tableName, 'Invalid deleting criteria') def update(self, tableName): try: condition = getInput( f'UPDATE {tableName}\nEnter criteria:', tableName) statement = getInput( "Enter columns and their new values", tableName) self.model.update(tableName, condition, statement) self.show_entity_menu(tableName, 'Update is successful') except Exception: self.show_entity_menu(tableName, 'Invalid update values') def search_players_on_level_by_levelname_health_nickname(self): try: levelname = getInput('Enter level name') a = getInput('Enter min health') b = getInput('Enter max health') nickname = getInput('Enter nickname') start_time = time.time() data = self.model.search_players_on_level_by_levelname_health_nickname(levelname, a, b, nickname) self.view.print(data) print("\nQuery time:", time.time() - start_time) input() self.run_menu() except Exception: self.run_menu('Invalid search arguments') def search_skin_by_playerhealth_online_levelname(self): try: minhealth = getInput('Enter minimum health') maxhealth = getInput('Enter max health') mindate = getInput('Enter min date player was online') maxdate = getInput('Enter max date player was online') levelname = getInput('Enter level name') start_time = time.time() data = self.model.search_skin_by_playerhealth_online_levelname(minhealth, maxhealth, mindate, maxdate, levelname) self.view.print(data) print("\nQuery time:", time.time() - start_time) input() self.run_menu() except Exception: self.run_menu('Invalid search arguments') def count_players_with_skin_by_skin_name_levelname_health(self): try: skintitle = getInput('Enter skin title') levelname = getInput('Enter level name') minhealth = getInput('Enter min player health') maxhealth = getInput('Enter max player health') start_time = time.time() data = self.model.count_players_with_skin_by_skin_name_levelname_health(skintitle, levelname, minhealth, maxhealth) self.view.print(data) print("\nQuery time:", time.time() - start_time) input() self.run_menu() except Exception: self.run_menu('Invalid search arguments') def fill_level_by_random_data(self): try: quantity = getInput('Enter quantity:') self.model.fill_level_by_random_data(quantity) self.run_menu('Generated successfully') except Exception: self.run_menu('Invalid quantity')
class Environment(object): """The simulation environment.""" OBS_TYPES_NPC = [ "closest_car", "closest_car_state", "all_cars", "obstacle_car_state" ] OBS_TYPES_MAP = ["local", "global", "none"] def __init__(self, env_name, **kwargs): """Initializes the environment. Args: env_name: The name of the environment to display. This should have a corresponding PNG image and YAML file with the same name in the maps folder. Keyword Args: render: Whether the environment should be rendered. Defaults to True. vision: Whether to return raw pixel values as observations. Defaults to False. obstacle: Whether to use the special Obstacle NPC. Defaults to False. decimals: Number of decimals in the observations. Defaults to None (no rounding). reward_function: The reward funtion to use. Defaults to internal reward. feature_function: A function to transform observations to a feature vector. tick: Whether to tick the clock at the desired frequency when stepping the env. Defaults to False. flip: Whether to flip the display so that the user can control the car more easily. Defaults to False. scroll: Whether to follow the view of the agent or generate the whole environment. Defaults to True. """ self.max_angle = global_var.MAX_ANGLE self.max_acc = global_var.MAX_ACC self.max_speed = global_var.MAX_SPEED set_env(env_name) # KEYWORD ARGS self.render = kwargs["render"] if "render" in kwargs else True self.vision = kwargs["vision"] if "vision" in kwargs else False self.obstacle = kwargs["obstacle"] if "obstacle" in kwargs else False self.decimals = kwargs["decimals"] if "decimals" in kwargs else None self.reward = kwargs[ "reward_function"] if "reward_function" in kwargs else self._default_reward self.feature_fn = kwargs[ "feature_function"] if "feature_function" in kwargs else self._default_feature_fn self.tick = kwargs["tick"] if "tick" in kwargs else False self.flip = kwargs["flip"] if "flip" in kwargs else False self.scroll = kwargs["scroll"] if "scroll" in kwargs else True # ZONES self.lanes = [] self.intersections = [] self.lane_markers = [] with open(os.path.join(global_var.PATH, "maps", env_name + ".yaml")) as f: description = yaml.load(f) # Width and height of the actual environment. self.width = description["width"] self.height = description["height"] self._create_zones(description) # Choose whether to use the pos from the config or the default pos from the map. if agent.USE_POS: self.agent = Agent() else: pos = description["agent_start"] self.agent = Agent(pos["x"], pos["y"], pos["theta"]) self._keep_agent_in_map() self.npc_manager = NPCManager(description["starts"], (self.width, self.height), self.obstacle) # Number of elements in the action and the observation vectors. self.observation_n = len(self._get_observation()) self.action_n = 2 self.clock = None self.display_surface = None # The PNG image of the map. if self.scroll: self.view = View(env_name, description["width"], description["height"], screen.WIDTH, screen.HEIGHT, self.flip) else: self.view = View(env_name, description["width"], description["height"]) self.setup() def setup(self): """Sets up the simulation environment and initializes the pygame environment.""" if self.render or self.vision: self.display_surface = pygame.display.set_mode( (self.view.screen_width, self.view.screen_height)) if self.render: pygame.init() self.clock = pygame.time.Clock() pygame.display.set_caption('Traffic World') pygame.display.update() def quit(self): if self.render: pygame.quit() def step(self, action, npc_action=None): """Advances the environment forward by one time step. Args: action: The action the agent should take, in format (linear acceleration, angular acceleration). npc_action: A list of actions to control the NPCs. Optional. """ # Bound the action values. limit(action[0], -1, 1) limit(action[1], -1, 1) # Convert the actions, which represent percentages, to the correct units. acc, theta = input_to_action(action) # Move the agent. self.agent.move(acc, theta) # Impose a limit on the agent's speed. self.agent.set_speed( limit(self.agent.get_speed(), -self.max_speed, self.max_speed)) # Move the traffic. self.npc_manager.step(self.agent.bounding_box, npc_action) # Update the view if we're in rendering or vision mode. if self.render or self.vision: # Collect a list of all the cars and their images and states. cars = self._get_cars() # Get the view. surf = self.view.update(self.agent.get_x(), self.agent.get_y(), cars) # Render, if necessary. if self.render: self.display_surface.blit(surf, (0, 0)) pygame.display.update() obs = self._get_observation() if self.tick: time.sleep(1.0 / global_var.FPS) done = self._get_done() self._keep_agent_in_map() return obs, self.reward(obs), done def reset(self, state=None): """Resets the simulation. Args: state: The state to reset the environment to. Optional. Returns: Initial state. """ self.agent.reset() self._keep_agent_in_map() self.npc_manager.reset() if self.render or self.vision: cars = self._get_cars() surf = self.view.update(self.agent.get_x(), self.agent.get_y(), cars) # Render, if necessary. if self.render: self.display_surface.blit(surf, (0, 0)) pygame.display.update() if state is not None: self.set_state(state) return self._get_observation() def _create_zones(self, desc): """Populates all the necessary variables which create the environment. Args: desc: The environment description. """ self.lanes = [] self.intersections = [] lane_i = 0 int_i = 0 for zone in desc["zones"]: if zone["label"] == "lane": self.lanes.append(Lane(zone["corner"], zone["size"], lane_i)) lane_i += 1 elif zone["label"] == "intersection": self.intersections.append( Intersection(zone["corner"], zone["size"], int_i)) int_i += 1 else: raise ("Incorrect zone type provided.") for lane in desc["lane_markers"]: if lane["shape"] == "straight": self.lane_markers.append(Line(lane["points"])) else: raise ("Unsupported lane marker shape.") def _get_lane(self): """Returns the lane ID of the the lane the agent is currently in. If the agent is not in a lane, returns None.""" for lane in self.lanes: if lane.is_inside(self.agent.get_pos()): return lane.id return None def _get_intersection(self): """Returns the intersection ID of the the intersection the agent is currently in. If the agent is not in a intersection, returns None.""" for intersection in self.intersections: if intersection.is_inside(self.agent.get_pos()): return intersection.id return None def get_zone(self): """Returns the zone which the agent is in using the format: ("type", ID) The types of zones are: - lane - intersection - on_road (for on an arbitrary type of road) - off_road """ lane = self._get_lane() if lane is not None: return ("lane", lane) intersection = self._get_intersection() if intersection is not None: return ("intersection", intersection) colour = self._check_pixels() if colour in ["grey", "white"]: return ("on_road", 0) return ("off_road", 0) def on_road(self): """Returns True if the agent is on a road, False otherwise.""" zone = self.get_zone()[0] if zone == "off_road": return False else: return True def _check_pixels(self): """Checks the colour of the pixel that the agent is on and returns the colour as a string. Supported colours are: - grey - black - white - green - unknown """ c = self.view.get_colour(self.agent.get_x(), self.agent.get_y()) r = c[0] g = c[1] b = c[2] # If the r, g and b values are close, the colour is grey, black or white. if is_close(r, g) and is_close(g, b): if r < 0.9 and r > 0.1: return "grey" elif r <= 0.1: return "black" else: return "white" # If g is sufficiently higher than r and b, the colour is green. if g - r > 0.2 and g - b > 0.2: return "green" return "unknown" def collided(self): """Returns True if the agent has collided with an NPC, False otherwise.""" return self.npc_manager.check_collision(self.agent.bounding_box) def _get_closest_marker(self): """Returns the closest marker.""" if len(self.lane_markers) == 0: return pos = self.agent.get_pos() min_idx = 0 min_dist = self.lane_markers[min_idx].dist_to_point(pos) for i in range(1, len(self.lane_markers)): dist = self.lane_markers[i].dist_to_point(pos) if dist < min_dist: min_dist = dist min_idx = i return (min_dist, self.lane_markers[i].angle - self.agent.get_heading()) def _get_done(self): """Returns whether the episode is done. Episode terminates if the agent collides with a car or leaves the map.""" # Check if the agent is outside the map. outside = not self.agent.in_map(self.width, self.height) # Check if the agent has collided with another car. collision = self.collided() return outside or collision def _get_cars(self): """Gets a list of tuples where each tuple is of the form: (img, x, y, theta) for each car currently in the environment. """ cars = [(self.agent.img, self.agent.get_x(), self.agent.get_y(), self.agent.get_heading())] for npc in self.npc_manager.npcs: cars.append((npc.img, npc.get_x(), npc.get_y(), npc.get_heading())) return cars def _get_observation(self): """The observation is either the raw pixels of the map, if the vision flag is True, or otherwise an array containing state information. All distances are in pixels, all angles are in radians and all speeds are in pixels/timestep. The array is a one dimentional array of length N, organized as follows: [AGENT STATE, NPC STATES] The components of the agent state are: x, y, theta, speed The NPC state is the state of all the NPC cars, zero padded if less than max cars are on the road: [x_i, y_i, theta_i, speed_i] x MAX CARS """ if self.vision: return pygame.surfarray.array3d(self.display_surface) # AGENT STATE agent_state = list(self.agent.get_state()) # NPC STATE npc_state = [] for npc in self.npc_manager.npcs: npc_state += list(npc.get_state()) # Pad with zeros. npc_state += [0, 0, 0, 0 ] * (self.npc_manager.MAX - len(self.npc_manager.npcs)) observation = agent_state + npc_state if self.decimals is not None: observation = [round(float(x), self.decimals) for x in observation] return self.feature_fn(observation) def set_state(self, x_0): """Force set the initial state to a single state vector. Only all_cars and none observation type supported. Only one NPC car supported.""" agent_state = x_0[0:4] npc_state = x_0[4:8] self.agent.set_state(agent_state[0], agent_state[1], agent_state[2], agent_state[3]) if len(self.npc_manager.npcs) > 0: self.npc_manager.npcs[0].set_state(npc_state[0], npc_state[1], npc_state[2], npc_state[3]) def _keep_agent_in_map(self): """Keeps the agent inside the map by limiting its position.""" x = limit(self.agent.get_x(), 0, self.width) y = limit(self.agent.get_y(), 0, self.height) self.agent.set_x(x) self.agent.set_y(y) def _default_reward(self, observation): """Default reward function, which always returns no reward.""" return 0 def _default_feature_fn(self, observation): """Default feature function, which returns the full observation.""" return observation
from controller import Controller from model import Model from view import View c = Controller(Model(), View()) c.show_menu()
def main(): import optparse parser = optparse.OptionParser() parser.add_option("-r", "--roadmap", help="Optional roadmap file to load", action="store", dest="roadmapName", default='') parser.add_option("-g", "--goals", help="Optional goal definition file to load", action="store", dest="goalsName", default='') parser.add_option("-b", "--obstacle", help="Optional obstacle file to load.", action="store", dest='obstName', default='') parser.add_option("-a", "--agent", help="Optional agent position file to load.", action="store", dest='agtName', default='') parser.add_option("-f", "--field", help="Optional vector field file to load.", action="store", dest='fieldName', default='') parser.add_option( "-c", "--createField", help= 'Creates a field based on the domain of the obstacles - ignored if --field(-f) is specified', action='store_true', dest='createField', default=False) parser.add_option("-s", "--scb", help="Optional scb file to load.", action="store", dest='scbName', default='') parser.add_option( "-i", "--inDir", help= "Optional directory to find input files - only applied to file names with relative paths", action="store", dest='inDir', default='.') parser.add_option( "-o", "--outDir", help= "Optional directory to write output files - only applied to file names with relative paths", action="store", dest='outDir', default='.') parser.add_option( '--region', help= 'Specify the bounding region of the action. If provided, it will set the initial camera properties. Format is minX minY maxX maxY', nargs=4, type='float', dest='boundRegion', default=None) options, args = parser.parse_args() paths.setInDir(options.inDir) paths.setOutDir(options.outDir) obstName = paths.getPath(options.obstName) agtName = paths.getPath(options.agtName) roadmapName = paths.getPath(options.roadmapName) fieldName = paths.getPath(options.fieldName) scbName = paths.getPath(options.scbName) goalsName = paths.getPath(options.goalsName) print "Arguments:" print "\tInput dir: ", options.inDir print "\tOutput dir:", options.outDir print "\tobstacles: ", obstName print "\tagents: ", agtName print "\troad map: ", roadmapName print "\tfield: ", fieldName print "\tscbName: ", scbName print "\tGoals: ", goalsName if (obstName): obstacles, bb = readObstacles(obstName) else: obstacles = ObstacleSet() bb = AABB() if (not options.boundRegion is None): bb.min = Vector3(options.boundRegion[0], options.boundRegion[1], 0) bb.max = Vector3(options.boundRegion[2], options.boundRegion[3], 0) print bb else: bb.min = Vector3(-100, -100, 0) bb.max = Vector3(100, 100, 0) agents = AgentSet(0.23) if (agtName): agents.initFromFile(agtName) if (scbName != ''): # This reads the agent radius from the file, but no longer visualizes the agents # This is a bit of a hack. It would be better to simply disable drawing the # agents when the scb playback context is active. But I don't have the time # to figure out an elegant solution to this. agents.clear() if (fieldName): field = GLVectorField((0, 0), (1, 1), 1) field.read(fieldName) elif (options.createField): print "Instantiate vector field from geometry:", bb bbSize = bb.max - bb.min field = GLVectorField((bb.min.x, bb.min.y), (bbSize.y, bbSize.x), 2.0) else: field = None graph = Graph() if (roadmapName): graph.initFromFile(roadmapName) # create viewer pygame.init() fontname = pygame.font.get_default_font() font = pygame.font.Font(fontname, 12) w = bb.max.x - bb.min.x h = bb.max.y - bb.min.y view = View((w, h), (bb.min.x, bb.min.y), (w, h), (bb.min.x, bb.min.y), (800, 600), font) view.HELP_TEXT = 'View controls:' + \ '\n\tpan - Ctrl + left mouse button' + \ '\n\tzoom in - mouse wheel up' + \ '\n\tzoom out - mouse wheel down' + \ '\n\tzoom - Shift + left mouse button (up and down)' view.initWindow('Create roadmap') pygame.key.set_repeat(250, 10) view.initGL() if (field): field.newGLContext() ## field = None # load goals if (goalsName): try: goalSets = Goals.readGoals(goalsName) except ValueError as e: print "Error parsing goals:", str(e) print "\tUsing empty GoalSet" goalSets = [Goals.GoalSet()] else: goalSets = [Goals.GoalSet()] goalVis = GoalEditor(goalSets) context = ContextSwitcher() context.addContext(PositionContext(), pygame.K_q) context.addContext(GoalContext(goalVis), pygame.K_g) context.addContext(AgentContext(agents), pygame.K_a) context.addContext(ObstacleContext(obstacles), pygame.K_o) if (field): context.addContext(FieldEditContext(field), pygame.K_f) if (scbName != ''): context.addContext(SCBContext(scbName, obstacles, agents.defRadius), pygame.K_s) context.newGLContext() redraw = True running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break elif (event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONUP or event.type == pygame.MOUSEBUTTONDOWN): result = handleMouse(event, context, view, graph, obstacles, agents, field) redraw |= result.needsRedraw() elif (event.type == pygame.KEYDOWN or event.type == pygame.KEYUP): try: result = handleKey(event, context, view, graph, obstacles, agents, field) redraw |= result.needsRedraw() except Exception as e: print "Error with keyboard event" print "\t", e running = False elif (event.type == pygame.VIDEORESIZE): view.resizeGL(event.size) if (field): field.newGLContext() context.newGLContext() redraw |= True elif (event.type == pygame.VIDEOEXPOSE): redraw |= True if (redraw): drawGL(view, context, obstacles, graph, agents, field, goalVis) message(view, updateMsg(agents.count())) pygame.display.flip() if (context): name = context.exportDisplay() if (name): pygame.image.save(view.surface, name) redraw = False writeRoadmap()
from __future__ import division from psychopy import visual, core, event, gui, misc, sound import time, random, cPickle, codecs, os, copy, math, collections from psychopy import parallel, monitors from view import View from eegsignal import Signal from dataCollector import DataCollector from controller import Controller from config import Config signal = Signal(Config.parallelPort) if Config.parallelDisabled: signal.disable() personData = View.collectPersonData(u'MOTOR') male = (personData['nem'] == u"férfi") right = (personData['kez'] == u"jobb") # pin number 2 for right hand and port number 3 for left hand if right: pinNumber = 2 else: pinNumber = 3 dataCollector = DataCollector('motor', personData['sorszam'], personData['nem'], personData['kez']) if not dataCollector.openFile(): View.showErrorAndQuit(
class Producer(Thread): def __init__(self): Thread.__init__(self) self.view = View() self.queue = self.readqueue() def dataPass(self, cmds): if cmds[0] == "add": if self.view.time_int(cmds[3]) >= self.view.time_int(cmds[4]): return False if cmds[1] in self.constructCalendar().keys(): return False return True elif cmds[0] == "del": if cmds[1] in self.constructCalendar().keys(): return True return False def readlog(self): record = {} try: f = open('acceptor.state', 'r') for line in f: record = eval(line) finally: return record def constructCalendar(self, record=None): if not record: record = self.readlog() calendar = {} for entryID in range(10000): if entryID in record.keys(): if "commitVal" in record[entryID].keys(): if record[entryID]["commitVal"]["operation"] == "add": if record[entryID]["commitVal"][ "app_name"] in calendar.keys(): print "Warning: add same appointment name for mulitiple times." break calendar[record[entryID]["commitVal"] ["app_name"]] = record[entryID]["commitVal"] elif record[entryID]["commitVal"]["operation"] == "del": if not record[entryID]["commitVal"][ "app_name"] in calendar.keys(): print "Warning: try to delete an non-exist appointment." break calendar.pop(record[entryID]["commitVal"]["app_name"], None) for key, ele in calendar.items(): self.convertDate(calendar[key]) return calendar def run(self): print "Welcome" while True: cmd = raw_input("") cmds = cmd.strip().split() if not cmds: print "Type something." continue if cmds[0] == "add": if len(cmds) != 6: warning = "format: add <calendar name> <day> <start time> <end time> <participant list>" print warning continue #@TODO Conflict else: if not self.dataPass(cmds): print "Wrong Input" continue self.queue.put({ "operation": "add", "app_name": cmds[1], "day": self.view.days_int(cmds[2]), "startTime": self.view.time_int(cmds[3]), "endTime": self.view.time_int(cmds[4]), "participants": set(cmds[5].split(',')) }) self.savequeue() print "Roger that. Your command queue:" self.printqueue() elif cmds[0] == "del": if len(cmds) != 2: warning = "format: del <calendar name>" print warning continue else: if not self.dataPass(cmds): print "Wrong Input" continue self.queue.put({"operation": "del", "app_name": cmds[1]}) self.savequeue() print "Roger that. Your command queue:" self.printqueue() elif cmds[0] == "viewlocal": if len(cmds) != 1: warning = "format: viewlocal" print warning continue else: print "Roger that. Your local commited log:" self.showCalendar() print "Your calendar:" print self.constructCalendar().keys() elif cmds[0] == "view": if len(cmds) != 1: warning = "format: view" print warning continue else: self.queue.put({"operation": "view"}) self.savequeue() print "Roger that. Your command queue:" self.printqueue() elif cmds[0] == "log": if len(cmds) != 1: warning = "format: log" print warning continue else: print "Roger that. Your local log:" self.showCalendar(committed=False) elif cmds[0] == "queue": if len(cmds) != 1: warning = "format: queue" print warning continue else: print "Roger that. Your command FIFO queue:" self.printqueue() else: print "Unknown command. Only accept add/del/view/log" print "-" * 32 time.sleep(1) def showCalendar(self, record=None, committed=True): if not record: record = self.readlog() try: print "<" * 25 for entryID in range(10000): if entryID in record.keys(): if committed: if "commitVal" in record[entryID].keys(): self.convertDate(record[entryID]["commitVal"]) print entryID, " | ", print record[entryID]["commitVal"].values() else: print entryID, ":", print record[entryID] print ">" * 25 except: print "Empty" def convertDate(self, dictionary): if "day" in dictionary.keys(): dictionary["day"] = self.view.days_str(dictionary["day"]) if "startTime" in dictionary.keys(): dictionary["startTime"] = self.view.time_str( dictionary["startTime"]) if "endTime" in dictionary.keys(): dictionary["endTime"] = self.view.time_str(dictionary["endTime"]) def savequeue(self): f = open('user.queue', 'w') f.write(str(list(self.queue.queue))) def printqueue(self): print str(list(self.queue.queue)) def readqueue(self): queue = Queue.Queue() try: f = open('user.queue', 'r') for line in f: queue.queue = deque(eval(line)) except: "" finally: return queue
from model import Model from view import View model = Model() properties = int(sys.argv[1]) per_index = 30 if not os.path.exists('properties'): os.mkdir('properties') for pid in xrange(0, properties): item = model.get_item(pid) f = open("properties/property_%06d.html" % pid, "w") f.write(View.render_property(item)) f.close() indices = (properties + per_index - 1) / per_index for page in xrange(0, indices): np = "index_%05d.html" % (page + 1) start = per_index * page end = min(per_index * (page + 1), properties) index = { 'page': page, 'nextp': None if page >= (indices - 1) else np, 'items': model.get_items(xrange(start, end)) }
'ref_column': 'if_f' } model.add_foreign_key(key1) key2 = { 'fk_table': 'Schedule', 'fk_column': 'id_s', 'ref_table': 'Sessions', 'ref_column': 'id_s' } model.add_foreign_key(key2) key3 = { 'fk_table': 'Schedule', 'fk_column': 'id_c', 'ref_table': 'Cinemas', 'ref_column': 'id_c' } model.add_foreign_key(key3) controller = Controller(model, View()) while True: controller.show_menu() option = int(input()) if option == 1: option1(controller) elif option == 2: option2(controller) elif option == 3: option3(controller) elif option == 4: break
class Controller: def __init__(self): self.chess = Chess() self.view = View() def on_init(self): self.chess.on_init() self.view.on_init() def select(self): # set a piece to be dragged using dragging field in View coordinates = pg.mouse.get_pos() self.view.setSelectedPiece(coordinates) def drag(self): # perform a drag operation if self.view.dragging != None: coordinates = pg.mouse.get_pos() self.view.drag(coordinates) def drop(self): # drop piece being dragged # attempt to perform a move on the dragged piece to that square if self.view.dragging != None: toCoords = pg.mouse.get_pos() fromCoords = self.view.dragging.pos toCo = viewCoordsToModelIndex(toCoords, self.view.dragging.size) fromCo = viewCoordsToModelIndex(fromCoords, self.view.dragging.size) moved = self.chess.move(tupleToInt(fromCo), tupleToInt(toCo)) if moved: self.view.removeImageAt(toCoords) self.view.drop(toCoords) else: self.view.drop(self.view.dragging.pos) self.view.dragging = None def getSurface(self): return self.view._display_surf
def reset(self): self._model = Model(self.rows, self.cols) self._view = View(self.rows, self.cols)
def __init__(self): viewListener = ViewListener() self.view = View(viewListener) self.model = Model(Listener(self.view)) viewListener.add_model(self.model)
from model import Model from view import View from controller import Controller model = Model() view = View(model) controller = Controller(model, view) while not model.isFinished(): view.printHangman() char = view.inputChar() controller.guess(char) if model.isSuccess(): view.printSuccess() elif model.isFail(): view.printFail() else: view.printError("Game Finished with unknown error")
def draw(self): self.get_all_walls() view = View() view.draw_line( self.wallFactory.set_all_x_and_y_values_in_right_order()[0], self.wallFactory.set_all_x_and_y_values_in_right_order()[1])
class Controller: def __init__(self): self.enter = {} self.now = datetime.now() self.csvFilePath = r'data.csv' self.jsonFilePath = r'data.json' self.database = Database() self.data = Data() self.view = View() self.table = None self.hello() def hello(self): try: self.view.hello() while True: res = self.view.main_() if res == "1": self.get_data() elif res == "2": self.graphs_plot() elif res == "3": self.graphs_pie() elif res == "4": self.database.backup() elif res == "5": self.database.restore() elif res == "6": self.analysis() elif res == "7": self.top() elif res == "8": self.view.bye() break else: self.view.inc() except Exception as er: print("Error,", er) def get_data(self): res = self.data.make_json() self.db_post_data(res) def graphs_plot(self): res = self.database.get_address() ans = self.view.graph_plot(res) self.database.f_request(ans) def analysis(self): res = self.database.get_address() ans = self.view.analysis(res) self.database.request_a1(ans) def top(self): ans = self.view.top() self.database.request_a2(ans) def graphs_pie(self): ans = self.view.graph_pie() self.database.s_request(ans) def db_post_data(self, d): try: for i in range(1, d + 1): res = self.data.obj_4_post(i) for post in res: d = self.db_post_det(post) hm = self.database.select_f(Location, post["Address"], Location.address) if hm is None: l = self.db_post_loc(post) id_l = l.id_loc else: id_l = hm.id_loc post["id_loc"] = id_l post["id_det"] = d.id_det self.db_post_cd(post) except Exception as er: print(er, 404) def db_post_det(self, add): return self.database.post_details(add) def db_post_cd(self, add): self.database.post_city_date(add) def db_post_loc(self, add): return self.database.post_loc(add)
'price': 0.5, 'quantity': 20 }, { 'name': 'milk', 'price': 1.0, 'quantity': 10 }, { 'name': 'wine', 'price': 10.0, 'quantity': 5 }, ] c = Controller(ModelMySQL(my_items), View()) c.show_items() c.show_items(bullet_points=True) c.show_item('chocolate') c.show_item('bread') c.insert_item('bread', price=1.0, quantity=5) c.insert_item('chocolate', price=2.0, quantity=10) c.show_item('chocolate') c.update_item('milk', price=1.2, quantity=20) c.update_item('ice cream', price=3.5, quantity=20) c.delete_item('fish') c.delete_item('bread')
def __init__(self): Thread.__init__(self) self.view = View() self.queue = self.readqueue()
# -*- encoding: utf-8 -*- from model import Model from view import View from controller import Controller model = Model() view = View() controller = Controller(model, view) controller.run()
elif p == '7': if m.update(2, 0, q): return True elif p == '8': if m.update(2, 1, q): return True elif p == '9': if m.update(2, 2, q): return True return False # init model m = Model() print(View.update(m.getBoard())) while True: pos1 = input("Player 1: choose your position\n") while not filled(pos1, 'x'): pos1 = input("Player 1: Invalid move. Choose your position\n") print(View.update(m.getBoard())) if m.end(): break pos2 = input("Player 2: choose your position\n") while not filled(pos2, 'o'): pos2 = input("Player 2: Invalid move. Choose your position\n") print(View.update(m.getBoard()))
from head import Head from shape import Shape from view import View from dots import Dots from handtracker import HandTracker #from controller import Controller from key_controller import KeyController from constants import Mode from os import kill import signal if __name__ == "__main__": head = Head() shape = Shape(height=0.4, width=0.4, x=0, y=0, z=-9) dots = Dots() view = View(head=head, shape=shape, dots=dots, mode=Mode.MPU_MODE) handtracker = HandTracker(dots) #controller = Controller(head, use_phidget=False, use_MPU=True) keycontroller = KeyController(head, shape) try: view.run() finally: handtracker.shutdown() kill(handtracker.proc.pid, signal.SIGINT) handtracker.proc.wait() print("FINISHED")
class Controller: ''' Manage progress through game ''' def __init__(self): self.model = Model() self.view = View() # create selection matrix for filter # create top row of card ranks top_row = [SelectionItem('', is_top_left=True)] + [ SelectionItem(Card.ranks[rank], is_card=False, is_top_row=True) for rank in range(1, RANKS + 1) ] # create selection item for each card self.model.selection_matrix = [top_row] + [[ SelectionItem(str(Card(rank, suit)), card=Card(rank, suit)) for rank in range(1, RANKS + 1) ] for suit in range(1, SUITS + 1)] # add leftmost column for suits for i in range(1, len(self.model.selection_matrix)): self.model.selection_matrix[i] = [ SelectionItem(Card.suits[i], is_card=False) ] + self.model.selection_matrix[i] # deselect all for row in self.model.selection_matrix: for item in row: item.is_selected = False # initialize game state self.model.deck = Deck() self.model.player_hand = Hand() self.model.dealer_hand = Hand() self.model.drawn_cards = [] def run_game(self): ''' Alternate between choosing filter and drawing cards until game ends ''' while True: # get card filter self.get_selection() # start drawing self.model.state = self.model.GameMode.DRAWING self.render() done = False self.model.drawn_cards = [] self.model.cursor = [0, 0] # move cursor off board while not done: # draw card card = self.model.deck.draw() self.model.drawn_cards.append(card) # give it to player or dealer if card in self.model.filter: self.model.player_hand.add_card(card) done = True # player got card, stop drawing else: self.model.dealer_hand.add_card(card) # update view self.render() # if out of cards if len(self.model.deck.cards) == 0: done = True # delay until next draw time.sleep(0.8) # check if game over if self.model.player_hand.size() >= 5: # draw until dealer has at least 8 cards if self.model.dealer_hand.size() < 8: self.model.state = self.model.GameMode.FINISHING while self.model.dealer_hand.size() < 8: card = self.model.deck.draw() self.model.drawn_cards.append(card) self.model.dealer_hand.add_card(card) self.render() time.sleep(0.8) # check winner won = HandScoring.compare_hands( self.model.player_hand.hand, self.model.dealer_hand.hand) == 1 self.model.message = 'YOU WIN' if won else 'YOU LOSE' self.render() sys.exit(0) # alternate end condition: player got less than 5 cards from entire deck if len(self.model.deck.cards) == 0: # player loses by default self.model.message = 'YOU LOSE' self.render() sys.exit(0) def render(self): ''' Update the view with the new model ''' self.view.render(self.model) def get_selection(self): ''' Get the selection of filtered cards from the user ''' # deselect all drawn cards for row in self.model.selection_matrix[1:]: for item in row[1:]: if not self.model.card_available(item.card): item.is_selected = False # reset selection box self.model.cursor = [1, 1] self.model.state = self.model.GameMode.FILTERING model = self.model self.render() # move cursor and handle item selection while True: keypress = readchar.readkey() # if not at edge, move cursor in specified direction if keypress == readchar.key.UP: if model.cursor[0] > 1 or model.cursor[ 0] == 1 and model.cursor[1] > 0: model.cursor[0] -= 1 self.render() elif keypress == readchar.key.DOWN: if model.cursor[0] < len(model.selection_matrix) - 1: model.cursor[0] += 1 self.render() elif keypress == readchar.key.LEFT: if model.cursor[1] > 1 or model.cursor[ 1] == 1 and model.cursor[0] > 0: model.cursor[1] -= 1 self.render() elif keypress == readchar.key.RIGHT: if model.cursor[1] < len(model.selection_matrix[0]) - 1: model.cursor[1] += 1 self.render() # handle selection elif keypress == readchar.key.SPACE: self.make_selection(model.cursor) self.render() # if at least one card is selected, stop selection elif keypress == readchar.key.ENTER: selected_cards = set() for row in model.selection_matrix[1:]: for card_item in row[1:]: if card_item.is_selected: selected_cards.add(card_item.card) if len(selected_cards) > 0: model.filter = selected_cards break # escape sequences elif keypress in (readchar.key.CR, readchar.key.CTRL_C): sys.exit(1) def make_selection(self, cursor): ''' Handle a selection of either an individual card or an entire suit or rank ''' i, j = cursor[0], cursor[1] # individual card selected if i > 0 and j > 0: card = self.model.selection_matrix[i][j].card # if card has not been drawn if self.model.card_available(card): self.model.selection_matrix[i][ j].is_selected = not self.model.selection_matrix[i][ j].is_selected # rank selected elif i == 0: # check if any of this column are not selected any_false = False for i_ in range(1, SUITS + 1): if not self.model.selection_matrix[i_][ j].is_selected and self.model.card_available( self.model.selection_matrix[i_][j].card): any_false = True break # set all to true if some were not, otherwise all to false for i_ in range(1, SUITS + 1): if self.model.card_available( self.model.selection_matrix[i_][j].card): self.model.selection_matrix[i_][j].is_selected = any_false # suit selected elif j == 0: # check if any of this row are not selected any_false = False for j_ in range(1, RANKS + 1): if not self.model.selection_matrix[i][ j_].is_selected and self.model.card_available( self.model.selection_matrix[i][j_].card): any_false = True break # set all to true if some were not, otherwise all to false for j_ in range(1, RANKS + 1): if self.model.card_available( self.model.selection_matrix[i][j_].card): self.model.selection_matrix[i][j_].is_selected = any_false
#Programa princial #importacao de classes from view import View from control import Control from model import Model from arquivo import Arquivo #Instanciar o Model m = Model() #Instanciar a View v = View() #Instanciar o arquivo a = Arquivo() #Instanciar a Control c = Control(v, m, a) #Guardando a control na model m.set_control(c) #Guardando a control na view v.set_control(c) #Exibir o menu c.exibir_menu() #print(m.carregar_arquivo())
def view(self, data, place_in_chain, possible_inputs): def create_inputs_summary(): summary = [] for input in self.input_to_select: choices = self.input_to_select[input].values.choices choice_texts = [ p[1] for p in possible_inputs if p[0] in choices ] #summary.append('%s: %s' % (input, choice_text)) summary.append('|'.join(choice_texts)) ret = ', '.join(summary) if ret: return 'Inputs: %s ' % ret else: if self.input_to_select: return 'Inputs' else: return '' #input_summary = View(self, '%sOutputs: %s' % ( # create_inputs_summary(), # ', '.join(self.get_outputs()))) input_summary = View(self, create_inputs_summary()) input_content_views = [] for k, v in self.input_to_select.items(): input_content_views.append( v.view(k, self.widgets.input_apply, possible_inputs, multiple=True)) input_content_views.append(self.widgets.input_apply.view()) input_content = view.stack_lines(*input_content_views) try: sub_widget_view = self.widgets.sub_widget.view( **self.create_input_map(data)) except Exception as e: logging.exception('Exception in view') sub_widget_view = View(self, str(e)) global CHAINABLE_WIDGETS widget_control_view = stack_left( self.widgets.new_widget_select.view('', self.widgets.apply_new_widget, zip(*CHAINABLE_WIDGETS)[0], False), self.widgets.apply_new_widget.view('Add before'), self.widgets.delete_button.view('Delete')) widget_control_view.main_html = '<div style="position:absolute; top:0; right:0;">%s</div>' % widget_control_view.main_html sub_view = view.stack_lines( widget_control_view, self.widgets.input_panel.view(input_summary, input_content), view.vertical_seperator(), sub_widget_view) #sub_view = self.widgets.sub_widget.view(data) #title_view = view.left_right( # View(self, self.title(place_in_chain)), # self.widgets.delete_button.view('Delete')) title_view = View(self, self.title(place_in_chain)) return self.widgets.expander.view(title_view, sub_view)