예제 #1
0
    def run(self):
        # Grade-A fugly workaround ahead! pyFreenet can't handle failing testDDARequests, because FCP doesn't work with Identifiers
        # in this request. So failing DDA jobs die. This is a trial-and-error workaround to see if we can upload the file from 
        # disk or if we have to send it over socket.
        # TODO GET RID OF PYFREENET or tell toad_ to fix testDDARequest!!!!!!
        testDDAResult = False
        keyType = self.nodeManager.config['warren']['file_keytype']
        tmpReq = urllib2.Request(self.url)
        if tmpReq.get_type() == 'file':
            plainUrl = tmpReq.get_selector()
            try:
                directory = os.path.split(plainUrl)[0]
                testDDA = self.nodeManager.node.testDDA(async=False, Directory=directory, WantReadDirectory=True, timeout=5)
                if 'TestDDAComplete' in str(testDDA.items()): #TODO check for the real keys
                    testDDAResult = True
            except Exception, e:
                testDDAResult = False

            if testDDAResult:
                opener = buildOpener(self.url, self.proxy)
                u = opener.open(self.url)
                filename = os.path.basename(self.url)
                insert = self.putData(plainUrl, filename, self.mimeType, 'disk', keyType)
                QThread.msleep(5000)
                if insert.result is not None and 'ProtocolError' in str(insert.result):
                    testDDAResult = False
                    opener.close()
예제 #2
0
파일: FileManager.py 프로젝트: saces/warren
    def run(self):
        # Grade-A fugly workaround ahead! pyFreenet can't handle failing testDDARequests, because FCP doesn't work with Identifiers
        # in this request. So failing DDA jobs die. This is a trial-and-error workaround to see if we can upload the file from
        # disk or if we have to send it over socket.
        # TODO GET RID OF PYFREENET or tell toad_ to fix testDDARequest!!!!!!
        testDDAResult = False
        keyType = self.nodeManager.config['warren']['file_keytype']
        tmpReq = urllib2.Request(self.url)
        if tmpReq.get_type() == 'file':
            plainUrl = tmpReq.get_selector()
            try:
                directory = os.path.split(plainUrl)[0]
                testDDA = self.nodeManager.node.testDDA(async=False,
                                                        Directory=directory,
                                                        WantReadDirectory=True,
                                                        timeout=5)
                if 'TestDDAComplete' in str(
                        testDDA.items()):  #TODO check for the real keys
                    testDDAResult = True
            except Exception, e:
                testDDAResult = False

            if testDDAResult:
                opener = buildOpener(self.url, self.proxy)
                u = opener.open(self.url)
                filename = os.path.basename(self.url)
                insert = self.putData(plainUrl, filename, self.mimeType,
                                      'disk', keyType)
                QThread.msleep(5000)
                if insert.result is not None and 'ProtocolError' in str(
                        insert.result):
                    testDDAResult = False
                    opener.close()
예제 #3
0
 def startSynchronizedProcess(self, proc, program, arguments, workingDir = None):
     """
     Public method to start a synchroneous process
     
     This method starts a process and waits
     for its end while still serving the Qt event loop.
     
     @param proc process to start (QProcess)
     @param program path of the executable to start (string or QString)
     @param arguments list of arguments for the process (QStringList)
     @param workingDir working directory for the process (string or QString)
     @return flag indicating normal exit (boolean)
     """
     if proc is None:
         return
         
     if workingDir:
         proc.setWorkingDirectory(workingDir)
     proc.start(program, arguments)
     procStarted = proc.waitForStarted()
     if not procStarted:
         KQMessageBox.critical(None,
             self.trUtf8('Process Generation Error'),
             self.trUtf8(
                 'The process %1 could not be started. '
                 'Ensure, that it is in the search path.'
             ).arg(program))
         return False
     else:
         while proc.state() == QProcess.Running:
             QApplication.processEvents()
             QThread.msleep(300)
             QApplication.processEvents()
         return (proc.exitStatus() == QProcess.NormalExit) and (proc.exitCode() == 0)
