示例#1
0
class MainWindow(QMainWindow):
    def __init__(self, appctxt):
        super(MainWindow, self).__init__()
        self.setWindowTitle("EncryptiiChat")
        self.appctxt = appctxt
        with open(self.appctxt.get_resource("config.json")) as f:
            cfg = json.load(f)
            server = cfg['server']
            port = int(cfg['port'])
        stylesheet = self.appctxt.get_resource('style.qss')
        self.setStyleSheet(open(stylesheet).read())
        print(server, port)
        self.server_exec = Executer(
            (server, port), alias_url=self.appctxt.get_resource("alias.json"))
        atexit.register(self.server_exec.on_exit)
        self.mainWidget = ChatWindow(self.server_exec, self.appctxt)
        self.setCentralWidget(self.mainWidget)

    def closeEvent(self, event):
        print("close")
        if self.server_exec.not_logged_in():
            return
        while True:
            try:
                rsp = self.server_exec.exec_("offline")
                if rsp != False:
                    print(rsp)
                    break
            except:
                continue
示例#2
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setWindowTitle("Chat application")
     self.server_exec = Executer(("202.182.119.187", 6000))
     atexit.register(self.server_exec.on_exit)
     self.setStyleSheet(open("style.qss", "r").read())
     self.mainWidget = ChatWindow(self.server_exec)
     self.setCentralWidget(self.mainWidget)
示例#3
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setWindowTitle("Chat application")
     with open("config.json") as f:
         cfg = json.load(f)
         server = cfg['server']
         port = int(cfg['port'])
     print(server, port)
     self.server_exec = Executer((server, port))
     atexit.register(self.server_exec.on_exit)
     self.setStyleSheet(open("style.qss", "r").read())
     self.mainWidget = ChatWindow(self.server_exec)
     self.setCentralWidget(self.mainWidget)
示例#4
0
文件: habitat.py 项目: hansl/habitat
    def __init__(self, should_start=True, *args, **kwargs):
        self.habitat_name = self.__class__.__name__
        super(Habitat, self).__init__(name='%(habitat_name)s')
        self.executer = Executer(self)
        self._args = args
        self._port_map = {}

        # We absolutely need a metadata file.
        metadata_path = self['metadata_path']
        if not os.path.exists(os.path.dirname(metadata_path)):
            os.makedirs(os.path.dirname(metadata_path))
        self.metadata = MetaDataFile(metadata_path)

        for name, component in self.get_all_components().iteritems():
            component.habitat = self
            component.name = name
            if component.name not in self.metadata:
                self.metadata[component.name] = {}
            component.metadata = self.metadata[component.name]

        # If we should start the Habitat, run the first argument as a command.
        if should_start:
            if self._args:
                command = self._args[0]
            else:
                command = 'run'
            self.command(command, *self._args[1:])
示例#5
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Chat application")
        with open("config.json") as f:
            cfg = json.load(f)
            server = cfg['server']
            port = int(cfg['port'])
        print(server, port)
        self.server_exec = Executer((server, port))
        atexit.register(self.server_exec.on_exit)
        self.setStyleSheet(open("style.qss", "r").read())
        self.mainWidget = ChatWindow(self.server_exec)
        self.setCentralWidget(self.mainWidget)

    def closeEvent(self, event):
        print("close")
        while True:
            try:
                rsp = self.server_exec.exec_("offline")
                if rsp != False:
                    print(rsp)
                    break
            except:
                continue
示例#6
0
文件: gui.py 项目: Altynai/imdb
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.logger = logging.getLogger()
        self.runner = Executer()

        self.setWindowTitle(u'内存数据库')
        self.centralWidget = QtGui.QTabWidget()
        self.tabWidge = QtGui.QTabWidget()
        vbox = QtGui.QVBoxLayout(self)
        
        self.initActionTableWidget()
        self.newFile()
        self.initMenuBar()
        self.statusBar()

        splitter = QtGui.QSplitter(QtCore.Qt.Vertical)
        splitter.addWidget(self.tabWidge)
        splitter.addWidget(self.actionTableWidget)

        vbox.addWidget(splitter)
        self.centralWidget.setLayout(vbox)
        self.setCentralWidget(self.centralWidget)

        screen = QtGui.QDesktopWidget().screenGeometry()
        self.setGeometry(screen.width() * 0.3, screen.height() * 0.3, screen.width() * 0.5, screen.height() * 0.6)
