Exemple #1
0
def run():

    _width = 600
    _height = 400
    _tile_arr = []
    _button_list = []
    _font = pygame.font.SysFont(None, 25)
    _current_dir = None
    _file_box_list = []
    _c = 0
    _default_x = 20
    _default_y = 20
    _mod = 20

    window = Screen.new(_width, _height, orange)
    mouse_cursor = cursor.Cursor(window)
    mouse_pointer = pointer.Pointer(_width / 2, _height / 2, window, black)

    dir_box = Display_Box(window, _current_dir, _default_x, _default_y, 20,
                          250, _font, 0)

    _button_list.append(dir_box)

    _current_dir = get_current_dir()
    _current_files = format_list(_current_dir)[0]

    for i in _current_files:

        try:
            file_box = Display_Box(window, _current_files[_c], _default_x,
                                   (_default_y + _mod), 20, 250, _font, 0)
            _button_list.append(file_box)
            _mod += 20
            _c += 1
        except:
            _c = 0
            _mod = 20
            break

    _obj_list = [mouse_pointer, mouse_cursor]

    handler.set_screen(window, _width, _height)

    update_obj_lists(_obj_list, _button_list, _tile_arr)

    while 1:

        ##########

        ##########

        update_obj_lists(_obj_list, _button_list, _tile_arr)

        handler.update(0)
        handler.draw()

        pygame.display.update()
        clock.tick(FPS)
Exemple #2
0
 def __init__(self, text, x, y, console, w=30, h=30):
     self.text = text
     self.width, self.height = w, h
     self.x, self.y = x, y
     self.lines = []
     self.console = console
     self.cursor = cursor.Cursor(libtcod.CHAR_BLOCK3, 0, 0, libtcod.white, self.console)
     self.spacing = 2
     
     self.word_manager = word_manager.InteractiveWordManager()