예제 #4
0
파일: SR830.py 프로젝트: AvirupRoy/research
 def regain(self, lower, higher):
     # needs to be fixed by Felix
     bChanged = False
     ts = self.tcSeconds()*5 + 0.1
     r = self.snapRadius()
     ovl = self.isOverload
     s = self.sensitivity()
     if (r > higher * self.sensitivityToVolt(s)):
         bChanged |= self.decreaseSensitivity(1)
         if (self.ov1):
             return bChanged
             # couldn't find a floatsleep function
             QThread.msleep(ts)
     # Can sensitivity be increased?
     ov1 = self.isOverload()
     if (not(ovl) & (r < lower*self.sensitivityToVolt(s))):
         self.increaseSensitivity(1)
         bChanged |= True
         time.sleep(ts)
     ok = True
     r=self.snapRadius()
     while((ov1 or (r>higher*self.sensitivityVoltage())) & ok):
         ok = self.decreaseSensitivity(1)
         bChanged |= ok
         time.sleep(ts)
     return bChanged
예제 #5
0
파일: USBComm.py 프로젝트: Introsys/fresh
 def run(self):
   ''' 
   Waits for a __serial port to be connected to the PC
   '''
   while self.__tryingToOpen:
     try:
       with QMutexLocker(self.mutex):
         self.__serial = serial.Serial(str(self.port), str(self.baudrate))
         self.__tryingToOpen = False;
       self.portAvailable.emit(self.__serial)
       self.statusNotification.emit('Serial Port Open With Success')
       self.f_log.info('Serial Port Open With Success')
     except serial.SerialException as e:
       self.statusNotification.emit('ERRO : {0}'.format(str(e)))
       self.f_log.error("ERRO : {0}".format(str(e)))
     except ValueError as e:
       self.statusNotification.emit('ERRO : {0}'.format(str(e)))
       self.f_log.error('ERRO : {0}'.format(str(e)))
     except: 
       e = sys.exc_info()[0]
       self.statusNotification.emit('ERRO: {0}'.format(str(e)))
       self.f_log.error('ERRO : {0}'.format(str(e)))
     finally:
       QThread.msleep(2000)
   self.finished.emit()
예제 #6
0
    def terminate(self):
        self.inferenceEngine.terminate()
        self.receiver_thread.quit()
        for count in range(10):
            QThread.msleep(50)

        self.close()
예제 #7
0
def getOverlap(Ch = 1, PowerBalanced = False, confirmDangerous = True):
    s = defaultDevice("SCOPE")
    s.setChannel(Ch)
    temp=s.getV_div()
    setShutters("balanceDetectors")
    s.write("ACQ:STOPA RUNST")
    s.write("ACQ:State RUN")
    if PowerBalanced == False:
        raw_input("balance power now, then press enter")
        
    setShutters("homodyne",confirmDangerous=confirmDangerous)
    QThread.msleep(30)
    s.autoScale(keepTrace=True)
    #triggerAndWait(s)
    V = s.getTrace()
    Vminx = V.Y.argmin()
    Vminy = mean(V.Y[Vminx-5:Vminx+5]) #average local environment of minimum 
    Vmaxx = V.Y.argmax()
    Vmaxy = mean(V.Y[Vmaxx-5:Vmaxx+5]) #average local environment of minimum
    Vhom = Vmaxy-Vminy
    disp(Vhom)
    setShutters("balanceDetectors")
    setShutter("detectorMinus",1)
    setShutter("detectorPlus",0)
    QThread.msleep(30)
    s.autoScale(keepTrace=True)
    #triggerAndWait(s)
    V = s.getTrace()
    VLOplus = mean(V.Y)
    disp(VLOplus)
    setShutter("detectorMinus",0)
    setShutter("detectorPlus",1)
    QThread.msleep(30)
    s.autoScale(keepTrace=True)
    #triggerAndWait(s)
    V = s.getTrace()
    VLOminus = mean(V.Y)
    disp(VLOminus)
    setShutter("LO",1)
    setShutter("signal",0,confirmDangerous=confirmDangerous)
    QThread.msleep(30)
    s.autoScale(keepTrace=True)
    #triggerAndWait(s)
    V = s.getTrace()
    Vsigminus = mean(V.Y)
    disp(Vsigminus)
    setShutter("detectorMinus",1)
    setShutter("detectorPlus",0)
    QThread.msleep(30)
    s.autoScale(keepTrace=True)
    #triggerAndWait(s)
    V = s.getTrace()
    Vsigplus = mean(V.Y)
    disp(Vsigplus)
    s.write("ACQ:STOPA RUNST")
    s.write("ACQ:State RUN")
    s.setV_div(temp)
    setShutters("homodyne",confirmDangerous=confirmDangerous)
    return overlap(Vhom,(VLOplus-VLOminus)*2,(Vsigplus-Vsigminus)*2)
