当前位置: 首页>>代码示例>>Python>>正文


Python Timer.seconds方法代码示例

本文整理汇总了Python中timer.Timer.seconds方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.seconds方法的具体用法?Python Timer.seconds怎么用?Python Timer.seconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在timer.Timer的用法示例。


在下文中一共展示了Timer.seconds方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: runScript

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
def runScript(fn,argv=[]):
    """Play a formex script from file fn.

    fn is the name of a file holding a pyFormex script.
    A list of arguments can be passed. They will be available under the name
    argv. This variable can be changed by the script and the resulting argv
    is returned to the caller.
    """
    from timer import Timer
    t = Timer()
    msg = "Running script (%s)" % fn
    if pf.GUI:
        pf.GUI.scripthistory.add(fn)
        pf.board.write(msg,color='red')
    else:
        message(msg)
    pf.debug("  Executing with arguments: %s" % argv,pf.DEBUG.SCRIPT)
    pye = fn.endswith('.pye')
    if pf.GUI and getcfg('check_print'):
        pf.debug("Testing script for use of print function",pf.DEBUG.SCRIPT)
        scr = checkPrintSyntax(fn)
        #
        # TODO: if scr is a compiled object, we could just execute it
        #

    res = playScript(file(fn,'r'),fn,fn,argv,pye)
    pf.debug("  Arguments left after execution: %s" % argv,pf.DEBUG.SCRIPT)
    msg = "Finished script %s in %s seconds" % (fn,t.seconds())
    if pf.GUI:
        pf.board.write(msg,color='red')
    else:
        message(msg)
    return res
开发者ID:dladd,项目名称:pyFormex,代码行数:35,代码来源:script.py

示例2: playFile

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
def playFile(fn,argv=[]):
    """Play a formex script from file fn.

    fn is the name of a file holding a pyFormex script.
    A list of arguments can be passed. They will be available under the name
    argv. This variable can be changed by the script and the resulting argv
    is returned to the caller.
    """
    from timer import Timer
    t = Timer()
    message("Running script (%s)" % fn)
    pf.debug("  Executing with arguments: %s" % argv)
    res = playScript(file(fn,'r'),fn,fn,argv,fn.endswith('.pye'))
    pf.debug("  Arguments left after execution: %s" % argv)
    message("Finished script %s in %s seconds" % (fn,t.seconds()))
    return res
开发者ID:BackupTheBerlios,项目名称:pyformex-svn,代码行数:18,代码来源:script.py