Exemple #3
0
        def on_button1_clicked(self, widget):
            _, winx, winy = widget.get_window().get_origin()

            offx, offy = widget.translate_coordinates(widget.get_toplevel(), 0,
                                                      -self.sizey)

            xpos = winx + offx + (self.sizex // 2)
            ypos = winy + offy + (self.sizey // 2)

            with cursor.Display() as display:
                cursor.Cursor(display).reset_mouse(xpos, ypos)
 def __init__(self):
     self.graphics = graphics.GameGraphics()
     self.mouse = cursor.Cursor()
     self.game_in_process = True
     self.menu_objects = []
     self.game_objects = []
     self.selected_units = []
     self.squad = []
     self.army = []
     self.resources = config.starting_resources
     self.graphics.create_menu(self.menu_objects, self.resources)
Exemple #5
0
 def __enter__(self):
     """Refreshes the connection and returns a cursor, starting a transaction."""
     if self.lock.acquire(False):  # Don't block. fail when it's in use.
         self.counter_transactions += 1
         del self.queries[:]
         self.ping(True)
         self.ping(self.autocommit)
         self.StartTransactionTimer()
         return cursor.Cursor(self)
     raise self.OperationalError(
         'A transaction is already open for this connection.')
Exemple #6
0
    def __init__(self):
        """ Automatically initialises the terminal and cursor. """

        colorama.init(wrap=True)  # Wraps stdout to enable most ansi support
        self.stdout = sys.stdout
        self.cursor = cursor.Cursor(self)
        self.cursor.pos(self.get_width() - 1, self.get_height() - 1)

        self.width = self.get_width()
        self.height = self.get_height()

        self.clear_screen()
Exemple #7
0
def get_list_timeline():
    try:
        # Get all the List created/owned by the authenticated user
        # for item in api.lists_all():
        # 	print item.name + " : slug = " + item.slug + " : list_id = " + str(item.id)
        # Get the members of the list 76209711 ( name = events ) Ravs's list of Conf
        for page in cursor.Cursor(api.list_members, list_id=76209711).pages():
            for member in page:
                print member.name
                list_member.write(member.name.encode('utf-8') + "\n")
        # Get the status of the list 76209711 ( name = events ) Ravs's list of Conf
        for page in cursor.Cursor(api.list_timeline, list_id=76209711).pages():
            for status in page:
                print status.text
                # Since tweets itself have new line, qoute each tweet.
                # This might be helpful in cleaning the training set.
                conf_training_set.write("\"" + status.text.encode('utf-8') +
                                        "\"" + "\n")
            if remaining_rate_limit() == 0:
                standby()
    except TweepError as e:
        print e.args
Exemple #8
0
	def __init__(self):
		self.log = logging.getLogger('.'.join((config.MAIN_LOG_NAME, 'Main')))
		#All files will be stored here as hashObjects, indexed by their filesize. The format follows:
		# {10000: [so1, so2], 1234: [so3], 4567:[so4, so5, so6]}
		self.scannedFiles = {}
		self.hashedFiles = {}
		#Basically the same as hashedFiles, but we only add duplicate enteries.
		self.duplicateFilesIndex = {}
		
		
		#cleanup old tables.
		# try:
		if config.DB_NAME != ":memory:" and os.path.exists(config.DB_NAME):
			os.remove(config.DB_NAME)
		# except Exception:
		# 	pass
			
		#Setup the db.	
		tables = [hashObject.HashObject, scanParent.ScanParent]
		for each in tables:
			cursor.Cursor.registerTable(each)
		self.cursor = cursor.Cursor()
		self.cursor.setupTables()
		
		#A simple time check for when we last committed to the database
		#Useful for determining if a caller *really* wants the same data
		#in some methods
		self.lastDBFetch = 0
		
		self.UPDATE_INTERVAL = config.UPDATE_INTERVAL
		self.updateCallbackFunction = None
		
		#Both these queues handle jobs. The file Queue is for the file manager, meant for scanning
		#files. The file manager then hands off more work to the hash queue, if it needs to.
		self.fileQueue = Queue.Queue()
		self.hashQueue = Queue.Queue()
		
		#Setup the file manager
		self.fileManager = fileManager.FileManager(self.fileQueue, self.hashQueue, self.scannedFiles, self.updateProgress)
		self.fileManager.setDaemon(True)
		self.fileManager.start()
			
		#Setup the hasher			
		self.hasher = hasher.Hasher(self.hashQueue, self.hashedFiles, self.duplicateFilesIndex, self.updateProgress)
		self.hasher.setDaemon(True)
		self.hasher.start()
		
		#Where we store update information and such about the hasher and fileManager
		self.stats = {}
Exemple #9
0
    def cursor_setup(self):
        #Cursor is used for selcting/moving/placing objects by holding a
        #function and arguments to call on clicks (or drags).
        self.cursor = cursor.Cursor(self)

        #Default settings for cursor (see on_key_press to toggle call_default).
        self.cursor_default_type = "Select"
        self.cursor_default_function = self.select_obj
        self.cursor_deflaut_function_args = [self.cursor.get_pos, True]
        self.cursor_default_visibility = True
        self.cursor.set_default(self.cursor_default_function,
                                self.cursor_deflaut_function_args,
                                self.cursor_default_type)

        self.cursor_selection_visibility = 112  #used in select_obj
Exemple #10
0
    def __init__(self, opciones):
        """Inicializa el menu de opciones"""
        playMenu()
        # musica_inicial = pygame.mixer.music.load("melodias/melodia1.mp3")#cargamos la melodia inicial
        # pygame.mixer.music.play(-1)#La ponemos a reproducir infinitamente
        self.opciones = []#Una arreglo donde se guardaran las opciones cada opciones una tupla ("Nombre_opcion", funcion_asociada)
        fuente = pygame.font.SysFont( "Algerian" , 20, italic = True, bold = True)#Fuente para la tipografia del menu
        x = 20# coord x del menu 
        y = 420# coord y del menu
        paridad = 1 
        self.cursor = cursor.Cursor(x , y, 30)#Creamos un objeto cursor, dandole su coordenada x e y, ademas de un dy, que sera la separacion del cursor de las opciones
        #self.escena_uno = scene_one.SceneOne()
        for titulo, funcion in opciones:
            self.opcion = opcion.Opcion(fuente, titulo, x, y, paridad, funcion)
            self.opciones.append(self.opcion)
            y += 30
            if paridad == 1:
                paridad = -1
            else:
                paridad = 1

        self.seleccionado = 0
        self.total = len(self.opciones)
        self.mantiene_pulsado = False
Exemple #11
0
    def run(self):
        self.cursor = cursor.Cursor()
        while True:
            try:
                #grabs host from fileQueue
                self.current = self.hashQueue.get(True, self.UPDATE_INTERVAL)
                self.status = 'Running'
                self.__hash(self.current)
                self.hashQueue.task_done()
                if self.hashQueue.empty():
                    self.status = "Done"
                    self.current = None
                    self.log.info("Hasher finished current queue.")
                    self.__update(True)
                else:
                    self.__update()
            except Queue.Empty:
                pass
            except Exception as e:
                self.log.exception(e)

            if self.__shouldShutdown():
                self.log.info("Shutting down...")
                break
Exemple #12
0
    def __init__(self, config):

        super(Window, self).__init__()
        self.currentPath = ''
        self._mode = "pan"
        self.photoList = []
        self.pathList = []
        self.tabClosed = False
        self.config = config
        self.image_worker = Image()

        #Defaults
        self.windowDefault = dict(self.config['windowDefault'].items())
        self.propertiesDefault = dict(self.config['propertiesDefault'].items())
        self.canvasDefault = dict(self.config['canvasDefault'].items())
        self.chartDefault = dict(self.config['chartDefault'].items())
        self.HS = int(self.windowDefault['hs'])
        self.VS = int(self.windowDefault['vs'])
        self.energy = int(self.windowDefault['energy'])
        self.azimuth = int(self.windowDefault['azimuth'])
        self.scaleBarLength = int(self.windowDefault['scalebarlength'])
        self.chiRange = int(self.windowDefault['chirange'])
        self.width = float(self.windowDefault['width'])
        self.widthSliderScale = int(self.windowDefault['widthsliderscale'])
        self.radius = int(self.windowDefault['radius'])
        self.radiusMaximum = int(self.windowDefault['radiusmaximum'])
        self.radiusSliderScale = int(self.windowDefault['radiussliderscale'])
        self.tiltAngle = int(self.windowDefault['tiltangle'])
        self.tiltAngleSliderScale = int(
            self.windowDefault['tiltanglesliderscale'])

        #Menu bar
        self.menu = QtWidgets.QMenuBar()
        self.menuFile = self.menu.addMenu("File")
        self.menuPreference = self.menu.addMenu("Preference")
        self.menu2DMap = self.menu.addMenu("Mapping")
        self.menuFit = self.menu.addMenu("Fit")
        self.menuSimulation = self.menu.addMenu("Simulation")
        self.menuRun = self.menu.addMenu("Run")
        self.menuHelp = self.menu.addMenu("Help")
        self.setMenuBar(self.menu)

        #File Menu
        self.openFile = self.menuFile.addAction("Open", self.manu_actions_open)
        self.export = self.menuFile.addMenu("Export")
        self.saveCanvasAsImage = self.export.addAction(
            "RHEED pattern as Image", self.menu_actions_save_as_image)
        self.saveProfileAsText = self.export.addAction(
            "Line profile as text", self.menu_actions_save_as_text)
        self.saveProfileAsImage = self.export.addAction(
            "Line profile as image", self.menu_actions_save_profile_as_image)
        self.saveProfileAsSVG = self.export.addAction(
            "Line profile as SVG", self.menu_actions_save_as_svg)

        #Preference Menu
        self.defaultSettings = self.menuPreference.addAction("Default Settings",\
                                    self.menu_actions_preferences_default_settings)

        #2D Map Menu
        self.Two_Dimensional_Mapping = self.menu2DMap.addAction("Configuration", \
                                            self.menu_actions_two_dimensional_mapping)

        self.Three_Dimensional_Graph = self.menu2DMap.addAction("3D Surface", \
                                        self.menu_actions_three_dimensional_graph)

        #Fit Menu
        self.Fit_Broadening = self.menuFit.addAction(
            "Broadening", self.menu_actions_broadening)
        self.Fit_ManualFit = self.menuFit.addAction(
            "Manual Fit", self.menu_actions_show_manual_fit)
        self.Fit_Report = self.menuFit.addAction(
            "Generate Report", self.menu_actions_generate_report)
        self.gmm = self.menuFit.addAction("Gaussian Mixture Modeling",
                                          self.menu_actions_gmm)

        #Simulation Menu
        self.Statistical_Factor = self.menuSimulation.addAction(
            "Statistical Factor", self.menu_actions_statistical_factor)
        self.Diffraction_pattern = self.menuSimulation.addAction(
            "Diffraction Pattern", self.menu_actions_diffraction_pattern)
        self.Kikuchi_pattern = self.menuSimulation.addAction(
            "Kikuchi Pattern", self.menu_actions_kikuchi_pattern)

        #Run Menu
        self.run_scenario = self.menuRun.addAction(
            "Run Scenario", self.menu_action_run_scenario)

        #Help Menu
        self.about = self.menuHelp.addAction("About", self.menu_actions_about)

        #Center Widget
        self.image_crop = [
            1200 + self.VS, 2650 + self.VS, 500 + self.HS, 3100 + self.HS
        ]

        self.mainSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
        self.mainTab = QtWidgets.QTabWidget()
        self.mainTab.setContentsMargins(0, 0, 0, 0)
        self.mainTab.setTabsClosable(True)
        self.controlPanelFrame = QtWidgets.QWidget(self)
        self.controlPanelGrid = QtWidgets.QGridLayout(self.controlPanelFrame)
        self.controlPanelGrid.setContentsMargins(0, 0, 0, 0)
        self.controlPanelSplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
        supportedFormats =    {'*.3fr','*.ari','*.arw','*.srf', '*.sr2','*.bay','*.cri','*.crw', '*.cr2',     '*.cr3', '*.cap','*.iiq','*.eip',\
                               '*.dcs','*.dcr','*.drf','*.k25', '*.kdc','*.dng','*.erf','*.fff', '*.mef',     '*.mdc', '*.mos','*.mrw','*.nef',\
                               '*.nrw','*.orf','*.pef','*.ptx', '*.pxn','*.r3d','*.raf','*.raw', '*.rw2',     '*.rwl', '*.rwz','*.srw','*.x3f',\
                               '*.3FR','*.ARI','*.ARW','*.SRF', '*.SR2','*.BAY','*.CRI','*.CRW', '*.CR2',     '*.CR3', '*.CAP','*.IIQ','*.EIP',\
                               '*.DCS','*.DCR','*.DRF','*.K25', '*.KDC','*.DNG','*.ERF','*.FFF', '*.MEF',     '*.MDC', '*.MOS','*.MRW','*.NEF',\
                               '*.NRW','*.ORF','*.PEF','*.PTX', '*.PXN','*.R3D','*.RAF','*.RAW', '*.RW2',     '*.RWL', '*.RWZ','*.SRW','*.X3F',\
                               '*.bmp','*.eps','*.gif','*.icns','*.ico','*.im', '*.jpg','*.jpeg','*.jpeg2000','*.msp', '*.pcx','*.png','*.ppm',\
                               '*.sgi','*.tiff','*.tif','*.xbm','*.BMP','*.EPS','*.GIF','*.ICNS','*.ICO',     '*.IM',  '*.JPG','*.JPEG','*.JPEG2000',\
                               '*.MSP','*.PCX','*.PNG','*.PPM','*.SGI','*.TIFF','*.TIF','*.XBM'}

        self.browser_widget = browser.Browser(self, supportedFormats)
        self.controlPanelBottomWidget = QtWidgets.QWidget()
        self.controlPanelBottomGrid = QtWidgets.QGridLayout(
            self.controlPanelBottomWidget)
        self.controlPanelBottomGrid.setContentsMargins(0, 0, 2, 0)
        self.properties_widget = properties.Properties(self, self.config)
        self.cursorInfo = cursor.Cursor(self)
        self.profile = profile_chart.ProfileChart(self.config)
        self.controlPanelBottomGrid.addWidget(self.properties_widget, 0, 0)
        self.controlPanelBottomGrid.addWidget(self.cursorInfo, 1, 0)
        self.controlPanelBottomGrid.addWidget(self.profile, 2, 0)
        self.controlPanelSplitter.addWidget(self.browser_widget)
        self.controlPanelSplitter.addWidget(self.controlPanelBottomWidget)

        self.controlPanelSplitter.setSizes([100, 500])
        self.controlPanelSplitter.setStretchFactor(0, 1)
        self.controlPanelSplitter.setStretchFactor(1, 1)
        self.controlPanelSplitter.setCollapsible(0, False)
        self.controlPanelSplitter.setCollapsible(1, False)
        self.controlPanelGrid.addWidget(self.controlPanelSplitter, 0, 0)

        self.mainSplitter.addWidget(self.mainTab)
        self.mainSplitter.addWidget(self.controlPanelFrame)
        self.mainSplitter.setSizes([800, 400])
        self.mainSplitter.setStretchFactor(0, 1)
        self.mainSplitter.setStretchFactor(1, 1)
        self.mainSplitter.setCollapsible(0, False)
        self.mainSplitter.setCollapsible(1, False)

        #Tool bar
        self.toolBar = QtWidgets.QToolBar(self)
        self.toolBar.setFloatable(False)
        self.toolBar.setMovable(False)
        self.open = QtWidgets.QAction(QtGui.QIcon("./icons/open.svg"), "open",
                                      self)
        self.saveAs = QtWidgets.QAction(QtGui.QIcon("./icons/save as.svg"),
                                        "save as", self)
        self.zoomIn = QtWidgets.QAction(QtGui.QIcon("./icons/zoom in.svg"),
                                        "zoom in (Ctrl + Plus)", self)
        self.zoomIn.setShortcut(QtGui.QKeySequence.ZoomIn)
        self.zoomOut = QtWidgets.QAction(QtGui.QIcon("./icons/zoom out.svg"),
                                         "zoom out (Ctrl + Minus)", self)
        self.zoomOut.setShortcut(QtGui.QKeySequence.ZoomOut)
        self.fitCanvas = QtWidgets.QAction(QtGui.QIcon("./icons/fit.svg"),
                                           "fit in view", self)
        self.line = QtWidgets.QAction(QtGui.QIcon("./icons/line.svg"), "line",
                                      self)
        self.line.setCheckable(True)
        self.rectangle = QtWidgets.QAction(
            QtGui.QIcon("./icons/rectangle.svg"), "rectangle", self)
        self.rectangle.setCheckable(True)
        self.arc = QtWidgets.QAction(QtGui.QIcon("./icons/arc.svg"), "arc",
                                     self)
        self.arc.setCheckable(True)
        self.pan = QtWidgets.QAction(QtGui.QIcon("./icons/move.svg"), "pan",
                                     self)
        self.pan.setCheckable(True)
        self.buttonModeGroup = QtWidgets.QActionGroup(self.toolBar)
        self.buttonModeGroup.addAction(self.line)
        self.buttonModeGroup.addAction(self.rectangle)
        self.buttonModeGroup.addAction(self.arc)
        self.buttonModeGroup.addAction(self.pan)
        self.toolBar.addAction(self.open)
        self.toolBar.addAction(self.saveAs)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.line)
        self.toolBar.addAction(self.rectangle)
        self.toolBar.addAction(self.arc)
        self.toolBar.addAction(self.pan)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.zoomIn)
        self.toolBar.addAction(self.zoomOut)
        self.toolBar.addAction(self.fitCanvas)
        self.addToolBar(self.toolBar)

        #Status bar
        self.statusBar = QtWidgets.QStatusBar(self)
        self.messageLoadingImage = QtWidgets.QLabel("Processing ... ", self)
        self.messageLoadingImage.setVisible(False)
        self.progressBar = QtWidgets.QProgressBar(self)
        self.progressBar.setMaximumHeight(12)
        self.progressBar.setVisible(False)
        self.progressBar.setOrientation(QtCore.Qt.Horizontal)
        self.progressBarSizePolicy = self.progressBar.sizePolicy()
        self.progressBarSizePolicy.setRetainSizeWhenHidden(True)
        self.progressBarSizePolicy.setHorizontalPolicy(
            QtWidgets.QSizePolicy.Expanding)
        self.progressBar.setSizePolicy(self.progressBarSizePolicy)
        self.editPixInfo = QtWidgets.QLabel(self)
        self.editPixInfo.setAlignment(QtCore.Qt.AlignRight)
        self.editPixInfo.setMinimumWidth(150)
        self.statusBar.addWidget(self.messageLoadingImage)
        self.statusBar.insertPermanentWidget(1, self.progressBar)
        self.statusBar.addPermanentWidget(self.editPixInfo)
        self.setStatusBar(self.statusBar)

        #Main Window Settings
        self.setCentralWidget(self.mainSplitter)
        self.mainSplitter.setContentsMargins(2, 2, 0, 0)
        self.setWindowTitle("PyRHEED")

        #Main Tab Connections
        self.mainTab.currentChanged.connect(self.switch_tab)
        self.mainTab.tabCloseRequested.connect(self.close_tab)

        #Toolbar Connections
        self.open.triggered.connect(
            lambda path: self.open_image(path=self.get_img_path()))
        self.line.triggered.connect(
            lambda cursormode: self.toggle_canvas_mode(cursormode="line"))
        self.rectangle.triggered.connect(
            lambda cursormode: self.toggle_canvas_mode(cursormode="rectangle"))
        self.arc.triggered.connect(
            lambda cursormode: self.toggle_canvas_mode(cursormode="arc"))
        self.pan.triggered.connect(
            lambda cursormode: self.toggle_canvas_mode(cursormode="pan"))

        #Progress Bar Connections
        self.PROGRESS_ADVANCE.connect(self.progress)
        self.PROGRESS_END.connect(self.progress_reset)

        #Browser Connections
        self.FILE_OPENED.connect(self.browser_widget.tree_update)
        self.IMG_CREATED.connect(self.profile.set_img)
        self.browser_widget.FILE_DOUBLE_CLICKED.connect(self.open_image)

        #Parameters Page Connections
        self.properties_widget.sensitivityEdit.textChanged.connect(
            self.check_sensitivity)
        self.properties_widget.energyEdit.textChanged.connect(
            self.change_energy)
        self.properties_widget.azimuthEdit.textChanged.connect(
            self.change_azimuth)
        self.properties_widget.scaleBarEdit.textChanged.connect(
            self.change_scale_bar)
        self.properties_widget.labelButton.clicked.connect(self.label_image)
        self.properties_widget.calibrateButton.clicked.connect(
            self.calibrate_image)

        #Image Adjust Page Connections
        self.properties_widget.brightnessSlider.valueChanged.connect(
            self.change_brightness)
        self.properties_widget.blackLevelSlider.valueChanged.connect(
            self.change_black_level)
        self.properties_widget.autoWBCheckBox.stateChanged.connect(
            self.change_auto_WB)
        self.properties_widget.applyButton2.clicked.connect(
            self.apply_image_adjusts)
        self.properties_widget.resetButton2.clicked.connect(
            self.reset_image_adjusts)

        #Profile Options Page Connections
        self.properties_widget.integralHalfWidthSlider.valueChanged.connect(
            self.change_width)
        self.properties_widget.chiRangeSlider.valueChanged.connect(
            self.change_chi_range)
        self.properties_widget.radiusSlider.valueChanged.connect(
            self.change_radius)
        self.properties_widget.tiltAngleSlider.valueChanged.connect(
            self.change_tilt_angle)
        self.properties_widget.applyButton3.clicked.connect(
            self.apply_profile_options)
        self.properties_widget.resetButton3.clicked.connect(
            self.reset_profile_options)

        #Appearance Page Connections
        self.profile.set_fonts(
            self.properties_widget.fontList.currentFont().family(),
            self.properties_widget.chartFontSizeSlider.value())
        self.properties_widget.CHART_FONTS_CHANGED.connect(
            self.profile.adjust_fonts)

        #Cursor Information Connections
        self.cursorInfo.choosedXYEdit.textChanged.connect(self.edit_choosed_XY)
        self.cursorInfo.startXYEdit.textChanged.connect(self.edit_start_XY)
        self.cursorInfo.endXYEdit.textChanged.connect(self.edit_end_XY)
        self.cursorInfo.widthEdit.textEdited.connect(self.edit_width)

        #Profile Canvas Connections
        self.SCALE_FACTOR_CHANGED.connect(self.profile.set_scale_factor)
        self.profile.CHART_MOUSE_MOVEMENT.connect(self.photo_mouse_movement)

        #Refresh Connections
        self.PROPERTIES_REFRESH.connect(self.properties_widget.refresh)
        self.CHART_REFRESH.connect(self.profile.refresh)

        self.get_scale_factor()
        self.WINDOW_INITIALIZED.emit()