예제 #8
0
 def send(self, text):
     if self.send_process.state() == QProcess.Running:
         self.send_process.close()
     self.show_terminal()
     args = ['-classname', self.id, '-sendcmd', text]
     self.send_process.start(os.path.join(dep_dir, Kitty.exe_name), args)
     self.send_process.waitForStarted()
     self.send_process.waitForFinished()
     QThread.msleep(Kitty.DELAY)
예제 #9
0
    def run(self):
        # self.emit(SIGNAL('observer()'))

        while (1):
            try:
                # call a fuction from the main thread
                self.emit(SIGNAL('observer()'))

                QThread.msleep(300)

            except (TypeError):
                pass
예제 #10
0
 def run(self):
     
     while(not self.stopThread):
       
         try:
             
             self.mm.SetButton("Z", False) # No ping method available atm, so value of not available button is set to test connection
             self.emit(SIGNAL('updateConnectionStatus'), True)
         except socket.error:
             self.emit(SIGNAL('updateConnectionStatus'), False)
       
         QThread.msleep(1000)
    def run(self):
        # call a fuction from the main thread
        self.emit(SIGNAL('update()'))

        while (1):
            try:
                # call a fuction from the main thread
                self.emit(SIGNAL('add_value()'))

                QThread.msleep(10)

            except (TypeError):
                pass
예제 #12
0
 def run(self):
     for i in range(0, 99):
         print(i + 1)
         self.save.emit(i + 1)
         while self.waitForPos:
             if self.cancel:
                 # self.cancel=False
                 break
             QThread.msleep(10)
             pass
         self.waitForPos = True
         if self.cancel:
             self.cancel = False
             break
     self.end.emit()
예제 #13
0
 def open(self):
     """ kitty -telnet -P 9696 hostname """
     if self.terminal.state() == QProcess.Running:
         return
     file_name = utils.set_log_name(self.log_name,
                                    self.log_path,
                                    ext='.txt')
     args = [
         '-{}'.format(self.protocol), self.ip, '-P', self.port, '-log',
         os.path.join(self.log_path, file_name), '-title',
         self.window_title, '-classname', self.id
     ]
     while self.terminal.state() == QProcess.NotRunning:
         self.terminal.start(os.path.join(dep_dir, Kitty.exe_name), args)
         self.terminal.waitForStarted()
         QThread.msleep(Kitty.DELAY)
예제 #14
0
 def _offset_and_limit_rows_to_get(self):
     """From the current set of rows to get, find the first
     continuous range of rows that should be fetched.
     :return: (offset, limit)
     """
     offset, limit, previous_length, i = 0, 0, 0, 0
     #
     # wait for a while until the rows under request don't change any
     # more
     #
     locker = QtCore.QMutexLocker(self._mutex)
     while previous_length != len(self.rows_under_request):
         previous_length = len(self.rows_under_request)
         locker.unlock()
         QThread.msleep(5)
         locker.relock()
     #
     # now filter out all rows that have been put in the cache
     # the gui thread didn't know about
     #
     rows_to_get = self.rows_under_request
     rows_already_there = set()
     for row in rows_to_get:
         if self.edit_cache.has_data_at_row(row):
             rows_already_there.add(row)
     rows_to_get.difference_update(rows_already_there)
     rows_to_get = list(rows_to_get)
     locker.unlock()
     #
     # see if there is anything left to do
     #
     try:
         if len(rows_to_get):
             rows_to_get.sort()
             offset = rows_to_get[0]
             #
             # find first discontinuity
             #
             for i in range(offset, rows_to_get[-1] + 1):
                 if rows_to_get[i - offset] != i:
                     break
             limit = i - offset + 1
     except IndexError, e:
         logger.error('index error with rows_to_get %s' %
                      unicode(rows_to_get),
                      exc_info=e)
         raise e
