def __init__(self, product_id_bytes = None, *a, **k):
     super(IdentifiableControlSurface, self).__init__(*a, **k)
     raise product_id_bytes is not None or AssertionError
     raise len(product_id_bytes) < 12 or AssertionError
     self._product_id_bytes = product_id_bytes
     self._request_task = self._tasks.add(Task.sequence(Task.wait(self.identity_request_delay), Task.run(self._send_identity_request)))
     self._request_task.kill()
 def add_mode(self, name, mode_or_component, toggle_value = False, groups = set(), behaviour = None):
     """
     Adds a mode of the given name into the component.  The mode
     object should be a Mode or ControlSurfaceComponent instance.
     
     The 'toggle_value' is the light value the toggle_botton will
     be set to when the component is on this mode.
     
     If 'group' is not None, the mode will be put in the group
     identified by the passed object.  When several modes are grouped:
     
       * All the buttons in the group will light up when any of the
         modes withing the group is selected.
     
       * Any of the group buttons will cancel the current mode when
         the current mode belongs to the group.
     """
     if not name not in self._mode_map.keys():
         raise AssertionError
         if not isinstance(groups, set):
             groups = set(groups)
         mode = tomode(mode_or_component)
         task = self._tasks.add(Task.sequence(Task.wait(Defaults.MOMENTARY_DELAY), Task.run(lambda : self._get_mode_behaviour(name).press_delayed(self, name))))
         task.kill()
         slot = self.register_slot(listener=partial(self._on_mode_button_value, name), event='value', extra_kws=dict(identify_sender=True))
         self._mode_list.append(name)
         self._mode_map[name] = _ModeEntry(mode=mode, toggle_value=toggle_value, behaviour=behaviour, subject_slot=slot, momentary_task=task, groups=groups)
         button_setter = 'set_' + name + '_button'
         hasattr(self, button_setter) or setattr(self, button_setter, partial(self.set_mode_button, name))
Example #3
0
def declare_chain(name='',action='',ext_in='',ext_out='',reentrant=1,color='BLUE',install=0,before=[],after=[],decider=None):
	if type(action)is types.StringType:
		act=Task.simple_task_type(name,action,color=color)
	else:
		act=Task.task_type_from_func(name,action,color=color)
	act.ext_in=tuple(Utils.to_list(ext_in))
	act.ext_out=tuple(Utils.to_list(ext_out))
	act.before=Utils.to_list(before)
	act.after=Utils.to_list(after)
	def x_file(self,node):
		if decider:
			ext=decider(self,node)
		elif type(ext_out)is types.StringType:
			ext=ext_out
		if type(ext)is types.StringType:
			out_source=node.change_ext(ext)
			if reentrant:
				self.allnodes.append(out_source)
		elif type(ext)==types.ListType:
			out_source=[node.change_ext(x)for x in ext]
			if reentrant:
				for i in xrange(reentrant):
					self.allnodes.append(out_source[i])
		else:
			raise Utils.WafError("do not know how to process %s"%str(ext))
		tsk=self.create_task(name)
		tsk.set_inputs(node)
		tsk.set_outputs(out_source)
		if Options.is_install and install:
			tsk.install=install
	declare_extension(act.ext_in,x_file)
Example #4
0
	def DeleteButtonClicked(self):
		#---- Delete Entries in file tasks ----
		global taskList		
		currentTaskLine = str(self.ui.TaskListWidget.currentItem().text())		
		if not currentTaskLine == "":
			self.ui.TaskListWidget.clear()
			#self.count = 0
			CTL = currentTaskLine.split(",")
			f = open('tasks_test.txt')
			output = []
			for line in f:
				line = line.rstrip("\n")			
				x = line.split(",")
   				if not CTL[1] == x[1]:
					#print(line+","+str(predTaskId))						
     		   			output.append(x[0]+","+x[1]+","+x[2]+"\n")					
			f.close()			
			f = open('tasks_test.txt', 'w')
			f.writelines(output)
			f.close()
			for line in output:
				line = line.rstrip("\n")				
				x = line.split(",")
				self.ui.TaskListWidget.addItem(x[0]+","+x[1]+","+x[2])
		#---- Create New task list ----
			taskList = []
			f = open('tasks_test.txt')
			for line in f:
				line = line.rstrip("\n")
				x = line.split(",")
				task = Task(int(x[0]),x[1])
				task.duration = int(x[2])
				preds = self.getPredecessorsFromFile(task.id)
				task.predecessors = preds			
				taskList.append(task)
						
				#self.ui.TaskListWidget.addItem(line)					
			f.close()
		#---- Delete Entries in file dependencies---

			self.ui.DependencyListWidget.clear()
			#CTL
			f = open('dependencies_test.txt')
			output1 = []
			for line in f:
				line = line.rstrip("\n")			
				x = line.split(",")
   				if not int(CTL[0]) == int(x[0]):
					#print(line+","+str(predTaskId)
					str1 = ""	
					for i in range(0,len(x)):
						if not int(x[i]) == int(CTL[0]): 
     		   					str1=str1+str(x[i])+","
					str1= str1.rstrip(",")
					output1.append(str1+"\n")					
			f.close()
			f = open('dependencies_test.txt', 'w')
			f.writelines(output1)
			f.close()
			self.populateDependencyList()
Example #5
0
 def lerpLookAt(self, point, time = 1.0, blink = 0):
     taskMgr.remove(self._ToonHead__stareAtName)
     lodName = self.getLODNames()[0]
     head = self.getPart('head', lodName)
     startHpr = head.getHpr()
     startLpupil = self._ToonHead__lpupil.getPos()
     startRpupil = self._ToonHead__rpupil.getPos()
     self._ToonHead__lookHeadAt(None, point, lod = lodName)
     self._ToonHead__lookPupilsAt(None, point)
     endHpr = head.getHpr()
     endLpupil = self._ToonHead__lpupil.getPos() * 0.5
     endRpupil = self._ToonHead__rpupil.getPos() * 0.5
     head.setHpr(startHpr)
     self._ToonHead__lpupil.setPos(startLpupil)
     self._ToonHead__rpupil.setPos(startRpupil)
     if startHpr.almostEqual(endHpr, 10):
         return 0
     
     if blink:
         self.blinkEyes()
     
     for lodName in self.getLODNames():
         head = self.getPart('head', lodName)
         head.lerpHpr(endHpr, time, blendType = 'easeInOut', task = self._ToonHead__stareAtName)
     
     lookToTgt_TimeFraction = 0.20000000000000001
     lookToTgtTime = time * lookToTgt_TimeFraction
     returnToEyeCenterTime = time - lookToTgtTime - 0.5
     origin = Point3(0, 0, 0)
     blend_type = 'easeOut'
     lPupilSeq = Task.sequence(self._ToonHead__lpupil.lerpPos(endLpupil, lookToTgtTime, blendType = blend_type), Task.pause(0.5), self._ToonHead__lpupil.lerpPos(origin, returnToEyeCenterTime, blendType = blend_type))
     rPupilSeq = Task.sequence(self._ToonHead__rpupil.lerpPos(endRpupil, lookToTgtTime, blendType = blend_type), Task.pause(0.5), self._ToonHead__rpupil.lerpPos(origin, returnToEyeCenterTime, blendType = blend_type))
     taskMgr.add(lPupilSeq, self._ToonHead__stareAtName)
     taskMgr.add(rPupilSeq, self._ToonHead__stareAtName)
     return 1
Example #6
0
def setup(bld):
    def run_unit_test(task):
        """ Execute unit tests, creating a test.passed cache file. Based on
         www.scons.org/wiki/UnitTest modified to run tests in the source dir """
        import subprocess
        import Options

        test_exe = task.inputs[0]
        app = test_exe.abspath(task.env)
        blddir = os.path.dirname(app)
        srcdir = os.path.dirname(test_exe.abspath())
        cwd = None
        if task.run_from_dir:
            cwd = task.run_from_dir
        target = os.path.join(blddir, task.outputs[0].name)
        process_pipe = subprocess.Popen(app, stdout=subprocess.PIPE, cwd=cwd)
        process_pipe.wait()
        returncode = process_pipe.returncode
        stdout = process_pipe.stdout.read()
        if Options.options.verbose or returncode:
            if task.run_from_dir:
                # this sorts out jump-to-errors in e.g. vim
                print "waf: Entering directory `%s'" % (bld.bdir)
            print stdout
        out = "FAILED"
        if returncode == 0:
            out = stdout
        open(str(target), "w").write(out + "\n")
        return returncode

    Task.task_type_from_func("unit_test", vars=[], func=run_unit_test, color="RED", after="cxx_link")
