示例#1
0
文件: tab.py 项目: Draak145/AtysRoom
 def addGuildPopup(self):
     key, comment, ok = AddGuildDialog.getGuild(self)
     if ok:
         self.addGuild(key, comment)
         self.guilds.append((key, comment))
         AppSettings.get().setValue("guilds", self.guilds)
         print(AppSettings.get().value("guilds"))
示例#2
0
文件: main.py 项目: Draak145/AtysRoom
def main():    
    app = QtGui.QApplication(sys.argv)
    QtCore.QCoreApplication.setOrganizationName("atysRoom")
    QtCore.QCoreApplication.setApplicationName("atysRoom")
    AppSettings.get()
    w = MainWindow()
    
    sys.exit(app.exec_())
示例#3
0
    def __init__(self, app):
        super(MainWindow, self).__init__()

        self.app = app

        # Set up the user interface from Designer
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        # wire up the UI
        self.ui.closeButton.clicked.connect(self.closeapp)
        self.ui.applyButton.clicked.connect(self.applysettings)
        self.ui.clipboardButton.clicked.connect(self.copytoclipboard)
        self.ui.portsandsensorscheckBox.stateChanged.connect(
            self.toggleportsandsensors)

        self.apptrayicon = AppTrayIcon(self)
        self.apptrayicon.onHide.connect(self.onHide)
        self.apptrayicon.onRestore.connect(self.onRestore)

        self.ui.statusEdit.setStyleSheet(self.COLOR_TXT)
        self.ui.settingsEdit.setStyleSheet(self.COLOR_TXT)

        self.setWindowIcon(self.apptrayicon.icon)

        self.setWindowTitle(APP_TITLE)
        self.setFixedSize(self.size())

        # application logic
        self.appsettings = AppSettings()
        jsontxt = self.appsettings.getjson()
        self.ui.settingsEdit.setPlainText(jsontxt)
        self.ui.settingsEdit.keyPressEvent = self.keyPressClosure(
            self.ui.settingsEdit)

        self.controller = Controller(self.appsettings)
        self.controller.uiUpdate.connect(self.update)

        startminimized = False
        if (self.appsettings.ok):
            startminimized = self.appsettings.settings["app"]["startminimized"]
            self.controller.start()
        else:
            # there may be a case when json is manually edited and corrupted.
            # we cannot start normally in this case.
            with StrStream() as x:
                print(
                    "Error reading settings from file.\nFan control cannot start."
                )
                print()
                print(self.appsettings.errorMessage)
            self.ui.statusEdit.setStyleSheet(self.COLOR_ERR)
            self.ui.statusEdit.setPlainText(x.data)

        if (not startminimized):
            self.show()
            self.controller.enableUICallbacks = True
示例#4
0
文件: api.py 项目: Draak145/AtysRoom
 def __init__(self, page, cacheFile, contentType = None):
     self.url = "http://atys.ryzom.com/api/"+page
     self.cacheFile = AppSettings.get().getPath()+"/cache/"+cacheFile
     self.contentType = contentType
     print(self.cacheFile)
     
     if os.path.isfile(self.cacheFile):
         self.data = self.readCache()
     else:
         self.update()
示例#5
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.images: Dict[str, Layer] = {}

        self.projectSettings: ProjectSettings = ProjectSettings()
        self.appSettings: AppSettings = AppSettings()
        self.loadAppSettings()
        self.connectActions()