예제 #15
0
 def _offset_and_limit_rows_to_get(self):
     """From the current set of rows to get, find the first
     continuous range of rows that should be fetched.
     :return: (offset, limit)
     """
     offset, limit, previous_length, i = 0, 0, 0, 0
     #
     # wait for a while until the rows under request don't change any
     # more
     #
     locker = QtCore.QMutexLocker(self._mutex)
     while previous_length != len(self.rows_under_request):
         previous_length = len(self.rows_under_request)
         locker.unlock()
         QThread.msleep(5)
         locker.relock()
     #
     # now filter out all rows that have been put in the cache
     # the gui thread didn't know about
     #
     rows_to_get = self.rows_under_request
     rows_already_there = set()
     for row in rows_to_get:
         if self.edit_cache.has_data_at_row(row):
             rows_already_there.add(row)
     rows_to_get.difference_update(rows_already_there)
     rows_to_get = list(rows_to_get)
     locker.unlock()
     #
     # see if there is anything left to do
     #
     try:
         if len(rows_to_get):
             rows_to_get.sort()
             offset = rows_to_get[0]
             #
             # find first discontinuity
             #
             for i in range(offset, rows_to_get[-1] + 1):
                 if rows_to_get[i - offset] != i:
                     break
             limit = i - offset + 1
     except IndexError, e:
         logger.error("index error with rows_to_get %s" % unicode(rows_to_get), exc_info=e)
         raise e
예제 #16
0
def getOverlap_AI(Ch = 2, confirmDangerous = True, t_sleep=30, n = 2000, samplerate=200000):
    from ..hardware.daqmx import do,ao,ai
    setShutters("homodyne",confirmDangerous=confirmDangerous)
    QThread.msleep(t_sleep)
    V=ai.readValues(Ch, n=n, samplerate=samplerate)
    Vminx = V.argmin()
    Vminy = mean(V[Vminx-2:Vminx+2]) #average local environment of minimum 
    Vmaxx = V.argmax()
    Vmaxy = mean(V[Vmaxx-2:Vmaxx+2]) #average local environment of minimum
    Vhom = Vmaxy-Vminy
    disp(Vhom)
    setShutters("balanceDetectors")
    setShutter("detectorMinus",1)
    setShutter("detectorPlus",0)
    QThread.msleep(t_sleep)
    
    V=ai.readValues(Ch, n=n, samplerate=samplerate)
    VLOplus = mean(V)
    disp(VLOplus)
    setShutter("detectorMinus",0)
    setShutter("detectorPlus",1)
    QThread.msleep(t_sleep)
    
    V=ai.readValues(Ch, n=n, samplerate=samplerate)
    VLOminus = mean(V)
    disp(VLOminus)
    setShutter("LO",1)
    setShutter("signal",0,confirmDangerous=confirmDangerous)
    QThread.msleep(t_sleep)
    
    V=ai.readValues(Ch, n=n, samplerate=samplerate)
    Vsigminus = mean(V)
    disp(Vsigminus)
    setShutter("detectorMinus",1)
    setShutter("detectorPlus",0)
    QThread.msleep(t_sleep)
    
    V=ai.readValues(Ch, n=n, samplerate=samplerate)
    Vsigplus = mean(V)
    disp(Vsigplus)
    
    setShutters("homodyne",confirmDangerous=confirmDangerous)
    return overlap(Vhom,(VLOplus-VLOminus)*2,(Vsigplus-Vsigminus)*2)
