Exemple #1
0
    def __init__(self):
        """Constructor method that inherits methods from QWidgets"""
        super().__init__()

        self.root = QFileInfo(__file__).absolutePath()
        self.settings = Settings(self)
        ##self.settings = QSettings(self.root+"/settings.ini", QSettings.IniFormat)

        script_dir = os.path.dirname(os.path.abspath(__file__))
        self.plugins_directory_path = os.path.join(script_dir, 'plugins')

        self.database = Db()

        self.default_open_dir = self.root + "/" + DATABASES_FOLDER

        self.recent_file_acts = []  # действия для открытия последних файлов
        self.available_plugins = []  # доступные в папке plugins плагины
        self.disabled_plugins = []  # не загружаемые плагины
        self.loaded_plugins = []  # загруженные плагины
        self.load_plugin_acts = []  # действия для открытия доступных плагинов
        self.recentFiles = []  # последние загруженные файлы
        self.curFile = ''

        self.initUI()

        if Settings.load_last_opened_database and Settings.last_opened_database:
            self.open_file(Settings.last_opened_database)
Exemple #2
0
    def ncm_add_node(self, node_id, **kwargs):

        s = Settings()
        settings = s.get_all_settings()

        # check that device isn't already managed in Orion NCM
        self.ip_check = self.con.query('SELECT NodeID FROM Cirrus.Nodes WHERE AgentIP=@ip_address', ip_address=kwargs.get('ip_address'))
        self.hostname_check = self.con.query('SELECT NodeID FROM Cirrus.Nodes WHERE NodeCaption=@hostname', hostname=kwargs.get('hostname'))
        if len(self.ip_check['results']) > 0 or len(self.hostname_check['results']) > 0:
            
            # if this is greater than 0, then the device already exists in orion
            return

        else:

            self.con.invoke('Cirrus.Nodes', 'AddNodeToNCM', node_id)

            # now update the selected columns to ensure we can log into this device
            # first using rhe NodeID from Orion.NPM get the Guid
            self.ncm_node_id = self.con.query('SELECT NodeID FROM Cirrus.Nodes WHERE CoreNodeID=@node', node=node_id)['results'][0]['NodeID']  

            # fetch the NCM Node Object
            self.ncm_node_data = self.con.invoke('Cirrus.Nodes', 'GetNode', self.ncm_node_id)

            # verfify that the submitted connection_profile exists
            # if it doesn't set the profile to '-1'
            self.profiles = self.con.invoke('Cirrus.Nodes', 'GetAllConnectionProfiles')
            for self.pro in self.profiles:
                if self.pro['ID'] == kwargs.get('connection_profile'):
                    self.connection_profile_id = kwargs.get('connection_profile')
                else:
                    self.connection_profile_id = -1

            # modify the device properties but only if the submitted profile is valid
            if self.connection_profile_id != -1:
                self.ncm_node_data['Username'] = ''
                self.ncm_node_data['Password'] = ''
                self.ncm_node_data['ConnectionProfile'] = self.connection_profile_id 

             # Commit our changes  
            self.con.invoke('Cirrus.Nodes', 'UpdateNode', self.ncm_node_data)
Exemple #3
0
def run_game():
    #initialize game nad create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(screen, ai_settings)
    bullets = Group()
    aliens = Group()
    game_functions.create_fleet(ai_settings, screen, aliens)
    #start the main
    while True:
        game_functions.check_events(ai_settings, screen, ship, bullets)
        game_functions.update_bullets(bullets)
        game_functions.update_screen(screen, ai_settings, ship, bullets,
                                     aliens)
Exemple #4
0
def run(mode):
    # Initialize game and create a screen object
    pygame.init()
    ai_settings = Settings(mode)

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Space Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)

    # Make a ship
    ship = Ship(ai_settings, screen)

    # Make a group to store bullets in.
    bullets = Group()

    # Make a group of aliens.
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    game_over = False

    # Start the main loop for the game
    while not game_over:
        # Watch for the keyboard and mouse events
        gf.check_events(ai_settings, screen, stats, play_button, ship, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets,
                             mode)

        gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets,
                         play_button)
