예제 #1
0
def table_size_to_contents(table_widget):
    """
    To make things look prettier...
    """
    table_widget.resizeColumnsToContents()
    QCoreApplication.processEvents()
    # sum all the new column widths and account for the verticalScrollBar and verticalHeader
    table_width = 0
    table_width += table_widget.verticalHeader().size().width()
    for col in range(table_widget.columnCount()):
        table_width += table_widget.columnWidth(col)
    table_width += table_widget.verticalScrollBar().width()
    table_width += 4

    # set the table width
    # not sure why we have to add 4 below, but we do..maybe something with
    # the border of the table
    table_widget.setFixedWidth(table_width)

    for row in range(table_widget.rowCount()):
        table_widget.resizeRowToContents(row)

    # sum all the new row heights
    table_height = 0
    # for row_num in range(table_widget.rowCount()):
    for row_num in range(TABLE_HEIGHT_IN_ROWS):
        table_height += table_widget.rowHeight(row_num)
    table_height += table_widget.horizontalHeader().size().height()
    table_height += 4
    table_widget.setFixedHeight(table_height)
    return
예제 #2
0
    def run(self):
        ser = pc.start_serial()

        # wait for reply
        for trial, bitpat, target_time in self.entries:
            if self.do_stop:
                self.do_stop = False
                break
            sys.stdout.write(bin(bitpat) + ' ')
            bitpat = pc.fix_bitpat(bitpat)
            sys.stdout.write("|")
            sys.stdout.write(' ' + bin(bitpat) + '\n')
            pc.send_command(bitpat, target_time, ser)
            sys.stdout.flush()
            while ser.inWaiting() == 0:
                QCoreApplication.processEvents()
                time.sleep(0.01)  # pause for 10 ms
            rcvd = ser.read(2)
            if rcvd == 's5':
                sys.stdout.write("*")
                sys.stdout.flush()
            self.progressBar.setValue(trial)

        time.sleep(0.02)
        # clear the last timeout warning
        # this should leave an 's0' waiting for next time
        ser.read(2)
        ser.close()
예제 #3
0
 def readDatas(self):
     if self.socket != None :
         if self.socket.isValid() :
             ins = QDataStream(self.socket)
             ins.setVersion(QDataStream.Qt_4_2)
             loop = 0
             while ins.atEnd() == False :
                 QCoreApplication.processEvents()
                 loop = loop + 1
                 if self.socket != None :               
                     if self.socket.isValid() :
                         if self.blockSize == 0:
                             if self.socket.isValid() :
                                 if self.socket.bytesAvailable() < 4:
                                     return
                                 self.blockSize = ins.readUInt32()
                             else :
                                 return
                         if self.socket.isValid() :
                             if self.socket.bytesAvailable() < self.blockSize:
                                 bytesReceived = str(self.socket.bytesAvailable())
                                 return
                             bytesReceived = str(self.socket.bytesAvailable())
                         else :
                             return  
                         action = ins.readQString()
                         self.handleAction(action, ins)
                         self.blockSize = 0
                     else : 
                         return    
                 else :
                     return
             return
예제 #4
0
파일: query.py 프로젝트: j3doucet/DBNN.NASA
def generate_classifier(mpec_data, mainWindow):
    for i in range(0, len(mpec_data)):
        mainWindow.ReadProgressBar.setValue(75 + 25 * i / len(mpec_data))
        tmp_out = open("classifier.csv", "w+")
        str_out = ""
        vector = []
        for j in range(1, 5):
            key = "w" + str(j) + "mpro"
            str_out += str(mpec_data[i][key]) + ","
            vector.append(float(mpec_data[i][key]))
        for j in range(1, 5):
            key = "w" + str(j) + "sigmpro"
            str_out += str(mpec_data[i][key])
            if j != 4:
                str_out += ","
            vector.append(float(mpec_data[i][key]))
        mainWindow.NetworkView.getData(vector)
        time.sleep(1)
        mainWindow.NetworkView.update()
        tmp_out.write(str_out)
        tmp_out.close()
        command = "java -jar ../out/artifacts/NASAProject_jar/NASAProject.jar ../Data/Model.NN classifier.csv"
        sub_proc = subprocess.Popen(command,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        (output, error) = sub_proc.communicate()
        output = output.split()
        mpec_data[i]['class'] = output[-1]
        if mpec_data[i]['class'] == "":
            mpec_data[i]['class'] = "0"
        mpec_tmp = mpec_data
        mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_tmp))
        mainWindow.Map.drawPlot(mpec_data)
        QCoreApplication.processEvents()
    return mpec_data