예제 #17
0
    def doWork(self):
        # Set starting system time [milliseconds]
        self.syst = int(time.time() * 1000.0)

        # Set starting simulation time [seconds]
        self.simt  = 0.0

        while not self.mode == Simulation.end:
            # Timing bookkeeping
            self.samplecount += 1

            # TODO: what to do with init
            if self.mode == Simulation.init:
                self.mode = Simulation.op

            if self.mode == Simulation.op:
                self.stack.checkfile(self.simt)

            # Always update stack
            self.stack.process(self, self.traf, self.screenio)

            if self.mode == Simulation.op:
                self.traf.update(self.simt, self.simdt)

                # Update metrics
                if self.metric is not None:
                    self.metric.update(self, self.traf)

                # Update time for the next timestep
                self.simt += self.simdt

            # Process Qt events
            QCoreApplication.processEvents()

            # When running at a fixed rate, increment system time with sysdt and calculate remainder to sleep
            if self.run_fixed:
                self.syst += self.sysdt
                remainder = self.syst - int(1000.0 * time.time())

                if remainder > 0:
                    QThread.msleep(remainder)
예제 #18
0
 def run(self):
     while self._do_run:
         self.tick()
         QThread.msleep(1000)
     self.deleteLater()
예제 #19
0
    def _handle_update_requests(self):
        #
        # wait for a while until the update requests array doesn't change any
        # more
        #
        previous_length = 0
        locker = QtCore.QMutexLocker(self._mutex)
        while previous_length != len(self._update_requests):
            previous_length = len(self._update_requests)
            locker.unlock()
            QThread.msleep(5)
            locker.relock()
        #
        # Copy the update requests and clear the list of requests
        #
        update_requests = [u for u in self._update_requests]
        self._update_requests = []
        locker.unlock()
        #
        # Handle the requests
        #
        return_list = []
        grouped_requests = collections.defaultdict(list)
        for flushed, row, column, value in update_requests:
            grouped_requests[row].append((flushed, column, value))
        for row, request_group in grouped_requests.items():
            #
            # don't use _get_object, but only update objects which are in the
            # cache, otherwise it is not sure that the object updated is the
            # one that was edited
            #
            o = self.edit_cache.get_entity_at_row(row)
            if not o:
                # the object might have been deleted from the collection while the editor
                # was still open
                self.logger.debug("this object is no longer in the collection")
                try:
                    self.unflushed_rows.remove(row)
                except KeyError:
                    pass
                continue
            #
            # the object might have been deleted while an editor was open
            #
            if self.admin.is_deleted(o):
                continue
            changed = False
            for flushed, column, value in request_group:
                attribute, field_attributes = self._columns[column]

                from sqlalchemy.exc import DatabaseError

                new_value = value()
                self.logger.debug("set data for row %s;col %s" % (row, column))

                if new_value == ValueLoading:
                    continue

                old_value = getattr(o, attribute)
                #
                # When the value is a related object, the related object might have changed
                #
                value_changed = (new_value != old_value) or (
                    field_attributes.get("embedded", False) and field_attributes.get("target", False)
                )
                #
                # In case the attribute is a OneToMany or ManyToMany, we cannot simply compare the
                # old and new value to know if the object was changed, so we'll
                # consider it changed anyway
                #
                direction = field_attributes.get("direction", None)
                if direction in ("manytomany", "onetomany"):
                    value_changed = True
                if value_changed:
                    # update the model
                    try:
                        setattr(o, attribute, new_value)
                        #
                        # setting this attribute, might trigger a default function to return a value,
                        # that was not returned before
                        #
                        self.admin.set_defaults(o, include_nullable_fields=False)
                    except AttributeError, e:
                        self.logger.error(u"Can't set attribute %s to %s" % (attribute, unicode(new_value)), exc_info=e)
                    except TypeError:
                        # type error can be raised in case we try to set to a collection
                        pass
                changed = value_changed or changed
예제 #20
0
 def show_terminal(self):
     if self.terminal.state() == QProcess.NotRunning:
         return
     autowin.show_window(autowin.get_qprocess_pid(self.terminal.pid()))
     QThread.msleep(Kitty.DELAY)