Exemple #5
0
class MainWindow(QMainWindow):
    """This is the class of the MainApp GUI system"""
    MaxRecentFiles = 5

    def __init__(self):
        """Constructor method that inherits methods from QWidgets"""
        super().__init__()

        self.root = QFileInfo(__file__).absolutePath()
        self.settings = Settings(self)
        ##self.settings = QSettings(self.root+"/settings.ini", QSettings.IniFormat)

        script_dir = os.path.dirname(os.path.abspath(__file__))
        self.plugins_directory_path = os.path.join(script_dir, 'plugins')

        self.database = Db()

        self.default_open_dir = self.root + "/" + DATABASES_FOLDER

        self.recent_file_acts = []  # действия для открытия последних файлов
        self.available_plugins = []  # доступные в папке plugins плагины
        self.disabled_plugins = []  # не загружаемые плагины
        self.loaded_plugins = []  # загруженные плагины
        self.load_plugin_acts = []  # действия для открытия доступных плагинов
        self.recentFiles = []  # последние загруженные файлы
        self.curFile = ''

        self.initUI()

        if Settings.load_last_opened_database and Settings.last_opened_database:
            self.open_file(Settings.last_opened_database)

        #self.open_test_file()

    def open_test_file(self):
        return
        #self.open_file(self.default_open_dir+"/4x20.ntr")
        self.open_file(self.default_open_dir + "/eurojackpot.sqlite")

    def closeEvent(self, event):
        """ случается при попытке закрыть виджет"""
        if self.maybe_exit():
            self.settings.write_settings()
            event.accept()
        else:
            event.ignore()

    def maybe_exit(self):
        return True

    def close_file(self):
        self.updateAct.setEnabled(False)
        self.historyForm.closeFile()
        self.statusBar().showMessage('')
        self.setWindowTitle(APPLICATION_NAME)

    def open_file(self, fileName=''):

        if not fileName:
            fileName, _ = QFileDialog.getOpenFileName(self, 'Open file',
                                                      self.default_open_dir,
                                                      FILES_TYPES)

        if fileName:
            self.historyForm.openFile(fileName)
            self.set_current_file(fileName)
            self.updateAct.setEnabled(self.historyForm.updateEnabled)

        self.statusBar().showMessage('File {}'.format(fileName))
        self.setWindowTitle('{} {}'.format(APPLICATION_NAME,
                                           self.stripped_name(self.curFile)))

    def open_recent_file(self):
        action = self.sender()
        if action:
            self.open_file(action.data())

    def load_plugin(self):
        action = self.sender()
        if action:
            module_name = action.data()
            plugin = import_plugin(self.database, self.plugins_directory_path,
                                   module_name)
            if plugin.plugin_name not in self.loaded_plugins:
                self.loaded_plugins.append(plugin.plugin_name)
            index = self.placeHolder.addForm(plugin)
            self.placeHolder.setCurrentIndex(index)

    def about(self):
        QMessageBox.about(
            self, "About Pythotron",
            "<p>Программа <b>Pythotron</b> для анализа лотерей. <a href='" +
            HELP_URL + "'>Подробнее на форуме Upad.ru</a></p> \
                <p><strong>Версия " + __version__ + " от " + __date__ +
            "</strong></p>")

    def show_options(self):
        dlg = OptionsForm(self)
        dlg.available_plugins = self.available_plugins
        dlg.disabled_plugins = self.disabled_plugins
        #dlg.loaded_plugins=self.loaded_plugins
        dlg.create_plugins_list()

        if dlg.exec_():
            self.disabled_plugins = dlg.disabled_plugins

    def play_lottery(self):
        openurl(LOTTERY_PLAY_URL)

    def update_lottery(self):
        try:
            if self.database.isClosed: return

            module = importlib.import_module(
                "." + self.database.lottery_config.DataImportPlugin.lower(),
                package='dataimport')
            form = module.DataImport(self, self.database)
            form.show_form()
            if form.added > 0:  #обновлено больше 0 тиражей нужно грид обновить
                self.database.update_history_view()

        except Exception as e:
            print('MainWindow:update_lottery error: ', e)
            dbg_except()
        pass

    def open_recent_file(self):
        action = self.sender()
        if action:
            self.open_file(action.data())

    def initUI(self):
        """ Создание GUI  """
        self.historyForm = HistoryForm(self.database)
        self.placeHolder = PlaceHolderForm()

        splitterV = QSplitter(Qt.Vertical)
        splitterV.setStyleSheet('background-color:beige')
        self.setCentralWidget(splitterV)

        splitterH = QSplitter(Qt.Horizontal)
        splitterH.setStyleSheet('background-color:beige')
        splitterH.addWidget(self.historyForm)
        splitterH.addWidget(self.placeHolder)

        splitterV.addWidget(splitterH)
        #splitterV.addWidget(self.messageForm);

        desktop = QApplication.desktop()
        self.setGeometry(50, 50, 900, 500)
        self.move(desktop.availableGeometry().center() -
                  self.rect().center())  #по умолчению в центре экрана

        self.settings.read_settings(
        )  # вначале восстанавливаем настройки, положение
        ##self.read_settings()

        self.create_plugins()  # затем читаем и загружаем нужные плагины

        self.create_actions()  # а затем создаем нужные действия
        self.create_menus()
        self.create_tool_bars()
        self.create_status_bar()

        self.setWindowTitle(APPLICATION_NAME)
        self.setWindowIcon(QIcon(self.root + '/images/logo.png'))

        splitterV.setStretchFactor(0, 200)
        splitterV.setStretchFactor(1, 1)

        splitterH.setHandleWidth(0)
        splitterV.setHandleWidth(0)
        #splitterV.setSizes([200, 1]);

        self.show()

    def create_plugins(self):
        self.available_plugins.clear()
        plugins = import_plugins(self.database, self.plugins_directory_path,
                                 self.disabled_plugins, self.available_plugins)

        lasIndex = 0
        self.loaded_plugins.clear()
        for plugin in plugins:
            self.loaded_plugins.append(plugin.plugin_name)
            lasIndex = self.placeHolder.addForm(plugin)

        self.placeHolder.setCurrentIndex(1)

    def create_actions(self):
        for i in range(MainWindow.MaxRecentFiles):
            self.recent_file_acts.append(
                QAction(self, visible=False,
                        triggered=self.open_recent_file))  #последние файлы

        for i in range(len(self.available_plugins)):
            self.load_plugin_acts.append(
                QAction(self, visible=False, triggered=self.load_plugin))

        self.closeAct = QAction(QIcon(self.root + '/images/close.png'),
                                "&Close",
                                self,
                                shortcut=QKeySequence.Close,
                                statusTip="Закрыть базу данных",
                                triggered=self.close_file)

        self.openAct = QAction(QIcon(self.root + '/images/open.png'),
                               "&Open...",
                               self,
                               shortcut=QKeySequence.Open,
                               statusTip="Открыть базу данных",
                               triggered=self.open_file)

        self.optionsAct = QAction(QIcon(self.root + '/images/options.png'),
                                  "O&ptions...",
                                  self,
                                  statusTip="Настройка программы",
                                  triggered=self.show_options)

        self.playAct = QAction(QIcon(self.root + '/images/chips.png'),
                               "Play lottery",
                               self,
                               statusTip="Играть в полулярные мировые лотереи",
                               triggered=self.play_lottery)

        self.exitAct = QAction(QIcon(self.root + '/images/exit.png'),
                               "E&xit",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Выйти из программы",
                               triggered=self.close)

        self.aboutAct = QAction("&About",
                                self,
                                statusTip="О программе",
                                triggered=self.about)

        self.updateAct = QAction(QIcon(self.root + '/images/update.png'),
                                 "&Update",
                                 self,
                                 statusTip="Обновить лотерею",
                                 triggered=self.update_lottery)

    def play_menu_action(self, item):
        try:
            openurl(item.data()[1])
        except:
            pass

    def create_menus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.closeAct)
        self.separatorAct = self.fileMenu.addSeparator()
        for i in range(MainWindow.MaxRecentFiles):
            self.fileMenu.addAction(self.recent_file_acts[i])

        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.tools_menu = self.menuBar().addMenu("&Tools")
        self.tools_menu.addAction(self.optionsAct)

        self.plugins_menu = self.menuBar().addMenu("&Plugins")
        for i, plugin in enumerate(self.available_plugins):
            text = "%d %s" % ((i + 1), plugin)
            self.load_plugin_acts[i].setText(text)
            self.load_plugin_acts[i].setData(plugin)
            self.load_plugin_acts[i].setVisible(True)
            self.plugins_menu.addAction(self.load_plugin_acts[i])

        self.play_menu = self.menuBar().addMenu("&Play")
        items = [("Eurojackpot", EUROJACKPOT_PLAY_URL),
                 ("Euromillions", EUROMILLIONS_PLAY_URL),
                 ("Мировые лотереи", LOTTERY_PLAY_URL)]

        # play_menu
        for item in items:
            fancyName = "%s" % (item[0])
            action = self.play_menu.addAction(fancyName)
            action.setData(item)
            action.triggered.connect(partial(self.play_menu_action, action))

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)

        self.update_recent_file_actions()

    def set_current_file(self, fileName):
        self.curFile = fileName
        Settings.last_opened_database = fileName

        #self.recentFiles = self.settings.value('recentFileList', [], 'QStringList')

        try:
            self.recentFiles.remove(
                fileName)  #TODO удаление независимо от регистра
        except ValueError:
            pass

        self.recentFiles.insert(0, fileName)
        del self.recentFiles[MainWindow.MaxRecentFiles:]

        #self.settings.setValue('recentFileList', files)

        self.update_recent_file_actions()

    def update_recent_file_actions(self):
        #files = self.settings.value('recentFileList', [])

        numRecentFiles = min(len(self.recentFiles), MainWindow.MaxRecentFiles)

        for i in range(numRecentFiles):
            text = "&%d %s" % (i + 1, self.stripped_name(self.recentFiles[i]))
            self.recent_file_acts[i].setText(text)
            self.recent_file_acts[i].setData(self.recentFiles[i])
            self.recent_file_acts[i].setVisible(True)

        for j in range(numRecentFiles, MainWindow.MaxRecentFiles):
            self.recent_file_acts[j].setVisible(False)

        self.separatorAct.setVisible((numRecentFiles > 0))

    def stripped_name(self, fullFileName):
        return QFileInfo(fullFileName).fileName()

    def create_tool_bars(self):
        self.fileToolBar = self.addToolBar("File")

        self.fileToolBar.addAction(self.openAct)
        self.fileToolBar.addAction(self.closeAct)
        self.fileToolBar.addAction(self.updateAct)

        self.playToolBar = self.addToolBar("Play")
        self.playToolBar.addAction(self.playAct)

        self.toolsToolBar = self.addToolBar("Tools")
        self.toolsToolBar.addAction(self.optionsAct)

        self.exitToolBar = self.addToolBar("Exit")
        self.exitToolBar.addAction(self.exitAct)

    def create_status_bar(self):
        self.statusBar().showMessage("Ready")