예제 #5
0
파일: query.py 프로젝트: j3doucet/DBNN.NASA
def generate_classifier(mpec_data,mainWindow):
	for i in range(0,len(mpec_data)):
		mainWindow.ReadProgressBar.setValue(75+25*i/len(mpec_data))
		tmp_out = open("classifier.csv","w+")
		str_out = ""
		vector = []
		for j in range(1,5):
			key = "w"+str(j)+"mpro"
			str_out += str(mpec_data[i][key])+","
			vector.append(float(mpec_data[i][key]))
		for j in range(1,5):
			key = "w"+str(j)+"sigmpro"
			str_out +=str(mpec_data[i][key])
			if j!=4:
				str_out+=","
			vector.append(float(mpec_data[i][key]))
		mainWindow.NetworkView.getData(vector)
		time.sleep(1)
		mainWindow.NetworkView.update()
		tmp_out.write(str_out)
		tmp_out.close()
		command = "java -jar ../out/artifacts/NASAProject_jar/NASAProject.jar ../Data/Model.NN classifier.csv"
		sub_proc = subprocess.Popen(command,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(output, error) = sub_proc.communicate()
		output = output.split()
		mpec_data[i]['class'] = output[-1]
		if mpec_data[i]['class'] =="":
			mpec_data[i]['class'] = "0"
		mpec_tmp = mpec_data
		mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_tmp))
		mainWindow.Map.drawPlot(mpec_data)
		QCoreApplication.processEvents()
	return mpec_data
 def readDatas(self):
     if self.socket is not None:
         if self.socket.isValid():
             ins = QDataStream(self.socket)
             ins.setVersion(QDataStream.Qt_4_2)
             loop = 0
             while not ins.atEnd():
                 QCoreApplication.processEvents()
                 loop += 1
                 if loop > 1000: break
                 if self.socket is not None:
                     if self.socket.isValid():
                         if self.blockSize == 0:
                             if self.socket.isValid():
                                 if self.socket.bytesAvailable() < 4:
                                     return
                                 self.blockSize = ins.readUInt32()
                             else:
                                 return
                         if self.socket.isValid():
                             if self.socket.bytesAvailable() < self.blockSize:
                                 bytesReceived = str(self.socket.bytesAvailable())
                                 return
                             bytesReceived = str(self.socket.bytesAvailable())
                         else:
                             return
                         action = ins.readQString()
                         self.handleAction(action, ins)
                         self.blockSize = 0
                     else:
                         return
                 else:
                     return
             return
예제 #7
0
파일: __init__.py 프로젝트: Firelinux/FQM
def run_app():
    app = create_app()
    create_db(app)
    appg = QApplication(sys.argv)
    if os.name != 'nt':
        # !!! it did not work creates no back-end available error !!!
        # !!! strange bug , do not remove !!!
        if listp():
            pass
    window = NewWindow(app)

    # switching the language with template folder path
    @app.route('/lang_switch/<lang>')
    def lang_switch(lang):
        session['lang'] = lang
        if current_user.is_authenticated:
            return redirect(str(request.referrer))
        return redirect(url_for('core.root'))
    @app.before_first_request
    def defLanguage():
        if session.get('lang') not in ['en', 'ar', 'fr', 'it', 'es']:
            session['lang'] = 'en'


    # Adding error handlers on main app instance
    @app.errorhandler(404)
    @app.errorhandler(500)
    @app.errorhandler(413)
    def page_not_found(error):
        if error == 413:
            flash(get_lang(55), "danger")
            if current_user.is_authenticated:
                return redirect(url_for('cust_app.multimedia', nn=1))
            return redirect(url_for('core.root'))
        flash(get_lang(56), "danger")
        return redirect(url_for('core.root'))
    # Injecting default variables to all templates

    @app.context_processor
    def inject_vars():
        # adding language support var
        ar = False
        if session.get('lang') == 'AR':
            ar = True
        # modifing side bar spacing for specific paths
        path = request.path
        adml = ['/users', '/user_a', '/admin_u', '/user_u',
                '/csvd', '/settings']
        adme = False
        if path in adml or path[:7] in adml or path[:5] in adml:
            adme = True
        return dict(path=path,
                    adme=adme, brp=Markup("<br>"), ar=ar,
                    version=version, str=str, defLang=session.get('lang'))
    QCoreApplication.processEvents()
    appg.exec_()
