Example #1
0
def build_argument_list(game_info, port, arguments=None):
    """
    Compiles an argument list to run the game with POpen style process invocation methods.
    Extends a potentially pre-existing argument list to allow for injection of special parameters
    """
    import client
    arguments = arguments or []

    if '/init' in arguments:
        raise ValueError("Custom init scripts no longer supported.")

    # Init file
    arguments.append('/init')
    arguments.append('init_{}.lua'.format(game_info.get('featured_mod', 'faf')))

    arguments.append('/numgames {}'.format(client.instance.me.number_of_games))

    # log file
    if Settings.get("game/logs", False, type=bool):
        arguments.append("/log")
        arguments.append('"' + util.LOG_FILE_GAME + '"')

    # Disable defunct bug reporter
    arguments.append('/nobugreport')

    # live replay
    arguments.append('/savereplay')
    arguments.append('"gpgnet://localhost/' + str(game_info['uid']) + "/" + str(game_info['recorder']) + '.SCFAreplay"')

    # gpg server emulation
    arguments.append('/gpgnet 127.0.0.1:' + str(port))

    return arguments
Example #2
0
 def __init__(self):
     self.logger = logger("")
     begin()
     self.settings = Settings(self)
     self.worlds = {}
     self.default_world = None
     self.level = Level.engine
     self.logger.info("CocoMUD engine started")
Example #3
0
    def loadSettings(self):
        self.mode = Settings.get(self._settings_key+'/mode', 'friends')

        if self.mode == 'friends':
            self.radioButtonFriends.setChecked(True)
        else:
            self.radioButtonAll.setChecked(True)
        self.parent.mode = self.mode
Example #4
0
def api_handler(request, service):
    service_handler = Settings.get_service_handler(service)
    if service_handler:
        logger.debug("Hitting service %s" % service)
        return csrf_exempt(service_handler)(request)
    else:
        msg = "Service %s not found" % service
        logger.info(msg)
        raise Http404(msg)
Example #5
0
    def render_config_from_template(self, template_name, variables_dict=None):
        logger = logging.getLogger(__name__)
        settings = Settings()
        try:
            with open(template_name, 'r') as t:
                template_data = t.readlines()
            configuration = list()
            conf_vars_dict = vars(self)
            if variables_dict:
                conf_vars_dict.update(variables_dict)
            conf_vars_dict['settings'] = dict()
            conf_vars_dict['settings'][
                'dmvpn_password'] = settings.dmvpn_password

            for line in template_data:
                line = line.rstrip('\n')
                t = Template(line)
                new_line = t.render(conf_vars_dict)
                configuration.append(new_line)
            return configuration
        except Exception as e:
            logger.error(e)
            return False
def test_settings():
    new_env = {
        "ADMIN_PASSWORD": "******",
        "BLOG_URL": "blog_url",
        "BOT_TOKEN": "bot_token",
        "DATABASE_URL": "database_url",
        "DEBUG": "True",
        "DEBUG_SQL": "False",
        "SERVICE_URL": "service_url",
        "WEBHOOK_SECRET": "webhook_secret",
    }

    with mock.patch.dict(os.environ, new_env, clear=True):
        settings = Settings()

    assert settings.admin_password == "admin_password"
    assert settings.blog_url == "blog_url"
    assert settings.bot_token == "bot_token"
    assert settings.database_url == "database_url"
    assert settings.debug is True
    assert settings.debug_sql is False
    assert settings.service_url == "service_url"
    assert settings.webhook_secret == "webhook_secret"
Example #7
0
    def busy_entered(self):
        # Don't display things when we're not logged in
        # FIXME - one day we'll have more obvious points of entry
        if self.client.state != client.ClientState.LOGGED_IN:
            return

        if self.selected_player is None:
            self.selected_player = self.client.players[self.client.login]
        if self.selected_player.league is not None:
            self.leagues.setCurrentIndex(self.selected_player.league - 1)
        else:
            self.leagues.setCurrentIndex(5)  # -> 5 = direct to Ladder Ratings

        if self.selected_player_loaded:
            return

        self.webview.setVisible(False)
        self.webview.setUrl(
            QtCore.QUrl(
                "{}/faf/leaderboards/read-leader.php?board=1v1&username={}".
                format(Settings.get('content/host'),
                       self.selected_player.login)))
        self.selected_player_loaded = True
Example #8
0
    def __show_message_box(self, title, icon, text, info):
        """
        Creates and shows a QMessageBox.

        :param title: String - Title of the message box
        :param icon: Icon of the message box, e.g. QMessageBox.Critical
        :param text: String - Text of the message box
        :param info: String - More text for the message box to provide further information
        """
        message_box = QMessageBox()
        current_stylesheet = Settings.get_instance().get_settings(
        ).design.color_theme.current
        if current_stylesheet == 0:
            message_box.setStyleSheet(
                open(Resources.files.qss_dark, "r").read())
        elif current_stylesheet == 1:
            message_box.setStyleSheet(
                open(Resources.files.qss_light, "r").read())

        message_box.setWindowTitle(title)
        message_box.setIcon(icon)
        message_box.setText(text)
        message_box.setInformativeText(info)
        message_box.exec_()
