def run(self): while display.isActive(): scan_id = long(display.getVar("LatestPointScanID")) if scan_id > 0: scanInfo = client.getScanInfo(scan_id) statusLabel.setPropertyValue("text", scanInfo.getState().toString()) if scanInfo.getState().isActive(): scanNameLabel.setPropertyValue("text", scanInfo.getName()) commandLabel.setPropertyValue("text", scanInfo.getCurrentCommand()) progressBar.setPropertyValue( "pv_value", scanInfo.getPercentage() / 100.0) # Mark scanned points as green for i in range(table.getRowCount()): xpos = float(table.getCellText(i, 1)) ypos = float(table.getCellText(i, 2)) if ( xpos == PVUtil.getDouble(pvs[1]) and ypos == PVUtil.getDouble(pvs[2]) and scanInfo.getPercentage() >= i * 100.0 / table.getRowCount() ): #To make sure the matched position is set from this scan Display.getDefault().asyncExec( SetRowColor(i, ColorFontUtil.GREEN)) elif scanInfo.getState().isDone(): display.setVar("LatestPointScanID", -1) else: scanNameLabel.setPropertyValue("text", "None") commandLabel.setPropertyValue("text", "") progressBar.setPropertyValue("pv_value", 0) Thread.sleep(1000)
def flyOneLine(self, gg, bx, by, cy): vpcount = gg.vpCount = 0 for cx in xrange(8): x, y = GeoUtil.getXY(22, 22, bx, by, cx, cy) lastZ = self.getLastZ(bx, by, cx, cy) - 150 self.setLastZ(bx, by, cx, cy, lastZ) if lastZ <= -15000: continue while vpcount > gg.vpCount + 2: Thread.sleep(5) if not gg.isOnline(): print "no gm" self.doneBlock[by * 256 + bx] = 0 return False if not self.gsge.isAlive(): print "gsge error" self.doneBlock[by * 256 + bx] = 0 return False if gg.vpCount > vpcount: vpcount = gg.vpCount self.fly(gg, x, y, lastZ, x, y, lastZ - 16) vpcount += 1 return True
def main(): assert len(sys.argv) == 2 strategy_module = sys.argv[1] path_manager = FilePathManager.getInstance() path_manager.setStrategiesFolderPath(STRATEGY_PATH) client = TesterFactory.getDefaultInstance() client.setSystemListener(SystemListener()) client.connect('file://' + JNLP, LOGIN, PASSWORD) client.setSubscribedInstruments({Instrument.EURUSD}) client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 5000) client.setDataInterval(ITesterClient.DataLoadingMethod.ALL_TICKS, Date(*STARTDATE).getTime(), Date(*ENDDATE).getTime()) client.downloadData(DownloadListener()) Thread.sleep(5000) while 1: strategy_class = load_strategy_from_module(strategy_module) if strategy_class: strategy = strategy_class() client.startStrategy(strategy, ProgressListener()) watch_file_for_changes(strategy_module)
def main(): assert len(sys.argv) == 2 strategy_module = sys.argv[1] path_manager = FilePathManager.getInstance() path_manager.setStrategiesFolderPath(STRATEGY_PATH) client = TesterFactory.getDefaultInstance() client.setSystemListener(SystemListener()) client.connect("file://" + JNLP, LOGIN, PASSWORD) client.setSubscribedInstruments({Instrument.EURUSD}) client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 5000) client.setDataInterval( ITesterClient.DataLoadingMethod.ALL_TICKS, Date(*STARTDATE).getTime(), Date(*ENDDATE).getTime() ) client.downloadData(DownloadListener()) Thread.sleep(5000) while 1: strategy_class = load_strategy_from_module(strategy_module) if strategy_class: strategy = strategy_class() client.startStrategy(strategy, ProgressListener()) watch_file_for_changes(strategy_module)
def __stopAll(self): logger.info("Producer stop BEGIN") # TODO #------- # MANAGE A CLEVER GRACEFUL PERIOD BASED ON GrinderQueue() waiting content # # Graceful period for Async if GrinderQueue. async: logger.debug( '[%s.__stopAll] Async graceful period [%d millisec]' % (self.__class__.__name__, GrinderQueue.graceful_period)) print 'Async graceful period [%d millisec] started ...' % ( GrinderQueue.graceful_period) Thread.sleep(GrinderQueue.graceful_period) # Clean up any tokens still in the queue size = len(self._queue.queue) if size > 0: logger.error( '(stopAll) Producer - Potential issue in your test (Thread starvation) - removing approximatively "%d" tokens' % (size)) # Cleaning up anyway self._queue.queue.clear() # The trick is to poison all consumer to force them to stop for _ in range(self.nbConsumers): self._queue.put(Token(-1)) Thread.sleep(5) logger.info("Producer stop END")
def __checkTokenReceived(self): ''' - return True if the RUN is aborted (async feature) or an explicit STOP RUN is triggered - return False is the token is known or of "None" type ... the run continue Remark: Metronom explicit STOP RUN is done by poisoning the "Token" object with a negative "time_to_sleep" attribute ''' if logger.isTraceEnabled(): logger.trace('_processToken() - [type=%s] [token ="%s"]' % (self.token.__class__.__name__, self.token)) # To ignore so useless Runs due to not executed async calls if isinstance(self.token, AbortRunToken): return True if isinstance(self.token, Token): # All token might be poisoned to stop processing properly if self.token.time_to_sleep < 0: # grace period Thread.sleep(properties.getInt('sleep_before_death', 5000)) logger.trace("Arghhh! - i have been poisoned !") grinder.stopThisWorkerThread() # No need to continue ... return True # Batch mode implementation. Sleep time is done per consumer thread if isinstance(self.token, ThroughputToken) and self.token.wait: Thread.sleep(self.token.time_to_sleep) return False
def bye(): print '' print '.' * 50 print 'bye() - Stopping everything properly ...' logger.info('bye() - Stopping everything properly ...') if Configuration. async: logger.info("Stopping the Async Http server ...") print 'Stopping the Async Http server ... (Graceful period of %d milliseconds)' % ( Configuration.http_graceful_period) Thread.sleep(Configuration.http_graceful_period) HTTPServerCallback.stop() if Configuration.smpp_started: if Configuration.getSmscDriver(): logger.info('Stopping the SMSCDriver (wait %d seconds) ...' % (Configuration.smpp_graceful_period)) print('Stopping the SMSCDriver (wait %d seconds) ...' % (Configuration.smpp_graceful_period)) time.sleep(Configuration.smpp_graceful_period) Configuration.getSmscDriver().stop() # If the contectIndentifier has been initialized then stop the reaper logger.info("Stopping the ContextIdentifier Thread") ContextIdentifier.stop() # Reset TPS at the end if Configuration.use_reporter: Configuration.getClientReporter().setTPS(0) logger.info('bye() - END - All is terminated') print('bye() - END - All is terminated')
def run(self): #print self._name while True: (time_to_sleep,is_break) = self._cadencer.next() # Condition to stop : -1 if time_to_sleep<0: break # Reset queue when changing rate if is_break: self._queue.clear() if self.debug: print "Sleeping time for %d ms" % (time_to_sleep) Thread.sleep(long(time_to_sleep)) self._inc = self._inc+1 if self.debug: print "Putting message %d " % time_to_sleep self._queue.put(time_to_sleep) if self.debug: print "Bottle object sent" if self.debug: print "OK - i quit and i force consumers to stop ..." # The trick is to poison all consumer to force them to stop for k in range(self.nbConsumers): self._queue.put(-1) Thread.sleep(5)
def run(self): i=0 while PVUtil.getLong(pvs[2]) ==1: Thread.sleep(500) timerLabel.setPropertyValue("foreground_color", ColorFontUtil.YELLOW if i%2==0 else ColorFontUtil.RED) i=i+1 timerLabel.setPropertyValue("foreground_color", ColorFontUtil.BLACK)
class Clock(object): """ **pyj2d.time.Clock** * Clock.get_time * Clock.tick * Clock.tick_busy_loop * Clock.get_fps """ def __init__(self): """ Return Clock. """ self.time = System.nanoTime()/1000000 self.time_init = self.time self.time_diff = [25]*10 self.pos = 0 self.thread = Thread() def get_time(self): """ Return time (in ms) between last two calls to tick(). """ return self.time_diff[self.pos] def tick(self, framerate=0): """ Call once per program cycle, returns ms since last call. An optional framerate will add pause to limit rate. """ if self.pos < 9: self.pos += 1 else: self.pos = 0 self.time = System.nanoTime()/1000000 self.time_diff[self.pos] = (self.time-self.time_init) self.time_init = self.time if framerate: time_diff = sum(self.time_diff)/10 time_pause = long( ((1.0/framerate)*1000) - time_diff ) if time_pause > 0: self.thread.sleep(time_pause) return self.time_diff[self.pos] def tick_busy_loop(self, framerate=0): """ Calls tick() with optional framerate. Returns ms since last call. """ time_diff = self.tick(framerate) return time_diff def get_fps(self): """ Return fps. """ return 1000/(sum(self.time_diff)/10)
def dialog(imp2, labelColorBarImp): gd = GenericDialogPlus("ROI labeller") categories=11 #placeholder slider variables so the class can be initiated slider1=0 slider2=0 slider3=0 slider4=0 test=previewLabelerAndListeners(imp2, slider1,slider2,slider3,slider4, gd) for i in range(1,categories): gd.addButton("label "+str(i), test) gd.addImage(labelColorBarImp) #imp7.close() - causes an error as image needed for the dialog gd.addButton("Set top",test) gd.addButton("Whole stack",test) gd.addButton("Set bottom", test) gd.addSlider("Top",1, imp2.getStackSize(), 1) gd.addSlider("Bottom",1, imp2.getStackSize(),imp2.getStackSize()) gd.addSlider("Minimum ROI size", 0, 9999, 0, 1) gd.addSlider("Maximum ROI size", 1, 10000, 10000, 1) slider1=gd.getSliders().get(0) slider2=gd.getSliders().get(1) test.slider1=slider1 test.slider2=slider2 slider3=gd.getSliders().get(2) slider4=gd.getSliders().get(3) test.slider3=slider3 test.slider4=slider4 slider1.addAdjustmentListener(test) slider2.addAdjustmentListener(test) slider3.addAdjustmentListener(test) slider4.addAdjustmentListener(test) gd.addChoice("Apply labeling to:", ["(Sub)stack", "Slice"], "(Sub)stack") gd.setLayout(GridLayout(0,2)) gd.setModal(False) buttons=gd.getButtons() gd.showDialog() while ((not gd.wasCanceled()) and not (gd.wasOKed())): Thread.sleep(50) return test
class Clock(object): """ **pyj2d.time.Clock** * Clock.get_time * Clock.tick * Clock.tick_busy_loop * Clock.get_fps """ def __init__(self): """ Return Clock. """ self.time = System.nanoTime() / 1000000 self.time_init = self.time self.time_diff = [25] * 10 self.pos = 0 self.thread = Thread() def get_time(self): """ Return time (in ms) between last two calls to tick(). """ return self.time_diff[self.pos] def tick(self, framerate=0): """ Call once per program cycle, returns ms since last call. An optional framerate will add pause to limit rate. """ if self.pos < 9: self.pos += 1 else: self.pos = 0 self.time = System.nanoTime() / 1000000 self.time_diff[self.pos] = (self.time - self.time_init) self.time_init = self.time if framerate: time_diff = sum(self.time_diff) / 10 time_pause = long(((1.0 / framerate) * 1000) - time_diff) if time_pause > 0: self.thread.sleep(time_pause) return self.time_diff[self.pos] def tick_busy_loop(self, framerate=0): """ Calls tick() with optional framerate. Returns ms since last call. """ time_diff = self.tick(framerate) return time_diff def get_fps(self): """ Return fps. """ return 1000 / (sum(self.time_diff) / 10)
def delay(time): """ **pyj2d.time.delay** Pause for given time (in ms). Return ms paused. """ start = System.nanoTime() / 1000000 Thread.sleep(time) return (System.nanoTime() / 1000000) - start
def run(self): me = Thread.currentThread( ); me.setPriority(Thread.MIN_PRIORITY); while self.thread == Thread.currentThread(): try: Thread.sleep(1) except InterruptedException: return self._draw()
def delay(time): """ **pyj2d.time.delay** Pause for given time (in ms). Return ms paused. """ start = System.nanoTime()/1000000 Thread.sleep(time) return (System.nanoTime()/1000000) - start
def sleep(SLEEP_MINUTES): # time.sleep() cannot wake up again, so use Java Thread.sleep() instead # time.sleep(SLEEP_MINUTES*60) if isJython(): from java.lang import Thread Thread.sleep(SLEEP_MINUTES * 60 * 1000) else: import time time.sleep(SLEEP_MINUTES * 60)
def take(cls, pollInterval=10): ''' This is the validation mode with some async steps ### WARNING ### This code is overloaded at runtime by "bloking_take()" - monkey patching !!!!! :param cls: :param pollInterval: a time for polling on the queue ''' # # PLS, read the warning above ! # logger.debug('take() - ValidationMode - [ContextLock=%d]' % (ContextLock.count())) # VIRTUALRUNS # # Among the virtual run, this one is for the normal scenario termination ContextLock.asyncCounterDecrease() # # We may get an asynchronous message, # Check the queue but after a small amount of sleep # If we come back too fastly with AbortRunToken(), we risk to consume all grinder "runs" aimed at executing asyn steps # Thread.sleep(500) try: return cls.queue.get(False) except Empty: pass # VIRTUALRUNS # # This is the real number of runs to execute in async mode if ContextLock.getAsyncCounterValue()<0: return AbortRunToken() # if ContextLock.count()<=0: logger.debug('take() - No more ContextLock - returning') return None # Wait after async callback Or waiting async timeout while( True) : logger.trace('take() - [ContextLock=%d] - Waiting after token (%s seconds) ...' % (ContextLock.count(), pollInterval)) try: token=cls.queue.get(True,pollInterval) logger.debug('Got a token of type: %s, class: %s' % (type(token), token.__class__.__name__)) return token except Empty: pass print '.' # ContextLock might be updated in the timeout reaper thread if ContextLock.count()<=0: try: return cls.queue.get(False) except Empty: return None
def delay(self, time): """ **pyj2d.time.delay** Pause for given time (in ms). Return ms paused. """ start = System.nanoTime() // 1000000 try: Thread.sleep(time) except InterruptedException: Thread.currentThread().interrupt() return (System.nanoTime() // 1000000) - start
def delay(self, time): """ **pyj2d.time.delay** Pause for given time (in ms). Return ms paused. """ start = System.nanoTime()//1000000 try: Thread.sleep(time) except InterruptedException: Thread.currentThread().interrupt() return (System.nanoTime()//1000000) - start
def run(self): before_time = None after_time = None time_diff = None sleep_time = None over_sleep_time = 0 no_delays = 0 excess = 0 game_start_time = System.nanoTime() prev_stats_time = game_start_time before_time = game_start_time running = True while running: self.game_update() self.game_render() self.paint_screen() after_time = System.nanoTime() time_diff = after_time - before_time sleep_time = (self.period - time_diff) - over_sleep_time if sleep_time > 0: try: Thread.sleep(sleep_time) except InterruptedException as e: pass over_sleep_time = (System.nanoTime() - after_time) - sleep_time else: excess -= sleep_time over_sleep_time = 0 if (no_delays + 1) >= self.NO_DELAYS_PER_YIELD: Thread.yield() no_delays = 0 before_time = System.nanoTime() skips = 0 while excess > self.period and skips < self.MAX_FRAME_SKIPS: excess -= self.period self.game_update() skips += 1 self.frames_skipped += skips self.store_stats() self.print_stats() System.exit(0)
def asynchronousMoveTo(self, new_position): output_move = 99 Thread.sleep(delayTime) try: if self.incli.isConfigured(): self.incli.caput(new_position) else: self.incli.configure() self.incli.caput(new_position) self.incli.clearup() except Exception, e: print "error in moveTo", e.getMessage(), e, output_move raise e
def run(self): while True: timestamp = int(time.time()) OneMessageSet = "" Thread.sleep(10000) ReportSet = self.Reporter.GetReportStructured() for ValueName in ReportSet: message = "%s.%s %s %d\n" % ( self.Reporter.getClientIdentifier(), ValueName, ReportSet[ValueName], timestamp) OneMessageSet += message self.socket.sendall(OneMessageSet)
def run(self): print("broad time...") if len(self.reg_obj_ip) > reg.i: reg.i += 5 for k in self.reg_obj_ip: if k.isConnected() and not (k.isClosed()): K = PrintStream(k.getOutputStream()) K.println("BroadCast Message....") else: self.reg_obj_ip.remove(k) else: print("here") Thread.sleep(5000)
def __controlled_rampup_call__(self): ''' Attempt to control thread starvation ''' # Block or not (depending of the configuration) self.token = GrinderQueue.take() # Token means we are using ramping mode (no thread mode) if self.token: # check abort, stop and options set on token (sleep for batch mode) if self.__checkTokenReceived(): return try: # Increase the number of active session for this process with self.__class__.lockSession: self.__class__.activeSession += 1 logger.trace('[CONTROL] active sessions: %d' % (self.__class__.activeSession)) # if number of active session is above a configurable threshold # - clear the current waiting operation # - sleep a bit to let some breath if self.__class__.activeSession >= Configuration.threshold_thread_active: self.__class__.controlSessionCount += 1 logger.info( '[CONTROL] Active sessions (%d) above threshold (%d) - clearing waiting tokens ' % (self.__class__.activeSession, Configuration.threshold_thread_active)) # Clear the queue GrinderQueue.clear() # Block all inactive thread (normally none or a few) Thread.sleep(Configuration.thread_wait_milli) # return here execute the finally part. return # The real work is done here ... self.__lanch_scenario__() # Release the active session counter in ANY case finally: with self.__class__.lockSession: self.__class__.activeSession -= 1 logger.trace('[CONTROL] active sessions: %d' % (self.__class__.activeSession))
def run(self): while display.isActive(): scanInfos = client.server.getScanInfos() findActive = False markedDone = False for scanInfo in scanInfos: if scanInfo.getId() == long( display.getVar("LatestPointScanID")): statusLabel.setPropertyValue( "text", scanInfo.getState().toString()) if scanInfo.getState().isDone(): #mark table to dark gray if it is done. if scanInfo.getId() == long( display.getVar( "LatestPointScanID")) and not markedDone: for i in range(table.getRowCount()): Display.getDefault().asyncExec( SetRowColor(i, ColorFontUtil.DARK_GRAY)) markedDone = True continue if scanInfo.getState().isActive(): scanNameLabel.setPropertyValue("text", scanInfo.getName()) commandLabel.setPropertyValue("text", scanInfo.getCurrentCommand()) progressBar.setPropertyValue( "pv_value", scanInfo.getPercentage() / 100.0) #Mark scanned points as green if scanInfo.getId() == long( display.getVar("LatestPointScanID")): markedDone = False for i in range(table.getRowCount()): xpos = float(table.getCellText(i, 1)) ypos = float(table.getCellText(i, 2)) if ( xpos == PVUtil.getDouble(pvs[1]) and ypos == PVUtil.getDouble(pvs[2]) and scanInfo.getPercentage() >= i * 100.0 / table.getRowCount() ): #To make sure the matched position is set from this scan Display.getDefault().asyncExec( SetRowColor(i, ColorFontUtil.GREEN)) findActive = True if not findActive: scanNameLabel.setPropertyValue("text", "None") commandLabel.setPropertyValue("text", "") progressBar.setPropertyValue("pv_value", 0) Thread.sleep(200)
def run(self, args, javaHome, jythonHome, jythonOpts, internals=False): ''' creates a start script, executes it and captures the output ''' (starterPath, outfilePath) = self.writeStarter(args, javaHome, jythonHome, jythonOpts, internals) try: process = Runtime.getRuntime().exec(starterPath) stdoutMonitor = StdoutMonitor(process) stderrMonitor = StderrMonitor(process) stdoutMonitor.start() stderrMonitor.start() while self.isAlive(process): Thread.sleep(300) return self.getOutput(outfilePath) finally: os.remove(starterPath) os.remove(outfilePath)
def wait(self): #0.23 """ Return an event from the queue, or wait for an event if none present. """ while True: if self.eventNum: self._lock() evt = self.JEvent(self.eventQueue.pop(0)) self.eventNum -= 1 self.eventQueue.append(None) self._unlock() return evt else: self._unlock() Thread.sleep(10)
def wait(self): # 0.23 """ Return an event from the queue, or wait for an event if none present. """ while True: if self.eventNum: self._lock() evt = self.JEvent(self.eventQueue.pop(0)) self.eventNum -= 1 self.eventQueue.append(None) self._unlock() return evt else: self._unlock() Thread.sleep(10)
def wait(self): """ Return an event from the queue, or wait for an event if none present. """ while True: try: self._lock() evt = self.eventQueue.pop(0) self.eventNum -= 1 self.eventQueue.append(None) self._unlock() return evt except IndexError: self._unlock() Thread.sleep(10)
def __enter__(self): """Enter the runtime context related to this object.""" system.db.setDatasourceEnabled(self.database, True) for _ in range(self.retries): Thread.sleep(1000) if self.status == "Valid": break if self.status == "Faulted": raise IOError("The database connection {!r} is {}.".format( self.database, self.status)) else: raise IOError( "The database connection {!r} could not be enabled.".format( self.database)) return self
def testEnrollInClass(self): """Integration Test for TurnitinReviewServiceImpl.enrollInClass TODO Change source code to make this test have better results to verify against (ie. return the rMessage and rCode for instance) """ user_serv = ComponentManager.get("org.sakaiproject.user.api.UserDirectoryService") tiiclassid = str(uuid.uuid1()) tiiasnnid = str(uuid.uuid1()) tiiemail = str(uuid.uuid1()) + "@sakaiproject.org" # SWG TODO Why does this fail if you create the Class first? self.tiireview_serv.createClass(tiiclassid) Thread.sleep(1000) self.tiireview_serv.createAssignment(tiiclassid, tiiasnnid ) Thread.sleep(1000) self.tiireview_serv.enrollInClass(user_serv.getUserId("stud01"), tiiemail, tiiclassid)
def run(self): IJ.resetEscape() IJ.setTool("point") listener = ML() self.imp.show() canvas = self.imp.getWindow().getCanvas() canvas.addMouseListener(listener) # wait for mouse click while (not listener.mouseWasPressed) and (not IJ.escapePressed()): Thread.sleep(200) # todo: how to make this better? canvas.removeMouseListener(listener) if IJ.escapePressed(): IJ.log("command has been aborted") else: print listener.x, listener.y self.pos = [listener.x, listener.y]
def run(self, args, javaHome, jythonHome, jythonOpts): ''' creates a start script, executes it and captures the output ''' (starterPath, outfilePath) = self.writeStarter(args, javaHome, jythonHome, jythonOpts) try: process = Runtime.getRuntime().exec(starterPath) stdoutMonitor = StdoutMonitor(process) stderrMonitor = StderrMonitor(process) stdoutMonitor.start() stderrMonitor.start() while self.isAlive(process): Thread.sleep(300) return self.getOutput(outfilePath) finally: os.remove(starterPath) os.remove(outfilePath)
def startUpgrade(appName, newVersion, targetEnvironment): envId = "Environments/" + targetEnvironment if not repository.exists(envId): print "ERROR: No environment named '%s' found" % (envId) return currentDeployment = None # find current deployment for deployedApps in repository.search("udm.DeployedApplication", envId): deployedAppName = deployedApps.replace(envId + '/', '') if deployedAppName == appName: currentDeployment = deployedApps if currentDeployment is None: print "ERROR: No existing deployment of '%s' to '%s'" % ( appName, targetEnvironment) return print "Upgrading existing deployment '%s'" % (currentDeployment) upgrade = deployment.prepareUpgrade( "Applications/%s/%s" % (appName, newVersion), currentDeployment) print "Validating deployment" deployment.validate(upgrade) taskInfo = deployment.deploy(upgrade) print "Starting deployment '%s' (ID: '%s')" % (taskInfo.label, taskInfo.id) deployit.startTask(taskInfo.id) taskState = 'EXECUTING' while taskState == 'EXECUTING': Thread.sleep(5000) taskInfo = deployit.retrieveTaskInfo(taskInfo.id) taskState = taskInfo.state currentStep = taskInfo.currentStepNr print "Task now at step %s of %s. State: %s" % ( currentStep, taskInfo.nrOfSteps, taskState) taskInfo = deployit.retrieveTaskInfo(taskInfo.id) print "Final task state: %s after %s of %s steps" % ( taskInfo.state, min(currentStep + 1, taskInfo.nrOfSteps), taskInfo.nrOfSteps) printSteps(taskInfo, True) if taskInfo.state != 'DONE': print "WARN: Deployment was not completed successfully. Please log in to Deployit to review the deployment or contact a Deployit administrator" return
def run(self): startButton.setEnabled(False) stopButton.setEnabled(True) resetButton.setEnabled(False) bar.setVisible(True) hourText.setEnabled(False) minText.setEnabled(False) secText.setEnabled(False) hour = PVUtil.getLong(hourPV) min = PVUtil.getLong(minPV) sec = PVUtil.getLong(secPV) #remember the values to be reset resetButton.setVar("hour", hour) resetButton.setVar("min",min) resetButton.setVar("sec",sec) timerLabel.setPropertyValue("foreground_color", ColorFontUtil.BLACK) timerLabel.setPropertyValue("text", "Time Left:") stopped=False total = hour*3600+min*60+sec for i in range(total,-1,-1): if not display.isActive(): return if PVUtil.getLong(pvs[0])==0: stopped = True break pvs[1].setValue(100-100*i/total) hourPV.setValue(int(i/3600)) minPV.setValue(int(i%3600/60)) secPV.setValue(int(i%60)) Thread.sleep(1000) timerLabel.setPropertyValue("foreground_color", ColorFontUtil.RED) if stopped: timerLabel.setPropertyValue("text", "Interrupted!") else: timerLabel.setPropertyValue("text", "Time's Up!!!") widget.executeAction(0) pvs[2].setValue(1) Thread(Blink()).start() startButton.setEnabled(True) stopButton.setEnabled(False) resetButton.setEnabled(True) bar.setVisible(False) hourText.setEnabled(True) minText.setEnabled(True) secText.setEnabled(True)
def run(self): display.getWidget("Start_Button_Py").setPropertyValue("visible", False) display.getWidget("Start_Button_JS").setPropertyValue("visible", False) display.getWidget("Progress_Bar").setPropertyValue("visible", True) for i in range(100, 0, -1): if not display.isActive(): return if i%10==0: widget.setPropertyValue("text", "I'm going to finish in %s seconds..." % (i/10)) pvs[1].setValue(100 - i) Thread.sleep(100) pvs[1].setValue(100) widget.setPropertyValue("text", "I'm done! Hit the button again to start me.") display.getWidget("Progress_Bar").setPropertyValue("visible", False) display.getWidget("Start_Button_Py").setPropertyValue("visible", True) display.getWidget("Start_Button_JS").setPropertyValue("visible", True)
def handle(self, action): if (yes.isSelected()) ^ (no.isSelected()): if self.app._EmeraldFX__LICENSE_ACCEPTANCE == "YES": #We're done here self.outer.license_check_stage.close() #Update properties.json self.license_check_stage_json['license'][ 'value'] = "YES" #Write Data, close stream with open("../resources/config/properties.json", "w") as prop: json.dump(self.license_check_stage_json, prop) else: # checked == "NO": BrowserSession.closeHistoryWriter(self.BS) Thread.sleep(300) Platform.exit()
def process(self, pm, req): self._log.info("inside process...") me=self.__class__.__name__ +'::'+VLAB.me() ProcessorUtils.setProcessorLoggingHandler(VLAB.DEFAULT_LOG_PREFIX, req, self.getName(), self.getVersion(), self.getCopyrightInformation()) #self._log.info("Parameter list:") #for i in range(req.getNumParameters()): # self._log.info(req.getParameterAt(i).getName() + " = " + req.getParameterAt(i).getValueAsText()) self._log.info(me + ': ' + ProcessorConstants.LOG_MSG_START_REQUEST) pm.beginTask("Running 3D Vegetation Lab Processor...", 10) # ensure at least 1 second to ensure progress popup feedback try: Thread.sleep(1000); except JException, e: raise RuntimeException(e.getMessage())
def run(self): print "connect to GS" sgs = Socket("127.0.0.1", 9011) i = DataInputStream(sgs.getInputStream()) print "connect to GeoEditor" sge = Socket("127.0.0.1", 2109) # o = DataOutputStream(sge.getOutputStream()) o = sge.getOutputStream() Thread.sleep(5000) GeoEditorListener.getInstance().getThread().addListener(self.vpl) print "gsge Ready" bufsize = 4096 lastpos = 0 buf = String("\0" * bufsize).getBytes() fc = 0 while True: if not i.available(): Thread.sleep(10) fc += 1 if fc % 500 == 0: o.flush() fc = 0 continue lastpos += i.read(buf, lastpos, bufsize - lastpos) while lastpos > 0 and lastpos > buf[0]: if buf[1] == 2: pass elif buf[1] == 1: x = self.list2num(buf[2:6]) y = self.list2num(buf[6:10]) z = self.list2num(buf[10:12]) if z > -15000: rx, ry = GeoUtil.getRegionXY(x, y) if (rx, ry) == (22, 22): bx, by = GeoUtil.getBlockXY(x, y) cx, cy = GeoUtil.getCellXY(x, y) o.write(struct.pack(">BBBBh", bx, by, cx, cy, z)) newpos = buf[0] + 1 if len(buf) - newpos < bufsize: buf = buf[newpos:] + String("\0" * bufsize).getBytes() else: buf = buf[newpos:] lastpos -= newpos
def vuln_param_lookup(self, vuln_params, vuln_name, vuln_param, parameter_decoded, parameter): # Put try catch url = "http://api.pearson.com/v2/dictionaries/ldoce5/entries?headword=" + parameter_decoded response = urllib2.urlopen(url) # Wait a second for response to come back Thread.sleep(1000) data = json.load(response) # Checks an English dictionary if parameter is a real word. If it isn't, add it. # Catches: id_param, param_id, paramID, etc. # Does not catch: idea, ideology, identify, etc. is_real_word = int(data["count"]) > 0 if not is_real_word: self.vuln_param_add(vuln_params, vuln_name, vuln_param, parameter_decoded, parameter.getValue())
def testCheckForReportsIndividual(self): """Test for TurnitinReviewServiceImpl.checkForReportsIndividual""" tiiclassid = str(uuid.uuid1()) tiiasnnid = str(uuid.uuid1()) self.tiireview_serv.createClass(tiiclassid) Thread.sleep(1000) self.tiireview_serv.createAssignment(tiiclassid, tiiasnnid ) tiicontentid = self.enrollAndQueueContentForStudent("stud01", tiiclassid, tiiasnnid) tiicontentid2 = self.enrollAndQueueContentForStudent("stud02", tiiclassid, tiiasnnid) #TODO Do the same thing the quartz job would self.tiireview_serv.processQueue() self.tiireview_serv.checkForReportsIndividual() for contentid in [tiicontentid, tiicontentid2]: status = self.tiireview_serv.getReviewStatus(contentid) self.log.warn("The status for " + contentid + " is: " + str(status)) self.assert_(status in [ContentReviewItem.SUBMITTED_REPORT_AVAILABLE_CODE, ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE]) self.assertNotEqual(status, ContentReviewItem.NOT_SUBMITTED_CODE)
def run(self): print "connect to GS" sgs = Socket("127.0.0.1", 9011) i = DataInputStream(sgs.getInputStream()) print "connect to GeoEditor" sge = Socket("127.0.0.1", 2109) #o = DataOutputStream(sge.getOutputStream()) o = sge.getOutputStream() Thread.sleep(5000) GeoEditorListener.getInstance().getThread().addListener(self.vpl) print "gsge Ready" bufsize = 4096 lastpos = 0 buf = String("\0" * bufsize).getBytes() fc = 0 while True: if not i.available(): Thread.sleep(10) fc += 1 if fc % 500 == 0: o.flush() fc = 0 continue lastpos += i.read(buf, lastpos, bufsize - lastpos) while lastpos > 0 and lastpos > buf[0]: if buf[1] == 2: pass elif buf[1] == 1: x = self.list2num(buf[2:6]) y = self.list2num(buf[6:10]) z = self.list2num(buf[10:12]) if z > -15000: rx, ry = GeoUtil.getRegionXY(x, y) if (rx, ry) == (22, 22): bx, by = GeoUtil.getBlockXY(x, y) cx, cy = GeoUtil.getCellXY(x, y) o.write(struct.pack('>BBBBh', bx, by, cx, cy, z)) newpos = buf[0] + 1 if len(buf) - newpos < bufsize: buf = buf[newpos:] + String("\0" * bufsize).getBytes() else: buf = buf[newpos:] lastpos -= newpos
def run(self): display.getWidget("Start_Button_Py").setPropertyValue("visible", False) display.getWidget("Start_Button_JS").setPropertyValue("visible", False) display.getWidget("Progress_Bar").setPropertyValue("visible", True) for i in range(100, 0, -1): if not display.isActive(): return if i % 10 == 0: widget.setPropertyValue( "text", "I'm going to finish in %s seconds..." % (i / 10)) pvs[1].setValue(100 - i) Thread.sleep(100) pvs[1].setValue(100) widget.setPropertyValue("text", "I'm done! Hit the button again to start me.") display.getWidget("Progress_Bar").setPropertyValue("visible", False) display.getWidget("Start_Button_Py").setPropertyValue("visible", True) display.getWidget("Start_Button_JS").setPropertyValue("visible", True)
def run(self): while True: if not display.isActive(): return self.get_pvs() north_height, south_height = self.calc_pair_height((self.north, self.south), self.max_y, background_height) east_width, west_width = self.calc_pair_height((self.east, self.west), self.max_x, background_width) south_y = background_y + background_height - south_height east_x = background_x + background_width - east_width north_blade.setPropertyValue("height", north_height) south_blade.setPropertyValue("height", south_height) south_blade.setPropertyValue("y", south_y) west_blade.setPropertyValue("width", west_width) east_blade.setPropertyValue("width", east_width) east_blade.setPropertyValue("x", east_x) Thread.sleep(200)
def testQueueContent(self): """Integration test for ContentReviewService.queueContent""" user_serv = ComponentManager.get("org.sakaiproject.user.api.UserDirectoryService") tiiclassid = str(uuid.uuid1()) tiiasnnid = str(uuid.uuid1()) tiiemail = str(uuid.uuid1()) + "@sakaiproject.org" userid = user_serv.getUserId("stud01") tiicontentid = addExampleAttachment()[0] # #self.tiireview_serv.createClass(tiiclassid) self.tiireview_serv.createAssignment(tiiclassid, tiiasnnid ) Thread.sleep(1000) self.tiireview_serv.enrollInClass(userid, tiiemail, tiiclassid) Thread.sleep(1000) self.tiireview_serv.queueContent(userid, tiiclassid, tiiasnnid, tiicontentid) #TODO Do the same thing the quartz job would self.tiireview_serv.processQueue() self.tiireview_serv.checkForReports() status = self.tiireview_serv.getReviewStatus(tiicontentid) self.log.warn("The status is: " + str(status)) self.assert_(status in [ContentReviewItem.SUBMITTED_REPORT_AVAILABLE_CODE, ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE]) self.assertNotEqual(status, ContentReviewItem.NOT_SUBMITTED_CODE)
def run(self): while display.isActive(): scan_id = long(display.getVar("LatestPointScanID")) if scan_id > 0: scanInfo = client.getScanInfo(scan_id) statusLabel.setPropertyValue("text", scanInfo.getState().toString()) if scanInfo.getState().isActive(): scanNameLabel.setPropertyValue("text", scanInfo.getName()) commandLabel.setPropertyValue("text", scanInfo.getCurrentCommand()) progressBar.setPropertyValue("pv_value", scanInfo.getPercentage()/100.0) # Mark scanned points as green for i in range(table.getRowCount()): xpos=float(table.getCellText(i, 1)) ypos=float(table.getCellText(i, 2)) if (xpos == PVUtil.getDouble(pvs[1]) and ypos==PVUtil.getDouble(pvs[2]) and scanInfo.getPercentage() >= i*100.0/table.getRowCount()): #To make sure the matched position is set from this scan Display.getDefault().asyncExec(SetRowColor(i, ColorFontUtil.GREEN)) elif scanInfo.getState().isDone(): display.setVar("LatestPointScanID", -1) else: scanNameLabel.setPropertyValue("text", "None") commandLabel.setPropertyValue("text", "") progressBar.setPropertyValue("pv_value", 0) Thread.sleep(1000)
def run(self): while display.isActive(): scanInfos = client.server.getScanInfos() findActive = False markedDone = False for scanInfo in scanInfos: if scanInfo.getId() == long(display.getVar("LatestPointScanID")): statusLabel.setPropertyValue("text", scanInfo.getState().toString()) if scanInfo.getState().isDone(): #mark table to dark gray if it is done. if scanInfo.getId() == long(display.getVar("LatestPointScanID")) and not markedDone : for i in range(table.getRowCount()): Display.getDefault().asyncExec(SetRowColor(i, ColorFontUtil.DARK_GRAY)) markedDone=True continue if scanInfo.getState().isActive(): scanNameLabel.setPropertyValue("text", scanInfo.getName()) commandLabel.setPropertyValue("text", scanInfo.getCurrentCommand()) progressBar.setPropertyValue("pv_value", scanInfo.getPercentage()/100.0) #Mark scanned points as green if scanInfo.getId() == long(display.getVar("LatestPointScanID")): markedDone=False for i in range(table.getRowCount()): xpos=float(table.getCellText(i, 1)) ypos=float(table.getCellText(i, 2)) if (xpos == PVUtil.getDouble(pvs[1]) and ypos==PVUtil.getDouble(pvs[2]) and scanInfo.getPercentage() >= i*100.0/table.getRowCount()): #To make sure the matched position is set from this scan Display.getDefault().asyncExec(SetRowColor(i, ColorFontUtil.GREEN)) findActive=True if not findActive: scanNameLabel.setPropertyValue("text", "None") commandLabel.setPropertyValue("text", "") progressBar.setPropertyValue("pv_value", 0) Thread.sleep(200)
def testUpdatingExistingAssignment(self): """Test to make sure changes to an existing assignment are getting updated and saved. """ tiiasnnid = "/unittests/asnnupdate/"+str(uuid.uuid1()) tiisiteid = str(uuid.uuid1()) opts = HashMap() opts.put('journal_check','1') self.tiireview_serv.createAssignment(tiisiteid, tiiasnnid, opts) Thread.sleep(1000) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) Thread.sleep(1000) self.assertEquals(str(tiiresult['object']['searchjournals']),str('1')) Thread.sleep(1000) opts.put('journal_check','0') self.tiireview_serv.createAssignment(tiisiteid, tiiasnnid, opts) Thread.sleep(1000) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) self.assertEquals(str(tiiresult['object']['searchjournals']),str('0'))
def testUpdateAssignment(self): """TurnitinReviewServiceImpl.updateAssignment TODO: I think this is suppose to actually test updating the due date. I believe the occasional running of doAssignments is to get around the 5 month due date limitation.""" tiiasnnid = "/unittests/asnnupdate/"+str(uuid.uuid1()) tiisiteid = str(uuid.uuid1()) opts = HashMap() opts.put('journal_check','1') self.tiireview_serv.createAssignment(tiisiteid, tiiasnnid, opts) Thread.sleep(1000) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) Thread.sleep(1000) self.assertEquals(str(tiiresult['object']['searchjournals']),str('1')) Thread.sleep(1000) self.tiireview_serv.updateAssignment(tiisiteid, tiiasnnid) Thread.sleep(1000) tiiresult = self.tiireview_serv.getAssignment(tiisiteid, tiiasnnid) self.assertEquals(str(tiiresult['object']['searchjournals']),str('1'))
def run(self): funVal = self.throttle.getF0() self.throttle.setF0( not funVal ) # HERE! print self.timeSleep Thread.sleep(self.timeSleep) self.throttle.setF0( funVal ) # HERE!
class Mixer(Runnable): """ **pyj2d.mixer** * pyj2d.mixer.init * pyj2d.mixer.quit * pyj2d.mixer.get_init * pyj2d.mixer.stop * pyj2d.mixer.pause * pyj2d.mixer.unpause * pyj2d.mixer.set_num_channels * pyj2d.mixer.get_num_channels * pyj2d.mixer.set_reserved * pyj2d.mixer.find_channel * pyj2d.mixer.get_busy * pyj2d.mixer.Sound * pyj2d.mixer.Channel """ def __init__(self): self._mixer = None Sound._mixer = self Channel._mixer = self self.Sound = Sound self.Channel = Channel self._channel_max = 8 self._channels = {} self._sounds = {} self._channel_reserved = [] self._channel_paused = [] self._channel_reserves = [id for id in range(self._channel_max-1,-1,-1)] self._channel_pool = [] self._lines = {} self._line_num = 0 self._thread = None self._initialized = False self._nonimplemented_methods() def init(self, frequency=22050, size=-16, channels=2, buffer=4096): """ Mixer initialization. Argument sampled frequency, bit size, channels, and buffer. Currently implements PCM 16-bit audio. Plays WAV, AIFF, and AU sampled audio. To specify the BigEndian format of AIFF and AU, use -16L for size. The mixing is done by Mixer.class, compiled with 'javac Mixer.java'. When a JAR is created, include with 'jar uvf Pyj2d_App.jar pyj2d/Mixer.class'. """ if not self._initialized: encoding = {True:AudioFormat.Encoding.PCM_SIGNED, False:AudioFormat.Encoding.PCM_UNSIGNED}[size<0] channels = {True:1, False:2}[channels<=1] framesize = int((abs(size)/8) * channels) isBigEndian = isinstance(size,long) self._audio_format = AudioFormat(encoding, int(frequency), int(abs(size)), channels, framesize, int(frequency), isBigEndian) self._bufferSize = buffer try: self._mixer = AudioMixer(self._audio_format, self._bufferSize) except TypeError: self._mixer = None return None if not self._mixer.isInitialized(): return None self._bufferSize = self._mixer.getBufferSize() self._byteArray = jarray.zeros(self._bufferSize, 'b') self._initialized = True self._thread = Thread(self) self._thread.start() return None def pre_init(self, frequency=22050, size=-16, channels=2, buffer=4096): """ Mixer initialization. """ self.init(frequency, size, channels, buffer) return None def quit(self): """ Stop mixer processing and release resources. """ self._initialized = False def _quit(self): self.stop() try: self._mixer.quit() except AttributeError: pass self._mixer = None def get_init(self): """ Get the audio format initialized. """ if self._initialized: frequency = int(self._audio_format.sampleRate) format = self._audio_format.sampleSizeInBits * {True:1,False:-1}[self._audio_format.bigEndian] channels = self._audio_format.channels return (frequency, format, channels) else: return None def stop(self): """ Stop mixer channels. """ for id in self._channel_pool: self._channels[id].stop() return None def pause(self): """ Pause mixer channels. """ for id in self._channel_pool: try: if self._channels[id]._active: self._channel_paused.append(id) self._channels[id].pause() except AttributeError: continue return None def unpause(self): """ Unpause mixer channels. """ for id in self._channel_paused: self._channels[id].unpause() self.channel_paused = [] return None def set_num_channels(self, count): """ Set maximum mixer channels. Argument channel count. """ if count >= self._channel_max: for id in range(self._channel_max, count): self._channels[id] = None self._channel_max = count elif count >= 0: for id in range(count, self._channel_max): self._channels[id].stop() del self._channels[id] self._channel_max = count return None def get_num_channels(self): """ Get maximum mixer channels. """ return self._channel_max def set_reserved(self, count): """ Reserve channel. Argument reserved channel count. """ if count > self._channel_max: count = self._channel_max reserved_len = len(self._channel_reserved) if reserved_len: if reserved_len >= count: for i in range(reserved_len-count): id = self._channel_reserved.pop() self._channels[id]._reserved = False self._channel_pool.append(id) count = 0 else: count -= len(self._channel_reserved) for id in range(reserved_len, count+reserved_len): try: self._channels[id]._reserved = True except AttributeError: self._channels[id] = Channel(id) try: self._channel_pool.remove(id) except ValueError: pass self._channel_reserved.append(id) return None def find_channel(self, force=False): """ Get an inactive mixer channel. Optional force attribute return longest running channel if all active. """ try: channel = self._channel_reserves.pop() try: return self._channels[channel] except KeyError: channel = Channel(channel) return channel except IndexError: for id in self._channel_pool: if not self._channels[id]._active: return self._channels[id] else: if force: channel = None longest = 0 for id in self._channel_pool: try: duration = self._channels[id]._stream.getMicrosecondPosition() if duration > longest: longest = duration channel = self._channels[id] except AttributeError: channel = self._channels[id] break try: channel.stop() return channel except AttributeError: return None else: return None def get_busy(self): """ Check if mixer channels are actively processing. """ for id in self._channel_pool: try: if self._channels[id]._active: return True except AttributeError: continue return False def run(self): while self._initialized: channel_active = [self._channels[id] for id in self._channel_pool if self._channels[id]._active] if not channel_active: try: self._thread.sleep(1) except InterruptedException: Thread.currentThread().interrupt() self.quit() continue if len(channel_active) > 1: for channel in channel_active: try: data, data_len, lvol, rvol = channel._get() except AttributeError: continue self._mixer.setAudioData(data, data_len, lvol, rvol) data_len = self._mixer.getAudioData(self._byteArray) if data_len > 0: try: self._mixer.write(self._byteArray, 0, data_len) except IllegalArgumentException: nonIntegralByte = data_len % self._audio_format.getFrameSize() if nonIntegralByte: data_len -= nonIntegralByte try: self._mixer.write(self._byteArray, 0, data_len) except (IllegalArgumentException, LineUnavailableException): pass except LineUnavailableException: pass else: try: data, data_len, lvol, rvol = channel_active[0]._get() except AttributeError: data_len = 0 if data_len > 0: if lvol < 1.0 or rvol < 1.0: data = self._mixer.processVolume(data, data_len, lvol, rvol) try: self._mixer.write(data, 0, data_len) except IllegalArgumentException: nonIntegralByte = data_len % self._audio_format.getFrameSize() if nonIntegralByte: data_len -= nonIntegralByte try: self._mixer.write(data, 0, data_len) except (IllegalArgumentException, LineUnavailableException): pass except LineUnavailableException: pass self._quit() def _register_channel(self, channel): id = channel._id if id < self._channel_max: try: if self._channels[id]._sound: channel._sound = self._channels[id]._sound channel._stream = self._channels[id]._stream self._channels[id] = channel except KeyError: self._channels[id] = channel self._channel_pool.append(id) else: raise AttributeError("Channel not available.") def _register_sound(self, sound): self._sounds[sound._id] = sound def _nonimplemented_methods(self): """ Non-implemented methods. """ self.fadeout = lambda *arg: None
def _lock(self): self.queueLock = True # block next event access while self.queueAccess: # complete current event access Thread.sleep(1) # ~should be via separate Java event thread
# Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() # Installs the Android package. Notice that this method returns a boolean, so you can test # to see if the installation worked. device.installPackage('/Users/hansthunberg/git-views/android-testing-demo/android-demo-app/target/android-demo-app-1.0-SNAPSHOT-aligned.apk') # sets a variable with the package's internal name package = 'org.callista.cadec.android' # sets a variable with the name of an Activity in the package activity = 'org.callista.cadec.android.LoginActivity' # sets the name of the component to start runComponent = package + '/' + activity # Runs the component device.startActivity(component=runComponent) # Presses the Menu button device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP) #Sleep some seconds to get a good shot Thread.sleep(2000); # Takes a screenshot result = device.takeSnapshot() # Writes the screenshot to a file result.writeToFile('/Users/hansthunberg/Temp/shot1.png','png')