예제 #8
0
 def play(self, do_loop=False, real_time=True):
     time = 0.0 # seconds
     timer = QElapsedTimer()
     timer.restart()
     dtime = 1.0 / self.frames_per_second
     key_frame_number = 0
     frame_number = 0
     for kf in self._key_frames:
         self.current_key_frame_index = key_frame_number
         key_frame_time = 0.0
         while key_frame_time < kf.time_to_next_frame:
             # Drop frames if we are going too slow
             # if real_time and (timer.elapsed() - 200) > time*1000.0:
             #     continue
             tf = key_frame_time / kf.time_to_next_frame
             interpolation_parameter = tf + key_frame_number
             camera_state = camera.State()
             focus_x = self.spline.interpolate_sequence(
                         self._focusx, 
                         interpolation_parameter,
                         do_loop)
             focus_y = self.spline.interpolate_sequence(
                         self._focusy, 
                         interpolation_parameter,
                         do_loop)
             focus_z = self.spline.interpolate_sequence(
                         self._focusz, 
                         interpolation_parameter,
                         do_loop)
             camera_state.focus= Vec3([focus_x, focus_y, focus_z])
             camera_state.zFocus_vheight = self.spline.interpolate_sequence(
                         self._zfv,
                         interpolation_parameter,
                         do_loop)
             quat = self.spline.interpolate_quaternion_sequence(
                         self._quat,
                         interpolation_parameter,
                         do_loop)
             camera_state.rotation = quat.to_rotation()
             if real_time:
                 while timer.elapsed() < time*1000.0:
                     # TODO - use threading instead
                     QCoreApplication.processEvents()
             frame = KeyFrame(camera_state)
             frame.frame_number = frame_number + 1
             frame.key_frame_number = key_frame_number + 1
             yield frame
             key_frame_time += dtime
             time += dtime
             frame_number += 1
             if (not do_loop) and (key_frame_number == len(self._key_frames) - 1):
                 return # Don't go past final frame
         key_frame_number += 1
예제 #9
0
    def on_action_update_triggered(self):
        """Sequentially updates all series in the database.

        .. todo::
            Update should also recognize/announce updated episodes.

        """
        series_factory = SeriesFactory()

        for series in db_get_series():
            logger.info("Updating series '{}'".format(series.series_name))

            tvdb_show = tvdb.get_series(series.id, "en", cache=False)
            tvdb_show.update()
            tvdb_show.load_banners()
            series_factory.new_series(tvdb_show, update=series)
            db_commit()

            series_index = self.model.index_of(series)

            for removed_season in series_factory.removed:
                season_index = self.model.index_of(removed_season, series_index)
                season_row = self.model.node_at(season_index).child_index()
                self.model.removeRow(season_row, series_index)
                logger.info("  Removed season {} from series '{}'".format(
                    removed_season.season_number, series.series_name))

            for added_season in series_factory.added:
                self.model.add_item(added_season, series_index)
                logger.info(
                    "  Added season {}".format(added_season.season_number))

            for updated_season in series_factory.updated:
                season, added_episodes, removed_episodes = updated_season

                logger.info(
                    "  Updated season {} (Episodes added: {}, removed: {})".format(
                        season.season_number, len(added_episodes),
                        len(removed_episodes)))

                season_index = self.model.index_of(season, series_index)

                for removed_episode in removed_episodes:
                    episode_index = self.model.index_of(removed_episode,
                                                        season_index)
                    episode_row = self.model.node_at(
                        episode_index).child_index()
                    self.model.removeRow(episode_row, season_index)
                for added_episode in added_episodes:
                    self.model.add_item(added_episode, season_index)

            series_factory.reset()
            QCoreApplication.processEvents()
예제 #10
0
    def readline ( self ):
        """ Emulate a file object.
        """
        self._reading = True
        self._clear_line()
        self.moveCursor( QTextCursor.EndOfLine )

        while self._reading:
            QCoreApplication.processEvents()

        if self._line.length():
            return str( self._line )

        return '\n'