Example #7
0
def declare_chain(name='',action='',ext_in='',ext_out='',reentrant=True,color='BLUE',install=0,before=[],after=[],decider=None,rule=None,scan=None):
	action=action or rule
	if isinstance(action,str):
		act=Task.simple_task_type(name,action,color=color)
	else:
		act=Task.task_type_from_func(name,action,color=color)
	act.ext_in=tuple(Utils.to_list(ext_in))
	act.ext_out=tuple(Utils.to_list(ext_out))
	act.before=Utils.to_list(before)
	act.after=Utils.to_list(after)
	act.scan=scan
	def x_file(self,node):
		if decider:
			ext=decider(self,node)
		else:
			ext=ext_out
		if isinstance(ext,str):
			out_source=node.change_ext(ext)
			if reentrant:
				self.allnodes.append(out_source)
		elif isinstance(ext,list):
			out_source=[node.change_ext(x)for x in ext]
			if reentrant:
				for i in xrange((reentrant is True)and len(out_source)or reentrant):
					self.allnodes.append(out_source[i])
		else:
			raise Utils.WafError("do not know how to process %s"%str(ext))
		tsk=self.create_task(name,node,out_source)
		if node.__class__.bld.is_install:
			tsk.install=install
	declare_extension(act.ext_in,x_file)
Example #8
0
 def __init__(self, name, system_id, client_id, **kwargs):
     Task.__init__(self, name, system_id, client_id)
     #print("Created task: %s" % str(self.task_id))
     
     self.target_hash = kwargs['target_hash']
     self.start = kwargs['start']
     self.end = kwargs['end']
 def showChanceRewards(self):
     tasks = []
     index = 0
     for reward in self.rewardList:
         if reward != -1:
             hcc = Task.Task(self.hideChanceMarker)
             hcc.chanceMarkers = self.chanceMarkers
             hcc.index = index
             sct = Task.Task(self.showChanceCard)
             sct.chanceCard = self.chanceCard
             sct.cardSound = self.cardSound
             stt = Task.Task(self.showChanceCardText)
             rewardEntry = RaceGameGlobals.ChanceRewards[reward]
             stt.rewardIdx = reward
             if rewardEntry[0][0] < 0 or rewardEntry[0][1] > 0:
                 stt.sound = self.negBuzzer
             else:
                 stt.sound = self.posBuzzer
             stt.picker = self.avIdList[index]
             stt.chanceCard = self.chanceCard
             rct = Task.Task(self.resetChanceCard)
             rct.chanceCard = self.chanceCard
             task = Task.sequence(hcc, sct, Task.pause(1.0), stt, Task.pause(3.0), rct, Task.pause(1.0))
             tasks.append(task)
         
         index += 1
     
     return tasks
 def __init__(self, mode = None, delay = None, parent_task_group = None, *a, **k):
     super(DelayMode, self).__init__(*a, **k)
     raise mode is not None or AssertionError
     raise parent_task_group is not None or AssertionError
     delay = delay or Defaults.MOMENTARY_DELAY
     self._mode = tomode(mode)
     self._mode_entered = False
     self._delay_task = parent_task_group.add(Task.sequence(Task.wait(delay), Task.run(self._enter_mode_delayed)))
     self._delay_task.kill()
Example #11
0
def declare_chain(
    name="",
    action="",
    ext_in="",
    ext_out="",
    reentrant=True,
    color="BLUE",
    install=0,
    before=[],
    after=[],
    decider=None,
    rule=None,
    scan=None,
):
    """
	see Tools/flex.py for an example
	while i do not like such wrappers, some people really do
	"""

    action = action or rule
    if isinstance(action, str):
        act = Task.simple_task_type(name, action, color=color)
    else:
        act = Task.task_type_from_func(name, action, color=color)
    act.ext_in = tuple(Utils.to_list(ext_in))
    act.ext_out = tuple(Utils.to_list(ext_out))
    act.before = Utils.to_list(before)
    act.after = Utils.to_list(after)
    act.scan = scan

    def x_file(self, node):
        if decider:
            ext = decider(self, node)
        else:
            ext = ext_out

        if isinstance(ext, str):
            out_source = node.change_ext(ext)
            if reentrant:
                self.allnodes.append(out_source)
        elif isinstance(ext, list):
            out_source = [node.change_ext(x) for x in ext]
            if reentrant:
                for i in xrange((reentrant is True) and len(out_source) or reentrant):
                    self.allnodes.append(out_source[i])
        else:
            # XXX: useless: it will fail on Utils.to_list above...
            raise Utils.WafError("do not know how to process %s" % str(ext))

        tsk = self.create_task(name, node, out_source)

        if node.__class__.bld.is_install:
            tsk.install = install

    declare_extension(act.ext_in, x_file)
    return x_file
 def _DistributedCannonGame__fireCannonTask(self, task):
     launchTime = task.fireTime
     avId = task.avId
     self.notify.debug('FIRING CANNON FOR AVATAR ' + str(avId))
     flightResults = self._DistributedCannonGame__calcFlightResults(avId, launchTime)
     for key in flightResults:
         exec "%s = flightResults['%s']" % (key, key)
     
     self.notify.debug('start position: ' + str(startPos))
     self.notify.debug('start velocity: ' + str(startVel))
     self.notify.debug('time of launch: ' + str(launchTime))
     self.notify.debug('time of impact: ' + str(timeOfImpact))
     self.notify.debug('location of impact: ' + str(trajectory.getPos(timeOfImpact)))
     if hitWhat == self.HIT_WATER:
         self.notify.debug('toon will land in the water')
     elif hitWhat == self.HIT_TOWER:
         self.notify.debug('toon will hit the tower')
     else:
         self.notify.debug('toon will hit the ground')
     head = self.toonHeadDict[avId]
     head.stopBlink()
     head.stopLookAroundNow()
     head.reparentTo(hidden)
     av = self.toonModelDict[avId]
     av.reparentTo(render)
     av.setPos(startPos)
     av.setHpr(startHpr)
     avatar = self.getAvatar(avId)
     avatar.loop('swim')
     avatar.setPosHpr(0, 0, -(avatar.getHeight() / 2.0), 0, 0, 0)
     shootTask = Task.Task(self._DistributedCannonGame__shootTask)
     flyTask = Task.Task(self._DistributedCannonGame__flyTask)
     seqDoneTask = Task.Task(self._DistributedCannonGame__flySequenceDoneTask)
     info = { }
     info['avId'] = avId
     info['trajectory'] = trajectory
     info['launchTime'] = launchTime
     info['timeOfImpact'] = timeOfImpact
     info['hitWhat'] = hitWhat
     info['toon'] = self.toonModelDict[avId]
     info['hRot'] = self.cannonPositionDict[avId][0]
     info['haveWhistled'] = 0
     info['maxCamPullback'] = CAMERA_PULLBACK_MIN
     (info['timeEnterTowerXY'], info['timeExitTowerXY']) = trajectory.calcEnterAndLeaveCylinderXY(self.tower.getPos(render), TOWER_RADIUS)
     shootTask.info = info
     flyTask.info = info
     seqDoneTask.info = info
     seqTask = Task.sequence(shootTask, flyTask, Task.pause(LAND_TIME), seqDoneTask)
     taskMgr.add(seqTask, 'flyingToon' + str(avId))
     if avId == self.localAvId:
         if info['hitWhat'] == self.HIT_WATER:
             self.sendUpdate('setToonWillLandInWater', [
                 info['timeOfImpact']])
         
     
     return Task.done
Example #13
0
 def __init__(self, name, system_id, client_id, **kwargs):
     Task.__init__(self, name, system_id, client_id)
     self.start_x = kwargs['start_x']
     self.rows = kwargs['rows']
     self.cols = kwargs['cols']
     self.min_y = kwargs['min_y']
     self.min_x = kwargs['min_x']
     self.pixel_size_y = kwargs['pixel_size_y']
     self.pixel_size_x = kwargs['pixel_size_x']
     self.iters = kwargs['iters']
Example #14
0
def Remove(addr):
	try:
		for c in clients:
			if c['address'] == addr:
				if c['type'] == CLIENT_ADMIN:
					print("\033[1;33madmin removed [%s from %s]\033[0m" % (c['username'], c['address']))
				elif c['type'] == CLIENT_SLAVE:
					print("\033[1;32madmin removed [%s from %s]\033[0m" % (c['hostname'], c['address']))
					Task.setTask(Task.getTaskBySlaveAddr(addr), Task.STATE_BROKEN)
				clients.remove(c)
	except ValueError:
		pass
Example #15
0
    def irisOutTask(self, task, time = 0.5, noIris = 1):
        if noIris:
            
            def noIrisTask(task):
                task.noIris()
                return Task.done

            nit = Task.Task(noIrisTask)
            nit.noIris = self.noIris
            seq = Task.sequence(self.irisOut(time, block = 1), task, nit)
        else:
            seq = Task.sequence(self.irisOut(time, block = 1), task)
        taskMgr.add(seq, 'irisOutTaskSeq')