示例3: EventRecorder

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
class EventRecorder( QObject ):
    """
    Records spontaneous events from the UI and serializes them as strings that can be evaluated in Python.
    """
    def __init__(self, parent=None, ignore_parent_events=True):
        QObject.__init__(self, parent=parent)
        self._ignore_parent_events = False
        if parent is not None and ignore_parent_events:
            self._ignore_parent_events = True
            self._parent_name = get_fully_qualified_name(parent)
        self._captured_events = []
        self._timer = Timer()
        
        assert isinstance(QApplication.instance(), EventRecordingApp)
        QApplication.instance().aboutToNotify.connect( self.handleApplicationEvent )

        # We keep track of which mouse buttons are currently checked in this set.
        # If we see a Release event for a button we think isn't pressed, then we missed something.
        # In that case, we simply generate a fake Press event.  (See below.)
        # This fixes a problem that can occur in Linux:
        # If the application doesn't have focus, but the user clicks a button in the window anyway,
        # the window is activated and the button works normally during recording.  
        # However, the "press" event is not recorded, and the button is never activated during playback.
        # This hack allows us to recognize that we missed the click and generate it anyway.
        self._current_observed_mouse_presses = set()

    def handleApplicationEvent(self, receiver, event):
        if not self.paused:
            self.captureEvent(receiver, event)

    @property
    def paused(self):
        return self._timer.paused

    IgnoredEventTypes = set( [ QEvent.Paint,
                              QEvent.KeyboardLayoutChange,
                              QEvent.WindowActivate,
                              QEvent.WindowDeactivate,
                              QEvent.ActivationChange,
                              QEvent.FileOpen,
                              QEvent.Clipboard,
                              # These event symbols are not exposed in pyqt, so we pull them from our own enum
                              EventTypes.Style,
                              EventTypes.ApplicationActivate,
                              EventTypes.ApplicationDeactivate,
                              EventTypes.NonClientAreaMouseMove,
                              EventTypes.NonClientAreaMouseButtonPress,
                              EventTypes.NonClientAreaMouseButtonRelease,
                              EventTypes.NonClientAreaMouseButtonDblClick
                               ] )
    IgnoredEventClasses = (QChildEvent, QTimerEvent, QGraphicsSceneMouseEvent, QWindowStateChangeEvent, QMoveEvent)

    def captureEvent(self, watched, event):
        if self._shouldSaveEvent(event):
            try:
                eventstr = event_to_string(event)
            except KeyError:
                logger.warn("Don't know how to record event: {}".format( str(event) ))
                print "Don't know how to record", str(event)
            else:
                # Perform a full garbage collection before determining the name of this widget
                gc.collect()
                if sip.isdeleted(watched):
                    return
                timestamp_in_seconds = self._timer.seconds()
                objname = str(get_fully_qualified_name(watched))
                if not ( self._ignore_parent_events and objname.startswith(self._parent_name) ):
                    # Special case: If this is a MouseRelease and we somehow missed the MousePress,
                    #               then create a "synthetic" MousePress and insert it immediately before the release
                    if event.type() == QEvent.MouseButtonPress or event.type() == QEvent.MouseButtonDblClick:
                        self._current_observed_mouse_presses.add( event.button() )
                    elif event.type() == QEvent.MouseButtonRelease:
                        try:
                            self._current_observed_mouse_presses.remove( event.button() )
                        except KeyError:
                            synthetic_press_event = QMouseEvent( QEvent.MouseButtonPress, event.pos(), event.globalPos(), event.button(), event.buttons(), event.modifiers() )
                            synthetic_eventstr = event_to_string(synthetic_press_event)
                            self._captured_events.append( (synthetic_eventstr, objname, timestamp_in_seconds) )
                    self._captured_events.append( (eventstr, objname, timestamp_in_seconds) )
        return

    def insertComment(self, comment):
        self._captured_events.append( (comment, "comment", None) )

    def _shouldSaveEvent(self, event):
        if isinstance(event, QMouseEvent):
            # Ignore most mouse movement events if the user isn't pressing anything.
            if event.type() == QEvent.MouseMove \
                and int(event.button()) == 0 \
                and int(event.buttons()) == 0 \
                and int(event.modifiers()) == 0:

                # If mouse tracking is enabled for this widget, 
                #  then we'll assume mouse movements are important to it.
                widgetUnderCursor = QApplication.instance().widgetAt( QCursor.pos() )
                if widgetUnderCursor is not None and widgetUnderCursor.hasMouseTracking():
                    return True

                # Somewhat hackish (and slow), but we have to record mouse movements during combo box usage.
                # Same for QMenu usage (on Mac, it doesn't seem to matter, but on Fedora it does matter.)
#.........这里部分代码省略.........
开发者ID:ilastik,项目名称:eventcapture,代码行数:103,代码来源:eventRecorder.py