예제 #11
0
    def on_search_button_clicked(self):
        """Performs the search for series.

        Called whenever a search is triggered. Gets a search string from
        the dialog's text field and uses the :mod:`.tvdb` module to retrieve
        matching series. Results are being added to the dialog's model for
        displaying them.

        """
        search = tvdb.search(self.ui.search_text_field.text(), "en")

        self.model.clear()

        for show in search:
            show.load_banners()
            self.model.add_node(SearchNode(show))
            QCoreApplication.processEvents()
예제 #12
0
파일: qt4reactor.py 프로젝트: shvar/redfs
class QtReactor(posixbase.PosixReactorBase):
    implements(IReactorFDSet)


    def __init__(self):
        _assert(in_main_thread())
        self._reads = {}
        self._writes = {}
        self._notifiers = {}
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate)

        self.qApp = QCoreApplication.instance()
        self._ownApp=False
        if self.qApp is None:
            self.qApp=QCoreApplication([])
            self._ownApp=True
        self._blockApp = None
        posixbase.PosixReactorBase.__init__(self)


    def _add(self, xer, primary, type):
        _assert(in_main_thread())
        """
        Private method for adding a descriptor from the event loop.

        It takes care of adding it if  new or modifying it if already added
        for another state (read -> read/write for example).
        """
        if xer not in primary:
            primary[xer] = TwistedSocketNotifier(None, self, xer, type)


    def addReader(self, reader):
        _assert(in_main_thread())
        """
        Add a FileDescriptor for notification of data available to read.
        """
        self._add(reader, self._reads, QSocketNotifier.Read)


    def addWriter(self, writer):
        _assert(in_main_thread())
        """
        Add a FileDescriptor for notification of data available to write.
        """
        self._add(writer, self._writes, QSocketNotifier.Write)


    def _remove(self, xer, primary):
        _assert(in_main_thread())
        """
        Private method for removing a descriptor from the event loop.

        It does the inverse job of _add, and also add a check in case of the fd
        has gone away.
        """
        if xer in primary:
            notifier = primary.pop(xer)
            notifier.shutdown()


    def removeReader(self, reader):
        _assert(in_main_thread())
        """
        Remove a Selectable for notification of data available to read.
        """
        self._remove(reader, self._reads)


    def removeWriter(self, writer):
        _assert(in_main_thread())
        """
        Remove a Selectable for notification of data available to write.
        """
        self._remove(writer, self._writes)


    def removeAll(self):
        _assert(in_main_thread())
        """
        Remove all selectables, and return a list of them.
        """
        rv = self._removeAll(self._reads, self._writes)
        return rv


    def getReaders(self):
        _assert(in_main_thread())
        return self._reads.keys()


    def getWriters(self):
        _assert(in_main_thread())
        return self._writes.keys()


    def callLater(self, howlong, *args, **kargs):
        try:
            _assert(in_main_thread(), (args, kargs))
        except AssertionError:
            for arg in args:
                if isinstance(arg, partial):
                    logger.debug('in callLater: %r', arg.func)
                elif isinstance(arg, LoopingCall):
                    if isinstance(arg.f, partial):
                        logger.debug('in callLater: %r', arg.f.func)
                    else:
                        logger.debug('in callLater: %r', arg.f)
            sys.exit()
        rval = super(QtReactor, self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval


    def reactorInvocation(self):
        _assert(in_main_thread())
        self._timer.stop()
        self._timer.setInterval(0)
        self._timer.start()


    def _iterate(self, delay=None, fromqt=False):
        _assert(in_main_thread())
        """
        See twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay, fromqt)


    iterate = _iterate


    def doIteration(self, delay=None, fromqt=False):
        _assert(in_main_thread())
        """
        This method is called by a Qt timer or by network activity on
        a file descriptor.

        If called becuase of network activiy then control should not
        be handed back to Qt as this would cause recursion.
        """

        if not self.running and self._blockApp:
            self._blockApp.quit()

        self._timer.stop()
        delay = max(delay, 1)
        if not fromqt:
            self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000)
        if self.timeout() is None:
            timeout = 0.1
        elif self.timeout() == 0:
            timeout = 0
        else:
            timeout = self.timeout()
        self._timer.setInterval(timeout * 1000)
        self._timer.start()


    def runReturn(self, installSignalHandlers=True):
        _assert(in_main_thread())
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self.reactorInvocation()


    def crash(self):
        _assert(in_main_thread())
        log.msg('crash')
        super(QtReactor, self).crash()
        if self._blockApp:
            self._blockApp.quit()


    def run(self, installSignalHandlers=True):
        _assert(in_main_thread())
        if self._ownApp:
            self._blockApp = self.qApp
        else:
            self._blockApp = QEventLoop()
        self.runReturn()
        self._blockApp.exec_()
예제 #13
0
class QtReactor(posixbase.PosixReactorBase):
    implements(IReactorFDSet)

    def __init__(self):
        self._reads = {}
        self._writes = {}
        self._notifiers = {}
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate)

        if QCoreApplication.instance() is None:
            # Application Object has not been started yet
            self.qApp=QCoreApplication([])
            self._ownApp=True
        else:
            self.qApp = QCoreApplication.instance()
            self._ownApp=False
        self._blockApp = None
        posixbase.PosixReactorBase.__init__(self)


    def _add(self, xer, primary, type):
        """
Private method for adding a descriptor from the event loop.

It takes care of adding it if new or modifying it if already added
for another state (read -> read/write for example).
"""
        if xer not in primary:
            primary[xer] = TwistedSocketNotifier(None, self, xer, type)


    def addReader(self, reader):
        """
Add a FileDescriptor for notification of data available to read.
"""
        self._add(reader, self._reads, QSocketNotifier.Read)


    def addWriter(self, writer):
        """
Add a FileDescriptor for notification of data available to write.
"""
        self._add(writer, self._writes, QSocketNotifier.Write)


    def _remove(self, xer, primary):
        """
Private method for removing a descriptor from the event loop.

It does the inverse job of _add, and also add a check in case of the fd
has gone away.
"""
        if xer in primary:
            notifier = primary.pop(xer)
            notifier.shutdown()

        
    def removeReader(self, reader):
        """
Remove a Selectable for notification of data available to read.
"""
        self._remove(reader, self._reads)


    def removeWriter(self, writer):
        """
Remove a Selectable for notification of data available to write.
"""
        self._remove(writer, self._writes)


    def removeAll(self):
        """
Remove all selectables, and return a list of them.
"""
        rv = self._removeAll(self._reads, self._writes)
        return rv


    def getReaders(self):
        return self._reads.keys()


    def getWriters(self):
        return self._writes.keys()


    def callLater(self,howlong, *args, **kargs):
        rval = super(QtReactor,self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval


    def reactorInvocation(self):
        self._timer.stop()
        self._timer.setInterval(0)
        self._timer.start()
        

    def _iterate(self, delay=None, fromqt=False):
        """See twisted.internet.interfaces.IReactorCore.iterate.
"""
        self.runUntilCurrent()
        self.doIteration(delay, fromqt)

    iterate = _iterate

    def doIteration(self, delay=None, fromqt=False):
        'This method is called by a Qt timer or by network activity on a file descriptor'
        
        if not self.running and self._blockApp:
            self._blockApp.quit()
        self._timer.stop()
        delay = max(delay, 1)
        if not fromqt:
            self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000)
        if self.timeout() is None:
            timeout = 0.1
        elif self.timeout() == 0:
            timeout = 0
        else:
            timeout = self.timeout()
        self._timer.setInterval(timeout * 1000)
        self._timer.start()


    def runReturn(self, installSignalHandlers=True):
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self.reactorInvocation()


    def run(self, installSignalHandlers=True):
        if self._ownApp:
            self._blockApp = self.qApp
        else:
            self._blockApp = QEventLoop()
        self.runReturn()
        self._blockApp.exec_()
예제 #14
0
    def setUp(self):
        super().setUp()

        for series in db_get_series():
            self.window.model.add_item(series)
        QCoreApplication.processEvents();
예제 #15
0
파일: gui.py 프로젝트: mrf345/chrome-cut
def gui():
    appg = QApplication(argv)
    window = CC_window()
    QCoreApplication.processEvents()
    appg.exec_()
    exit(0)
예제 #16
0
파일: query.py 프로젝트: j3doucet/DBNN.NASA
def query_objects(mpec_data, mainWindow, new_query=True):
    wise_filename = "WISE_results.csv"
    if new_query:
        mpec_data_new = []
        for i in range(0, len(mpec_data)):
            print("Querying " + str(i) + " out of " + str(len(mpec_data)))
            mainWindow.ReadProgressBar.setValue(50 + 25 * i / len(mpec_data))
            QCoreApplication.processEvents()
            entry = mpec_data[i]
            ra_dec = formatCoords(entry['ra'], entry['dec'])
            #only do the first one until we're sure we got it right
            [num_sources, closest_entry] = get_ipac(ra_dec, new_query)
            mpec_data[i]["num_sources"] = num_sources
            for j in range(1, 5):
                key = "w" + str(j) + "mpro"
                key2 = "w" + str(j) + "sigmpro"
                mpec_data[i][key] = closest_entry[key]
                if closest_entry[key2] == "null":
                    mpec_data[i][key2] = 0
                else:
                    mpec_data[i][key2] = closest_entry[key2]
            mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_data))
            QCoreApplication.processEvents()
        #write this data to a file for future use
        f_out = open(wise_filename, "w+")
        keys = mpec_data[0].keys()
        f_out.write(",".join(keys) + "\n")
        for entry in mpec_data:
            str_out = ""
            for key in keys:
                if isinstance(entry[key], list):
                    tmpstr = str(entry[key][0]) + " " + str(
                        entry[key][1]) + " " + str(entry[key][2])
                    #str_out+=tmpstr+","
                if isinstance(entry[key], datetime.date):
                    tmpstr = entry[key].strftime("%Y-%m-%d")
                    str_out += tmpstr + ","
                else:
                    str_out += str(entry[key]) + ","
            f_out.write(str_out + "\n")
        f_out.close()
    else:
        print "loading old data"
        #load old data
        if not os.path.exists(wise_filename):
            print("File not found!")
            return 0
        f_in = open(wise_filename, "r")
        lines = f_in.readlines()
        mpec_data = []
        for i in range(0, len(lines)):
            if i == 0:
                keys = lines[i].split(",")
            else:
                row = {}
                cells = lines[i].split(",")
                data_int = 0
                for j in range(0, len(keys)):
                    keys[j] = keys[j].strip()
                    if keys[j].find("date") > 0:
                        parts = cells[data_int].split("-")
                        tmp_date = datetime.date(int(parts[0]), int(parts[1]),
                                                 int(parts[2]))
                        row[keys[j]] = tmp_date
                        data_int += 1
                    elif keys[j].find("ra") >= 0 or keys[j].find("dec") >= 0:

                        parts = [0, 0, 0]
                        for k in range(0, 3):
                            cells[data_int] = cells[data_int].replace("[", "")
                            cells[data_int] = cells[data_int].replace("]", "")
                            cells[data_int] = cells[data_int].replace("'", "")
                            parts[k] = float(cells[data_int])
                            data_int += 1
                        row[keys[j]] = parts
                    else:
                        row[keys[j]] = cells[data_int]
                        data_int += 1
                row["dec"] = row["last_dec"]
                mpec_data.append(row)
        mainWindow.ReadProgressBar.setValue(75)
    print "load dec 2 " + str(mpec_data[1]["dec"][0])
    return mpec_data
예제 #17
0
    def wait_event(self, queue):
        from PySide.QtCore import QCoreApplication

        while queue.empty():
            QCoreApplication.processEvents()
        return queue.get_nowait()
예제 #18
0
    def wait_event(self, queue):
        from PySide.QtCore import QCoreApplication

        while queue.empty():
            QCoreApplication.processEvents()
        return queue.get_nowait()
예제 #19
0
class QTReactor(PosixReactorBase):
    """
    Qt based reactor.
    """
    implements(IReactorFDSet)

    _timer = None

    def __init__(self):
        self._reads = {}
        self._writes = {}
        self._timer=QTimer()
        self._timer.setSingleShot(True)
        if QCoreApplication.startingUp():
            self.qApp=QCoreApplication([])
            self._ownApp=True
        else:
            self.qApp = QCoreApplication.instance()
            self._ownApp=False
        self._blockApp = None
        self._readWriteQ=[]

        """ some debugging instrumentation """
        self._doSomethingCount=0

        PosixReactorBase.__init__(self)

    def addReader(self, reader):
        if not reader in self._reads:
            self._reads[reader] = TwistedSocketNotifier(self, reader,
                                                       QSocketNotifier.Read)


    def addWriter(self, writer):
        if not writer in self._writes:
            self._writes[writer] = TwistedSocketNotifier(self, writer,
                                                        QSocketNotifier.Write)


    def removeReader(self, reader):
        if reader in self._reads:
            #self._reads[reader].shutdown()
            #del self._reads[reader]
            self._reads.pop(reader).shutdown()

    def removeWriter(self, writer):
        if writer in self._writes:
            self._writes[writer].shutdown()
            #del self._writes[writer]
            self._writes.pop(writer)


    def removeAll(self):
        return self._removeAll(self._reads, self._writes)


    def getReaders(self):
        return self._reads.keys()


    def getWriters(self):
        return self._writes.keys()

    def callLater(self,howlong, *args, **kargs):
        rval = super(QTReactor,self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval

    def crash(self):
        super(QTReactor,self).crash()

    def iterate(self,delay=0.0):
        t=self.running # not sure I entirely get the state of running
        self.running=True
        self._timer.stop() # in case its not (rare?)
        try:
            if delay == 0.0:
                self.reactorInvokePrivate()
                self._timer.stop() # supports multiple invocations
            else:
                endTime = delay + time.time()
                self.reactorInvokePrivate()
                while True:
                    t = endTime - time.time()
                    if t <= 0.0: return
                    self.qApp.processEvents(QEventLoop.AllEvents |
                                      QEventLoop.WaitForMoreEvents,t*1010)
        finally:
            self.running=t

    def addReadWrite(self,t):
        self._readWriteQ.append(t)

    def runReturn(self, installSignalHandlers=True):
        QObject.connect(self._timer, SIGNAL("timeout()"),
                        self.reactorInvokePrivate)
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self._timer.start(0)

    def run(self, installSignalHandlers=True):
        try:
            if self._ownApp:
                self._blockApp=self.qApp
            else:
                self._blockApp = fakeApplication()
            self.runReturn(installSignalHandlers)
            self._blockApp.exec_()
        finally:
            self._timer.stop() # should already be stopped

    def reactorInvocation(self):
        self._timer.setInterval(0)

    def reactorInvokePrivate(self):
        if not self.running:
            self._blockApp.quit()
        self._doSomethingCount += 1
        self.runUntilCurrent()
        t = self.timeout()
        if t is None: t=0.1
        else: t = min(t,0.1)
        self._timer.setInterval(t*1010)
        self.qApp.processEvents() # could change interval
        self._timer.start()

    def doIteration(self):
        assert False, "doiteration is invalid call"
예제 #20
0
class QtReactor(posixbase.PosixReactorBase):
    implements(IReactorFDSet)

    def __init__(self):
        self._reads = {}
        self._writes = {}
        self._notifiers = {}
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate)

        if QCoreApplication.instance() is None:
            # Application Object has not been started yet
            self.qApp = QCoreApplication([])
            self._ownApp = True
        else:
            self.qApp = QCoreApplication.instance()
            self._ownApp = False
        self._blockApp = None
        posixbase.PosixReactorBase.__init__(self)

    def _add(self, xer, primary, type):
        """
Private method for adding a descriptor from the event loop.

It takes care of adding it if new or modifying it if already added
for another state (read -> read/write for example).
"""
        if xer not in primary:
            primary[xer] = TwistedSocketNotifier(None, self, xer, type)

    def addReader(self, reader):
        """
Add a FileDescriptor for notification of data available to read.
"""
        self._add(reader, self._reads, QSocketNotifier.Read)

    def addWriter(self, writer):
        """
Add a FileDescriptor for notification of data available to write.
"""
        self._add(writer, self._writes, QSocketNotifier.Write)

    def _remove(self, xer, primary):
        """
Private method for removing a descriptor from the event loop.

It does the inverse job of _add, and also add a check in case of the fd
has gone away.
"""
        if xer in primary:
            notifier = primary.pop(xer)
            notifier.shutdown()

    def removeReader(self, reader):
        """
Remove a Selectable for notification of data available to read.
"""
        self._remove(reader, self._reads)

    def removeWriter(self, writer):
        """
Remove a Selectable for notification of data available to write.
"""
        self._remove(writer, self._writes)

    def removeAll(self):
        """
Remove all selectables, and return a list of them.
"""
        rv = self._removeAll(self._reads, self._writes)
        return rv

    def getReaders(self):
        return self._reads.keys()

    def getWriters(self):
        return self._writes.keys()

    def callLater(self, howlong, *args, **kargs):
        rval = super(QtReactor, self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval

    def reactorInvocation(self):
        self._timer.stop()
        self._timer.setInterval(0)
        self._timer.start()

    def _iterate(self, delay=None, fromqt=False):
        """See twisted.internet.interfaces.IReactorCore.iterate.
"""
        self.runUntilCurrent()
        self.doIteration(delay, fromqt)

    iterate = _iterate

    def doIteration(self, delay=None, fromqt=False):
        'This method is called by a Qt timer or by network activity on a file descriptor'

        if not self.running and self._blockApp:
            self._blockApp.quit()
        self._timer.stop()
        delay = max(delay, 1)
        if not fromqt:
            self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000)
        if self.timeout() is None:
            timeout = 0.1
        elif self.timeout() == 0:
            timeout = 0
        else:
            timeout = self.timeout()
        self._timer.setInterval(timeout * 1000)
        self._timer.start()

    def runReturn(self, installSignalHandlers=True):
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self.reactorInvocation()

    def run(self, installSignalHandlers=True):
        if self._ownApp:
            self._blockApp = self.qApp
        else:
            self._blockApp = QEventLoop()
        self.runReturn()
        self._blockApp.exec_()
예제 #21
0
파일: query.py 프로젝트: j3doucet/DBNN.NASA
def query_objects(mpec_data,mainWindow,new_query = True):
	wise_filename = "WISE_results.csv"
	if new_query:
		mpec_data_new = []
		for i in range(0,len(mpec_data)):
			print("Querying "+str(i)+" out of "+str(len(mpec_data)))
			mainWindow.ReadProgressBar.setValue(50+25*i/len(mpec_data))
			QCoreApplication.processEvents()
			entry = mpec_data[i]
			ra_dec = formatCoords(entry['ra'],entry['dec'])
			#only do the first one until we're sure we got it right
			[num_sources, closest_entry] = get_ipac(ra_dec,new_query)
			mpec_data[i]["num_sources"] = num_sources
			for j in range(1,5):
				key = "w"+str(j)+"mpro"
				key2 = "w"+str(j)+"sigmpro"
				mpec_data[i][key] = closest_entry[key]
				if closest_entry[key2]=="null":
					mpec_data[i][key2] = 0
				else:
					mpec_data[i][key2] = closest_entry[key2]
			mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_data))
			QCoreApplication.processEvents()
		#write this data to a file for future use
		f_out = open(wise_filename,"w+")
		keys = mpec_data[0].keys()
		f_out.write(",".join(keys)+"\n")
		for entry in mpec_data:
			str_out = ""
			for key in keys:
				if isinstance(entry[key],list):
					tmpstr=str(entry[key][0])+" "+str(entry[key][1])+" "+str(entry[key][2])
					#str_out+=tmpstr+","
				if isinstance(entry[key],datetime.date):
					tmpstr=entry[key].strftime("%Y-%m-%d")
					str_out+=tmpstr+","
				else:
					str_out +=str(entry[key])+","
			f_out.write(str_out+"\n")
		f_out.close()
	else:
		print "loading old data"
		#load old data
		if not os.path.exists(wise_filename):
			print("File not found!")
			return 0
		f_in = open(wise_filename,"r")
		lines = f_in.readlines()
		mpec_data = []
		for i in range(0,len(lines)):
			if i ==0:
				keys = lines[i].split(",")
			else:
				row = {}
				cells = lines[i].split(",")
				data_int = 0
				for j in range(0,len(keys)):
					keys[j]= keys[j].strip()
					if keys[j].find("date")>0:
						parts = cells[data_int].split("-")
						tmp_date = datetime.date(int(parts[0]),int(parts[1]),int(parts[2]))
						row[keys[j]] = tmp_date
						data_int+=1
					elif keys[j].find("ra")>=0 or keys[j].find("dec")>=0:
						
						parts = [0,0,0]
						for k in range(0,3):
							cells[data_int] = cells[data_int].replace("[","")
							cells[data_int] = cells[data_int].replace("]","")
							cells[data_int] = cells[data_int].replace("'","")
							parts[k] = float(cells[data_int])
							data_int+=1
						row[keys[j]] = parts
					else:
						row[keys[j]]=cells[data_int]
						data_int+=1
				row["dec"] = row["last_dec"]
				mpec_data.append(row)
		mainWindow.ReadProgressBar.setValue(75)
	print "load dec 2 "+str(mpec_data[1]["dec"][0])
	return mpec_data