Exemple #6
0
    def npm_add_node(self, **kwargs):

        s = Settings()
        settings = s.get_all_settings()

        # first check this device isn't already in Orion
        self.ip_check = self.con.query('SELECT NodeID FROM Orion.Nodes WHERE IPAddress=@ip_address', ip_address=kwargs.get('ip_address'))
        self.hostname_check = self.con.query('SELECT NodeID FROM Orion.Nodes WHERE Caption=@hostname', hostname=kwargs.get('hostname'))
        if len(self.ip_check['results']) > 0 or len(self.hostname_check['results']) > 0:

            # if this is greater than 0, then the device already exists in orion
            return

        else:

            # assign the device poperties for adding to the database
            # support only for SNMPv2 at this stage
            self.properties = {
                'Caption': kwargs.get('hostname'),
                'IPAddress': kwargs.get('ip_address'),
                'DynamicIP': False,
                'EngineID': kwargs.get('engine_id') or 1, 
                'Status': 1,
                'Allow64BitCounters': 1,
                'ObjectSubType': 'SNMP',
                'SNMPVersion': kwargs.get('snmp_version') or 2,
                'Community': kwargs.get('community'),
                # Set NextRediscovery to now + 2 mins so that rediscovery happens at the next rediscovery interval, default 30mins
                'NextRediscovery': datetime.datetime.now() + datetime.timedelta(minutes = 2)
            }

            # create the node
            self.results = self.con.create('Orion.Nodes', **self.properties)

            # get the NodeID
            self.node_id = re.search('(\d+)$', self.results).group(0)

            # setup device pollers
            self.pollers_enabled = {
                'N.Status.ICMP.Native': True,
                'N.Status.SNMP.Native': False,
                'N.ResponseTime.ICMP.Native': True,
                'N.ResponseTime.SNMP.Native': False,
                'N.Details.SNMP.Generic': True,
                'N.Uptime.SNMP.Generic': True,
                'N.Cpu.SNMP.HrProcessorLoad': True,
                'N.Memory.SNMP.NetSnmpReal': True,
                'N.AssetInventory.Snmp.Generic': True,
                'N.Topology_Layer3.SNMP.ipNetToMedia': False,
                'N.Routing.SNMP.Ipv4CidrRoutingTable': False
            }  

            # create a list of dictionarys for each poller
            self.pollers = []
            for self.k in self.pollers_enabled:
                self.pollers.append(
                    {
                        'PollerType': self.k,
                        'NetObject': 'N:' + self.node_id,
                        'NetObjectType': 'N',
                        'NetObjectID': self.node_id,
                        'Enabled': self.pollers_enabled[self.k]
                    }
                )

            # loop through pollers and turn them on
            for self.poller in self.pollers:
                 self.response = self.con.create('Orion.Pollers', **self.poller)

            # add the custom properties
            self.results = self.con.query(
                "SELECT Uri FROM Orion.Nodes WHERE NodeID=@id",
                id=self.node_id
            )

            # grab the uri - whatever this is
            self.uri = self.results['results'][0]['Uri']

            # update the custom properties
            self.con.update(
                self.uri + '/CustomProperties',
                City = kwargs.get('city'),
                Site = kwargs.get('site'),
                Network = kwargs.get('network')
            )

            return self.node_id
                tutorial.draw()

        clock.tick(settings.FPS)