예제 #21
0
파일: pooky.py 프로젝트: sbackus/pooky
    def execute(self):
        end = len(self.commands)

        # Set this to exit the loop
        done = False

        # Reset if at the end
        if self.cp == end or (self.sp == len(self.stdin) and self.stdin):
            #print "Resetting w/ quickinit"
            self.quickinit()
            # We're in need of a good wipedown
            self.dirty = True

        while self.cp < end and not done:
            # Pass if not stepping or playing
            if not self.stepping and not self.playing:
                QThread.msleep(100)
                return

            cmd = self.commands[self.cp]

            if cmd is ">":
                self.mp += 1

            elif cmd is "<":
                self.mp -= 1

            elif cmd is "+":
                self.memory[self.mp] += 1
                if self.memory[self.mp] > 255:
                    self.memory[self.mp] = 0

            elif cmd is "-":
                self.memory[self.mp] -= 1
                if self.memory[self.mp] < 0:
                    self.memory[self.mp] = 255

            elif cmd is ",":
                if self.sp < len(self.stdin):
                    c = self.stdin[self.sp]
                    self.sp += 1
                    self.memory[self.mp] = ord(c)
                else:
                    done = True

            elif cmd is ".":
                #sys.stdout.write(chr(self.memory[self.mp]))
                self.emit(SIGNAL("stdout(QString)"),
                          QString("" + chr(self.memory[self.mp])))

            elif cmd is "[":
                if self.memory[self.mp] == 0:
                    # Skipping the loop, condition not met
                    self.cp = self.j1[self.cp]

            elif cmd is "]":
                if self.memory[self.mp] != 0:
                    # Jump back to starting bracket
                    self.cp = self.j2[self.cp]

            if not self.playing or self.cp + 1 == end:
                self.highlight()

            # Increment command pointer
            self.cp += 1

            # We're done stepping, return
            if self.stepping:
                done = True

        if self.playing or self.stepping:
            # We're done stepping if we're stepping
            if self.stepping:
                self.stepping = False
            # Stop playing after running through the program once
            if self.playing:
                self.stop()
                self.emit(SIGNAL("donePlaying()"))
            self.highlight()
예제 #22
0
    def download_button_clicked(self):
        tags = str(self.custom_tags.text())

        # url_id = self.recipes.model.data(1, QtCore.Qt.UserRole)    # TODO: 获得选中的recipes
        url_id = str(self.row_clicked(self.recipes.currentIndex()))

        if url_id == 'None':
            QtGui.QMessageBox.information(self, u"Error", u"选择需要爬取的网站!")
            return

        readlist_content = self.plainTextEdit.toPlainText()

        if readlist_content == '':
            QtGui.QMessageBox.information(self, u"Error", u"请在文本框中输入网址")
            return

        read_list_path = Path.read_list_path

        readList_file = open(read_list_path, 'w')
        readList_file.write(readlist_content)

        readList_file.close()

        game = EEBook(recipe_kind=url_id)

        progress_dlg = QProgressDialog(self)  # TODO: 设置大小, 区域
        progress_dlg.setWindowModality(Qt.WindowModal)
        progress_dlg.setMinimumDuration(5)
        progress_dlg.setWindowTitle(u"请等待")
        progress_dlg.setLabelText(u"制作中...请稍候")
        progress_dlg.setCancelButtonText(u"取消")
        progress_dlg.resize(350, 250)
        progress_dlg.show()
        progress_dlg.setRange(0, 20)

        for i in range(0, 15):
            progress_dlg.setValue(i)
            QThread.msleep(100)

        for i in range(15, 20):
            progress_dlg.setValue(i)
            QThread.msleep(100)
            if progress_dlg.wasCanceled():
                QtGui.QMessageBox.information(self, u"Error",
                                              u"电子书制作失败, 请重新操作")
                return

            try:
                filename = game.begin()  # TODO: 一次只能生成一本书
            except TypeError:
                QtGui.QMessageBox.information(self, u"Error", u"第一次使用请登录")
                progress_dlg.close()
                return
            progress_dlg.close()

            info_filename = ','.join(filename)
            QtGui.QMessageBox.information(
                self, u"info", u"电子书" + str(info_filename) + u"制作成功")

            for item in filename:
                file_path = EPUBSTOR_DIR + '/' + item
                Path.copy(str(file_path + '.epub'), LIBRARY_DIR)
                file_name = os.path.basename(str(file_path))
                book_id = file_name.split('.epub')[0]

                Path.mkdir(LIBRARY_DIR + book_id)
                shutil.move(LIBRARY_DIR + book_id + '.epub',
                            LIBRARY_DIR + book_id)

                book = Book(str(book_id))
                book.date = time.strftime(ISOTIMEFORMAT, time.localtime())
                book.tags += tags.replace(' ', '')
                book.tags += ',' + str(self.now_url)
                if self.add_title_tag.isChecked():
                    book.tags += ',' + str(book.title)
                insert_library(book)
            return