Example #16
0
    def fadeOutTask(self, task, time = 0.29999999999999999, noFade = 1):
        if noFade:
            
            def noFadeTask(task):
                task.noFade()
                return Task.done

            nft = Task.Task(noFadeTask)
            nft.noFade = self.noFade
            seq = Task.sequence(self.fadeOut(time, block = 1), task, nft)
        else:
            seq = Task.sequence(self.fadeOut(time, block = 1), task)
        taskMgr.add(seq, 'fadeOutTaskSeq')
 def __init__(self, msg_type = None, channel = None, identifier = None, sysex_identifier = None, request_rebuild_midi_map = None, *a, **k):
     raise msg_type in MIDI_MSG_TYPES or AssertionError
     raise in_range(channel, 0, 16) or channel is None or AssertionError
     raise in_range(identifier, 0, 128) or identifier is None or AssertionError
     raise msg_type != MIDI_SYSEX_TYPE or channel == None or AssertionError
     raise msg_type != MIDI_SYSEX_TYPE or identifier == None or AssertionError
     raise msg_type == MIDI_SYSEX_TYPE or sysex_identifier == None or AssertionError
     super(InputControlElement, self).__init__(*a, **k)
     self._request_rebuild = request_rebuild_midi_map
     self._msg_type = msg_type
     self._msg_channel = channel
     self._msg_identifier = identifier
     self._msg_sysex_identifier = sysex_identifier
     self._original_channel = channel
     self._original_identifier = identifier
     self._needs_takeover = True
     self._is_mapped = True
     self._is_being_forwarded = True
     self._delayed_messages = []
     self._force_next_send = False
     self._mapping_feedback_delay = 0
     self._mapping_sensitivity = 1.0
     self._send_delayed_messages_task = self._tasks.add(Task.run(self._send_delayed_messages))
     self._send_delayed_messages_task.kill()
     self._parameter_to_map_to = None
     self._in_parameter_gesture = False
     self._last_sent_message = None
     self._report_input = False
     self._report_output = False
 def __init__(self, *a, **k):
     super(TransportComponent, self).__init__(*a, **k)
     self._ffwd_button = None
     self._rwd_button = None
     self._tap_tempo_button = None
     self._tempo_control = None
     self._tempo_fine_control = None
     self._song_position_control = None
     self._rwd_task = Task.Task()
     self._ffwd_task = Task.Task()
     self._fine_tempo_needs_pickup = True
     self._prior_fine_tempo_value = -1
     self._end_undo_step_task = self._tasks.add(Task.sequence(Task.wait(1.5), Task.run(self.song().end_undo_step)))
     self._end_undo_step_task.kill()
     song = self.song()
     self._loop_toggle, self._punch_in_toggle, self._punch_out_toggle, self._record_toggle, self._play_toggle, self._stop_toggle, self._nudge_down_toggle, self._nudge_up_toggle, self._metronome_toggle, self._session_record_toggle, self.arrangement_overdub_toggle, self._overdub_toggle = self.register_components(ToggleComponent('loop', song), ToggleComponent('punch_in', song, is_momentary=True), ToggleComponent('punch_out', song, is_momentary=True), ToggleComponent('record_mode', song), ToggleComponent('is_playing', song, model_transform=const(True)), ToggleComponent('is_playing', song, model_transform=const(False), view_transform=const(False)), ToggleComponent('nudge_down', song, is_momentary=True), ToggleComponent('nudge_up', song, is_momentary=True), ToggleComponent('metronome', song), ToggleComponent('session_record', song), ToggleComponent('arrangement_overdub', song), ToggleComponent('overdub', song))
Example #19
0
def get_task():
	"""

	:rtype : object
	"""
	obj_str = r.blpop(settings.WORKER_NAME)
	return Task.deserialize(obj_str)
 def showLaffString(self, text, duration = 0.84999999999999998, scale = 0.69999999999999996):
     if self.LaffNumbersEnabled:
         if text != '':
             if self.laffNumber:
                 self.hideLaffNumber()
             
             self.LaffNumberGenerator.setFont(ToontownGlobals.getSignFont())
             self.LaffNumberGenerator.setText(text)
             self.LaffNumberGenerator.clearShadow()
             self.LaffNumberGenerator.setAlign(TextNode.ACenter)
             r = 1.0
             a = 1.0
             g = 0.0
             b = 0.0
             self.LaffNumberGenerator.setTextColor(r, g, b, a)
             self.laffNumberNode = self.LaffNumberGenerator.generate()
             self.laffNumber = self.attachNewNode(self.laffNumberNode)
             self.laffNumber.setScale(scale)
             self.laffNumber.setBillboardAxis()
             self.laffNumber.setPos(0, 0, self.height / 2)
             seq = Task.sequence(self.laffNumber.lerpPos(Point3(0, 0, self.height + 1.5), 1.0, blendType = 'easeOut'), Task.pause(duration), self.laffNumber.lerpColor(Vec4(r, g, b, a), Vec4(r, g, b, 0), 0.10000000000000001), Task.Task(self.hideLaffNumberTask))
             taskMgr.add(seq, self.uniqueName('laffNumber'))
         
     
     return None
    def runInPlace(self, avatar, lane, currentPlace, newPlace, time):
        place = min(newPlace, len(self.posHprArray[lane]) - 1)
        step = (place - currentPlace) / 3
        pos1 = self.posHprArray[lane][currentPlace + step]
        pos2 = self.posHprArray[lane][currentPlace + 2 * step]
        pos3 = self.posHprArray[lane][place]
        
        def startRun(task):
            task.avatar.setAnimState('run', 1)
            return Task.done

        startRunTask = Task.Task(startRun, 'startRun-' + str(lane))
        startRunTask.avatar = avatar
        
        def stopRun(task, raceBoard = self.raceBoard, pos3 = pos3):
            task.avatar.setAnimState('neutral', 1)
            task.avatar.setPosHpr(raceBoard, pos3[0], pos3[1], pos3[2], pos3[3], 0, 0)
            return Task.done

        stopRunTask = Task.Task(startRun, 'stopRun-' + str(lane))
        stopRunTask.avatar = avatar
        runTask = Task.sequence(startRunTask, avatar.lerpPosHpr(pos1[0], pos1[1], pos1[2], pos1[3], 0, 0, time / 3.0, other = self.raceBoard), avatar.lerpPosHpr(pos2[0], pos2[1], pos2[2], pos2[3], 0, 0, time / 3.0, other = self.raceBoard), avatar.lerpPosHpr(pos3[0], pos3[1], pos3[2], pos3[3], 0, 0, time / 3.0, other = self.raceBoard), stopRunTask)
        runTask.avatar = avatar
        runTask.pos3 = pos3
        runTask.raceBoard = self.raceBoard
        taskMgr.add(runTask, 'runAvatar-' + str(lane))
    def walkInPlace(self, avatar, lane, place, time):
        place = min(place, len(self.posHprArray[lane]) - 1)
        posH = self.posHprArray[lane][place]
        
        def startWalk(task):
            task.avatar.setAnimState('walk', 1)
            return Task.done

        startWalkTask = Task.Task(startWalk, 'startWalk-' + str(lane))
        startWalkTask.avatar = avatar
        
        def stopWalk(task, raceBoard = self.raceBoard, posH = posH):
            task.avatar.setAnimState('neutral', 1)
            if raceBoard.isEmpty():
                task.avatar.setPosHpr(0, 0, 0, 0, 0, 0)
            else:
                task.avatar.setPosHpr(raceBoard, posH[0], posH[1], posH[2], posH[3], 0, 0)
            return Task.done

        stopWalkTask = Task.Task(stopWalk, 'stopWalk-' + str(lane))
        stopWalkTask.avatar = avatar
        walkTask = Task.sequence(startWalkTask, avatar.lerpPosHpr(posH[0], posH[1], posH[2], posH[3], 0, 0, time, other = self.raceBoard), stopWalkTask)
        walkTask.avatar = avatar
        walkTask.posH = posH
        walkTask.raceBoard = self.raceBoard
        taskMgr.add(walkTask, 'walkAvatar-' + str(lane))
Example #23
0
def setup(bld):
	for name in('cc','cxx'):
		if name not in Task.TaskBase.classes:
			continue
		task=Task.TaskBase.classes[name]
		line=task.run.code.replace('SRC','SRC[0].abspath(env)')
		(fun,v)=Task.compile_fun(name,line,False)
		fun.code=line
		task.run=fun