Example #9
0
class GUI(Ui_mainWindow):
    def __init__(self, window):
        super().__init__()
        self.setupUi(window)
        self.window = window
        self.settings = Settings()
        self.window.closeEvent = self.closeEvent
        self.server = Server()
        self.downman = DownloadManager()
        self.browser = Browser()
        # snapshot updater is to be started on exchange connect
        self.xchgClient = ExchangeClient()
        self.lastKnownDir = "/tmp"
        self.destPrefix = ''
        self.userlist = None
        self.di_list = []
        self.addEventListeners()
        self.browserTable.setColumnHidden(0, True)
        self.userListTable.setColumnHidden(0, True)
        self.tabWidget.setCurrentIndex(0)
        self.urlFrame.setVisible(False)
        self.window.setWindowIcon(QIcon(":/images/favicon.ico"))
        self.window.setWindowTitle("21Lane")
        self.makeMenuBar()
        self.setupSystemTray()
        self.loadSettings()
        self.window.show()

    def makeMenuBar(self):
        self.menuBar = QMenuBar(self.window)
        self.fileMenu = QMenu("File")
        self.menuBar.addMenu(self.fileMenu)
        self.exitAction = QAction("Exit", self.window)
        self.exitAction.triggered.connect(self.closeEvent)
        self.minimizeToTrayAction = QAction("Minimize to Tray", self.window)
        self.minimizeToTrayAction.setCheckable(True)
        self.minimizeToTrayAction.setChecked(True)
        self.fileMenu.addAction(self.minimizeToTrayAction)
        self.fileMenu.addAction(self.exitAction)
        self.window.layout().setMenuBar(self.menuBar)

    def loadSettings(self):
        success = self.settings.load()
        self.publicNameInput.setText(self.settings.configDic["publicName"])
        self.port.setValue(self.settings.configDic["port"])
        self.sharedLocationInput.setText(self.settings.configDic["sharedDir"])
        self.downloadLocationInput.setText(
            self.settings.configDic["downloadDir"])
        self.speedLimitSlider.setValue(self.settings.configDic["speedLimit"])
        self.speedLimitSpin.setValue(self.settings.configDic["speedLimit"])
        self.exchangeURLInput.setText(self.settings.configDic["exchangeURL"])
        if success:
            self.toggleShare()
            self.tabWidget.setCurrentIndex(1)
            self.reloadUsersBtn.click()

    def keyPressedEvent(self, event):
        if event.key() == Qt.Key_Escape:
            event.ignore()

    def closeEvent(self, event):
        if (self.window.sender()
                == None) and (self.minimizeToTrayAction.isChecked()):
            self.showWindow(False)
            self.activateAction.setChecked(False)
            event.ignore()
            return
        if self.server.isRunning():
            self.server.stopServer()
        if self.xchgClient.isRunning():
            print('attempting to shut down exchange client')
            self.xchgClient.quit()
            print('asked to end xchgclient politely')
            if not self.xchgClient.wait(1):
                print('forced closure of xchgclient required')
                self.xchgClient.terminate()
            print('xchgclient forcefully closed')
        if self.downman.running:
            self.downman.stopDownloader()
        qApp.exit()

    def showMessage(self, maintext=None, subtext=None):
        QMessageBox.information(self.window, maintext, subtext, QMessageBox.Ok,
                                QMessageBox.Ok)

    def getPathFromDialog(self):
        return QFileDialog.getExistingDirectory(self.window, "Select folder",
                                                self.lastKnownDir,
                                                QFileDialog.ShowDirsOnly)

    def addEventListeners(self):
        self.speedLimitSlider.valueChanged[int].connect(self.updateSpeedLimit)
        self.speedLimitSpin.valueChanged[int].connect(self.updateSpeedLimit)
        self.sharedLocationBtn.clicked.connect(self.showDirectorySelector)
        self.downloadLocationBtn.clicked.connect(self.showDirectorySelector)
        self.toggleShareBtn.setText("Start Sharing")
        self.toggleShareBtn.clicked.connect(self.toggleShare)
        self.server.ftp_handler.stats.clientConnect.connect(
            self.statClientConnected)
        self.server.ftp_handler.stats.clientDisconnect.connect(
            self.statClientDisconnected)
        self.server.ftp_handler.stats.fileTransfer[int].connect(
            self.statFileTransferred)
        self.reloadUsersBtn.clicked.connect(self.loadUsers)
        self.browserInput.returnPressed.connect(self.browserGoBtn.click)
        self.browserGoBtn.clicked.connect(self.loadBrowserTable)
        self.browserHomeBtn.clicked.connect(self.loadBrowserTable)
        self.browserPrevBtn.clicked.connect(self.handleBackBtnClick)
        self.userListTable.doubleClicked.connect(self.showBrowser)
        self.browserTable.doubleClicked.connect(self.handleFileSelection)
        self.developerLink.linkActivated.connect(xdg_open)
        self.projectLink.linkActivated.connect(xdg_open)

    def showDirectorySelector(self, event):
        if self.window.sender() is self.downloadLocationBtn:
            self.downloadLocationInput.setText(self.getPathFromDialog())
            self.destPrefix = self.downloadLocationInput.text()
        elif self.window.sender() is self.sharedLocationBtn:
            self.sharedLocationInput.setText(self.getPathFromDialog())

    def updateSpeedLimit(self, value):
        self.speedLimitSlider.setValue(value)
        self.speedLimitSpin.setValue(value)

    def statClientConnected(self):
        self.server.connected += 1
        self.stats_connected.setText(str(self.server.connected))

    def statClientDisconnected(self):
        self.server.connected -= 1
        self.stats_connected.setText(str(self.server.connected))

    def statFileTransferred(self, filesize):
        self.server.bytesTransferred += filesize
        self.server.filesTransferred += 1
        self.stats_files.setText(str(self.server.filesTransferred))
        self.stats_bytes.setText(toHumanReadable(self.server.bytesTransferred))

    def toggleShare(self):
        try:
            if  (not self.publicNameInput.text()) or \
                (not self.port.value()) or \
                (not self.sharedLocationInput.text()):
                raise FormIncompleteError
            if self.xchgClient.isRunning():
                self.xchgClient.quit()
                if not self.xchgClient.wait(1):
                    self.xchgClient.terminate()
            if self.server.isRunning():
                self.server.stopServer()
                self.toggleShareBtn.setText("Start Sharing")
                self.toggleShareBtn.setIcon(QIcon(":/images/failed.svg"))
                self.urlFrame.setVisible(False)
            else:
                self.server.setPort(self.port.value())
                self.server.setSharedDirectory(self.sharedLocationInput.text())
                self.server.start()
                if not self.exchangeURLInput.text():
                    self.xchgClient.updateInfo(self.publicNameInput.text(),
                                               None, self.port.value())
                else:
                    self.xchgClient.updateInfo(self.publicNameInput.text(),
                                               self.exchangeURLInput.text(),
                                               self.port.value())
                self.xchgClient.updateDir(self.sharedLocationInput.text())
                self.settings.update(self.publicNameInput.text(), self.port.value(), \
                    self.sharedLocationInput.text(), self.downloadLocationInput.text(), self.speedLimitSlider.value(), self.exchangeURLInput.text())
                self.toggleShareBtn.setText("Stop Sharing")
                self.toggleShareBtn.setIcon(QIcon(":/images/complete.svg"))
                addresses = getAllAddresses()
                print(addresses)
                if len(addresses) != 0:
                    lblstr = "<html><body>"
                    current = 0
                    end = len(addresses) - 1
                    for addr in addresses:
                        hyperlink = 'ftp://' + addr + ':' + str(
                            self.server.port)
                        lblstr += "<a href=\'" + hyperlink + "\'>" + hyperlink + "</a>"
                        if current != (end - 1):
                            lblstr += '<br>'
                        current += 1
                    lblstr += "</body></html>"
                    self.urlLabel.setText(lblstr)
                    self.urlFrame.setVisible(True)
                    print(self.urlFrame.isVisible(), 'url frame is visivle')
        except FileNotFoundError:
            self.showMessage("Don't fool me", "Shared location doesn't exist")
        except PortUnavailableError:
            self.showMessage("Port unavailable",
                             "Please select some other port number")
        except FormIncompleteError:
            self.showMessage("Form incomplete",
                             "Please fill in proper values!")

    def loadUsers(self):
        userlist = self.xchgClient.getUserList()
        self.userlist = userlist
        if not userlist:
            self.showMessage("Sorry", "Cannot retrieve list of users")
            return
        table = self.userListTable
        table.clearContents()
        table.setRowCount(len(userlist))
        for i, entry in enumerate(userlist):
            table.setItem(i, 0, QTableWidgetItem(str(i)))
            table.setItem(
                i, 1,
                QTableWidgetItem(toHumanReadable(int(entry["sharedSize"]))))
            table.setItem(i, 2, QTableWidgetItem(entry["publicName"]))

    def showBrowser(self):
        if not self.userlist:
            return
        current = self.userListTable.selectedItems()[0]
        index = int(self.userListTable.item(current.row(), 0).text())
        user = self.userlist[index]
        self.browser.update(user["ip"], int(user["port"]))
        self.tabWidget.setCurrentIndex(2)
        self.browserInput.setText("/")
        self.browserGoBtn.click()

    def loadBrowserTable(self):
        pwd = self.browserInput.text()
        filelist = []
        try:
            if not self.browser.pathExists(self.browser.host,
                                           self.browser.port, pwd):
                self.showMessage("Error", "The path does not exist!")
                return
            self.browser.historyStack.append(pwd)
            filelist = self.browser.getFileList(self.browser.host,
                                                self.browser.port, pwd)
            self.browser.filelist = filelist
        except ConnectionRefusedError:
            self.showMessage(
                "Offline",
                "The remote machine cannot be contacted!\nBetter luck next time."
            )
            self.tabWidget.setCurrentIndex(1)
        table = self.browserTable
        table.clearContents()
        table.setRowCount(len(filelist))
        for i, file in enumerate(filelist):
            table.setItem(i, 0, QTableWidgetItem(str(i)))
            table.setItem(i, 1,
                          QTableWidgetItem(QIcon(":images/download.png"), ""))
            table.setItem(i, 2,
                          QTableWidgetItem(toHumanReadable(file["filesize"])))
            if file["isDir"]:
                table.setItem(
                    i, 3, QTableWidgetItem(QIcon(":/images/folder.png"), ""))
            else:
                table.setItem(
                    i, 3, QTableWidgetItem(guess_mime(file["filename"])[0]))
            table.setItem(i, 4, QTableWidgetItem(file["filename"]))

    def handleBackBtnClick(self):
        if not self.userlist:
            self.showMessage(
                "Confused",
                "What should I load? \nFind someone from list of connected users."
            )
            return
        if len(self.browser.historyStack) < 2:
            self.showMessage("Sorry", "Hey, there's no looking back!")
            return
        self.browser.historyStack.pop()
        prev = self.browser.historyStack.pop()
        self.browserInput.setText(prev)
        self.loadBrowserTable()

    def handleFileSelection(self):
        if not self.browser.filelist:
            return
        current = self.browserTable.selectedItems()[0]
        index = int(self.browserTable.item(current.row(), 0).text())
        file = self.browser.filelist[index]
        print("index", index, file["pathname"], current.text())
        if file["isDir"] and current.column() is not 1:
            pwd = join_path(self.browserInput.text(), file["pathname"])
            self.browserInput.setText(pwd)
            self.browserGoBtn.click()
            return
        # a download is to be handled
        print("downloading directory", file["filename"])
        # decide it is a file or directory
        if not self.destPrefix:
            destDir = join_path(self.getPathFromDialog())
        else:
            destDir = self.destPrefix
        meta = None
        if file["isDir"]:
            meta = self.browser.getRecursiveFileList(self.browser.host,
                                                     self.browser.port,
                                                     file["pathname"])
            filelist = self.browser.recfilelist
        else:
            meta = {"totalFiles": 1, "totalSize": file["filesize"]}
            filelist = [file]
        signal = DownloadItemUpdater()
        diui = self.createDownloadItemBox(file["filename"], meta["totalSize"])
        dilist = []
        for item in filelist:
            di = DownloadItem(item["filename"], self.browser.host,
                              self.browser.port, item["pathname"],
                              join_path(destDir, item["filename"]),
                              item["filesize"], signal)
            di.updateGuiComponents(diui)
            dilist.append(di)

        # create callbacks for gui events
        def cancelCallback():
            for di in dilist:
                di.cancel()
            diui["cancelBtn"].setIcon(QIcon(":/images/reload.png"))
            diui["cancelBtn"].clicked.disconnect()
            diui["cancelBtn"].clicked.connect(retryCallback)

        def updateProgressCallback(progress):
            sum = 0
            for di in dilist:
                sum += di.completed
            diui["progress"].setValue(sum)
            diui["completion"].setText(toHumanReadable(sum))

        def retryCallback():
            print("retrying")
            di.completed = 0
            self.downman.addItem(di)
            diui["cancelBtn"].clicked.disconnect()
            diui["cancelBtn"].clicked.connect(cancelCallback)
            diui["cancelBtn"].setIcon(QIcon(":/images/cancel.png"))

        def errorCallback():
            diui["completion"].setText("Failed")
            cancelCallback()

        def completeCallback():
            diui["completion"].setText("Completed")
            diui["cancelBtn"].clicked.disconnect()
            diui["cancelBtn"].setToolTip("Open")
            diui["cancelBtn"].setIcon(QIcon(":/images/open.png"))
            diui["cancelBtn"].clicked.connect(openFile)

        def openFile():
            xdg_open(join_path(destDir, file["filename"]))

        def openDir():
            xdg_open(destDir)

        diui["cancelBtn"].clicked.connect(cancelCallback)
        signal.progress[int].connect(updateProgressCallback)
        signal.error.connect(errorCallback)
        signal.complete.connect(completeCallback)
        diui["openDestBtn"].clicked.connect(openDir)
        self.downloadsLayout.insertWidget(0, diui["widget"])
        for entry in dilist:
            self.downman.addItem(entry)
        # print ("downloading", di.filename, di.filesize, "to")

    def createDownloadItemBox(self, filename, filesize):
        diui = {}
        frame = QFrame(self.window)
        frame.setFrameStyle(QFrame.StyledPanel)
        layout = QHBoxLayout()
        filesize = filesize if not filesize is 0 else 1
        diui["layout"] = layout
        diui["widget"] = frame
        diui["filename"] = QLabel(filename)
        diui["filename"].setToolTip(filename)
        diui["filename"].setMaximumWidth(30)
        diui["filesize"] = QLabel(toHumanReadable(filesize))
        diui["filesize"].setAlignment(Qt.AlignCenter)
        diui["progress"] = QProgressBar()
        diui["progress"].setRange(0, filesize)
        diui["completion"] = QLabel("Waiting...")
        diui["completion"].setAlignment(Qt.AlignCenter)
        diui["cancelBtn"] = QPushButton(QIcon(":/images/cancel.png"), '')
        diui["openDestBtn"] = QPushButton(QIcon(":/images/folder.png"), '')
        diui["cancelBtn"].setToolTip("Cancel download")
        diui["openDestBtn"].setToolTip("Open folder")
        diui["layout"].addWidget(diui["filename"])
        diui["layout"].addWidget(diui["filesize"])
        diui["layout"].addWidget(diui["progress"])
        diui["layout"].addWidget(diui["completion"])
        diui["layout"].addWidget(diui["openDestBtn"])
        diui["layout"].addWidget(diui["cancelBtn"])
        diui["layout"].setSpacing(0)
        layout.setContentsMargins(5, 2, 5, 2)
        layout.setSpacing(6)
        layout.setStretch(0, 3)
        layout.setStretch(1, 2)
        layout.setStretch(2, 5)
        layout.setStretch(3, 2)
        layout.setStretch(4, 1)
        layout.setStretch(5, 1)
        frame.setLayout(layout)
        return diui

    def showWindow(self, checked):
        self.window.setVisible(checked)

    def setupSystemTray(self):
        self.activateAction = QAction("Show", self.window)
        self.activateAction.setCheckable(True)
        self.activateAction.setChecked(True)
        self.activateAction.triggered.connect(self.showWindow)
        self.quitAction = QAction("Quit", self.window)
        self.quitAction.triggered.connect(self.closeEvent)
        self.trayIconMenu = QMenu(self.window)
        self.trayIconMenu.addAction(self.activateAction)
        self.trayIconMenu.addAction(self.quitAction)
        self.trayIcon = QSystemTrayIcon(QIcon(":/images/icon.ico"),
                                        self.window)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.show()