示例4: add_location

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
 def add_location(self, pos = None):
     if pos is None:
         pos = helpers.parse_coords(self.location_str.get())
     pos = tuple(pos)
     styles = ["b", "g", "r", "c", "m", "y", "k"]
     threshold = 1e-4
     if len(pos) == 2:
         pos = pos[0], pos[1], 0.0
     if PROJECTIONS[self.opts.projection.get()] != '3d':
         pos = pos[0], pos[1], 0.0
         self.location_str.set("%0.4g, %0.4g" % (pos[0], pos[1]))
     else:
         self.location_str.set("%0.4g, %0.4g, %0.4g" % pos)
     #Search for a fixed point
     ## fp = self.system.find_fp(pos, threshold = 1e-4)
     ## if fp is not None:
     ##     fp_clean = tuple(np.round(fp, 3))
     ##     if not fp_clean in self.fixed_points:
     ##         self.fixed_points.add(fp_clean)
     ##         self.fig.draw_fp(fp_clean)
     ##         self.update_fig()
     ##         vel = self.system(fp_clean)
     ##         logging.info("Found a fixed point: %s %s\n" % (str(fp_clean), str(vel)))
     if pos in self.trajectories:
         logging.warning("Trajectory already exists.")
         self.status.info("Trajectory already exists.")
         return
     self.status.info("Computing trajectory...")
     try:
         t = Timer()
         t.start()
         traj = self.system.trajectory(pos, self.opts.tmax.get(), threshold = threshold,
             bidirectional = self.opts.reverse.get(), nsteps = 5 * (self.opts.tmax.get()/self.opts.dt.get()),
             max_step = self.opts.dt.get(), use_ode = True)
         t.stop()
         logging.debug("Computing trajectory (%d points) took %g seconds" % (len(traj.x), t.seconds()))
     except:
         pos_str = ", ".join(map(str, pos))
         logging.warning("Could not compute trajectory from: %s" % pos_str)
         logging.debug(traceback.format_exc())
         return
     #if traj.dist[-1] < 10*threshold:
     #    return
     self.trajectories[pos] = traj
     if traj.t[-1] > self.anim_tmax:
         self.anim_tmax = traj.t[-1]
     style = (len(self.trajectories) - 1) % len(styles)
     traj.style = styles[style]
     self.status.info("Drawing trajectory...")
     self.fig.add_trajectory(traj)
     self.status.clear()
     #self.fig.draw_trajectory(traj)
     self.fig.draw()
     self.last_loc = pos
开发者ID:grajkiran,项目名称:ezeplot,代码行数:56,代码来源:gui.py

示例5: runApp

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
def runApp(appname,argv=[],refresh=False):
    global exitrequested
    if len(pf.scriptlock) > 0:
        pf.message("!!Not executing because a script lock has been set: %s" % pf.scriptlock)
        #print(pf.scriptlock)
        return

    import apps
    from timer import Timer
    t = Timer()
    pf.message("Loading application %s with refresh=%s" % (appname,refresh))
    app = apps.load(appname,refresh=refresh)
    if app is None:
        errmsg = "An  error occurred while loading application %s" % appname
        if pf.GUI:
            if apps._traceback and pf.cfg['showapploaderrors']:
                print(apps._traceback)

            from gui import draw
            fn = apps.findAppSource(appname)
            if os.path.exists(fn):
                errmsg += "\n\nYou may try executing the application as a script,\n  or you can load the source file in the editor."
                res = draw.ask(errmsg,choices=['Run as script', 'Load in editor', "Don't bother"])
                if res[0] in 'RL':
                    if res[0] == 'L':
                        draw.editFile(fn)
                    elif res[0] == 'R':
                        pf.GUI.setcurfile(fn)
                        draw.runScript(fn)
            else:
                errmsg += "and I can not find the application source file."
                draw.error(errmsg)
        else:
            error(errmsg)

        return

    if hasattr(app,'_status') and app._status == 'unchecked':
        pf.warning("This looks like an Example script that has been automatically converted to the pyFormex Application model, but has not been checked yet as to whether it is working correctly in App mode.\nYou can help here by running and rerunning the example, checking that it works correctly, and where needed fixing it (or reporting the failure to us). If the example runs well, you can change its status to 'checked'")

    scriptLock('__auto__')
    msg = "Running application '%s' from %s" % (appname,app.__file__)
    pf.scriptName = appname
    if pf.GUI:
        pf.GUI.startRun()
        pf.GUI.apphistory.add(appname)
        pf.board.write(msg,color='green')
    else:
        message(msg)
    pf.debug("  Passing arguments: %s" % argv,pf.DEBUG.SCRIPT)
    app._args_ = argv
    try:
        try:
            res = app.run()
        except _Exit:
            pass
        except _ExitSeq:
            exitrequested = True
        except:
            raise
    finally:
        if hasattr(app,'atExit'):
            app.atExit()
        if pf.cfg['autoglobals']:
            g = app.__dict__
            exportNames = listAll(clas=Geometry,dic=g)
            pf.PF.update([(k,g[k]) for k in exportNames])
        scriptRelease('__auto__') # release the lock
        if pf.GUI:
            pf.GUI.stopRun()

    pf.debug("  Arguments left after execution: %s" % argv,pf.DEBUG.SCRIPT)
    msg = "Finished %s in %s seconds" % (appname,t.seconds())
    if pf.GUI:
        pf.board.write(msg,color='green')
    else:
        message(msg)
    pf.debug("Memory: %s" % vmSize(),pf.DEBUG.MEM)