Exemple #13
0
    def __init__(self):
        self.running = True # set the game loop good to go
        config = ConfigParser.ConfigParser()
        config.readfp(open('main.cfg'))
        self.fsw = config.getint('main', 'fullscreenwidth')
        self.fsh = config.getint('main', 'fullscreenheight')
        self.ww = config.getint('main', 'windowedwidth')
        self.wh = config.getint('main', 'windowedheight')
        self.tw = config.getint('main', 'tilewidth')
        self.mapw = config.getint('main', 'mapwidth')
        self.maph = config.getint('main', 'mapheight')
        self.fullscreen = config.getboolean('main', 'fullscreen')
        self.paused = False
        self.white = (255, 255, 255) # the colour :)

        #fullscreen = False
        self.FPS = 60
        pygame.init()
        #setup the default screen size
        if self.fullscreen == True:
            self.screen = pygame.display.set_mode((self.fsw, self.fsh), FULLSCREEN)
        else:
            self.screen = pygame.display.set_mode((self.ww, self.wh), RESIZABLE)

        pygame.display.set_caption('pyDF')
        #Intro's on by default, will need to add a config file entry for this.
        self.intro = True
        self.mainclock = pygame.time.Clock()
        # various rendering offsets
        self.vpRenderOffset = (self.tw, self.tw)
        self.statsOffset = (math.floor(int(0.8 * self.ww) + 2 * self.tw), self.tw)
        self.menuOffset = (math.floor(int(0.8 * self.ww) + 2 * self.tw), 4 * self.tw)
        self.menuOffset2 = (math.floor(int(0.8 * self.ww) + 2 * self.tw), 5 * self.tw)
        self.menuOffset3 = (math.floor(int(0.8 * self.ww) + 2 * self.tw), 6 * self.tw) # testing for ezmenu
        self.idleOffset = (math.floor(int(0.8 * self.ww) + 2 * self.tw), 0) # testing for ezmenu
        self.pauseDisplayOffset = (self.tw, 0)
        self.digTypeOffset = (math.floor(int(0.8 * self.ww) + 2 * self.tw), 4 * self.tw)
        self.showmenu = False
        self.currentmenu = None
        self.vpCoordinate = [0, 0] # Starting coordinates for the view port
        self.vpDimensions = (math.floor(int(0.8 * self.ww) / self.tw) * self.tw, math.floor(int(0.9 * self.wh) / self.tw) * self.tw) # resolution of the view port
        self.vpStep = self.tw # move 1 tile over.
        self.vpShiftStep = self.tw * 10 # move 10 tile over.
        self.minHorizScrollBound = 0
        self.minVertScrollBound = 0
        self.maxHorizScrollBound = self.mapw * self.tw
        self.maxVertScrollBound = self.maph * self.tw
        self.numXTiles = int(math.ceil(int(self.vpDimensions[0]) / self.tw)) # the number of tiles to be shown at one time for X
        self.numYTiles = int(math.ceil(int(self.vpDimensions[1]) / self.tw)) # the number of tiles to be shown at one time for y
        self.startXTile = math.floor(int(self.vpCoordinate[0]) / self.tw)
        self.startYTile = math.floor(int(self.vpCoordinate[1]) / self.tw)

        if not pygame.font.get_init():
            pygame.font.init()
        self.arialFnt = pygame.font.SysFont('Arial', 16)
        self.m = gamemap.GameMap(self.tw, self.mapw, self.maph, self.startXTile, self.startYTile, self.numXTiles, self.numYTiles)
        self.m.initMap()
        self.m.initEMap()
        self.editmode = [None, None]
        self.selectmode = False
        self.testmode = False
        self.roomtiles = []
        self.selectcursor = cursor.Cursor(self.tw, self.m.numXTiles / 2 * self.tw, self.m.numYTiles / 2 * self.tw)
        self.queued_jobs = []
        self.mobs = []
        self.mapvalue = None
        self.tilecontent = None
        #self.currentZlevel = self.m.currentZlevel
        openspot = self.m.find_open_spot()
        self.currentZlevel = openspot[2]
        self.mobs.append(mob.Mob(openspot, self.tw))
        self.addTileMob(openspot[0], openspot[1], openspot[2], self.mobs[0])
        self.mobs.append(mob.Mob(openspot, self.tw))
        self.addTileMob(openspot[0], openspot[1], openspot[2], self.mobs[0])
        self.mobs.append(mob.Mob(openspot, self.tw))
        self.addTileMob(openspot[0], openspot[1], openspot[2], self.mobs[0])
        self.buttons = {}
        #self.keys = set()
        self.motion = None