示例#7
0
 def __init__(self, appctxt):
     super(MainWindow, self).__init__()
     self.setWindowTitle("EncryptiiChat")
     self.appctxt = appctxt
     with open(self.appctxt.get_resource("config.json")) as f:
         cfg = json.load(f)
         server = cfg['server']
         port = int(cfg['port'])
     stylesheet = self.appctxt.get_resource('style.qss')
     self.setStyleSheet(open(stylesheet).read())
     print(server, port)
     self.server_exec = Executer(
         (server, port), alias_url=self.appctxt.get_resource("alias.json"))
     atexit.register(self.server_exec.on_exit)
     self.mainWidget = ChatWindow(self.server_exec, self.appctxt)
     self.setCentralWidget(self.mainWidget)
示例#8
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Chat application")
        self.server_exec = Executer(("202.182.119.187", 6000))
        atexit.register(self.server_exec.on_exit)
        self.setStyleSheet(open("style.qss", "r").read())
        self.mainWidget = ChatWindow(self.server_exec)
        self.setCentralWidget(self.mainWidget)

    def closeEvent(self, event):
        print("close")
        while True:
            try:
                rsp = self.server_exec.exec_("offline")
                if rsp != False:
                    print(rsp)
                    break
            except:
                continue
示例#9
0
文件: jarvis.py 项目: giosch/jarvis
import audioop
from collections import deque
import subprocess
import math
import time
from executer import Executer

DEBUG = 1


def plog(s):
    if DEBUG:
        print s


myExecuter = Executer()

CHUNK = 1024  # CHUNKS of bytes to read each time from mic
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
#finally is in DB!!!
THRESHOLD = 60
#number of frame over the THRESHOLD to define the command started
FRAME_TO_START = 10
FRAME_TO_STOP = 3
ACTIVATION_TOKEN = 'wake up jarvis'
# TOKEN_THRESHOLD = '1e-35' # for silence
TOKEN_THRESHOLD = 1e-30

modeldir = "model"
示例#10
0
import sys
from statements import Factory as StatementFactory
from lexer import tokenize
from executer import Executer
from tracer import is_debug
"""

"""
if __name__ == '__main__':
    try:
        filename = sys.argv[1]
        file = open(filename)
        code = file.read()
        file.close()
    except (IndexError, FileNotFoundError):
        raise

    factory = StatementFactory()
    idx = 1
    plan = {}
    for token in tokenize(code):
        if is_debug():
            print(token)
        plan[idx] = factory.create_statement(token.value, token.paramaters)
        idx += 1

    executer = Executer(plan)
    executer.__run__()
示例#11
0
文件: habitat.py 项目: hansl/habitat
class Habitat(ComponentBase):
    class KeyValueDefault:
        user = getpass.getuser()
        home = os.path.expanduser("~")
        habitat_root = '%(home)s/.habitats/%(habitat_name)s'
        metadata_path = '%(habitat_root)s/metadata'

        base_port = 8000
        host = '127.0.0.1'

        timeout = 30

    class __ShouldThrow(object):
        pass

    def __init__(self, should_start=True, *args, **kwargs):
        self.habitat_name = self.__class__.__name__
        super(Habitat, self).__init__(name='%(habitat_name)s')
        self.executer = Executer(self)
        self._args = args
        self._port_map = {}

        # We absolutely need a metadata file.
        metadata_path = self['metadata_path']
        if not os.path.exists(os.path.dirname(metadata_path)):
            os.makedirs(os.path.dirname(metadata_path))
        self.metadata = MetaDataFile(metadata_path)

        for name, component in self.get_all_components().iteritems():
            component.habitat = self
            component.name = name
            if component.name not in self.metadata:
                self.metadata[component.name] = {}
            component.metadata = self.metadata[component.name]

        # If we should start the Habitat, run the first argument as a command.
        if should_start:
            if self._args:
                command = self._args[0]
            else:
                command = 'run'
            self.command(command, *self._args[1:])

    def command(self, name, *args):
        if hasattr(self.Commands, name):
            getattr(self.Commands, name)(self, *args)
        elif (    name in self
              and isinstance(self[name], ComponentBase)
              and len(args) > 0
              and hasattr(self[name].Commands, args[0])):
            component = self[name]
            name, args = args[0], args[1:]
            getattr(component.Commands, name)(component, *args)
        else:
            self.command('help')

    def _start(self):
        for component in self.get_all_components().values():
            component.start()
            self.metadata.storage.save()

    def wait_if_needed(self):
        # If we are running a component, we wait for a CTRL-C from the user.
        should_wait = False
        for name, component in self.get_all_components().iteritems():
            if component.is_running():
                should_wait = True
                break

        if should_wait:
            print 'Waiting for CTRL-C...'
            try:
                while True:
                    sys.stdin.readlines()
            except KeyboardInterrupt:
                pass

    def _stop(self):
        for name, component in reversed(self.get_all_components().items()):
            if component.is_running():
                component.stop()

        self.metadata.storage.save()        

    def get_all_components(self):
        return {
            name: getattr(self, name)
            for name in dir(self)
            if (not name.startswith('_')
                and hasattr(self, name)
                and isinstance(getattr(self, name), ComponentBase))
        }

    def get_component(self, name):
        if isinstance(name, basestring):
            return self[name]
        if isinstance(name, ComponentBase):
            return name
        raise Exception('Invalid component: %s' % name)

    def get_component_from_stack(self):
        i = 2
        # Get the first stack level out of Habitat
        stack = inspect.stack()[i]
        while 'self' in stack[0].f_locals and isinstance(stack[0].f_locals["self"], Habitat):
            i += 1
            stack = inspect.stack()[i]
        if 'self' in stack[0].f_locals and isinstance(stack[0].f_locals["self"], ComponentBase):
            return stack[0].f_locals["self"]
        return None

    def execute(self, **kwargs):
        """Run a command line tool using an environment and redirecting the
           STDOUT/STDERR to the local logs. Throw an exception if the command
           failed.
        """
        return self.executer.execute(**kwargs)

    def execute_or_die(self, **kwargs):
        """Run a command line tool using an environment and redirecting the
           STDOUT/STDERR to the local logs. Throw an exception if the command
           failed.
        """
        return self.executer.execute_or_die(**kwargs)

    def execute_in_thread(self, **kwargs):
        """Run a command line tool using an environment and redirecting the
           STDOUT/STDERR to the local logs. The tool is ran in a separate
           thread.
        """
        return self.executer.execute_in_thread(**kwargs)

    def execute_interactive(self, **kwargs):
        """Run a command line tool using an environment and redirecting the
           STDOUT/STDERR to the local logs. The tool is ran interactively.
        """
        return self.executer.execute_interactive(**kwargs)

    class Commands:
        @staticmethod
        def run(habitat, *args):
            """Run a list of components by their names."""
            try:
                habitat.start()
                habitat.wait_if_needed()
            except Exception, ex:
                print ex
            finally:
示例#12
0
#!/bin/env python
from executer import Executer

ROBOT_WIDHT = 5.5
LOOKDIST = 2.4

executer = Executer(4)
executer.addRobot("0")
executer.addRobot("1")
executer.startListening()
executer.startHTTPServer()
示例#13
0
文件: gui.py 项目: Altynai/imdb
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.logger = logging.getLogger()
        self.runner = Executer()

        self.setWindowTitle(u'内存数据库')
        self.centralWidget = QtGui.QTabWidget()
        self.tabWidge = QtGui.QTabWidget()
        vbox = QtGui.QVBoxLayout(self)
        
        self.initActionTableWidget()
        self.newFile()
        self.initMenuBar()
        self.statusBar()

        splitter = QtGui.QSplitter(QtCore.Qt.Vertical)
        splitter.addWidget(self.tabWidge)
        splitter.addWidget(self.actionTableWidget)

        vbox.addWidget(splitter)
        self.centralWidget.setLayout(vbox)
        self.setCentralWidget(self.centralWidget)

        screen = QtGui.QDesktopWidget().screenGeometry()
        self.setGeometry(screen.width() * 0.3, screen.height() * 0.3, screen.width() * 0.5, screen.height() * 0.6)


    def initActionTableWidget(self):
        self.actionTableWidget = QtGui.QTableWidget(0, 5)
        self.actionCount = 0
        headerLabels = [u'状态', u'时间', u'语句', u'结果', u'执行时间']
        self.actionTableWidget.setHorizontalHeaderLabels(headerLabels)
        self.actionTableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
        self.actionTableWidget.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked)
        self.actionTableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Interactive)


    def initMenuBar(self):
        menubar = self.menuBar()

        # new
        newAction = QtGui.QAction(u'新建', self)
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip(u'新建文件')
        self.connect(newAction, QtCore.SIGNAL('triggered()'), self.newFile)
        
        # open
        openAction = QtGui.QAction(u'打开', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip(u'打开文件')
        self.connect(openAction, QtCore.SIGNAL('triggered()'), self.openFile)

        # save
        saveAction = QtGui.QAction(u'保存', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip(u'保存文件')
        self.connect(saveAction, QtCore.SIGNAL('triggered()'), self.saveFile)

        # saveAs
        saveAsAction = QtGui.QAction(u'另存为', self)
        saveAsAction.setShortcut('Ctrl+Shift+S')
        saveAsAction.setStatusTip(u'另存为')
        self.connect(saveAsAction, QtCore.SIGNAL('triggered()'), self.saveAsFile)

        # closeFile
        closeFileAction = QtGui.QAction(u'关闭', self)
        closeFileAction.setShortcut('Ctrl+W')
        closeFileAction.setStatusTip(u'关闭文件')
        self.connect(closeFileAction, QtCore.SIGNAL('triggered()'), self.closeFile)

        # exit
        exitAction = QtGui.QAction(u'退出', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip(u'退出程序')
        self.connect(exitAction, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))


        file = menubar.addMenu(u'&文件')
        file.addAction(newAction)
        file.addAction(openAction)
        file.addAction(saveAction)
        file.addAction(saveAsAction)
        file.addAction(closeFileAction)
        file.addAction(exitAction)

        # run
        runAction = QtGui.QAction(u'命令', self)
        runAction.setShortcut('Ctrl+R')
        runAction.setStatusTip(u'运行命令')
        self.connect(runAction, QtCore.SIGNAL('triggered()'), self.runCommand)

        # clear
        clearAction = QtGui.QAction(u'清除', self)
        clearAction.setShortcut('Ctrl+D')
        clearAction.setStatusTip(u'清除执行记录')
        self.connect(clearAction, QtCore.SIGNAL('triggered()'), self.clearCommand)

        run = menubar.addMenu(u'&运行')
        run.addAction(runAction)
        run.addAction(clearAction)

        # Help
        helpAction = QtGui.QAction(u'帮助', self)
        helpAction.setShortcut('Ctrl+H')
        helpAction.setStatusTip('获得帮助')
        self.connect(helpAction, QtCore.SIGNAL('triggered()'), self.help)

        help = menubar.addMenu(u'&帮助')
        help.addAction(helpAction)

    def help(self):
        helpDialog = QtGui.QDialog(self)
        helpDialog.setWindowTitle(u'帮助')
        layout = QtGui.QVBoxLayout()
        textArea = QtGui.QLabel()
        text = QtCore.QString()
        with open("help", "r") as fin:
            for line in fin.readlines():
                # line = line.strip("\n")
                text.append(QtCore.QString.fromUtf8(line))
        textArea.setText(text)
        layout.addWidget(textArea)
        helpDialog.setLayout(layout)
        helpDialog.show()

    def newFile(self):
        mainFrame = MainFrame()
        self.tabWidge.addTab(mainFrame, mainFrame.fileName)
        self.tabWidge.setCurrentWidget(mainFrame)

    def openFile(self):
        self.saveFile()
        currentFrame = self.tabWidge.currentWidget()
        currentIndex = self.tabWidge.currentIndex()
        filePath = QtGui.QFileDialog.getOpenFileName(self, u'打开文件')
        if filePath == '':
            return
        fileName = filePath.split('/')[-1]
        self.tabWidge.setTabText(currentIndex, fileName)
        currentFrame.fileName = fileName
        currentFrame.filePath = filePath
        currentFrame.textEdit.clear()

        with open(filePath, "r") as fin:
            while True:
                line = fin.readline()
                if not line:
                    break
                line = line.strip("\n")
                currentFrame.textEdit.append(QtCore.QString.fromUtf8(line))

    def saveAsFile(self):
        self.saveFile()
        filePath = QtGui.QFileDialog.getOpenFileName(self, u'另存为')
        if not filePath:
            return
        with open(filePath, "w") as fout:
            fout.write(currentFrame.textEdit.toPlainText().toUtf8())

    def saveFile(self):
        currentFrame = self.tabWidge.currentWidget()
        currentIndex = self.tabWidge.currentIndex()
        modified = currentFrame.textEdit.document().isModified()
        fileName = currentFrame.fileName
        filePath = currentFrame.filePath
        
        if not modified:
            return
        if not filePath:
            filePath = QtGui.QFileDialog.getSaveFileName(self, u'保存')
            if not filePath:
                return
            fileName = filePath.split('/')[-1]

        self.tabWidge.setTabText(currentIndex, fileName)
        currentFrame.fileName = fileName
        currentFrame.filePath = filePath
        with open(filePath, "w") as fout:
            fout.write(currentFrame.textEdit.toPlainText().toUtf8())

    def closeFile(self):
        self.saveFile()
        tabCount = self.tabWidge.count()
        currentIndex = self.tabWidge.currentIndex()
        self.tabWidge.removeTab(currentIndex)
        if tabCount == 1:
            self.newFile()

    def addAction(self, action = "", message = "", duration = "", correct = False):
        self.actionTableWidget.insertRow(self.actionCount)
        currentTime = time.strftime(r"%H:%M:%S", time.localtime())

        png = "icon/yes.png" if correct else "icon/no.png"
        icon = QtGui.QIcon(QtGui.QPixmap(png))

        arglist = ['', currentTime, action, message, duration]
        for i in xrange(len(arglist)):
            content = QtCore.QString.fromUtf8(arglist[i])
            if i:
                self.actionTableWidget.setItem(self.actionCount, i, QtGui.QTableWidgetItem(content))
            else:
                self.actionTableWidget.setItem(self.actionCount, i, QtGui.QTableWidgetItem(icon, ""))
        self.actionCount +=1

    def runCommand(self):
        currentFrame = self.tabWidge.currentWidget()
        text = str(currentFrame.textEdit.toPlainText().toUtf8())

        for action in self.runner.splitCommand(text):
            if action[-1] == ';':action = action[0:-1]
            if isRedisCommand(action):
                durantion = self.runRedisCommand(action)
            else:
                durantion = self.runSQLCommand(action)


    def runRedisCommand(self, command):
        currentFrame = self.tabWidge.currentWidget()
        startTime = time.time()
        success, resultlist = self.runner.executeRedis(command)
        durantion = "%.4lfsec" % (time.time() - startTime)

        self.logger.debug("%s:%s, %s", command, str(success), str(resultlist))

        # if success:
        #     currentFrame.tableWidget.insertRow(rowCount)
        #     currentFrame.tableWidget.setColumnCount(1)
        #     currentFrame.tableWidget.setRowCount(1)
        #     currentFrame.tableWidget.setHorizontalHeaderLabels([QtCore.QString.fromUtf8('结果')])
        #     currentFrame.tableWidget.setItem(0, 0, QtGui.QTableWidgetItem(QtCore.QString.fromUtf8(str(resultlist))))
        #     message = "OK"
        # else:
        message = str(resultlist)

        self.addAction(command, message, durantion, success)

    def runSQLCommand(self, command):
        startTime = time.time()
        currentFrame = self.tabWidge.currentWidget()
        success, resultlist = self.runner.executeSQL(command)
        durantion = "%.4lfsec" % (time.time() - startTime)

        self.logger.debug(command)
        self.logger.debug(str(success) + " " + str(resultlist))

        # select * from book
        if success:
            if isinstance(resultlist, list):
                header = [QtCore.QString.fromUtf8(x[0]) for x in resultlist[0]]
                resultlist = resultlist[1:]
                columnCount = len(header)
                rowCount = len(resultlist)
                currentFrame.tableWidget.setColumnCount(columnCount)
                currentFrame.tableWidget.setRowCount(rowCount)
                currentFrame.tableWidget.setHorizontalHeaderLabels(header)
                for i in xrange(rowCount):
                    for j in xrange(columnCount):
                        content = QtCore.QString.fromUtf8(str(resultlist[i][j]))
                        currentFrame.tableWidget.setItem(i, j, QtGui.QTableWidgetItem(content))
                message = "%d rows returned" % rowCount
            else:
                message = "%d rows affected" % resultlist

        else:
            message = str(resultlist)

        self.addAction(command, message, durantion, success)

    def clearCommand(self):
        for i in xrange(self.actionTableWidget.rowCount()):
            self.actionTableWidget.removeRow(0)
        self.actionCount = 0
示例#14
0
from executer import Executer
import atexit

exc = Executer(("202.182.119.187", 6000))
atexit.register(exc.on_exit)
while True:
    inp = input("enter your command:\n")
    if inp == "bye":
        break
    ret = exc.exec_(inp)
    print(ret)
def p_expression_action_8(p):
    'expression_action_8 :'
    global operators_stack
    operators_stack.append(p[-1])


def p_expression_action_9(p):
    'expression_action_9 :'
    global operands_stack, operators_stack, temporal_count, relation_operators, quadruples
    if len(operators_stack) and operators_stack[-1] in relation_operators:
        operand_2 = operands_stack.pop()
        operand_1 = operands_stack.pop()
        temporal = '#' + str(temporal_count)
        temporal_count = temporal_count + 1
        quadruples.append(
            (operators_stack.pop(), operand_1, operand_2, temporal))
        operands_stack.append(temporal)


# Build the parser
parser = yacc.yacc()

s = file('multiply.eskr', 'r').read()
result = parser.parse(s)
for i in range(len(quadruples)):
    print(i, quadruples[i])

executer = Executer(quadruples, symbols_table, temporal_count)
executer.execute()
示例#16
0
from executer import Executer
from serialFaker import SerialFaker
from multiprocessing import Queue

queue = Queue()
seri = SerialFaker(queue)
exi = Executer(queue)

seri.start()
exi.run()