Example #10
0
 def renameAccount(self):
     QtGui.QDesktopServices.openUrl(
         QtCore.QUrl(Settings.get("NAME_CHANGE_URL")))
Example #11
0
def get_settings() -> Settings:
    return Settings()
Example #12
0
 def saveSettings(self):
     Settings.set(self._settings_key+'/mode', self.mode)
     self.parent.mode = self.mode
Example #13
0


from PyQt4 import QtCore, QtGui, QtNetwork

import functools

import logging

import config
from config import Settings

FAF_PROXY_HOST = Settings.get('proxy/host')
FAF_PROXY_PORT = Settings.get('proxy/port')

UNIT16 = 8


class proxies(QtCore.QObject):
    __logger = logging.getLogger(__name__)

    def __init__(self, parent=None):
        super(proxies, self).__init__(parent)

        self.client = parent

        self.proxies = {}
        self.proxiesDestination = {}
        port = 12000
        errored = False
        for i in range(11) :
Example #14
0
 def tech_support(self):
     QtGui.QDesktopServices().openUrl(QtCore.QUrl(Settings.get("HELP_URL")))
def add_cluster():
    logger = logging.getLogger(__name__)
    settings = Settings()
    form = AddCluster()
    form.Region.choices = settings.get_regions_tuples()
    form.InstanceType.choices = settings.get_instances_tuples()

    if form.validate_on_submit():
        region_routers_candidate, region_vgws_candidate, region_vpns_candidate, available_clusters, region_tgws_candidate = get_cluster_data(
            form.Region.data)
        if form.cluster_value.data in available_clusters:
            flash("Cluster name '{}' has already been deployed in '{}'".format(
                form.cluster_value.data, form.Region.data))
            return redirect(url_for('add_cluster'))

        if form.InstanceType.data not in settings.get_region_supported_instances(
                form.Region.data):
            flash("Instance type '{}' is not available in '{}'".format(
                form.InstanceType.data, form.Region.data))
            return redirect(url_for('add_cluster'))

        az_names = get_availability_zones_available(form.Region.data)
        all_routers = get_all_routers()
        available_dmvpn_addresses = get_available_dmvpn_addresses_hub(
            all_routers, form.cluster_value.data, 2)
        available_subnets = get_available_vpc_cidr_space(
            all_routers, form.cluster_value.data, 2)

        router1 = Cgw(
            Region=form.Region.data,
            hub=True,
            region_extension=False,
            AvailabilityZone=az_names[0],
            InstanceType=form.InstanceType.data,
            asn=form.asn.data,
            cluster_value=form.cluster_value.data,
            available_bandwidth=Settings.instance_types[
                form.InstanceType.data],
            AmiId=Settings.regions[form.Region.data]['ami'],
            max_bandwidth=Settings.instance_types[form.InstanceType.data],
            KeyName=Settings.regions[form.Region.data]['key'],
            DmvpnAddress=available_dmvpn_addresses[0],
            DmvpnNetmask=str(
                ipaddress.ip_network(Settings.dmvpn_address_space).netmask),
            eligible='False',
            DmvpnCidr=Settings.dmvpn_address_space,
            vpc_cidr=available_subnets[0])
        router2 = Cgw(
            Region=form.Region.data,
            hub=True,
            region_extension=False,
            AvailabilityZone=az_names[1],
            InstanceType=form.InstanceType.data,
            asn=form.asn.data,
            cluster_value=form.cluster_value.data,
            available_bandwidth=Settings.instance_types[
                form.InstanceType.data],
            AmiId=Settings.regions[form.Region.data]['ami'],
            max_bandwidth=Settings.instance_types[form.InstanceType.data],
            KeyName=Settings.regions[form.Region.data]['key'],
            DmvpnAddress=available_dmvpn_addresses[1],
            DmvpnNetmask=str(
                ipaddress.ip_network(Settings.dmvpn_address_space).netmask),
            eligible='False',
            DmvpnCidr=Settings.dmvpn_address_space,
            vpc_cidr=available_subnets[1])

        r1, r2 = setup_add_cluster.main(router1, router2)
        if r1 == 'fail':
            flash("Cluster '{}' deployment and configuration failed".format(
                form.cluster_value.data))
            logger.warning("Cluster %s deployment and configuration failed",
                           form.cluster_value.data)
        elif r1.registration_failed or r2.registration_failed:
            if r1.registration_failed:
                flash(
                    "Router '{}' failed to register with Cisco Smart Licensing"
                    .format(r1.PublicIp))
            if r2.registration_failed:
                flash(
                    "Router '{}' failed to register with Cisco Smart Licensing"
                    .format(r2.PublicIp))
        else:
            flash("Cluster '{}' deployed successfully!".format(
                r1.cluster_value))
            logger.info("Cluster %s deployed successfully!", r1.cluster_value)

        return redirect(url_for('add_cluster'))
    return render_template('add_cluster.html', title='Add Cluster', form=form)