예제 #23
0
파일: pooky.py 프로젝트: sbackus/pooky
    def execute(self):
        end = len(self.commands)

        # Set this to exit the loop
        done = False

        # Reset if at the end
        if self.cp == end or (self.sp == len(self.stdin) and self.stdin):
            #print "Resetting w/ quickinit"
            self.quickinit()
            # We're in need of a good wipedown
            self.dirty = True

        while self.cp < end and not done:
            # Pass if not stepping or playing
            if not self.stepping and not self.playing:
                QThread.msleep(100)
                return

            cmd = self.commands[self.cp]

            if cmd is ">":
                self.mp += 1

            elif cmd is "<":
                self.mp -= 1

            elif cmd is "+":
                self.memory[self.mp] += 1
                if self.memory[self.mp] > 255:
                    self.memory[self.mp] = 0

            elif cmd is "-":
                self.memory[self.mp] -= 1
                if self.memory[self.mp] < 0:
                    self.memory[self.mp] = 255

            elif cmd is ",":
                if self.sp < len(self.stdin):
                    c = self.stdin[self.sp]
                    self.sp += 1
                    self.memory[self.mp] = ord(c)
                else:
                    done = True

            elif cmd is ".":
                #sys.stdout.write(chr(self.memory[self.mp]))
                self.emit(SIGNAL("stdout(QString)"),QString(""+chr(self.memory[self.mp])))

            elif cmd is "[":
                if self.memory[self.mp] == 0:
                    # Skipping the loop, condition not met
                    self.cp = self.j1[self.cp]

            elif cmd is "]":
                if self.memory[self.mp] != 0:
                    # Jump back to starting bracket
                    self.cp = self.j2[self.cp]

            if not self.playing or self.cp+1 == end:
                self.highlight()

            # Increment command pointer
            self.cp += 1

            # We're done stepping, return
            if self.stepping:
                done = True

        if self.playing or self.stepping:
            # We're done stepping if we're stepping
            if self.stepping:
                self.stepping = False
            # Stop playing after running through the program once
            if self.playing:
                self.stop()
                self.emit(SIGNAL("donePlaying()"))
            self.highlight()
예제 #24
0
 def run(self):
     while self._do_run:
         self.tick()
         QThread.msleep(1000)
예제 #25
0
 def run(self):
     while self._do_run:
         self.tick()
         QThread.msleep(1000)
     self.deleteLater()
예제 #26
0
def triggerAndWait(s):
    s.write("ACQ:STOPA SEQ")
    s.write("ACQ:State RUN")
    while int(s.ask("ACQ:State?")):
        QThread.msleep(20)
예제 #27
0
    def _handle_update_requests(self):
        #
        # wait for a while until the update requests array doesn't change any
        # more
        #
        previous_length = 0
        locker = QtCore.QMutexLocker(self._mutex)
        while previous_length != len(self._update_requests):
            previous_length = len(self._update_requests)
            locker.unlock()
            QThread.msleep(5)
            locker.relock()
        #
        # Copy the update requests and clear the list of requests
        #
        update_requests = [u for u in self._update_requests]
        self._update_requests = []
        locker.unlock()
        #
        # Handle the requests
        #
        return_list = []
        grouped_requests = collections.defaultdict(list)
        for flushed, row, column, value in update_requests:
            grouped_requests[row].append((flushed, column, value))
        for row, request_group in grouped_requests.items():
            #
            # don't use _get_object, but only update objects which are in the
            # cache, otherwise it is not sure that the object updated is the
            # one that was edited
            #
            o = self.edit_cache.get_entity_at_row(row)
            if not o:
                # the object might have been deleted from the collection while the editor
                # was still open
                self.logger.debug('this object is no longer in the collection')
                try:
                    self.unflushed_rows.remove(row)
                except KeyError:
                    pass
                continue
            #
            # the object might have been deleted while an editor was open
            #
            if self.admin.is_deleted(o):
                continue
            changed = False
            for flushed, column, value in request_group:
                attribute, field_attributes = self._columns[column]

                from sqlalchemy.exc import DatabaseError
                new_value = value()
                self.logger.debug('set data for row %s;col %s' % (row, column))

                if new_value == ValueLoading:
                    continue

                old_value = getattr(o, attribute)
                value_changed = (new_value != old_value)
                #
                # In case the attribute is a OneToMany or ManyToMany, we cannot simply compare the
                # old and new value to know if the object was changed, so we'll
                # consider it changed anyway
                #
                direction = field_attributes.get('direction', None)
                if direction in ('manytomany', 'onetomany'):
                    value_changed = True
                if value_changed:
                    # update the model
                    try:
                        setattr(o, attribute, new_value)
                        #
                        # setting this attribute, might trigger a default function to return a value,
                        # that was not returned before
                        #
                        self.admin.set_defaults(o,
                                                include_nullable_fields=False)
                    except AttributeError, e:
                        self.logger.error(u"Can't set attribute %s to %s" %
                                          (attribute, unicode(new_value)),
                                          exc_info=e)
                    except TypeError:
                        # type error can be raised in case we try to set to a collection
                        pass
                changed = value_changed or changed