示例#6
0
文件: app.py 项目: raikel/anvid
    def __init__(self):
        super(MainWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.connectActions()

        self.videoAnnoWidget = VideoAnnoWidget(self)
        self.setCentralWidget(self.videoAnnoWidget)

        self.project: Project = Project()
        self.appSettings: AppSettings = AppSettings()
        self.loadAppSettings()
示例#7
0
    def loadAppSettings(self):

        try:
            self.appSettings = AppSettings.load()
        except Exception as err:
            logger.error(err)

        self.ui.pos = self.appSettings.mainWindowPos
        self.ui.size = self.appSettings.mainWindowSize

        lastProjectPath = self.appSettings.lastProjectPath
        if utils.fileExists(lastProjectPath):
            self.loadProjectFile(lastProjectPath)
        self.updateRecentProjectsActions()
示例#8
0
文件: tab.py 项目: Draak145/AtysRoom
 def __init__(self):
     super(GuildsTab, self).__init__()
     
     self.vLayout = QtGui.QVBoxLayout(self)
     
     self.hLayout = QtGui.QHBoxLayout()
     self.vLayout.addLayout(self.hLayout)
     
     self.addGuildButton = QtGui.QPushButton("Add")
     self.hLayout.addWidget(self.addGuildButton)
     self.addGuildButton.clicked.connect(self.addGuildPopup)
     
     self.editGuildButton = QtGui.QPushButton("Edit")
     self.hLayout.addWidget(self.editGuildButton)
     
     self.deleteGuildButton = QtGui.QPushButton("Delete")
     self.hLayout.addWidget(self.deleteGuildButton)
     
     self.guildRoomButton = QtGui.QPushButton("Room")
     self.hLayout.addWidget(self.guildRoomButton)
     
     self.hLayout.addStretch(1)
     
     self.guildsTable = QtGui.QTableWidget()
     self.guildsTable.setColumnCount(3)
     
     self.guildsTable.setHorizontalHeaderLabels(["Guild", "Comment", "Key"])
     self.guildsTable.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
     self.guildsTable.horizontalHeader().setMinimumSectionSize(150)
     
     self.guildsTable.verticalHeader().hide()
     self.guildsTable.verticalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
     
     self.guildsTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
     self.guildsTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
     self.guildsTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
     self.guildsTable.setIconSize(QtCore.QSize(32, 32))
     self.guildsTable.doubleClicked.connect(self.openGuildView)
     
     self.guilds = AppSettings.get().value("guilds", [])
     self.guildClasses = {}
     self.setUpTable()
     
     self.vLayout.addWidget(self.guildsTable)
示例#9
0
from .asset_template import Asset
from .bitcoin_address_format_checker import Checker
from .create_user import User
from bigchaindb_driver import BigchainDB
from settings import AppSettings
from hypothesis import given, settings, Verbosity, assume
from hypothesis.strategies import text

app_setting = AppSettings.get_settings()


def test_good_address():
    chk = Checker('1AMb4wcaZ7wZDLJ8frgjX9UZwcXs2mWRW8')
    assert chk.check_address() is True


def test_bad_checksum_address():
    chk = Checker('12Mb4wcaZ7wZDLJ8frgjX9UZwcXs2mWRW6')
    assert chk.check_address() is False


def test_short_address():
    chk = Checker('1AMb4wcaZ7wZDLJ8')
    assert chk.check_address() is False


def test_long_address():
    chk = Checker('12Mb4wcaZ7wZDLJ8frgjX9UZwcXs2mWRW61AMb4wcaZ7wZDLJ8frgjX9UZwcXs2mWRW8')
    assert chk.check_address() is False

from utils import webCrawl
from utils import readConfig
from utils.dataRequest import DataRequest, PostHandler
from urls import urls, Authenticated
from settings import AppSettings
import hashlib
reload(sys)
sys.setdefaultencoding("utf-8")

__author__ = 'Lei Ji'

# configure the service settings
# web.config.debug = False
render = web.template.render("./templates/")
app = web.application(urls, globals())
configs = AppSettings()
configs.sessionConfig()
db = configs.db
bicopyright = '<p id="copyright"> Author: Lei Ji. All rights reserved.<p>'

if web.config.get('_session') is None:
    #store = web.session.DBStore(self.db, 'sessions')  # for later test, use database to store session
    store = web.session.DiskStore('sessions')
    session = web.session.Session(app, store, initializer={'login': 0, 'privilege': 0})
    web.config._session = session
else:
    session = web.config._session

# login page service
class login:
    def GET(self):
示例#11
0
def main():
    # load the settings
    settings = AppSettings()

    parser = argparse.ArgumentParser(
        description="Create time window statistics for pcap stream or file"
    )
    parser.add_argument(
        "-s",
        "--sourcefile",
        default=settings.input_file_name,
        help="provide a pcap input file name instead of reading live stream",
        action="store",
    )
    parser.add_argument(
        "-i",
        "--interface",
        default=settings.interface,
        help="use an interface.  [" + settings.interface + "]",
        action="store",
    )
    parser.add_argument(
        "-l",
        "--howlong",
        default=settings.how_long,
        help="number of seconds to run live mode. [" + str(settings.how_long) + "]",
        action="store",
        type=int,
    )
    parser.add_argument(
        "-o",
        "--outfile",
        default=settings.output_file_name,
        help="change the name of the output file [" + settings.output_file_name + "]",
        action="store",
    )
    parser.add_argument(
        "-w",
        "--window",
        default=settings.time_window,
        help="time window in msec [" + str(settings.time_window) + "]",
        action="store",
        type=int,
    )
    parser.add_argument(
        "-t",
        "--tshark",
        default=settings.tshark_program,
        help="tshark program [" + settings.tshark_program + "]",
        action="store",
    )
    args = parser.parse_args()
    print("main:main Running with: ", vars(args))

    if args.sourcefile:
        settings.input_file_name = args.sourcefile
    if args.interface:
        settings.interface = args.interface
    if args.howlong:
        settings.how_long = args.howlong
    if args.outfile:
        settings.output_file_name = args.outfile
    if args.window:
        settings.time_window = args.window
    if args.tshark:
        settings.tshark_program = args.tshark

    data_collect = PacketCapture(
        "packet capture packet_dict",
        settings.tshark_program,
        settings.input_file_name,
        settings.interface,
        settings.how_long,
        queues.sharedQ,
    )
    data_c_p = data_collect.start()

    data_process = PacketAnalyse(
        "packet analyzing thread", queues.sharedQ, queues.serviceQ
    )
    data_p_p = data_process.start()

    services_process = ServiceIdentity(
        "service detecter", queues.serviceQ, queues.timesQ
    )
    services_p_p = services_process.start()

    time_counts = TimesAndCounts(
        "time the packets",
        settings.time_window,
        settings.output_file_name,
        queues.timesQ,
    )
    time_c_p = time_counts.start()

    try:
        time_c_p.wait
    except KeyboardInterrupt:
        # This does not reliably clean up :-(
        # Without cleanup have to do this on dev box pkill -f tshark and pkill -f python3
        data_c_p.terminate()
        data_p_p.terminate()
        services_p_p.terminate()
        time_c_p.terminate()
示例#12
0
# dataRes = sourceDB.execQuery()
# data = dataRes.fetchall()
# sourceDB.connClose()

# for table in data:
#     #import pdb; pdb.set_trace()
#     obj = DataConverter(table[0])
#     obj.insertDataIntoDest()
#     obj.dataTest()

# from utils.dataRequest import DataRequest

# import pdb; pdb.set_trace()
# obj = DataRequest()
# err_data = obj.errDataRequest(item='unfixed')

from utils import readConfig
from utils.dataRequest import DataRequest, PostHandler
from urls import urls, Authenticated
from settings import AppSettings

import pdb

pdb.set_trace()
configs = AppSettings()
configs.sessionConfig()
db = configs.db
db.connOpen()
db.sqlQuery = "select count(*) from Sample_Users where email='" + '*****@*****.**' + "'"
result = db.execQuery()
示例#13
0
import sys
from flask import Flask
from flask_restful import Api, Resource, reqparse
from bigchaindb_driver import BigchainDB
from settings import AppSettings
# from flask_jwt import JWT, jwt_required, current_identity
# from werkzeug.security import safe_str_cmp

sys.path.append('./Asset_Handling/')
from Asset_Handling.exceptions import InvalidAliasException

app = Flask(__name__)
api = Api(app)
settings = AppSettings.get_settings()
# class ApiUser(object):
#
#     def __init__(self, asset):
#         self.id - asset.transaction_id
#         self.username = asset.username
#         self.password = asset.password

app.secret_key = settings['secret_key']


class Query(Resource):
    BDB = BigchainDB(settings['bigchainurl'])

    # TODO: add jwt auth to this
    # @jwt_required()
    def get(self):
        parser = reqparse.RequestParser()
示例#14
0
from dataclasses import dataclass
from typing import Optional, Union, Callable, Coroutine, Iterable, AsyncIterable

import discord
from discord.ext import commands
from discord.ext.commands import MemberConverter, Context, TooManyArguments, ArgumentParsingError, BadArgument

from deepl import DeeplApi, DeeplApiLanguage
from settings import AppSettings

_MESSAGE_HISTORY_LIMIT: int = 100

_COMMAND_PREFIX: str = '!'

settings: AppSettings = AppSettings.from_file()
translator: DeeplApi = DeeplApi(settings.deepl_token)
bot: commands.Bot = commands.Bot(command_prefix=_COMMAND_PREFIX)


@bot.command()
async def ping(context: commands.Context) -> None:
    await context.send('Pong')


@dataclass
class TranslateArguments:
    source_language: Optional[DeeplApiLanguage]
    target_language: DeeplApiLanguage
    target_member: Optional[discord.Member]

示例#15
0
class MainWindow(QMainWindow):
    app = None
    appsettings = None
    controller = None
    apptrayicon = None

    COLOR_TXT = "color: rgb(20, 20, 20);"
    COLOR_ERR = "color: rgb(255, 32, 32);"

    def __init__(self, app):
        super(MainWindow, self).__init__()

        self.app = app

        # Set up the user interface from Designer
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        # wire up the UI
        self.ui.closeButton.clicked.connect(self.closeapp)
        self.ui.applyButton.clicked.connect(self.applysettings)
        self.ui.clipboardButton.clicked.connect(self.copytoclipboard)
        self.ui.portsandsensorscheckBox.stateChanged.connect(
            self.toggleportsandsensors)

        self.apptrayicon = AppTrayIcon(self)
        self.apptrayicon.onHide.connect(self.onHide)
        self.apptrayicon.onRestore.connect(self.onRestore)

        self.ui.statusEdit.setStyleSheet(self.COLOR_TXT)
        self.ui.settingsEdit.setStyleSheet(self.COLOR_TXT)

        self.setWindowIcon(self.apptrayicon.icon)

        self.setWindowTitle(APP_TITLE)
        self.setFixedSize(self.size())

        # application logic
        self.appsettings = AppSettings()
        jsontxt = self.appsettings.getjson()
        self.ui.settingsEdit.setPlainText(jsontxt)
        self.ui.settingsEdit.keyPressEvent = self.keyPressClosure(
            self.ui.settingsEdit)

        self.controller = Controller(self.appsettings)
        self.controller.uiUpdate.connect(self.update)

        startminimized = False
        if (self.appsettings.ok):
            startminimized = self.appsettings.settings["app"]["startminimized"]
            self.controller.start()
        else:
            # there may be a case when json is manually edited and corrupted.
            # we cannot start normally in this case.
            with StrStream() as x:
                print(
                    "Error reading settings from file.\nFan control cannot start."
                )
                print()
                print(self.appsettings.errorMessage)
            self.ui.statusEdit.setStyleSheet(self.COLOR_ERR)
            self.ui.statusEdit.setPlainText(x.data)

        if (not startminimized):
            self.show()
            self.controller.enableUICallbacks = True

    def keyPressClosure(self, uiControl):
        """Wraps event with a closure to avoid subclassing PlainTextEdit"""
        baseEvent = uiControl.keyPressEvent

        # apply settings on Ctrl+Enter
        def settingsKeyPressEvent(event):
            if (event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter) \
                and event.modifiers() & Qt.ControlModifier:
                self.applysettings()
            else:
                baseEvent(event)

        return settingsKeyPressEvent

    def changeEvent(self, event):
        # tracks mimimize/restore events
        if event.type() == QEvent.WindowStateChange:
            if self.windowState() & Qt.WindowMinimized:
                self.apptrayicon.minimizeToTray()
            elif event.oldState() & Qt.WindowMinimized:
                #print ("window restore event")
                self.onRestore()
        super().changeEvent(event)

    def closeEvent(self, event):
        closeToSystemTray = False
        if (self.appsettings.ok):
            closeToSystemTray = self.appsettings.settings["app"]["closetotray"]
        if (closeToSystemTray and not self.apptrayicon.closeConfirmed):
            # instead of closing the app minimize it to tray
            self.apptrayicon.minimizeToTray()
            event.ignore()
        else:
            # close app for real, cleanup on application exit
            self.controller.stop()
            event.accept()

    def onRestore(self):
        self.controller.enableUICallbacks = True
        txt = self.ui.statusEdit.toPlainText()
        if (txt == ""): self.ui.statusEdit.setPlainText("Updating status...")
        #print ("window restored/maximized/fullscreen")

    def onHide(self):
        self.controller.enableUICallbacks = False
        #print ("window minimized")

    def closeapp(self):
        # button pressed: close app
        self.apptrayicon.doClose()

    def toggleportsandsensors(self):
        self.ui.statusEdit.setPlainText("updating...")

    def copytoclipboard(self):
        # button pressed: copy to clipboard
        cb = self.app.clipboard()
        txt = self.ui.statusEdit.toPlainText()
        cb.setText(txt)
        self.ui.statusEdit.setPlainText("Copied to clipboard.")

    def applysettings(self):
        # button pressed: update settings
        jsontxt = self.ui.settingsEdit.toPlainText()
        self.ui.statusEdit.setStyleSheet(self.COLOR_TXT)
        self.ui.statusEdit.setPlainText("Updating settings...")
        # apply new settings and save to file if no errors
        self.appsettings.parse(jsontxt, save=True)

    def update(self, data):
        # Displays current status in the UI
        # Connected to the signal from the polling thread.
        # When the window is not mimimized, updates UI every 1000 ms
        sensors = data["sensors"]
        signals = data["signals"]
        fans = data["fans"]
        speed = data["fanspeed"]
        fannames = []
        for f in range(1, NZXTGrid.NUM_FANS + 1):
            fan = self.appsettings.settings["policy"]["fan" + str(f)]
            fannames.append(fan["name"])

        with StrStream() as x:  # dump the current status into a string:
            err = False
            # if there are any errors, print the error messages instead of real-time data
            if (not self.appsettings.ok):
                err = True
                print(self.appsettings.errorMessage)
                print()
                print()
            if (not self.controller.ok):
                err = True
                print(self.controller.errorMessage)
                print()
                print()
            if (not self.controller.hamon.ok):
                err = True
                print(self.controller.hamon.errorMessage)
                print()
                print()
            if (not self.controller.grid.ok):
                err = True
                print(self.controller.grid.errorMessage)
                print()
                self.listports()

            if (not err):
                # print current status
                self.ui.statusEdit.setStyleSheet(self.COLOR_TXT)
                portsandsensors = self.ui.portsandsensorscheckBox.isChecked()
                if (portsandsensors):
                    self.listports()
                    self.printsensors(sensors)
                self.printsignals(signals)
                self.printfans(fannames, fans, speed)
                if (portsandsensors and self.appsettings.gridstats):
                    print("\nGrid reads: {0}, writes: {1}, errors: {2}".format(
                        self.controller.grid.readCount,
                        self.controller.grid.writeCount,
                        self.controller.grid.errorCount))
            else:
                self.ui.statusEdit.setStyleSheet(self.COLOR_ERR)

        # Output rendered string to the UI
        self.ui.statusEdit.setPlainText(x.data)

    # Various functions for printing various data
    def listports(self):
        ports = list_comports()
        print("COM ports on this computer:")
        for port in ports:
            device, description, hardwareID = port
            #print("  {:10}{:30}{:30}".format(device, description, hardwareID))
            print("  {:10}{:30}".format(device, description))
        if len(ports) == 0:
            print("  No ports detected")
        print()

    def printsensors(self, sensors):
        print("Sensor readings (\u2103):")
        if len(sensors) == 0:
            print("  No data available")
        else:
            for sensor in sensors:
                print("  {:20}{:20}{:>4.1f}".format(sensor.parent, sensor.name,
                                                    sensor.value))
        print()

    def printsignals(self, signals):
        print(u"Temperature signals (\u2103):")
        for sname in signals.keys():
            s = signals[sname]
            print("  {0} - {1:>4.1f}  [{2:>4.1f} .. {3:>4.1f}]".format(
                sname.upper(), s.value, s.min, s.max))
        if len(signals) == 0:
            print("  No data available")
        print()

    def printfans(self, fannames, fandata, speeddata):
        print("Fans:")
        index = 0
        for d in fandata:
            fanid, rpm, voltage, amperage = d
            fanname = fannames[index]
            fanspeed = speeddata[index]
            if (fanname != ""):
                print("  {0:14} {1:4.0f}% {2:7d} rpm {3:8.2f} V".format(
                    fanname, fanspeed, rpm, voltage))  #amperage*1000
            index += 1
        if len(fandata) == 0:
            print("  No fan data available")
        return self._database_path

    @property
    def database(self):
        return self._database

    @property
    def database_proxy(self):
        return self._database_proxy

    # singleton
    instance = None

    @classmethod
    def get(cls):
        if cls.instance is None:
            cls.instance = cls()
        return cls.instance


RepoConfig().get().set_database_path(AppSettings.get().database_path)

#DATABASE_PROXY.initialize(DATABASE)
# DATABASE_PATH = './my_database_2.db'
# DATABASE = SqliteDatabase(DATABASE_PATH)
# DATABASE_PROXY = Proxy()
# DATABASE_PROXY.initialize(DATABASE)

# def set_database_path(path):
#     DATABASE_PATH = path
#     DATABASE_PROXY.initialize(SqliteDatabase(DATABASE_PATH))
示例#17
0
def showConsole():
    appsettings = AppSettings()
    controller = Controller(appsettings)
    controller.start()
    pause()
    controller.stop()