Exemple #14
0
def search(trie,
           query_term,
           trie_seqs,
           index_seqs,
           search_prefix,
           term_is,
           dynamic=True):
    gdocs, gtids, gpos, gchpos = index_seqs
    # TODO rename gtids. Is in both trie and index seqs

    term_ids, group_map, group_doc_lens, group_term_lens, group_term_ids = trie_seqs
    query_term = query_term.strip()

    tid_weight_map = {}
    groupped_groups = {}
    result = []
    for word, d, node in trie.search_dynamic(query_term,
                                             search_prefix=search_prefix,
                                             dynamic=dynamic):
        d += abs(len(query_term) - len(word)) / (1 + len(query_term) * 3)
        term_id = term_ids[node]
        group_id = group_map[term_id]

        if group_id not in groupped_groups:
            groupped_groups[group_id] = GroupList(group_id,
                                                  group_doc_lens[group_id],
                                                  group_doc_lens[group_id + 1])
        groupped_groups[group_id].term_ids.append(term_id)
        result.append([word, d, term_id, group_id])
        tid_weight_map[term_id] = d

    # TODO ENABLE TO PRINT FOUND TERMS
    # sorted by d
    #for x in sorted(result, key=lambda r: -r[1]):
    #    print(*x)
    #print()

    terms_sum = 0

    cursors = []
    for group_id, x in groupped_groups.items():
        group_terms = group_term_lens[group_id + 1] - group_term_lens[group_id]
        terms_sum += len(x.term_ids)

        docs = gdocs.subseq(x.start, x.end)
        tids = gtids.subseq(x.start, x.end)
        pos = gpos.subseq(x.start, x.end)
        chpos = gchpos.subseq(x.start, x.end)

        # print(set(x - min_group_tid for x in tid_filter))

        #print("FILTER", tid_filter)
        #print("MINGROUPTID", min_group_tid)
        size = x.end - x.start
        fill_factor = len(x.term_ids) / group_terms

        min_group_tid = group_term_ids[group_term_lens[group_id]]
        tid_filter = set(x.term_ids)

        cur = cursor.Cursor(docs, tids, pos, chpos, size)
        if fill_factor == 1.0:
            cur = cursor.FullCursor(cur, min_group_tid, term_is)
        else:
            cur = cursor.FilteredCursor(cur, min_group_tid, tid_filter,
                                        fill_factor, term_is)

        # print("LENSET", len(set(x.term_ids)))
        cursors += [cur]

        print("{},\t docs: {}\t({}-{}),\t terms: {}/{}".format(
            group_id, size, x.start, x.end, len(x.term_ids), group_terms))

    final_cursor = None
    if len(cursors) > 1:
        final_cursor = cursor.CursorUnion1(cursors)
        print("UNION CURSOR", final_cursor)
    elif len(cursors) == 1:
        final_cursor = cursors[0]
    else:
        final_cursor = None

    print("--- Groups", len(groupped_groups), terms_sum)
    return final_cursor, tid_weight_map