Example #24
0
def declare_chain(name='', action='', ext_in='', ext_out='', reentrant=1, color='BLUE', install=0, before=[], after=[], decider=None, rule=None):
	"""
	see Tools/flex.py for an example
	while i do not like such wrappers, some people really do
	"""

	action = action or rule
	if type(action) is types.StringType:
		act = Task.simple_task_type(name, action, color=color)
	else:
		act = Task.task_type_from_func(name, action, color=color)
	act.ext_in = tuple(Utils.to_list(ext_in))
	act.ext_out = tuple(Utils.to_list(ext_out))
	act.before = Utils.to_list(before)
	act.after = Utils.to_list(after)

	def x_file(self, node):
		if decider:
			ext = decider(self, node)
		elif type(ext_out) is types.StringType:
			ext = ext_out

		if type(ext) is types.StringType:
			out_source = node.change_ext(ext)
			if reentrant:
				self.allnodes.append(out_source)
		elif type(ext) == types.ListType:
			out_source = [node.change_ext(x) for x in ext]
			if reentrant:
				for i in xrange(reentrant):
					self.allnodes.append(out_source[i])
		else:
			# XXX: useless: it will fail on Utils.to_list above...
			raise Utils.WafError("do not know how to process %s" % str(ext))

		tsk = self.create_task(name)
		tsk.set_inputs(node)
		tsk.set_outputs(out_source)

		if Options.is_install and install:
			tsk.install = install

	declare_extension(act.ext_in, x_file)
 def setCannonWillFire(self, avId, fireTime, zRot, angle):
     if not self._DistributedCannonGame__playing():
         return None
     
     self.notify.debug('setCannonWillFire: ' + str(avId) + ': zRot=' + str(zRot) + ', angle=' + str(angle) + ', time=' + str(fireTime))
     self.cannonPositionDict[avId][0] = zRot
     self.cannonPositionDict[avId][1] = angle
     self._DistributedCannonGame__updateCannonPosition(avId)
     task = Task.Task(self._DistributedCannonGame__fireCannonTask)
     task.avId = avId
     task.fireTime = fireTime
     timeToWait = task.fireTime - self.getCurrentGameTime()
     if timeToWait > 0.0:
         fireTask = Task.sequence(Task.pause(timeToWait), task)
     else:
         fireTask = task
     fireTask = task
     taskMgr.add(fireTask, 'fireCannon' + str(avId))
     self.airborneToons += 1
Example #26
0
  	def NewTaskButtonClicked(self):	
    		Dialog = frmDialog(self)
    		Dialog.show()
    		ret = Dialog.exec_()
    		global taskName,taskDuration,isAdded,taskList
		if(isAdded):    		
			self.count+=1
			self.ui.TaskListWidget.addItem(str(self.count)+","+taskName+","+taskDuration)
			self.populateDependencyList()			
			task = Task(self.count,taskName)
			task.duration = int(taskDuration)
			taskList.append(task) 			
			
			f = open('tasks_test.txt','a') 
			f.write(str(self.count)+","+taskName+","+taskDuration+"\n") 
			f.close()
			f1 = open('dependencies_test.txt','a') 
			f1.write(str(self.count)+"\n") 
			f1.close()
 def __init__(self, *a, **k):
     super(ModesComponent, self).__init__(*a, **k)
     self._last_toggle_value = 0
     self._mode_toggle = None
     self._mode_toggle_task = self._tasks.add(Task.wait(Defaults.MOMENTARY_DELAY))
     self._mode_toggle_task.kill()
     self._mode_list = []
     self._mode_map = {}
     self._last_selected_mode = None
     self._mode_stack = StackingResource(self._do_enter_mode, self._do_leave_mode)
     self._shift_button = None
Example #28
0
    def create_xml2po_task(lang):
        node = self.path.find_resource(lang + os.sep + lang+'.po')
        src = self.path.find_resource('C' + os.sep + self.doc_module+'.xml')
        out = self.path.find_or_declare(lang + os.sep + self.doc_module+'.xml')

        if self.env['IS_WIN32']:
            # FIXME - xml2po on win32 fails with flags containing backslashes '\'
            # failing example:  python xml2po -e -p fr\fr.po C\xiphos.xml
            node_str = replace_backslash(node)
            src_str = replace_backslash(src)

            # it is necessary pas to xml2po only paths with '/'
            Task.simple_task_type('xml2po',
                    '${XML2PO} -e -p %s %s > ${TGT}' % (node_str, src_str),
                    color='BLUE')

        tsk = self.create_task('xml2po')
        tsk.set_inputs([node, src])
        # waf will control output file if it exists, when task is done
        tsk.set_outputs(out)
        return tsk, out
    def schedule_message(self, delay_in_ticks, callback, parameter = None):
        """ Schedule a callback to be called after a specified time """
        if not delay_in_ticks > 0:
            raise AssertionError
            if not callable(callback):
                raise AssertionError
                self._is_sending_scheduled_messages or delay_in_ticks -= 1
            message_reference = [None]

            def message(delta):
                if parameter:
                    callback(parameter)
                else:
                    callback()
                self._remaining_scheduled_messages.remove(message_reference)

            message_reference[0] = message
            self._remaining_scheduled_messages.append(message_reference)
            delay_in_ticks and self._task_group.add(Task.sequence(Task.delay(delay_in_ticks), message))
        else:
            self._task_group.add(message)
Example #30
0
 def judge_json(self, json_data, con_sock):
     """
     get the json data like:
         {"NODES":env}
         {"TASKS":task}
         {"OUPUT":msg}
     """
     print '[NOTICE]:get data is', json_data
     tuple_addr = con_sock.getsockname()
     if json_data.has_key("NODES"):
         node = Server.Node(tuple_addr[0], tuple_addr[1], json_data["NODES"], con_sock)
         self._nodes.append(node)
     elif json_data.has_key("TASKS"):
         task = Task.Task(tuple_addr[0], tuple_addr[1], con_sock, json_data["TASKS"])
         if task.get_task_msg() != dict():
             self._tasks.append(task)
         else:
             task.get_sock().close()
     elif json_data.has_key("OUTPUT"):
         self.exchange_msg(json_data["OUTPUT"], con_sock)
     else:
         print "[Error]:the msg is not a node or task"
Example #31
0
class UnmountTask(Task.LoggingTask):
    def __init__(self, job, hdd):
        Task.LoggingTask.__init__(self, job, _("Unmount"))
        self.hdd = hdd
        self.mountpoints = []

    def prepare(self):
        try:
            dev = self.hdd.disk_path.split('/')[-1]
            open('/dev/nomount.%s' % dev, "wb").close()
        except Exception, e:
            print "ERROR: Failed to create /dev/nomount file:", e
        self.setTool('umount')
        self.args.append('-f')
        for dev in self.hdd.enumMountDevices():
            self.args.append(dev)
            self.postconditions.append(Task.ReturncodePostcondition())
            self.mountpoints.append(dev)
        if not self.mountpoints:
            print "UnmountTask: No mountpoints found?"
            self.cmd = 'true'
            self.args = [self.cmd]
Example #32
0
    def __start_task(self, ra, dec, fov, lowermag, uppermag, star_catalog):

        cat_obj = {'usnob': self.usnob, 'gsc': self.gsc, 'sao': self.sao}
        method = 'search'
        task_list = []
        for catalog in star_catalog.split(','):
            catalog = catalog.strip()
            self.logger.debug("%s thread starting..." % catalog)
            cat = cat_obj[catalog]
            #search = ("self.%s.search" %catalog)
            try:
                search = getattr(cat, method)
                #t = Task.FuncTask(eval(search), [ra, dec, fov, lowermag, uppermag], {}, logger=self.logger)
                t = Task.FuncTask(search, [ra, dec, fov, lowermag, uppermag],
                                  {},
                                  logger=self.logger)
                task_list.append(t)
            except Exception as e:
                self.logger.error('error: starting task. %s' % str(e))
                continue

        return task_list
Example #33
0
def apply_qt4(self):
    if getattr(self, 'lang', None):
        update = getattr(self, 'update', None)
        lst = []
        trans = []
        for l in self.to_list(self.lang):

            if not isinstance(l, Node.Node):
                l = self.path.find_resource(l + '.ts')

            t = self.create_task('ts2qm')
            t.set_inputs(l)
            t.set_outputs(l.change_ext('.qm'))
            lst.append(t.outputs[0])

            if update:
                trans.append(t.inputs[0])

        if update and Options.options.trans_qt4:
            # we need the cpp files given, except the rcc task we create after
            # FIXME may be broken
            u = Task.TaskCmd(translation_update, self.env, 2)
            u.inputs = [a.inputs[0] for a in self.compiled_tasks]
            u.outputs = trans

        if getattr(self, 'langname', None):
            t = Task.TaskBase.classes['qm2rcc'](self.env)
            t.set_inputs(lst)
            t.set_outputs(self.path.find_or_declare(self.langname + '.qrc'))
            t.path = self.path
            k = create_rcc_task(self, t.outputs[0])
            self.link_task.inputs.append(k.outputs[0])

    lst = []
    for flag in self.to_list(self.env['CXXFLAGS']):
        if len(flag) < 2: continue
        if flag[0:2] == '-D' or flag[0:2] == '-I':
            lst.append(flag)
    self.env['MOC_FLAGS'] = lst