开发者ID:dladd,项目名称:pyFormex,代码行数:80,代码来源:script.py

示例6: run

# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import seconds [as 别名]
def run():
    clear()
    smooth()

    options = ["Cancel","Image files","DICOM files","Generated from function"]
    ans = ask("This IsoSurface example can either reconstruct a surface from a series of 2D images, or it can use data generated from a function. Use which data?",options)
    ans = options.index(ans)

    if ans == 0:
        return

    elif ans in [1,2]:
        ## fp = askDirname(byfile=True)
        ## if not fp:
        ##     return

        ## files = utils.listTree(fp,listdirs=False)

        fn = askFilename(multi=True)
        if not fn:
            return

        if len(fn) == 1:
            files = utils.NameSequence(fn[0]).files()

        print(files)

        if ans == 1:
            data = loadImages(files)
            scale = ones(3)
        else:
            data,scale = ia.dicom2numpy(files)
            print("Spacing: %s" % scale)
            # normalize
            dmin,dmax = data.min(),data.max()
            data = (data-dmin).astype(float32)/(dmax-dmin)

        # level at which the isosurface is computed
        res = askItems([('isolevel',0.5)])
        if not res:
            return
        level = res['isolevel']
        if level <= 0.0 or level >= 1.0:
            level = data.mean()

    else:
        # data space: create a grid to visualize
        if ack("Large model (takes some time)?"):
            nx,ny,nz = 100,150,200 # for time testing
        else:
            nx,ny,nz = 6,8,10
        F = elements.Hex8.toFormex().rep([nz,ny,nx]).setProp(1)
        #draw(F,mode='wireframe')

        # function to generate data: the distance from the origin
        dist = lambda x,y,z: sqrt(x*x+y*y+z*z)
        data = fromfunction(dist,(nz+1,ny+1,nx+1))
        scale = ones(3)

        # level at which the isosurface is computed
        level = 0.5*data.max()

    print("IMAGE DATA: %s, %s" % (data.shape,data.dtype))
    print("Pixel Spacing: %s" % str(scale))
    print("levels: min = %s, max = %s" % (data.min(),data.max()))
    print("isolevel: %s" % level)

    fast = True

    # Compute the isosurface
    from timer import Timer
    pf.GUI.setBusy()
    timer = Timer()
    tri = sf.isosurface(data,level,nproc=4)
    sec = timer.seconds()
    print("Got %s triangles in %s seconds" % (len(tri),sec))
    if len(tri) > 0:
        S = TriSurface(tri).scale(scale[::-1])
        draw(S)
        export({'isosurf':S})
    pf.GUI.setBusy(False)
开发者ID:dladd,项目名称:pyFormex,代码行数:83,代码来源:IsoSurface.py


注:本文中的timer.Timer.seconds方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。