Exemple #15
0
 def __enter__(self):
     """Starts a transaction."""
     self.transaction_lock.acquire()
     return cursor.Cursor(self)
Exemple #16
0
 def __enter__(self):
     """Starts a transaction."""
     self.logger.debug('Beginning new transaction.')
     return cursor.Cursor(self)
Exemple #17
0
 def parser_basic_info(self, parse):
     '''
     @brief Método que parsea los componentes básicos del menú
     
     @param parse Archivo xml parsea com xml.dom.minidom
     '''
     parent = parse.firstChild
     
     #Obtenemos la imagen de fondo
     image_code = str(parent.getAttribute('background'))
     self.background = resource.get_image(image_code)
     
     #Obtenemos el cursor del menú
     #cursor_xml = str(parent.getAttribute('cursor'))
     #self.cursor = cursor.Cursor(data.get_path_xml(cursor_xml))
     self.cursor = cursor.Cursor()
     
     self.music_file = None
     if parent.hasAttribute('music'):
         self.music_file = str(parent.getAttribute('music'))
     
     #Obtenemos el titulo del menú
     for element in parse.getElementsByTagName('title'):
         #Obtenemos tamaño y fuente
         font_code = str(element.getAttribute('font'))
         font_size = int(element.getAttribute('size'))
         self.font = resource.get_font(font_code, font_size)
         text = element.getAttribute('text')
         
         #Colores
         r = int(element.getAttribute('r'))
         g = int(element.getAttribute('g'))
         b = int(element.getAttribute('b'))
         color = (r, g, b)
         
         #Renderizamos
         self.title = self.font.render(text, True, color)
         
         #Obtenemos la posición
         self.title_rect = self.title.get_rect()
         self.title_rect.x = int(element.getAttribute('x'))
         self.title_rect.y = int(element.getAttribute('y'))
     
     #Obtenemos todas las imagenes que aparecen
     for element in parse.getElementsByTagName('image'):
         
         #Obtenemos la imagen
         image_code = str(element.getAttribute('image_code'))
         image = resource.get_image(image_code)
         
         #Si la imagen tiene el atributo scale
         if element.hasAttribute('scale'):
             #Escalamos la imagen
             scale = float(element.getAttribute('scale'))
             if scale != 1:
                 temporal = image.copy()
                 image = pygame.transform.rotozoom(temporal, 0, scale)
         
         #Obtenemos la posición de la imagen
         rect = image.get_rect()
         rect.x = int(element.getAttribute('x'))
         rect.y = int(element.getAttribute('y'))
         
         #La incluimos en la lista de imagenes
         self.images.append((image_code, image, rect))
     
     #Obtenemos los distintos botones del menú
     for element in parse.getElementsByTagName('option'):
         
         #Ruta del archivo xml con la configuración
         xml_file = str(element.getAttribute('xml_file'))
         
         #Fuente y texto que apareceran en el boton
         font_code = str(element.getAttribute('font'))
         text = element.getAttribute('text')
         
         
         x = int(element.getAttribute('x'))
         y = int(element.getAttribute('y'))
         show_text = True
         
         #Miramos si se indica si se debe mostrar o no el texto en el botón
         if element.hasAttribute('show_text'):
             show_text = element.getAttribute('show_text')
             show_text = button.strTobool(show_text)
         
         type_button = 'normal'
         
         #Obtenemos el tipo de boton
         if element.hasAttribute('type'):
             type_button = str(element.getAttribute('type'))
                     
         #Según el tipo de boton obtendremos un boton u otro
         if type_button == 'normal':
             aux_button = button.Button(self, xml_file, text, x, y, 
                                 font_code, show_text)
                                 
         elif type_button == 'image_button':
             image_code = str(element.getAttribute('image'))
             image_x = int(element.getAttribute('image_x'))
             image_y = int(element.getAttribute('image_y'))
             aux_button = imagebutton.ImageButton(self, xml_file, text, x, 
                                                 y, font_code, image_code, 
                                                 image_x, image_y, 
                                                 show_text)
         
         #Lo añadimos a la lista de botones
         self.buttons.append(aux_button)