Example #34
0
 def createExt4ConversionJob(self):
     if not isFileSystemSupported('ext4'):
         raise Exception, _("You system does not support ext4")
     job = Task.Job(_("Convert ext3 to ext4..."))
     if not path.exists('/sbin/tune2fs'):
         task = Task.LoggingTask(job, "update packages")
         task.setTool('opkg')
         task.args.append('update')
         task = Task.LoggingTask(job, "Install e2fsprogs-tune2fs")
         task.setTool('opkg')
         task.args.append('install')
         task.args.append('e2fsprogs-tune2fs')
     if self.findMount():
         # Create unmount task if it was not mounted
         UnmountTask(job, self)
         dev = self.mount_device
     else:
         # otherwise, assume there is one partition
         dev = self.partitionPath("1")
     task = Task.LoggingTask(job, "fsck")
     task.setTool('fsck.ext3')
     task.args.append('-p')
     task.args.append(dev)
     task = Task.LoggingTask(job, "tune2fs")
     task.setTool('tune2fs')
     task.args.append('-O')
     task.args.append('extents,uninit_bg,dir_index')
     task.args.append('-o')
     task.args.append('journal_data_writeback')
     task.args.append(dev)
     task = Task.LoggingTask(job, "fsck")
     task.setTool('fsck.ext4')
     task.postconditions = []  # ignore result, it will always "fail"
     task.args.append('-f')
     task.args.append('-p')
     task.args.append('-D')
     task.args.append(dev)
     MountTask(job, self)
     task = Task.ConditionTask(job, _("Wait for mount"))
     task.check = self.mountDevice
     return job
Example #35
0
def setup(bld):
    outfile = ''
    if sys.platform.startswith('linux'):
        outfile = ' > /dev/null'
    ndstool_str = '${NDSTOOL} -c ${TGT} -9 ${SRC[0].bldpath(env)} %s ' + outfile
    Task.simple_task_type('ndstool',
                          ndstool_str % '',
                          before='unit_test',
                          after='elf2bin')
    Task.simple_task_type('ndstool_banner',
                          ndstool_str %
                          " -b ${SRC[1].srcpath(env)} '${NDSTOOL_BANNER}'",
                          before='unit_test',
                          after='elf2bin')
    Task.simple_task_type('elf2bin',
                          '${OBJCOPY} -O binary ${SRC} ${TGT}',
                          after='cc_link cxx_link')
 def __init__(self, c_instance = None, publish_self = True, *a, **k):
     """ Define and Initialize standard behavior """
     super(ControlSurface, self).__init__(*a, **k)
     if not c_instance:
         raise AssertionError
         self.canonical_parent = None
         publish_self and publish_control_surface(self)
     self._c_instance = c_instance
     self.log_message('Initialising...')
     self._pad_translations = None
     self._suggested_input_port = str('')
     self._suggested_output_port = str('')
     self._components = []
     self._displays = []
     self.controls = []
     self._highlighting_session_component = None
     self._device_component = None
     self._device_selection_follows_track_selection = False
     self._forwarding_long_identifier_registry = {}
     self._forwarding_registry = {}
     self._is_sending_scheduled_messages = BooleanContext()
     self._remaining_scheduled_messages = []
     self._task_group = Task.TaskGroup(auto_kill=False)
     self._in_build_midi_map = BooleanContext()
     self._suppress_requests_counter = 0
     self._rebuild_requests_during_suppression = 0
     self._enabled = True
     self._in_component_guard = BooleanContext()
     self._accumulate_midi_messages = BooleanContext()
     self._midi_message_dict = {}
     self._midi_message_list = []
     self._midi_message_count = 0
     self._control_surface_injector = inject(parent_task_group=const(self._task_group), show_message=const(self.show_message), log_message=const(self.log_message), register_component=const(self._register_component), register_control=const(self._register_control), request_rebuild_midi_map=const(self.request_rebuild_midi_map), set_pad_translations=const(self.set_pad_translations), send_midi=const(self._send_midi), song=self.song).everywhere()
     with self.setting_listener_caller():
         self.register_slot(self.song(), self._on_track_list_changed, 'visible_tracks')
         self.register_slot(self.song(), self._on_scene_list_changed, 'scenes')
         self.register_slot(self.song().view, self._on_selected_track_changed, 'selected_track')
         self.register_slot(self.song().view, self._on_selected_scene_changed, 'selected_scene')
 def __init__(self,
              msg_type=None,
              channel=None,
              identifier=None,
              sysex_identifier=None,
              request_rebuild_midi_map=None,
              *a,
              **k):
     raise msg_type in MIDI_MSG_TYPES or AssertionError
     raise in_range(channel, 0, 16) or channel is None or AssertionError
     raise in_range(identifier, 0,
                    128) or identifier is None or AssertionError
     raise msg_type != MIDI_SYSEX_TYPE or channel == None or AssertionError
     raise msg_type != MIDI_SYSEX_TYPE or identifier == None or AssertionError
     raise msg_type == MIDI_SYSEX_TYPE or sysex_identifier == None or AssertionError
     super(InputControlElement, self).__init__(*a, **k)
     self._request_rebuild = request_rebuild_midi_map
     self._msg_type = msg_type
     self._msg_channel = channel
     self._msg_identifier = identifier
     self._msg_sysex_identifier = sysex_identifier
     self._original_channel = channel
     self._original_identifier = identifier
     self._needs_takeover = True
     self._is_mapped = True
     self._is_being_forwarded = True
     self._delayed_messages = []
     self._force_next_send = False
     self._mapping_feedback_delay = 0
     self._mapping_sensitivity = 1.0
     self._send_delayed_messages_task = self._tasks.add(
         Task.run(self._send_delayed_messages))
     self._send_delayed_messages_task.kill()
     self._parameter_to_map_to = None
     self._in_parameter_gesture = False
     self._last_sent_message = None
     self._report_input = False
     self._report_output = False
Example #38
0
    def updateTask(self, tasktaskNameVar, descriptionVar, dateVar, priorityVar, whichSelected):
        try:
            self.todoitem = Task(tasktaskNameVar, descriptionVar, priorityVar, dateVar, self.today)

            conn = pymysql.connect(host='127.0.0.1', user='******', passwd=None, db='todolist')
            cur = conn.cursor()
            update_task = "UPDATE task SET TaskTitle=%s, TaskDescription=%s, TaskPriority=%s, TaskDueDate=%s, CreationDate=%s WHERE TaskTitle=%s AND TaskDescription=%s AND TaskPriority=%s AND TaskDueDate=%s AND CreationDate=%s"
            task_data = (self.todoitem.TaskTitle, self.todoitem.TaskDescription, self.todoitem.TaskPriority, self.todoitem.TaskDueDate, self.todoitem.CreationDate,
                         self.taskList[whichSelected].TaskTitle, self.taskList[whichSelected].TaskDescription,
                         self.taskList[whichSelected].TaskPriority, self.taskList[whichSelected].TaskDueDate, self.taskList[whichSelected].CreationDate)
            cur.execute(update_task, task_data)

            conn.commit()

            cur.close()
            conn.close()

            self.taskList[whichSelected] = self.todoitem

        except ValueError:
            print("Please select an task to update")
        except TypeError:
            print("Type Error")
    def setUp(self):
        """
        - Initialize logger
        - Create 20-thread thread pool
        - Make a fake parentTask using the thread pool
        """
        if  LOGDEBUG:
            print "\n*** TestTask01: setting up thread pool"
        self.logger = logging.getLogger( 'TestTask01Logger' )
        self.logger.setLevel(logging.WARN)
    
        self.tpool = Task.ThreadPool(numthreads=20, logger=self.logger)
        self.tpool.startall(wait=True)

        # Make a fake 'parent' task
        self.parentTask = make_SimpleTask('t1')
        self.parentTask.tag = 'tasks'

        sl = logging.getLogger( 'TestTask01ParentLogger' )
        sl.setLevel(logging.WARN)
        self.parentTask.logger = sl

        self.parentTask.threadPool = self.tpool
Example #40
0
    def __init__(self):
        self.sepwin = []
        super().__init__()
        self.setupUi(self)
        self.setWindowIcon(
            QIcon('.computerhousekeeper\\img\\ComputerHousekeeper.jpg'))

        self.task = Task()
        self.tool = Tool()
        self.more = More()

        self.qsl = QStackedLayout(self.frame_ui)
        self.qsl.addWidget(self.task)
        self.qsl.addWidget(self.tool)
        self.qsl.addWidget(self.more)

        self.pushButton_task.clicked.connect(self.show_panel)
        self.pushButton_task.customContextMenuRequested.connect(
            self.pushButton_task_showrightmenu)
        self.pushButton_tool.clicked.connect(self.show_panel)
        self.pushButton_tool.customContextMenuRequested.connect(
            self.pushButton_tool_showrightmenu)
        self.pushButton_more.clicked.connect(self.show_panel)
        self.pushButton_more.customContextMenuRequested.connect(
            self.pushButton_more_showrightmenu)
        self.tool.listWidget_tool.doubleClicked.connect(self.start_tool)
        self.tool.listWidget_tool.doubleClicked.disconnect(
            self.tool.start_tool)

        self.pushButton_task.setIcon(
            QIcon('.computerhousekeeper\\img\\task.jpg'))
        self.pushButton_tool.setIcon(
            QIcon('.computerhousekeeper\\img\\tool.jpg'))
        self.pushButton_more.setIcon(
            QIcon('.computerhousekeeper\\img\\more.jpg'))

        logging.info(f'初始化{type(self).__name__}窗口')
 def _DistributedCannonGame__startIntro(self):
     self.T_WATER = 1
     self.T_WATER2LONGVIEW = 1
     self.T_LONGVIEW = 1
     self.T_LONGVIEW2TOONHEAD = 2
     self.T_TOONHEAD = 2
     self.T_TOONHEAD2CANNONBACK = 2
     taskLookInWater = Task.Task(self._DistributedCannonGame__taskLookInWater)
     taskPullBackFromWater = Task.Task(self._DistributedCannonGame__taskPullBackFromWater)
     taskFlyUpToToon = Task.Task(self._DistributedCannonGame__flyUpToToon)
     taskFlyToBackOfCannon = Task.Task(self._DistributedCannonGame__flyToBackOfCannon)
     commonData = { }
     taskLookInWater.data = commonData
     taskPullBackFromWater.data = commonData
     taskFlyUpToToon.data = commonData
     taskFlyToBackOfCannon.data = commonData
     introTask = Task.sequence(taskLookInWater, Task.pause(self.T_WATER), taskPullBackFromWater, Task.pause(self.T_WATER2LONGVIEW + self.T_LONGVIEW), taskFlyUpToToon, Task.pause(self.T_LONGVIEW2TOONHEAD + self.T_TOONHEAD), taskFlyToBackOfCannon)
     taskMgr.add(introTask, self.INTRO_TASK_NAME)