# initialize pygame
pygame.init()
pygame.display.set_caption('Run, Bernie, Run!')
screen = pygame.display.set_mode((600, 600))

# set up pygame icon
icon = pygame.image.load('images/bernie_icon.bmp')
pygame.display.set_icon(icon)

# create global objects
settings = Settings()
clock = pygame.time.Clock()

# game over background color
LIGHT_BLUE = (0, 121, 214)
RED = (255, 0, 0)

# declare event types
game_clock_tick = pygame.USEREVENT + 2

# score image
game_over_font = pygame.font.SysFont('Arial Black', 32)
game_over_score_image = game_over_font.render('4200', True, RED, LIGHT_BLUE)
game_over_score_rect = game_over_score_image.get_rect()
game_over_score_rect.left = 330
game_over_score_rect.top = 330
#-*- coding: utf-8 -*-
import speech_recognition as sr
from termcolor import colored
import sys, os, platform
from subprocess import call  #necessario para usar em linux e MAC
from classes.voice import Voice
from classes.actions import Actions
from classes.settings import Settings

base_dir_name = os.path.dirname(os.path.abspath(__file__))
base_dir_name = base_dir_name.replace("classes", "")

settings = Settings(base_dir_name + "/settings.ini")
general = settings.get_section_settings('GENERAL')
voice_capture = settings.get_section_settings('VOICE_CAPTURE')
speech_api = settings.get_section_settings('SPEECH_API')
other_settings = settings.get_section_settings('OTHERS')


class Assistent():
    def __init__(self):
        #Configurações
        self.hotword = general['keyword']
        self.name = general['assistent_name']
        self.full_name = general['assistent_full_name']
        self.recognizer = sr.Recognizer()
        self.set_configurations()
        self.voice = Voice(self.language)

    def set_configurations(self):
        self.__you_said_color = general['human_text_color']