예제 #28
0
파일: download.py 프로젝트: bindx/EE-Book
    def download_button_clicked(self):
        tags = str(self.custom_tags.text())

        # url_id = self.recipes.model.data(1, QtCore.Qt.UserRole)    # TODO: 获得选中的recipes
        url_id = str(self.row_clicked(self.recipes.currentIndex()))

        if url_id == 'None':
            QtGui.QMessageBox.information(self, u"Error", u"选择需要爬取的网站!")
            return

        readlist_content = self.plainTextEdit.toPlainText()

        if readlist_content == '':
            QtGui.QMessageBox.information(self, u"Error", u"请在文本框中输入网址")
            return

        read_list_path = Path.read_list_path

        readList_file = open(read_list_path, 'w')
        readList_file.write(readlist_content)

        readList_file.close()

        game = EEBook(recipe_kind=url_id)

        progress_dlg = QProgressDialog(self)        # TODO: 设置大小, 区域
        progress_dlg.setWindowModality(Qt.WindowModal)
        progress_dlg.setMinimumDuration(5)
        progress_dlg.setWindowTitle(u"请等待")
        progress_dlg.setLabelText(u"制作中...请稍候")
        progress_dlg.setCancelButtonText(u"取消")
        progress_dlg.resize(350, 250)
        progress_dlg.show()
        progress_dlg.setRange(0, 20)

        for i in range(0, 15):
            progress_dlg.setValue(i)
            QThread.msleep(100)

        for i in range(15, 20):
            progress_dlg.setValue(i)
            QThread.msleep(100)
            if progress_dlg.wasCanceled():
                QtGui.QMessageBox.information(self, u"Error", u"电子书制作失败, 请重新操作")
                return

            try:
                filename = game.begin()      # TODO: 一次只能生成一本书
            except TypeError:
                QtGui.QMessageBox.information(self, u"Error", u"第一次使用请登录")
                progress_dlg.close()
                return
            progress_dlg.close()

            info_filename = ','.join(filename)
            QtGui.QMessageBox.information(self, u"info", u"电子书"+str(info_filename)+u"制作成功")

            for item in filename:
                file_path = EPUBSTOR_DIR + '/' + item
                Path.copy(str(file_path+'.epub'), LIBRARY_DIR)
                file_name = os.path.basename(str(file_path))
                book_id = file_name.split('.epub')[0]

                Path.mkdir(LIBRARY_DIR + book_id)
                shutil.move(LIBRARY_DIR+book_id+'.epub', LIBRARY_DIR+book_id)

                book = Book(str(book_id))
                book.date = time.strftime(ISOTIMEFORMAT, time.localtime())
                book.tags += tags.replace(' ', '')
                book.tags += ','+str(self.now_url)
                if self.add_title_tag.isChecked():
                    book.tags += ','+str(book.title)
                insert_library(book)
            return
예제 #29
0
파일: api.py 프로젝트: feth/simuleds
def delay(msecs):
    QThread.msleep(msecs)