Example #42
0
    def post(self):
        # get data ,return error page if it's empty
        try:
            fileinfo = self.request.files["rbf_gamma_data"][0]
            rbf_gamma_data = fileinfo["body"]
        except KeyError:
            self.render("error.html", error_info="Please Upload Your Data.")
            return

        try:
            # save data for calculate
            filename = upload_dir + fileinfo["filename"]

            while os.path.exists(filename):
                filename = filename + str(random.randint(1, 9))

            f = open(filename, "w")
            f.write(rbf_gamma_data)
            f.close()

            min_g = float(self.get_argument("gamma_min", "1"))
            max_g = float(self.get_argument("gamma_max", "10"))
            step = float(self.get_argument("gamma_step", "1"))
            C = float(self.get_argument("C", "1"))

            # min_g = 1.0e-8
            # max_g = 2.0e-8
            # step = 1e-9
            # task of calculate with different gamma of RBF
            rgTask = Task.RBFGammaTask(filename, min_g, max_g, step, C)

            # remove data after calculating
        except Exception, e:
            os.remove(filename)
            self.render(
                "error.html", error_info="Please Check Your Data Format or Selected Gammas")
            return
Example #43
0
 def createExt4ConversionJob(self):
     if not isFileSystemSupported('ext4'):
         raise Exception, _('You system does not support ext4')
     job = Task.Job(_('Convert ext3 to ext4...'))
     if not path.exists('/sbin/tune2fs'):
         task = Task.LoggingTask(job, 'update packages')
         task.setTool('opkg')
         task.args.append('update')
         task = Task.LoggingTask(job, 'Install e2fsprogs-tune2fs')
         task.setTool('opkg')
         task.args.append('install')
         task.args.append('e2fsprogs-tune2fs')
     if self.findMount():
         UnmountTask(job, self)
         dev = self.mount_device
     else:
         dev = self.partitionPath('1')
     task = Task.LoggingTask(job, 'fsck')
     task.setTool('fsck.ext3')
     task.args.append('-p')
     task.args.append(dev)
     task = Task.LoggingTask(job, 'tune2fs')
     task.setTool('tune2fs')
     task.args.append('-O')
     task.args.append('extents,uninit_bg,dir_index')
     task.args.append('-o')
     task.args.append('journal_data_writeback')
     task.args.append(dev)
     task = Task.LoggingTask(job, 'fsck')
     task.setTool('fsck.ext4')
     task.postconditions = []
     task.args.append('-f')
     task.args.append('-p')
     task.args.append('-D')
     task.args.append(dev)
     MountTask(job, self)
     task = Task.ConditionTask(job, _('Wait for mount'))
     task.check = self.mountDevice
     return job
Example #44
0
def exec_rule(self):
	if not getattr(self,'rule',None):
		return
	try:
		self.meths.remove('apply_core')
	except ValueError:
		pass
	func=self.rule
	vars2=[]
	if isinstance(func,str):
		(func,vars2)=Task.compile_fun('',self.rule,shell=getattr(self,'shell',True))
		func.code=self.rule
	vars=getattr(self,'vars',vars2)
	if not vars:
		if isinstance(self.rule,str):
			vars=self.rule
		else:
			vars=Utils.h_fun(self.rule)
	name=getattr(self,'name',None)or self.target or self.rule
	cls=Task.task_type_from_func(name,func,vars)
	tsk=self.create_task(name)
	if getattr(self,'target',None):
		cls.quiet=True
		tsk.outputs=[self.path.find_or_declare(x)for x in self.to_list(self.target)]
	if getattr(self,'source',None):
		cls.quiet=True
		tsk.inputs=[]
		for x in self.to_list(self.source):
			y=self.path.find_resource(x)
			if not y:
				raise Utils.WafError('input file %r could not be found (%r)'%(x,self.path.abspath()))
			tsk.inputs.append(y)
	if getattr(self,'always',None):
		Task.always_run(cls)
	if getattr(self,'scan',None):
		cls.scan=self.scan
	if getattr(self,'install_path',None):
		tsk.install_path=self.install_path
	if getattr(self,'cwd',None):
		tsk.cwd=self.cwd
	if getattr(self,'on_results',None):
		Task.update_outputs(cls)
	for x in['after','before']:
		setattr(cls,x,getattr(self,x,[]))
Example #45
0
    def process_request(self, request, client_address):
        """Start a new thread to process the request."""

        if self.useThread:
            if self.threadPool:
                self.logger.debug("Handing off request %s to threadpool." % (
                        str(client_address)))
                # If there is a threadpool with worker tasks, use it
                task = Task.FuncTask2(self.fn, request, client_address)
                task.initialize(self)
                self.threadPool.addTask(task)
            else:
                self.logger.debug("Creating thread to handle request %s." % (
                        str(client_address)))
                # otherwise create a new thread
                t = threading.Thread(target=self.fn,
                                     args=(request, client_address))
                if self.daemon_threads:
                    t.setDaemon(1)
                t.start()
            
        # Default behavior is single-threaded sequential execution
        else:
            self.fn(request, client_address)
Example #46
0
def run_optimize(sort_tasks):
    t = tsk.Task("", 0, 0, 0, 0)
    dtime = sort_tasks[len(sort_tasks) -
                       1].start + sort_tasks[len(sort_tasks) - 1].length
    for i in range(0, len(sort_tasks) - 1):
        index = len(sort_tasks) - 1 - i
        for j in range(0, len(sort_tasks) - 1 - i):
            if (sort_tasks[j].deadline >= dtime) and (
                    sort_tasks[j].length < sort_tasks[index].length):
                index = j

        if index != (len(sort_tasks) - 1 - i):
            t.length = sort_tasks[len(sort_tasks) - 1 - i].length
            t.title = sort_tasks[len(sort_tasks) - 1 - i].title
            t.deadline = sort_tasks[len(sort_tasks) - 1 - i].deadline
            sort_tasks[len(sort_tasks) - 1 -
                       i].length = sort_tasks[index].length
            sort_tasks[len(sort_tasks) - 1 - i].title = sort_tasks[index].title
            sort_tasks[len(sort_tasks) - 1 -
                       i].deadline = sort_tasks[index].deadline

            sort_tasks[index].length = t.length
            sort_tasks[index].title = t.title
            sort_tasks[index].deadline = t.deadline

        dtime = dtime - sort_tasks[len(sort_tasks) - 1 - i].length

    for i in range(0, len(sort_tasks) - 1):
        if i == 0:
            sort_tasks[i].start = dtime - sort_tasks[i].length
        else:
            sort_tasks[i].start = sort_tasks[i -
                                             1].start + sort_tasks[i -
                                                                   1].length

    return sort_tasks
    def workThread(self,client):
        sl = SocketStreamReader(client)
        while True:
            msg = sl.readline()
            msg = msg.decode("utf-8")
            try:
                msg = json.loads(msg)
                No = msg["No"]
                id = msg["taskId"]
                if(No=="submit"):
                    t = Task(id)
                    self.tm.addTask(t)
                elif(No=="GetData"):
                    line = self.tm.getCureveData(id,msg["pos"])
                    client.send((line+'\n').encode("utf-8"))

                else:
                    mode = msg["mode"]
                    if(mode=="start"):
                        print("start")
                        self.tm.startTask(id)
                    elif(mode=="suspend"):
                        print("suspend")
                        self.tm.suspendTask(id)
                    elif(mode=="goon"):
                        print("goon")
                        self.tm.goonTask(id)
                    elif(mode=="stop"):
                        print("stop")
                        self.tm.stopTask(id)
                    elif(mode=="restart"):
                        print("restart")
                        self.tm.restartTask(id)
            except Exception:
                val = traceback.format_exc()
                print(val)