Example #16
0
from config import Settings, Labels

from datetime import datetime
from json import dumps
import logging

# Fix logging faliure issue
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

# Initialise custom logging format
FORMAT = "%(relativeCreated)6d %(levelname)-8s %(name)s %(process)d %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
logger = logging.getLogger(__name__)

settings = Settings()
labels = Labels()
camera = Camera()
thermal = ThermalCamera()
cloud = Cloud()
classify = Classify()
data = Data()
control = Control()


class OnionBot(object):
    """Main OnionBot script"""

    def __init__(self):

        self.quit_event = Event()
Example #17
0
 def renameAccount(self):
     QtGui.QDesktopServices.openUrl(QtCore.QUrl(Settings.get("NAME_CHANGE_URL")))
Example #18
0
 def forgotPassword(self):
     QtGui.QDesktopServices.openUrl(QtCore.QUrl(Settings.get("PASSWORD_RECOVERY_URL")))
Example #19
0
 def linkAccount(self):
     QtGui.QDesktopServices.openUrl(QtCore.QUrl(Settings.get("STEAMLINK_URL")))
Example #20
0
    def saveSettings(self):
        Settings.set('notifications/enabled', self.enabled)
        Settings.set('notifications/popup_lifetime', self.popup_lifetime)

        self.client.actionNsEnabled.setChecked(self.enabled)
Example #21
0
    def loadSettings(self):
        self.enabled = Settings.get('notifications/enabled', True, type=bool)
        self.popup_lifetime = Settings.get('notifications/popup_lifetime', 5, type=int)

        self.nsEnabled.setChecked(self.enabled)
        self.nsPopLifetime.setValue(self.popup_lifetime)
Example #22
0
 def reportBug(self):
     QtGui.QDesktopServices.openUrl(QtCore.QUrl(Settings.get("TICKET_URL")))
Example #23
0
# Initialize logging system
import logging

from PyQt4.QtNetwork import QNetworkAccessManager
from enum import IntEnum

from config import Settings
from .player import Player

logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)

# Initialize all important globals
LOBBY_HOST = Settings.get("lobby/host")
LOBBY_PORT = Settings.get("lobby/port")
LOCAL_REPLAY_PORT = Settings.get("lobby/relay/port")


class ClientState(IntEnum):
    """
    Various states the client can be in.
    """

    SHUTDOWN = -666  # Going... DOWN!

    # Disconnected state
    # We enter this state if either:
    #  - The user requested it
    #  - We've reconnected too many times
    DISCONNECTED = -4
    
    cfg = None #It is probably not a good idea to proceed if the settings are 'none'
    logger = logging.getLogger('ncbi_sync')
    logger.setLevel(logging.INFO)
    for o, a in opts:
        if o == "-v":
            logger.setLevel(logging.DEBUG)
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-c", "--config"):
            cfg = a
        else:
            assert False, "unhandled option"
    
    settings = Settings()
    if(cfg != None):
        settings.load_yaml(cfg)
    else:
        #Abandon Ship?
        logging.warn('No configuration specified!')
        
    try:
        f = open('.my.cnf')
        
    except:
        """No local mysql configuration"""
    genbank_sync(settings)

if __name__ == '__main__':
    main(sys.argv)
Example #25
0
The purpose of this game is to build intuition for gravitational forces in a fun way.

The objective of the game is to manoeuvre a ship from one planet to another,
using gravitational forces of planets inbetween.

The following simplifications have been made:
    
   * The game universe is two-dimensional
   
   * Distances between planets are vastly reduced.
   
   * Planets have no atmosphere
   
   * Ships are launched vertically. 
     Once launched, they can not be further controlled.
     
   * Ships are launched with infinite acceleration, ie. the user can determine 
     the initial thrust and the ship will reach its maximum speed instantly.
     
   * Ships land with infinite (negative) acceleration, ie. we are not concerned 
     with "soft" landings (assuming fantastic airbag technology :)
     