Example #48
0
    def __init__(self):
        # get tasktable for administrating tasks
        self.taskTable = Task.TaskTable()

        handlers = [
            (r"/", ClassifierHandler),
            (r"/format/(\w+)", DataFormatHandler),
            (r"/result/(\w+).(\w+)", ResultDataHandler),
            (r"/delete", DeleteHandler),
            (r"/stat_feature", StatFeatureHandler),
            (r"/rbf_gamma", RBFGammaHandler),
            (r"/soft_margin", SoftMarginHandler),
            (r"/forward_stepwise", ForwardStepwiseHandler),
            (r"/state/(\w+)", StateHandler),
            (r"/knn", KnnHandler)
        ]

        settings = {
            'template_path': 'templates',
            'static_path': 'static',
            'debug': 'True'
        }

        tornado.web.Application.__init__(self, handlers, **settings)
Example #49
0
def eventAbduction(compoundTask, componentTask):
    # TODO< assert on types of task >

    resultTaskStamp = Stamp.merge(compoundTask.stamp, componentTask.stamp)
    resultTask = Task(Task.ENUMTYPE_GOAL, resultTaskStamp)
    resultTask.sdr = sdrDetachmentForward(compoundTask.sdr, componentTask.sdr)
    resultTask.identifyingSdr = resultTask.sdr  # we do this because they are the same for NARS tasks!
    resultTask.truth = TruthValue.abduction(compoundTask.truth,
                                            componentTask.truth)
    resultTask.attention = AttentionValue()

    if DEBUG:
        ## TODO< used debug cookie of name of SDR if possible >
        print("[t] event ABDUCTION   {{{}., {}!}} |- {}!".format(
            compoundTask.retHumanReadableId(),
            componentTask.retHumanReadableId(),
            resultTask.sdr.retHumanReadableId()))

    return resultTask
Example #50
0
    def parseCommands(self, r):
        tasks=Task.TaskGroup()

        for c in r.getchildren():
        #
        # <message>
            if c.tag == 'message': # end message
                sendto     = c.get('sendto')
                if not sendto : sendto = c.get('host')
                task = Task.TaskMessage(self.parent, sendto, c.text, c.get('encode'), c.get('input'))
                tasks.addTask(task)
        #
        # <statetransition>
            elif c.tag == 'statetransition': # get statetransition
                task = Task.TaskStatetransition(self.parent, c.get('func'), c.text)
                tasks.addTask(task)
        #
        # <log>
            elif c.tag == 'log': #  logging
                task = Task.TaskLog(self.parent, c.text)
                tasks.addTask(task)
        #
        # <shell>
            elif c.tag == 'shell': # get shell
                sendto = c.get('sendto')
                if not sendto : sendto = c.get('host')
                task = Task.TaskShell(self.parent, sendto, c.text)
                tasks.addTask(task)
        #
        # <script>
            elif c.tag == 'script': # get script
                sendto  = c.get('sendto')
                if not sendto : sendto = c.get('host')
                task = Task.TaskScript(self.parent, sendto,
                    self.getScripts(c), c.get('execfile'), c.get('import'))
                tasks.addTask(task)
        return tasks
    def processTask(self, data):
        """
        This function determines which task is being asked to run on the robot
        and calls the apprropriate task function. It also adds the task to the
        active task list if a robot is assigned, or a priority queue if no robot
        is assigned. Please look at the task code data structure above to see what that task codes mean. 
        :param data: the string containing the robot and task information.
                     i.e. <task name> <robot name> <X coordinate> <Y coordinate>
        :return None
        """
        # Have to know if the task has been unnassigned
        # have to know what the task is
        # Task Strings: 'task_name robot_name X Y [vars ...]'
        # DLV vars = fromX fromY
        if type(data) == str:
            dataList = data.split()
            if (data == ""):
                return
        else:
            if(data.data == ""):
                return
            dataList = data.data.split()

        supervisorID = dataList[0]
        supervisor = self.activeSupervisorDictionary[supervisorID]
        taskName = dataList[1]
        # passed as unassigned if task is not assigned
        robotName = dataList[2]

        yaw = -float(dataList[5]) + np.pi
        raisePriority = dataList[6]
        if (raisePriority == "False"):
            priorityRaised = False
        else:
            priorityRaised = True
        print('Split Task Data')
        print("PRIORITY RAISED: ", priorityRaised)
        print(len(dataList))
        print(dataList)

        # if len(dataList) > 5:
        #     variables = dataList[5]
        # else:
        #     variables = " "

        if (taskName != 'SOS'):
            X = float(dataList[3])
            Y = float(dataList[4])
            newTask = Task(taskName, self.taskPrios[taskName], robotName, X, Y, yaw, priorityRaised, supervisorID)
            newTaskMsg = newTask.convertTaskToTaskMsg()
            if robotName != "unassigned":
                # remove current task form active task list
                oldTaskMsg = self.activeRobotDictionary[robotName].currentTask
                for task in supervisor.activeTaskList:
                    if oldTaskMsg.ID == task.getID():
                        supervisor.activeTaskList.remove(task)
                        break
                self.taskFns[taskName](newTaskMsg)
                supervisor.activeTaskList.append(newTask)
            else:
                supervisor.taskPriorityQueue.append(newTask)
                supervisor.taskPriorityQueue.sort(key=lambda task: task.getPriority())
            print('Called Task Function')
        elif (taskName == 'SOS'):
            self.passRobotToQueueForOperator(robotName)
Example #52
0
            mode = '2'
        debug('msvc: embedding manifest')
        lst = []
        lst.extend(Utils.to_list(env['MT']))
        lst.extend(Utils.to_list(env['MTFLAGS']))
        lst.extend(Utils.to_list("-manifest"))
        lst.extend(Utils.to_list(manifest))
        lst.extend(Utils.to_list("-outputresource:%s;%s" % (outfile, mode)))
        lst = [lst]
        return self.exec_command(*lst)
    return None


cls = Task.task_type_from_func('msvc_manifest',
                               vars=['MT', 'MTFLAGS'],
                               color='BLUE',
                               func=exec_mf,
                               ext_in='.bin')
cls.quiet = 1


def exec_command_msvc(self, *k, **kw):
    if self.env['CC_NAME'] == 'msvc':
        if isinstance(k[0], list):
            lst = []
            carry = ''
            for a in k[0]:
                if len(a) == 3 and a.startswith(
                        '/F') or a == '/doc' or a[-1] == ':':
                    carry = a
                else:
Example #53
0
	def createInitializeJob(self):
		job = Task.Job(_("Initializing storage device..."))
		size = self.diskSize()
		print "[HD] size: %s MB" % size

		task = UnmountTask(job, self)

		task = Task.PythonTask(job, _("Removing partition table"))
		task.work = self.killPartitionTable
		task.weighting = 1

		task = Task.LoggingTask(job, _("Rereading partition table"))
		task.weighting = 1
		task.setTool('hdparm')
		task.args.append('-z')
		task.args.append(self.disk_path)

		task = Task.ConditionTask(job, _("Waiting for partition"), timeoutCount=20)
		task.check = lambda: not os.path.exists(self.partitionPath("1"))
		task.weighting = 1

		if os.path.exists('/usr/sbin/parted'):
			use_parted = True
		else:
			if size > 2097151:
				addInstallTask(job, 'parted')
				use_parted = True
			else:
				use_parted = False

		task = Task.LoggingTask(job, _("Creating partition"))
		task.weighting = 5
		if use_parted:
			task.setTool('parted')
			if size < 1024:
				# On very small devices, align to block only
				alignment = 'min'
			else:
				# Prefer optimal alignment for performance
				alignment = 'opt'
			if size > 2097151:
				parttype = 'gpt'
			else:
				parttype = 'msdos'
			task.args += ['-a', alignment, '-s', self.disk_path, 'mklabel', parttype, 'mkpart', 'primary', '0%', '100%']
		else:
			task.setTool('sfdisk')
			task.args.append('-f')
			task.args.append('-uS')
			task.args.append(self.disk_path)
			if size > 128000:
				# Start at sector 8 to better support 4k aligned disks
				print "[HD] Detected >128GB disk, using 4k alignment"
				task.initial_input = "8,\n;0,0\n;0,0\n;0,0\ny\n"
			else:
				# Smaller disks (CF cards, sticks etc) don't need that
				task.initial_input = "0,\n;\n;\n;\ny\n"

		task = Task.ConditionTask(job, _("Waiting for partition"))
		task.check = lambda: os.path.exists(self.partitionPath("1"))
		task.weighting = 1

		task = MkfsTask(job, _("Creating filesystem"))
		big_o_options = ["dir_index"]
		if isFileSystemSupported("ext4"):
			task.setTool("mkfs.ext4")
			if size > 20000:
				try:
					file = open("/proc/version","r")
					version = map(int, file.read().split(' ', 4)[2].split('.',2)[:2])
					file.close()
					if (version[0] > 3) or (version[0] > 2 and version[1] >= 2):
						# Linux version 3.2 supports bigalloc and -C option, use 256k blocks
						task.args += ["-C", "262144"]
						big_o_options.append("bigalloc")
				except Exception, ex:
					print "Failed to detect Linux version:", ex