"""

from gui import App
from config import Settings

app = App(Settings())
app.run()
def csr_redeploy():
    logger = logging.getLogger(__name__)
    all_routers = get_all_routers()
    settings = Settings()
    form = CsrRedeploy()
    form.InstanceType.choices = settings.get_instances_tuples()

    candidates = list()
    for router in all_routers:
        if router.eligible == 'False':
            candidates.append(router)

    candidates = sorted(candidates,
                        key=lambda k: k.cluster_value,
                        reverse=False)

    csr_t = list()
    for i in candidates:
        csr_t.append((i.PublicIp, i.PublicIp))
    form.csr.choices = csr_t

    if form.validate_on_submit():

        csr_ip = form.csr.data
        for router in candidates:
            if router.PublicIp == csr_ip:
                old_cgw = router

        if form.InstanceType.data not in settings.get_region_supported_instances(
                old_cgw.Region):
            flash("Instance type '{}' is not available in '{}'".format(
                form.InstanceType.data, old_cgw.Region))
            return redirect(url_for('csr_redeploy'))

        hubs = list()
        for rou in all_routers:
            if (rou.cluster_value == old_cgw.cluster_value) and (rou.hub
                                                                 == 'True'):
                hubs.append(rou)

        if old_cgw.hub == 'False':
            available_dmvpn_addresses = get_available_dmvpn_addresses(
                all_routers, old_cgw.cluster_value, 1)
            DmvpnAddress = available_dmvpn_addresses.pop(0)
        else:
            DmvpnAddress = old_cgw.DmvpnAddress
        available_subnets = get_available_vpc_cidr_space(
            all_routers, old_cgw.cluster_value, 1)
        new_cgw = Cgw(
            Region=old_cgw.Region,
            AvailabilityZone=old_cgw.AvailabilityZone,
            hub=old_cgw.hub,
            region_extension=old_cgw.region_extension,
            InstanceType=form.InstanceType.data,
            asn=old_cgw.asn,
            cluster_value=old_cgw.cluster_value,
            available_bandwidth=settings.instance_types[
                form.InstanceType.data],
            AmiId=Settings.regions[old_cgw.Region]['ami'],
            max_bandwidth=Settings.instance_types[form.InstanceType.data],
            KeyName=Settings.regions[old_cgw.Region]['key'],
            DmvpnAddress=DmvpnAddress,
            DmvpnNetmask=old_cgw.DmvpnNetmask,
            DmvpnCidr=old_cgw.DmvpnCidr,
            eligible='False',
            h1_public=hubs[0].PublicIp,
            h1_private=hubs[0].DmvpnAddress,
            h2_public=hubs[1].PublicIp,
            h2_private=hubs[1].DmvpnAddress,
            vpc_cidr=available_subnets.pop(0))

        result = setup_redeploy_csr.main(old_cgw, new_cgw)
        # result = False or cgw object
        if not result:
            flash("Redeploy Failed")
            logger.warning("Redeploy Failed")
        else:
            if result.registration_failed:
                flash(
                    "Router '{}' failed to register with Cisco Smart Licensing"
                    .format(result.PublicIp))
                logger.info(
                    "Router %s failed to register with Cisco Smart Licensing",
                    result.PublicIp)
            flash('The redeploy completed!')
            logger.info('The redeploy of router %s successfully completed!',
                        old_cgw.PublicIp)

        return redirect(url_for('csr_redeploy'))
    return render_template('csr_redeploy.html',
                           title='CSR Redeploy',
                           form=form,
                           cgws=candidates)
Example #27
0
from PyQt4 import QtCore, QtNetwork, QtGui

import logging
import json
from config import Settings

import struct

FAF_SERVER_HOST = Settings.get('relay_server/host')
FAF_SERVER_PORT = Settings.get('relay_server/port')


class Packet():
    def __init__(self, header=None , data=None, *values, **kwvalues):

        self._data = data
        self._values = kwvalues
        self._header = header

    def Pack(self):

        data = ""

        headerSize = len(str(self._header))
        headerField = str(self._header).replace("\t","/t").replace("\n","/n")
        chunkSize = len(self._data)
        headerPackStr = "<i" + str(headerSize) + "si"
        data += struct.pack(headerPackStr, headerSize, headerField, chunkSize)

        for field in self._data :
Example #28
0
    def __init__(self, *args, **kwargs):
        self.func = args[0] if len(args) == 1 and callable(args[0]) else None

        self.options = dict(settings)
        if self.func is None:
            self.options.update(Settings(**kwargs))
Example #29
0
def get_px_per_second():
    s = Settings.get_instance().get_settings()
    return int(s.Invisible.pixels_per_second)
Example #30
0
 def reportBug(self):
     QtGui.QDesktopServices.openUrl(QtCore.QUrl(Settings.get("TICKET_URL")))
Example #31
0
    def __init__(self, exc_info, *args, **kwargs):
        QtGui.QDialog.__init__(self, *args, **kwargs)

        exc_type, exc_value, traceback_object = exc_info

        dialog = self
        if kwargs.get('automatic'):
            automatic = True
        else:
            automatic = Settings.get('client/auto_bugreport', type=bool, default=True)

        self.trace = "".join(traceback.format_exception(exc_type, exc_value, traceback_object, 10))

        if automatic:
            self.title = "Bug report"
        else:
            self.title = "Report from " + CRASH_REPORT_USER + u": " + str(exc_value)

        self.bugreport_target = BugReportTarget('client',
                                                'https://github.com/FAForever/client',
                                                config.VERSION)
        self.bugreport = BugReport(self.title,
                                   target=self.bugreport_target,
                                   traceback=self.trace,
                                   automatic=automatic)

        dialog.setWindowTitle(self.title)

        description = u""
        try:
            description += (u"\n**FAF Username:** " + CRASH_REPORT_USER)
            description += (u"\n**FAF Version:** " + VERSION_STRING)
            description += (u"\n**FAF Environment:** " + config.environment)
            description += (u"\n**FAF Directory:** " + APPDATA_DIR)
            description += (u"\n**FA Path:** " + str(util.settings.value("ForgedAlliance/app/path", None, type=str)))
            description += (u"\n**Home Directory:** " + PERSONAL_DIR)
        except StandardError:
            description += (u"\n**(Exception raised while writing debug vars)**")

        log = u""
        try:
            log += (u"\n".join(readlines(LOG_FILE_FAF, False)[-128:]))
        except StandardError:
            log += (unicode(LOG_FILE_FAF))
            log += (u"empty or not readable")

        self.bugreport.description = description
        self.bugreport.log = log

        if not automatic:
            self.box = QtGui.QTextEdit()
            self.box.setFont(QtGui.QFont("Lucida Console", 8))
            self.box.append(description)
            dialog.layout().addWidget(self.box)
            dialog.setLayout(QtGui.QVBoxLayout())
            label = QtGui.QLabel()
            label.setText(
                    "An error has occurred in the FAF client. <br><br>You can report it by clicking the ticket button.")
            label.setWordWrap(True)
            dialog.layout().addWidget(label)

            label = QtGui.QLabel()
            label.setText("<b>This is what happened. If you have more to add please write in the field below.</b>")
            label.setWordWrap(False)
            dialog.layout().addWidget(label)
            self.sendButton = QtGui.QPushButton("\nReport error\n")
            self.sendButton.pressed.connect(self.post_report)

            dialog.layout().addWidget(self.sendButton)

            label = QtGui.QLabel()
            label.setText("<b></b><br/><i>(please note that the error may be fatal, proceed at your own risk)</i>")
            label.setWordWrap(False)
            dialog.layout().addWidget(label)

            self.buttons = QtGui.QDialogButtonBox()
            buttons = self.buttons
            buttons.addButton("Continue", QtGui.QDialogButtonBox.AcceptRole)
            buttons.addButton("Close FAF", QtGui.QDialogButtonBox.RejectRole)
            buttons.addButton("Help", QtGui.QDialogButtonBox.HelpRole)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            buttons.helpRequested.connect(self.tech_support)
            dialog.layout().addWidget(buttons)
        else:
            dialog.setLayout(QtGui.QVBoxLayout())
            label = QtGui.QLabel()
            label.setText("An error has occurred in the FAF client. It has been automatically reported.")
            label.setWordWrap(True)
            dialog.layout().addWidget(label)
            self.post_report()
            self.sendButton = QtGui.QPushButton("\nOK\n")
            self.sendButton.pressed.connect(dialog.accept)
            dialog.layout().addWidget(self.sendButton)
def capacity_add():
    logger = logging.getLogger(__name__)
    settings = Settings()
    all_routers = get_all_routers()
    form = AddCapacity()

    form.Region.choices = settings.get_regions_tuples()
    form.InstanceType.choices = settings.get_instances_tuples()
    form.instance_number.choices = (('1', '1'), ('2', '2'), ('3', '3'),
                                    ('4', '4'), ('5', '5'), ('6', '6'))
    unique_clusters = get_available_clusters(all_routers)
    cluster_list = []
    for i in unique_clusters:
        cluster_list.append((i, i))
    cluster_list.sort()
    form.cluster_value.choices = cluster_list

    if form.validate_on_submit():
        if form.InstanceType.data not in settings.get_region_supported_instances(
                form.Region.data):
            flash("Instance type '{}' is not available in '{}'".format(
                form.InstanceType.data, form.Region.data))
            return redirect(url_for('capacity_add'))

        cluster_already_there_result = check_router_in_region(
            all_routers, form.cluster_value.data, form.Region.data)
        if not cluster_already_there_result:
            flash("Region '{region}' does not yet contain cluster '{cluster}'."
                  " Maybe you want to extend cluster '{cluster}' into region.".
                  format(region=form.Region.data,
                         cluster=form.cluster_value.data))
            return redirect(url_for('capacity_add'))

        available_dmvpn_addresses = get_available_dmvpn_addresses(
            all_routers, form.cluster_value.data,
            int(form.instance_number.data))
        available_subnets = get_available_vpc_cidr_space(
            all_routers, form.cluster_value.data,
            int(form.instance_number.data))
        az_list = get_best_az(all_routers, form.Region.data,
                              form.cluster_value.data,
                              int(form.instance_number.data))

        hubs = list()
        for rou in all_routers:
            if (rou.cluster_value == form.cluster_value.data) and (rou.hub
                                                                   == 'True'):
                hubs.append(rou)
        cgw_template = hubs[0]
        list_router_objects = list()
        for i in range(int(form.instance_number.data)):
            list_router_objects.append(
                Cgw(Region=form.Region.data,
                    hub=False,
                    region_extension=False,
                    AvailabilityZone=az_list.pop(-1),
                    InstanceType=form.InstanceType.data,
                    asn=int(cgw_template.asn),
                    cluster_value=form.cluster_value.data,
                    available_bandwidth=Settings.instance_types[
                        form.InstanceType.data],
                    AmiId=Settings.regions[form.Region.data]['ami'],
                    max_bandwidth=Settings.instance_types[
                        form.InstanceType.data],
                    KeyName=Settings.regions[form.Region.data]['key'],
                    DmvpnAddress=available_dmvpn_addresses.pop(0),
                    DmvpnNetmask=str(
                        ipaddress.ip_network(
                            Settings.dmvpn_address_space).netmask),
                    eligible='False',
                    DmvpnCidr=Settings.dmvpn_address_space,
                    h1_public=hubs[0].PublicIp,
                    h1_private=hubs[0].DmvpnAddress,
                    h2_public=hubs[1].PublicIp,
                    h2_private=hubs[1].DmvpnAddress,
                    vpc_cidr=available_subnets.pop(0)))
        results_list = setup_capacity_add.main(list_router_objects)

        if not results_list:
            flash("Capacity add failed")
            logger.warning("Capacity add failed")
        else:
            for i in results_list:
                if i.get('success', False):
                    flash("Router '{}' successfully deployed".format(
                        i['success'].PublicIp))
                    logger.info("Router %s deployed successfully!",
                                i['success'].PublicIp)
                    if i['success'].registration_failed:
                        flash(
                            "Router '{}' failed to register with Cisco Smart Licensing"
                            .format(i['success'].PublicIp))
                        logger.info(
                            "Router %s failed to register with Cisco Smart Licensing",
                            i['success'].PublicIp)
                else:
                    flash("Router '{}' failed to deploy".format(
                        i['fail'].PublicIp))
                    logger.warning(
                        "Router %s deployment and configuration failed",
                        i['fail'].PublicIp)

        return redirect(url_for('capacity_add'))
    return render_template('capacity_add.html',
                           title='Add Capacity',
                           form=form)
Example #33
0
 def loadSettings(self):
     self.popup = Settings.get(self._settings_key + '/popup',
                               True, type=bool)
     self.sound = Settings.get(self._settings_key + '/sound',
                               True, type=bool)
Example #34
0
from config import Settings

from .sql_db import Database

# Database connection
rdbms = Database(
    uri=Settings().SQLALCHEMY_DATABASE_URI, args=Settings().SQLALCHEMY_ENGINE_OPTIONS
)
Example #35
0
 def saveSettings(self):
     Settings.set(self._settings_key+'/popup', self.popup)
     Settings.set(self._settings_key+'/sound', self.sound)
Example #36
0
import orm
import sqlalchemy
from pymessenger import Bot
from config import Settings

from activity_crawling import is_select_user_identify

PAGE_ACCESS_TOKEN = Settings().PAGE_ACCESS_TOKEN
bot = Bot(PAGE_ACCESS_TOKEN)


async def subscribed_activity(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    if not user.role_id:
        await is_select_user_identify(sender_id, headers, params)
        return

    user.subscribed = True
    user.state_id = sqlalchemy.sql.null()
    db.add(user)
    db.commit()

    bot.send_text_message(sender_id, "訂閱成功!")
    db.close()
Example #37
0
    def loadSettings(self):
        self.mode = Settings.get(self._settings_key+'/mode', 'friends')

        self.checkBoxFriends.setCheckState(QtCore.Qt.Checked if self.mode == 'friends' else QtCore.Qt.Unchecked)
        self.parent.mode = self.mode
Example #38
0
# Initialize logging system
import logging

from PyQt5.QtNetwork import QNetworkAccessManager
from enum import IntEnum

from config import Settings

logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)

# Initialize all important globals
LOBBY_HOST = Settings.get('lobby/host')
LOBBY_PORT = Settings.get('lobby/port')
LOCAL_REPLAY_PORT = Settings.get('lobby/relay/port')


class ClientState(IntEnum):
    """
    Various states the client can be in.
    """
    SHUTDOWN = -666  # Going... DOWN!

    DISCONNECTED = -2
    CONNECTING = -1
    NONE = 0
    CONNECTED = 1
    LOGGED_IN = 2


from ._clientwindow import ClientWindow
Example #39
0
from PyQt4 import QtCore, QtNetwork, QtGui

import os
import logging
import util
import fa
import json
import time

from config import Settings

INTERNET_REPLAY_SERVER_HOST = Settings.get('replay_server/host')
INTERNET_REPLAY_SERVER_PORT = Settings.get('replay_server/port')

from . import DEFAULT_LIVE_REPLAY
from . import DEFAULT_RECORD_REPLAY


class ReplayRecorder(QtCore.QObject):
    """
    This is a simple class that takes all the FA replay data input from its inputSocket, writes it to a file,
    and relays it to an internet server via its relaySocket.
    """
    __logger = logging.getLogger(__name__)

    def __init__(self, parent, local_socket, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        self.parent = parent
        self.inputSocket = local_socket
        self.inputSocket.setSocketOption(QtNetwork.QTcpSocket.KeepAliveOption,
                                         1)
Example #40
0
    def loadSettings(self):
        self.mode = Settings.get(self._settings_key + '/mode', 'friends')

        self.checkBoxFriends.setCheckState(QtCore.Qt.Checked if self.mode ==
                                           'friends' else QtCore.Qt.Unchecked)
        self.parent.mode = self.mode
Example #41
0
def configure_spoke_main(cgw):
    logger = logging.getLogger(__name__)
    settings = Settings()
    keyfile = settings.regions[cgw.Region]['key']
    result = check_responsive(cgw)
    if result == 'fail':
        clean_up(cgw)
        result = {'fail': cgw}
        return result

    try:
        hub_routers = {
            'h1_public': cgw.h1_public,
            'h1_private': cgw.h1_private,
            'h2_public': cgw.h2_public,
            'h2_private': cgw.h2_private
        }
        with open('templates/cgw_spoke_base.j2', 'r') as t:
            template_data = t.readlines()
        configuration = list()
        conf_vars_dict = dict()
        conf_vars_dict['hub_routers'] = hub_routers
        conf_vars_dict['cgw'] = cgw.__dict__
        conf_vars_dict['settings'] = dict()
        conf_vars_dict['settings']['dmvpn_password'] = settings.dmvpn_password

        for line in template_data:
            line = line.rstrip('\n')
            t = Template(line)
            new_line = t.render(conf_vars_dict)
            configuration.append(new_line)

        c = paramiko.SSHClient()
        c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        c.connect(cgw.PublicIp,
                  username='******',
                  key_filename=f'keys/{keyfile}.pem',
                  timeout=15.0)
        ssh = c.invoke_shell()
        ssh.send('config t\n')
        prompt(ssh)

        for line in configuration:
            ssh.send(line + '\n')
            prompt(ssh)

        ssh.send('end\n')
        prompt(ssh)
        ssh.send('event manager run 10interface\n')
        prompt(ssh)
        ssh.send('wr mem\n')
        prompt(ssh)
        ssh.close()
        result = {'success': cgw}
        logger.info('Redeployed spoke %s successfully configured',
                    cgw.CustomerGatewayId)
        return result
    except Exception as e:
        logger.error("Exception occurred", exc_info=True)
        clean_up(cgw)
        result = {'fail': cgw}
        return result
Example #42
0
import keras
import math
from keras.applications.vgg16 import VGG16
from keras.initializers import RandomNormal
from keras.layers import Input, Conv2D, TimeDistributed, Dense, Flatten, Dropout
from keras.models import Model
from keras import backend as K

from losses import rpn_reg_loss, rpn_cls_loss, full_model_classifier_loss, full_model_regression_loss
from config import Settings
from roi_max_pool import ROIMaxPool
from labeling import DataProvider

# A tuple of (height, width, channels). Thus data_format needs to be set to 'channels_last' when needed.
C = Settings()


def vgg_base(shape_tuple):

    # base network is just VGG16 on ImageNet weights. We extract the last convolutional layer and use it as the "top" of our network.
    vgg_model = VGG16(include_top=False, input_shape=shape_tuple)
    last_conv_layer = vgg_model.get_layer('block5_conv3')
    new_model = Model(inputs=vgg_model.input, outputs=last_conv_layer.output)
    return new_model  # has input built in already


def rpn(shared_layers):
    # here's the RPN layers
    sliding_window = Conv2D(512,
                            kernel_size=(3, 3),
Example #43
0
 def send_the_orcs():
     route = Settings.get('mordor/host')
     if _id != -1:
         QtGui.QDesktopServices.openUrl(QUrl("{}/users/{}".format(route, _id)))
     else:
         QtGui.QDesktopServices.openUrl(QUrl("{}/users/{}".format(route, name)))
Example #44
0
 def linkAccount(self):
     QtGui.QDesktopServices.openUrl(
         QtCore.QUrl(Settings.get("STEAMLINK_URL")))
Example #45
0
import util
import logging
from vault import luaparser
import warnings

import io
import zipfile
from config import Settings
from downloadManager import FileDownload
from vault.dialogs import VaultDownloadDialog, downloadVaultAsset

logger = logging.getLogger(__name__)

MODFOLDER = os.path.join(util.PERSONAL_DIR, "My Games", "Gas Powered Games",
                         "Supreme Commander Forged Alliance", "Mods")
MODVAULT_DOWNLOAD_ROOT = "{}/faf/vault/".format(Settings.get('content/host'))

installedMods = []  # This is a global list that should be kept intact.
# So it should be cleared using installedMods[:] = []

# mods selected by user, are not overwritten by temporary mods selected when joining game
selectedMods = Settings.get('play/mods', default=[])


class ModInfo(object):
    def __init__(self, **kwargs):
        self.name = "Not filled in"
        self.version = 0
        self.folder = ""
        self.__dict__.update(kwargs)
Example #46
0
 def forgotPassword(self):
     QtGui.QDesktopServices.openUrl(
         QtCore.QUrl(Settings.get("PASSWORD_RECOVERY_URL")))
def configure_main(config_results_queue, cgw):
    logger = logging.getLogger(__name__)
    settings = Settings()
    keyfile = settings.regions[cgw.Region]['key']
    result = check_responsive(cgw)
    if result == 'fail':
        result = {'fail': cgw}
        clean_up(cgw)
        config_results_queue.put(result)

    else:
        try:
            hub_routers = {
                'h1_public': cgw.h1_public,
                'h1_private': cgw.h1_private,
                'h2_public': cgw.h2_public,
                'h2_private': cgw.h2_private
            }
            with open('templates/cgw_spoke_base.j2', 'r') as t:
                template_data = t.readlines()

            configuration = list()
            conf_vars_dict = dict()
            conf_vars_dict['hub_routers'] = hub_routers
            conf_vars_dict['cgw'] = cgw.__dict__
            conf_vars_dict['settings'] = dict()
            conf_vars_dict['settings'][
                'dmvpn_password'] = settings.dmvpn_password

            for line in template_data:
                line = line.rstrip('\n')
                t = Template(line)
                new_line = t.render(conf_vars_dict)
                configuration.append(new_line)

            c = paramiko.SSHClient()
            c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            c.connect(cgw.PublicIp,
                      username='******',
                      key_filename=f'keys/{keyfile}.pem',
                      timeout=15.0)
            ssh = c.invoke_shell()
            ssh.send('config t\n')
            prompt(ssh)

            for line in configuration:
                ssh.send(line + '\n')
                prompt(ssh)

            ssh.send('end\n')
            prompt(ssh)
            ssh.send('event manager run 10interface\n')
            prompt(ssh)
            ssh.send('wr mem\n')
            prompt(ssh)
            ssh.close()
            logger.info('Successfully configured csr %s for cluster %s',
                        cgw.CustomerGatewayId, cgw.cluster_value)

            if settings.regions[cgw.Region]['smart_licensing'] == 'True':
                sl_helper = LicenseHelper(cgw)
                result, license_throughput = sl_helper.register()
                if not result:
                    cgw.eligible = 'False'
                    cgw.registration_failed = True
                    logger.warning(
                        'Smart Licensing Registration failed for router %s',
                        cgw.PublicIp)
                else:
                    cgw.eligible = settings.regions[
                        cgw.Region]['eligible_default']
                    cgw.registration_failed = False
                    # Make the available_bandwidth TAG the lesser of the Smart Licensing and instance max performance
                    if license_throughput < cgw.available_bandwidth:
                        cgw.available_bandwidth = license_throughput
                        cgw.update_available_bandwidth_tag()
            else:
                cgw.eligible = settings.regions[cgw.Region]['eligible_default']
                cgw.registration_failed = False
            cgw.update_eligible_tag()

            result = {'success': cgw}
            config_results_queue.put(result)
        except Exception as e:
            logger.error("Exception occurred", exc_info=True)
            clean_up(cgw)
            result = {'fail': cgw}
            config_results_queue.put(result)
Example #48
0
class GameEngine:

    """A class representing the game engine.

    An instance of this class is to be created each time the program
    runs.  It doesn't handle thegraphical user interface, but centralizes
    about anything else:  the main configuration, world configuration
    of different games, aliases, macros, triggers and so on.  The
    GUI has a direct access to the engine and can therefore access it.

    """

    def __init__(self):
        self.logger = logger("")
        begin()
        self.settings = Settings(self)
        self.worlds = {}
        self.default_world = None
        self.level = Level.engine
        self.logger.info("CocoMUD engine started")

    def load(self):
        """Load the configuration."""
        self.logger.info("Loading the user's configuration...")
        self.settings.load()
        self.TTS_on = self.settings["options.TTS.on"]
        self.TTS_outside = self.settings["options.TTS.outside"]

        # For each world, set the game engine
        for world in self.worlds.values():
            world.engine = self

    def open(self, host, port, world):
        """Connect to the specified host and port.

        This method creates and returns a 'GUIClient' class initialized
        with the specified information.

        """
        self.logger.info("Creating a client for {host}:{port}".format(
                host=host, port=port))

        client = GUIClient(host, port, engine=self, world=world)
        sharp_engine = SharpScript(self, client, world)
        world.client = client
        client.sharp_engine = sharp_engine
        world.sharp_engine = sharp_engine
        return client

    def open_help(self, name):
        """Open the selected help file in HTML format.

        This method open the browser with the appropriate file.
        The file is the one in the user's language, unless it cannot
        be found.

        """
        lang = self.settings.get_language()
        filename = name + ".html"
        path = os.path.join("doc", lang, filename)
        if os.path.exists(path):
            self.logger.debug("Open the help file for {} (lang={})".format(
                    name, lang))
            os.startfile(path)
            return

        # Try English
        path = os.path.join("doc", "en", filename)
        if os.path.exists(path):
            self.logger.debug("Open the help file for {} (lang=en)".format(
                    name))
            os.startfile(path)
            return

        # Neither worked
        self.logger.debug("The documentation for the {} help file " \
                "cannot be found, either using lang={} or lang=en".format(
                name, lang))

    def get_world(self, name):
        """Return the selected world either by its name or location."""
        name = name.lower()
        for world in self.worlds.values():
            if world.name.lower() == name:
                return world
            elif world.location == name:
                return world

        return None

    def create_world(self, name):
        """Create a world."""
        world = World(name.lower())
        world.engine = self
        return world

    def prepare_world(self, world, merge=None):
        """Prepare the world, creating appropriate values."""
        if not world.sharp_engine:
            sharp_engine = SharpScript(self, None, world)
            world.sharp_engine = sharp_engine

        if merge is not None:
            if merge == "ignore":
                world.merging = MergingMethod.ignore
            elif merge == "replace":
                world.merging = MergingMethod.replace
            else:
                raise ValueError("unkwno merging method: {}".format(
                        merge))

    def stop(self):
        """Stop the game engine and close the sessions."""
        end()
def build_main(results_queue, cgw):
    logger = logging.getLogger(__name__)
    settings = Settings()
    try:
        ec2 = boto3.resource('ec2', region_name=cgw.Region)

        client = boto3.client('ec2', region_name=cgw.Region)

        response = client.allocate_address(Domain='vpc')
        cgw.eip_AllocationId = response['AllocationId']
        cgw.PublicIp = response['PublicIp']

        vpc = ec2.create_vpc(CidrBlock=cgw.vpc_cidr)
        time.sleep(5)
        cgw.VpcId = vpc.id
        vpc.wait_until_available()
        vpc.create_tags(Tags=[{
            "Key": "Name",
            "Value": "transit_vpc"
        }, {
            "Key": settings.tvpc_program_key,
            "Value": cgw.cluster_value
        }])

        ig = ec2.create_internet_gateway()
        vpc.attach_internet_gateway(InternetGatewayId=ig.id)

        # create a route table and route to igw
        route_table = vpc.create_route_table()
        route_table.create_route(DestinationCidrBlock='0.0.0.0/0',
                                 GatewayId=ig.id)

        subnet_1 = ec2.create_subnet(AvailabilityZone=cgw.AvailabilityZone,
                                     CidrBlock=cgw.vpc_cidr,
                                     VpcId=vpc.id)
        route_table.associate_with_subnet(SubnetId=subnet_1.id)

        sec_group = ec2.create_security_group(GroupName='tvpc security group',
                                              Description='tvpc ipsec',
                                              VpcId=vpc.id)

        sec_group.authorize_ingress(
            IpPermissions=[{
                'FromPort': 4500,
                'IpProtocol': 'udp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 4500
            }, {
                'FromPort': 0,
                'IpProtocol': '50',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 0
            }, {
                'FromPort': 500,
                'IpProtocol': 'udp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 500
            }, {
                'FromPort': 22,
                'IpProtocol': 'tcp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 22
            }])

        instance_1 = ec2.create_instances(ImageId=cgw.AmiId,
                                          InstanceType=cgw.InstanceType,
                                          MaxCount=1,
                                          MinCount=1,
                                          KeyName=cgw.KeyName,
                                          NetworkInterfaces=[{
                                              'SubnetId':
                                              subnet_1.id,
                                              'DeviceIndex':
                                              0,
                                              'AssociatePublicIpAddress':
                                              True,
                                              'Groups': [sec_group.group_id]
                                          }],
                                          TagSpecifications=[{
                                              'ResourceType':
                                              'instance',
                                              'Tags': [{
                                                  'Key':
                                                  settings.tvpc_program_key,
                                                  'Value':
                                                  cgw.cluster_value
                                              }]
                                          }])
        instance_1[0].wait_until_running()

        cgw.InstanceId = instance_1[0].id

        response = client.associate_address(
            AllocationId=cgw.eip_AllocationId,
            InstanceId=instance_1[0].id,
        )
        cgw.eip_AssociationId = response['AssociationId']

        ec2.create_tags(Resources=[
            instance_1[0].id, ig.id, route_table.id, subnet_1.id, sec_group.id,
            cgw.eip_AllocationId
        ],
                        Tags=[
                            {
                                'Key': 'Name',
                                'Value': cgw.PublicIp
                            },
                            {
                                'Key': settings.tvpc_program_key,
                                'Value': cgw.cluster_value
                            },
                            {
                                'Key': 'tvpc_hub',
                                'Value': str(cgw.hub)
                            },
                            {
                                'Key': 'tvpc_region_extension',
                                'Value': str(cgw.region_extension)
                            },
                            {
                                'Key': 'tvpc_eligible',
                                'Value': 'False'
                            },
                            {
                                'Key': 'tvpc_asn',
                                'Value': str(cgw.asn)
                            },
                            {
                                'Key': 'tvpc_available_bandwidth',
                                'Value': str(cgw.available_bandwidth)
                            },
                            {
                                'Key': 'tvpc_vpc_cidr',
                                'Value': cgw.vpc_cidr
                            },
                            {
                                'Key': 'tvpc_DmvpnAddress',
                                'Value': cgw.DmvpnAddress
                            },
                        ])
        response = client.create_customer_gateway(BgpAsn=cgw.asn,
                                                  PublicIp=cgw.PublicIp,
                                                  Type='ipsec.1')
        cgw.CustomerGatewayId = response['CustomerGateway'][
            'CustomerGatewayId']
        ec2.create_tags(Resources=[
            cgw.CustomerGatewayId,
        ],
                        Tags=[
                            {
                                'Key': 'Name',
                                'Value': cgw.PublicIp
                            },
                            {
                                'Key': settings.tvpc_program_key,
                                'Value': cgw.cluster_value
                            },
                            {
                                'Key': 'InstanceId',
                                'Value': cgw.InstanceId
                            },
                        ])
        result = {'success': cgw}
        results_queue.put(result)
        logger.info('Successfully built extension VPC %s', vpc.id)
    except Exception as e:
        logger.error("Exception occurred", exc_info=True)
        clean_up(cgw)
        result = {'fail': cgw}
        results_queue.put(result)
Example #50
0
 def viewAliases(self):
     QtGui.QDesktopServices.openUrl(QUrl("{}?name={}".format(Settings.get("NAME_CHANGE_URL"), self.name)))
Example #51
0
import pygame
import pygame.locals
import sys
import cv2
from udp import udp
from config import Settings
from controller import keyboard
from event import KeyboardControlState

settings = Settings('settings.ini')
keyboardControlState = KeyboardControlState()

udp_client_enabled = settings.getParser().getboolean('default',
                                                     'udp_client_enabled')
video_enabled = settings.getParser().getboolean('default',
                                                'video_streaming_enabled')
width_height = (settings.getParser().getint('default', 'window_width'),
                settings.getParser().getint('default', 'window_height'))
video_stream_url = (settings.getParser().get('default', 'video_stream_url'))

if video_enabled:
    stream = cv2.VideoCapture(video_stream_url)


def init():
    pygame.init()
    keyboard.init_keyboard()
    return create_window()


def create_window():
Example #52
0
import stat
import struct
import shutil
import urllib.request, urllib.error, urllib.parse
import zipfile
import tempfile
import re
# module imports
import fa
# local imports
from config import Settings
from vault.dialogs import downloadVaultAssetNoMsg

logger = logging.getLogger(__name__)

route = Settings.get('content/host')
VAULT_PREVIEW_ROOT = "{}/faf/vault/map_previews/small/".format(route)
VAULT_DOWNLOAD_ROOT = "{}/faf/vault/".format(route)
VAULT_COUNTER_ROOT = "{}/faf/vault/map_vault/inc_downloads.php".format(route)

from model.game import OFFICIAL_MAPS as maps

__exist_maps = None


def isBase(mapname):
    """
    Returns true if mapname is the name of an official map
    """
    return mapname in maps
Example #53
0



from PyQt4 import QtCore, QtNetwork, QtGui

import os
import logging
import util
import fa
import json
import time

from config import Settings

INTERNET_REPLAY_SERVER_HOST = Settings.get('replay_server/host')
INTERNET_REPLAY_SERVER_PORT = Settings.get('replay_server/port')

from . import DEFAULT_LIVE_REPLAY
from . import DEFAULT_RECORD_REPLAY

class ReplayRecorder(QtCore.QObject): 
    """
    This is a simple class that takes all the FA replay data input from its inputSocket, writes it to a file,
    and relays it to an internet server via its relaySocket.
    """
    __logger = logging.getLogger(__name__)

    def __init__(self, parent, local_socket, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        self.parent = parent