Example #54
0
			# No more than 256k i-nodes (prevent problems with fsck memory requirements)
			task.args += ["-T", "largefile", "-N", "262144"]
			big_o_options.append("sparse_super")
		elif size > 16384:
			# between 16GB and 250GB: 1 i-node per megabyte
			task.args += ["-T", "largefile"]
			big_o_options.append("sparse_super")
		elif size > 2048:
			# Over 2GB: 32 i-nodes per megabyte
			task.args += ["-T", "largefile", "-N", str(size * 32)]
		task.args += ["-m0", "-O", ",".join(big_o_options), self.partitionPath("1")]

		task = MountTask(job, self)
		task.weighting = 3

		task = Task.ConditionTask(job, _("Waiting for mount"), timeoutCount=20)
		task.check = self.mountDevice
		task.weighting = 1

		return job

	def initialize(self):
		# no longer supported
		return -5

	def check(self):
		# no longer supported
		return -5

	def createCheckJob(self):
		job = Task.Job(_("Checking filesystem..."))
Example #55
0
        elif size > 16384:
            # between 16GB and 250GB: 1 i-node per megabyte
            task.args += ["-T", "largefile"]
            big_o_options.append("sparse_super")
        elif size > 2048:
            # Over 2GB: 32 i-nodes per megabyte
            task.args += ["-T", "largefile", "-N", str(size * 32)]
        task.args += [
            "-m0", "-O", ",".join(big_o_options),
            self.partitionPath("1")
        ]

        task = MountTask(job, self)
        task.weighting = 3

        task = Task.ConditionTask(job, _("Waiting for mount"), timeoutCount=20)
        task.check = self.mountDevice
        task.weighting = 1

        task = Task.PythonTask(job, _("Create directory") + ": movie")
        task.work = self.createMovieDir
        task.weighting = 1

        return job

    def initialize(self):
        # no longer supported
        return -5

    def check(self):
        # no longer supported
Example #56
0
        dep.post()
        for dep_task in dep.tasks:
            task.set_run_after(dep_task)
    if not task.inputs:
        task.runnable_status = type(Task.TaskBase.run)(runnable_status, task,
                                                       task.__class__)
        task.post_run = type(Task.TaskBase.run)(post_run, task, task.__class__)


def post_run(self):
    for x in self.outputs:
        h = Utils.h_file(x.abspath(self.env))
        self.generator.bld.node_sigs[self.env.variant()][x.id] = h


def runnable_status(self):
    return Constants.RUN_ME


Task.task_type_from_func('copy', vars=[], func=action_process_file_func)
TaskGen.task_gen.classes['command-output'] = cmd_output_taskgen

feature('cmd')(apply_cmd)
feature('copy')(apply_copy)
before('apply_core')(apply_copy)
feature('subst')(apply_subst)
before('apply_core')(apply_subst)
feature('command-output')(init_cmd_output)
feature('command-output')(apply_cmd_output)
after('init_cmd_output')(apply_cmd_output)
Example #57
0
    def createInitializeJob(self):
        job = Task.Job(_("Initializing storage device..."))
        size = self.diskSize()
        print "[HD] size: %s MB" % size

        task = UnmountTask(job, self)

        task = Task.PythonTask(job, _("Removing partition table"))
        task.work = self.killPartitionTable
        task.weighting = 1

        task = Task.LoggingTask(job, _("Rereading partition table"))
        task.weighting = 1
        task.setTool('hdparm')
        task.args.append('-z')
        task.args.append(self.disk_path)

        task = Task.ConditionTask(job,
                                  _("Waiting for partition"),
                                  timeoutCount=20)
        task.check = lambda: not os.path.exists(self.partitionPath("1"))
        task.weighting = 1

        if os.path.exists('/usr/sbin/parted'):
            use_parted = True
        else:
            if size > 2097151:
                addInstallTask(job, 'parted')
                use_parted = True
            else:
                use_parted = False

        task = Task.LoggingTask(job, _("Creating partition"))
        task.weighting = 5
        if use_parted:
            task.setTool('parted')
            if size < 1024:
                # On very small devices, align to block only
                alignment = 'min'
            else:
                # Prefer optimal alignment for performance
                alignment = 'opt'
            if size > 2097151:
                parttype = 'gpt'
            else:
                parttype = 'msdos'
            task.args += [
                '-a', alignment, '-s', self.disk_path, 'mklabel', parttype,
                'mkpart', 'primary', '0%', '100%'
            ]
        else:
            task.setTool('sfdisk')
            task.args.append('-f')
            task.args.append('-uS')
            task.args.append(self.disk_path)
            if size > 128000:
                # Start at sector 8 to better support 4k aligned disks
                print "[HD] Detected >128GB disk, using 4k alignment"
                task.initial_input = "8,\n;0,0\n;0,0\n;0,0\ny\n"
            else:
                # Smaller disks (CF cards, sticks etc) don't need that
                task.initial_input = "0,\n;\n;\n;\ny\n"

        task = Task.ConditionTask(job, _("Waiting for partition"))
        task.check = lambda: os.path.exists(self.partitionPath("1"))
        task.weighting = 1

        task = MkfsTask(job, _("Creating filesystem"))
        big_o_options = ["dir_index"]
        if isFileSystemSupported("ext4"):
            task.setTool("mkfs.ext4")
        else:
            task.setTool("mkfs.ext3")
        if size > 250000:
            # No more than 256k i-nodes (prevent problems with fsck memory requirements)
            task.args += ["-T", "largefile", "-N", "262144"]
            big_o_options.append("sparse_super")
        elif size > 16384:
            # between 16GB and 250GB: 1 i-node per megabyte
            task.args += ["-T", "largefile"]
            big_o_options.append("sparse_super")
        elif size > 2048:
            # Over 2GB: 32 i-nodes per megabyte
            task.args += ["-T", "largefile", "-N", str(size * 32)]
        task.args += [
            "-m0", "-O ^metadata_csum", "-O", ",".join(big_o_options),
            self.partitionPath("1")
        ]

        task = MountTask(job, self)
        task.weighting = 3

        task = Task.ConditionTask(job, _("Waiting for mount"), timeoutCount=20)
        task.check = self.mountDevice
        task.weighting = 1

        return job
Example #58
0
				add_path(fu,lst,'LD_LIBRARY_PATH')
			else:
				add_path(fu,lst,'LD_LIBRARY_PATH')
		try:
			ret=Utils.cmd_output(filename,cwd=self.inputs[0].parent.abspath(self.env),env=fu)
		except Exception,e:
			fail=True
			ret=''+str(e)
		else:
			pass
		stats=getattr(self.generator.bld,'utest_results',[])
		stats.append((filename,fail,ret))
		self.generator.bld.utest_results=stats
	finally:
		testlock.release()
cls=Task.task_type_from_func('utest',func=exec_test,color='RED',ext_in='.bin')
old=cls.runnable_status
def test_status(self):
	if getattr(Options.options,'all_tests',False):
		return RUN_ME
	return old(self)
cls.runnable_status=test_status
cls.quiet=1
def summary(bld):
	lst=getattr(bld,'utest_results',[])
	if lst:
		Utils.pprint('CYAN','execution summary')
		for(f,fail,ret)in lst:
			col=fail and'RED'or'GREEN'
			Utils.pprint(col,(fail and'FAIL'or'ok')+" "+f)
			if fail:Utils.pprint('NORMAL',ret.replace('\\n','\n'))
Example #59
0
File: cxx.py Project: knixeur/meran
		val = self.env['CXXDEFINES_'+l]
		if val: milst += self.to_list(val)

	self.env['DEFLINES'] = ["%s %s" % (x[0], Utils.trimquotes('='.join(x[1:]))) for x in [y.split('=') for y in milst]]
	y = self.env['CXXDEFINES_ST']
	self.env['_CXXDEFFLAGS'] = [y%x for x in milst]

@extension(EXT_CXX)
def cxx_hook(self, node):
	# create the compilation task: cpp or cc
	if getattr(self, 'obj_ext', None):
		obj_ext = self.obj_ext
	else:
		obj_ext = '_%d.o' % self.idx

	task = self.create_task('cxx', node, node.change_ext(obj_ext))
	try:
		self.compiled_tasks.append(task)
	except AttributeError:
		raise Utils.WafError('Have you forgotten to set the feature "cxx" on %s?' % str(self))
	return task

cxx_str = '${CXX} ${CXXFLAGS} ${CPPFLAGS} ${_CXXINCFLAGS} ${_CXXDEFFLAGS} ${CXX_SRC_F}${SRC} ${CXX_TGT_F}${TGT}'
cls = Task.simple_task_type('cxx', cxx_str, color='GREEN', ext_out='.o', ext_in='.cxx', shell=False)
cls.scan = ccroot.scan
cls.vars.append('CXXDEPS')

link_str = '${LINK_CXX} ${CXXLNK_SRC_F}${SRC} ${CXXLNK_TGT_F}${TGT[0].abspath(env)} ${LINKFLAGS}'
cls = Task.simple_task_type('cxx_link', link_str, color='YELLOW', ext_in='.o', ext_out='.bin', shell=False)
cls.maxjobs = 1
cls.install = Utils.nada