def button(self): #Botão MorseToText self.buttonMorse = Button(text='MorseToText', command=ctrl.ButtonFunction().buttonMorse) self.buttonMorse.place(relx=0.5, rely=0.4, relwidth=0.5, anchor=CENTER) self.buttonText = Button(text='TextToMorse', command=ctrl.ButtonFunction().buttonText) self.buttonText.place(relx=0.5, rely=0.5, relwidth=0.5, anchor=CENTER)
def login(): x=e1.get() y=e2.get() db=mc.connect(host="localhost",user="******",database="deepak_home",password="******") cur=db.cursor() cmd="select * from users;" cur.execute(cmd) z=cur.fetchall() l=0 for i in z: l+=1 if x==i[1] and y==i[2]: messagebox.showinfo(title="Welcome", message="Hi! Welcome to Home control") Control.control() log.destroy() break if l==len(x): messagebox.showinfo(title="ERROR", message="User name or Password incorrect") db.commit() cur.close() db.close()
def start_round(sock, team_id): game = Game(sock, team_id) game.register() with open("log.txt", "a+") as f: f.write("success register") while True: game.receive_msg() msg_name = game.get_msg_name() if msg_name == "round": game.round_start() control = Control(team_id, game.our_tank_id, game.maps, game.data) strategy = Strategy(game) # 操作函数 game.set_tank_msg() try: # AI_zx.start_zx(game,control) new_start.start_5_28(game, control, strategy) except Exception as e: log.log("start:") log.log(e) control.send_msg(sock) game.round_clear() elif msg_name == "leg_start": game.leg_start() elif msg_name == MSG_NAME_LEG_END: print(game.data["msg_data"]) game.leg_clear() elif msg_name == MSG_NAME_GAME_OVER: print("Game Over ...") break
def collectData(db): global lock if db.connect(): try: Control.getSettings (db)#Control sistema calefaccio records=db.select("SELECT ipv6,thingToken FROM motes where type=0 and thingToken IS NOT NULL and thingToken !=''") lowTemp=False#Control sistema calefaccio for row in records: try: ipv6=str(row[0]) temp =ObjectCoAP.sendGET(ipv6,'temp' ) if temp is not None: tempValue = ConvertValue.getTemperature(temp) if not lowTemp: #Control sistema calefaccio lowTemp = Control.checkTemp(tempValue) #Control sistema calefaccio hum =ObjectCoAP.sendGET(ipv6,'hum' ) if hum is not None: humValue=ConvertValue.getHumidity(hum) if (tempValue or humValue) is not None: send=SendDataToServer(lock,tempValue,humValue,ipv6,str(row[1]))#Emmagatzematge a thethings.iO send.start()#Emmagatzematge a thethings.iO except: Log.writeError( "No hi ha comunicacio amb la mota "+ ipv6) pass Control.checkAction(lowTemp)#Control sistema calefaccio except: pass db.close()
class Interface: def __init__(self, robothost, robotport): self.ctr = Control(self.__class__.__name__) self.robot = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: self.robot.connect((robothost, robotport)) except socket.error: print "NO CONNECTION TO THE ROBOT, WTF ARE YOU DOING!" sleep(5) continue break self.mainloop() exit(0) def mainloop(self): #Spawn Bro-bot self.robot.send(ROBOT_COMMAND) while True: recv = self.ctr.receive(True) if recv: src, data = recv if src == 'main' and data == 'STOP': break self.robot.send(data) ready, _, _ = select(list(self.robot),(),(), 0.05) for x in ready: data = x.recv(1024) self.ctr.send('Sensors', data)
def createHipShoudersControls(drvStart, drvEnd, jntList): pymelLogger.debug('Starting: createHipShoudersControls()...') # Get drvStart Position drvS_pos = pm.xform(drvStart[0], query=True, translation=True) # Get drvEnd Position drvE_pos = pm.xform(drvEnd[0], query=True, translation=True) # Create Hip Control ctrl = jntList[0] + '_' + Names.suffixes['control'] rot = pm.xform(drvStart[0], q=1, ws=1, ro=1) rot = [-90, 0, 90] hips_cnt = Control.create(name=ctrl, offsets=2, shape='cube', size=[1, 1, 1], color='cyan', pos=drvS_pos, rot=rot, parent=None, typ='body') # Create Shoulder Ctrl #shoulder_cnt = Control.create() ######## fix this !!! top spine ctrl shoud b called SpineX_ctrl ctrl = jntList[-1] + '_' + Names.suffixes['control'] rot = pm.xform(jntList[-1], ws=1, q=1, ro=1) shoulder_cnt = Control.create(name=ctrl, offsets=2, shape='circle_01', size=2, color='red', pos=drvE_pos, rot=rot, parent=None, typ='body') # Connect CC to Drv Jnts pm.parentConstraint(hips_cnt.listRelatives(ad=1)[0].getParent(), drvStart, maintainOffset=True) pm.parentConstraint(shoulder_cnt.listRelatives(ad=1)[0].getParent(), drvEnd, maintainOffset=True) # Clean Ctrls Attributes (Lock and Hide Scale and Visibility) hideLockAttr(hips_cnt, lockHideSV) hideLockAttr(shoulder_cnt, lockHideSV) hideLockAttr(drvStart[0], lockHideS) hideLockAttr(drvEnd[0], lockHideS) rList = [hips_cnt, shoulder_cnt] pymelLogger.debug('End: createHipShoudersControls()...') return rList
class ControlTestCase(unittest.TestCase): def setUp(self): self.prefix = "ControlTeam: Control: " self.con = Control() self.om = self.con.getObsManager() def tearDown(self): self.con.close()
def get_response(user_input): global database, resource, turn_id, time, wizard, socket global TemplateLib, TopicLib, TreeState, Template, connection, filepointer,engaged_input, topic_id filepointer.write('turn_id: ' + str(turn_id) + '\n') turn_id = turn_id+1 filepointer.write('time:' + str(datetime.datetime.now())+ '\n') filepointer.write('user_input:' + user_input + '\n') relavance, answer = Control.FindCandidate(database, resource, user_input) filepointer.write('relevance: ' + str(relavance)+ '\n') filepointer.write('RetrievedAnswer: ' + str(answer) + '\n') #connection.send('input engagement') #global connection, address #Log('before get response') if wizard is 1: if connection is None: #Log('I asm here') serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Log('serversocket') serversocket.bind(('localhost', 13011)) serversocket.listen(5) connection, address = serversocket.accept() print 'connection established' print connection connection.send('ready') engagement = connection.recv(64) #engagement = raw_input('What is the engagement state of the user of this turn?, score 1-5. ') #engagement = 2 elif wizard is 2: # this is taking the automatic engagement computed as the engagement input print 'Sending request' socket.send("ready\0") engagement = socket.recv() #print engagement #print("Received reply [ %s ]" % message) else:# this is random generating engagement for testing. engagement = random.choice('12345') print engagement filepointer.write('engagement: ' + engagement + '\n') if int(engagement)>3: engaged_input.append(user_input) state = Control.SelectState(relavance, int(engagement), TreeState,engaged_input) filepointer.write('State:' + str(state['name']) + '\n') Log('DM STATE is [ %s ]' %(state)) print 'state:', state['name'] print "candidate answer ", answer #relavance, unicodedata.normalize('NFKD',answer).encode('ascii','ignore')#answer #make an exception to back_state. output,topic_id, engagement_input = NLG.FillTemplate(TemplateLib, TopicLib, Template[state['name']],topic_id, engaged_input, answer) if isinstance(output, unicode): output = unicodedata.normalize('NFKD',output).encode('ascii','ignore') Log('OUTPUT is [ %s ]' %(output)) filepointer.write('TickTockResponse:' + output + '\n') print "end response generation ==================" filepointer.flush() #fileout = open('input_response_history.txt', 'a') #fileout.write(str(user_input) + '\n') #fileout.write(str(output) + '\n') #fileout.close() return output
def __init__(self): self.tcp_flag = False self.led = Led() self.adc = ADS7830() self.servo = Servo() self.buzzer = Buzzer() self.control = Control() self.sonic = Ultrasonic() self.control.Thread_conditiona.start()
def createBlueprinter( name, args ): 'Creates a default blueprinters' ret = {} sctl = [] jnt = "" functArgs = {"shape":"cube", "size":1, "t":0, "r":0, "s":0} functArgs = dict(functArgs.items() + args.items()) #create Control if(functArgs["shape"] == "cube"): sctl = Control.cubeCtl( name, functArgs ) elif(functArgs["shape"] == "sphere"): sctl = Control.sphereCtl( name, functArgs ) elif(functArgs["shape"] == "arrow"): sctl = Control.arrowCtl( name , functArgs ) elif(functArgs["shape"] == "locator"): sctl = Control.locatorCtl( name , functArgs ) else: print "Shape not supported...\n" return 0 #lock hide unwanted Attribute if functArgs["t"] == 1: Attribute.lockHide(sctl[0], {"t":1, "h":1, "l":1}) if functArgs["r"] == 1: Attribute.lockHide(sctl[0], {"r":1, "h":1, "l":1}) if functArgs["s"] == 1: Attribute.lockHide(sctl[0], {"s":1, "h":1, "l":1}) #add blueprinter joint jnt = cmds.joint( n = ( name + "_SJNT" ), p= (0, 0, 0 ) ) Constraint.constrain(sctl[0], jnt, args={ "t":1, "mo":0, "name":(name)} ) #matrixConstraint(sctl[0] , jnt, 0, {}) #template(jnt) #parent to root cmds.parent(jnt,sctl[0]) #cmds.parent(ret["sctl"][1],rootGrp) #rename suffix newName = sctl[0].replace("_CTL","_SCTL") cmds.rename(sctl[0],newName) sctl[0] = newName newName = sctl[1].replace("Ctl_GRP","Sctl_GRP") cmds.rename(sctl[1],newName) sctl[1] = newName #create blueprinter variable """for blueprinter in sctl: storeString(blueprinter, "blueprinter", "") storeString(jnt, "sjoint", "")""" ret["sctl"] = sctl ret["jnt"] = jnt return ret
def f(): Control.go(canvas, dx, dy) window.after(50, lambda: f()) if canvas.coords('box')[3] == 610: canvas.create_rectangle(r * random.randint(0, 19) + 100, r * 1 + 100, r * random.randint(0, 19) + r + 100, r * 1 + r + 100, fill='yellow', tag='box')
def __init__(self, name): self.name = name # init control as it is independent of the state of planning while interacting and needed to build behaviors self.control = Control() self.planning = None self.defaultSocialProfile = SocialProfile("Default", ComposedBehavior(self.control, []), 30.0, []) self.defaultCreativityProfile = CreativityProfile("Default", 5, {}, StoryArcBehaviorType.MIRROR, 5.0, {}, StoryArcBehaviorType.MIRROR, 5.0, {}, StoryArcBehaviorType.MIRROR) self.defaultGeneralProfile = self.generateGeneralProfile("Default", Color(rgb=(0.1 ,0.1 ,0.1)), 1.0)
def LogicAnalyzer(): controler = Control() Infodoc.addWidget(controler) global probes probes = controler.getProbes() #Add plot Widgets to Docks probe1.addWidget(probes[0]) probe2.addWidget(probes[1]) probe3.addWidget(probes[2]) probe4.addWidget(probes[3])
def __init__(self): self.reg = Registers() self.ram = numpy.zeros((128), numpy.uint8) CtrlA = Control.Dummy() CtrlB = Control.Dummy() self.tia = TIA.TIA(self.clock, CtrlA, CtrlB) self.riot = RIOT.RIOT(CtrlA, CtrlB) self.cart = None self.clocks = 0 self.execute = self.stepFrame self.step = self.stepNoDump
def start_round(sock, team_id): game = Game(sock, team_id) game.register() with open("log.txt", "a+") as f: f.write("success register") while True: game.receive_msg() msg_name = game.get_msg_name() if msg_name == "round": game.round_start() control = Control(team_id, game.our_tank_id, game.maps, game.data) # 操作函数 for tank_id in game.our_tank_id: control.move(tank_id, "up") control.fire(tank_id, "up", 0) control.send_msg(sock) game.round_clear() elif msg_name == "leg_start": game.leg_start() elif msg_name == MSG_NAME_LEG_END: print(game.data["msg_data"]) game.leg_clear() elif msg_name == MSG_NAME_GAME_OVER: print("Game Over ...") break
def get_response(user_input): global database, resource global TemplateLib, TopicLib, TreeState, Template relavance, answer = Control.FindCandidate(database, resource, user_input) state = Control.SelectState(relavance, TreeState) Log('DM STATE is [ %s ]' %(state)) print 'state:', state['name'] print "candidate answer ", relavance, answer output = NLG.FillTemplate(TemplateLib, TopicLib, Template[state['name']], answer) Log('OUTPUT is [ %s ]' %(output)) fileout = open('input_response_history.txt', 'a') fileout.write(str(user_input) + '\n') fileout.write(str(output) + '\n') fileout.close() return output
def start(select): if select != (): keylist = [] stack = [] row = DBHelper.load(select[0] + 1) for k in range(18): keylist.append(row[k + 2]) stack.append(0) stack.append(0.0) #keylist에는 없고 stack에만 존재. 마우스의 x와y값. stack.append(0.0) stack[15] = keylist[15] #mouse sensitivy Control.control(keylist, stack)
def main(): pygame.init() pygame.display.set_caption(settings.GAME_NAME) hero = HeroPlane.HeroPlane( 240, 550, settings.screen) # import module 与 from module import 的区别, 前者调用要先加模块名 enemy = Enemy.Enemy(settings.screen) while True: settings.screen.blit(settings.bg, (0., 0.)) hero.display() enemy.display() pygame.display.update() Control.key_control(hero)
def loadPoseFile(fileName): poses = {} #should use the g.pandaPath ? -Michael reed s10 file = findCSV(fileName) if file is not None: fileLoader = open(file, "r") contents = fileLoader.read().split("\n") for line in contents[1:]: data = line.split(",") if len(data) >= 5: poseName = data[0].strip() jointName = data[1].strip() jointHpr = SHPR(float(data[2].lstrip("(")), float(data[3]), float(data[4].rstrip(")"))) if not poses.has_key(poseName): poses[poseName] = {} poses[poseName][jointName] = jointHpr fileLoader.close() result = {} for pose, dict in poses.iteritems(): result[pose] = Control(dict) return result print "File " + fileName + " not found." exit()
def _makeEnv(self): ''' Generate a dictionary of the environment variables after applying all the required actions. ''' # prepare the environment control instance control = Control.Environment() if not self.opts.ignore_environment: control.presetFromSystem() # apply all the actions for action, args in self.opts.actions: apply(getattr(control, action), args) # extract the result env dictionary env = control.vars() # set the library search path correctly for the non-Linux platforms if "LD_LIBRARY_PATH" in env: # replace LD_LIBRARY_PATH with the corresponding one on other systems if sys.platform.startswith("win"): other = "PATH" elif sys.platform.startswith("darwin"): other = "DYLD_LIBRARY_PATH" else: other = None if other: if other in env: env[other] = env[other] + os.pathsep + env[ "LD_LIBRARY_PATH"] else: env[other] = env["LD_LIBRARY_PATH"] del env["LD_LIBRARY_PATH"] self.env = env
def screen(self): self.window.title("TextToMorse") self.window.configure(background='lightslategray') self.window.geometry('400x400') self.window.resizable(True, True) self.window.maxsize(width=900, height=900) self.window.minsize(width=200, height=200) self.fileMenu.add_command(label="Historico", \ command=ctrl.ControlScreens().showHistoricoMorse) self.fileMenu.add_command(label="Lista dos codigos", \ command=ctrl.ControlScreens().showCodesMorse) self.menubar.add_cascade(label="File", \ menu=self.fileMenu) self.window.config(menu=self.menubar)
def _makeFkControls(fkControls=None, side=None): pymelLogger.debug('Starting: _makeControls()...') topNodeList = [] for ctrl in fkControls: parent = ctrl.replace('_'+Names.suffixes['fk']+'_'+Names.suffixes['control'],'') topNode = Control.create( name=ctrl, offsets=3, shape='circle_01', size=1.5, color=_getSideColor(side), pos=None, parent=parent, typ='body' ) pm.parent(topNode, world=1) topNodeList.append(topNode) # getting ctrl and contrainting it directly to the jnt childs = topNode.listRelatives(ad=1) if 'Shape' in str(childs[0]): cc = childs[1] else: cc = childs[0] pm.parentConstraint(cc,parent, mo=1) # parent each offset to the previous ctrl topNodeList.reverse() last = '' for element in topNodeList: if last: last.setParent(element.listRelatives(ad=1)[1]) # getting transform node not shape last = element topOffsetNode = last return topOffsetNode pymelLogger.debug('End: _makeControls()...')
def createOriginalViewer(imagesDirectory,htmlPath,Reducer,QLSA): try: os.mkdir(imagesDirectory) except: print "Error Creating folder" # he maximum in the swimmer matrix is 39 return Control.imageOriginalViewGenerator(39.0,imagesDirectory,htmlPath,32,True,QLSA)
def InitResource(version): global database, resource, socket, listflie, tfidfmodel, tfidfdict, table_state_strategy if version is 'v1': listfile = 'cnn_qa_human_response_name.list' if version is 'v2': listfile = 'cnn_qa_human_response_name_high_app.list' if version is 'v2.5': listfile = 'cnn_qa_human_response_name_high_app.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') if version is 'v3': listfile = 'cnn_hr_v1_v2.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') if version is 'v4': listfile = 'cnn_hr_v1_v2_v4.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') datalist = [line.strip() for line in open(listfile)] database = Loader.LoadDataPair(datalist) resource = Loader.LoadLanguageResource() global TemplateLib, TopicLib, TreeState, Template, model TemplateLib = Loader.LoadTemplate(template_list) TopicLib = Loader.LoadTopic(topicfile) TreeState, Template = Control.Init() model = models.Doc2Vec.load('/tmp/word2vec_50') if wizard is 2: context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") with open('table_state_strategy.pkl') as f: table_state_strategy = pickle.load(f)
def __init__(self): self.ctrl = Control(self.__class__.__name__) self.TRESHOLD_S = 0.4 self.TRESHOLD_L = 0.25 self.RECOVERTIME = 3 self.running = True self.run()
def __init__(self, filepath, control = None, encoding = 'utf-8'): if control == None: control = Control.control() self.control = control self.filepath = filepath with codecs.open(filepath, 'r', encoding) as f: self.lines = self._genlines(f.read())
def createOriginalViewer(imagesDirectory,htmlPath,Reducer): try: os.mkdir(imagesDirectory) except: print "Error Creating folder" # he maximum in the swimmer matrix is 39 return Control.imageOriginalViewGenerator(Reducer.reduction.data.max(),imagesDirectory,htmlPath,241)
def initControl(): ''' Initialize our controller with the qube job. ''' control = Control.Control(qb.jobobj()) return control
def clusterizeCurve(curve): curveNumber = getCurveCVNumber(curve) curveName = String.removeSuffix(curve) clusterName = (curveName + "Cluster") clusterList = [] for x in range(curveNumber): clusterList.append( Control.createCluster( ( clusterName + str(x) ), ( curve + ".cv["+ str(x) +"]" ) ) ) return clusterList
def Upload(frame,access_token,group_id_list): global faceUploadbit #获取全局变量faceUploadbit global faceflag #获取全局变量faceflag if (!faceUploadbit): #判断上传位是否为0 img=f.open_picture() #读取照片并编码为base64 output=f.FaceSearch (img,access_token,group_id_list) #开始匹配并将反馈信息赋值给output flag=f.ReadData(output,70) #处理反馈信息并获取是否识别成功标志,相似度判断值默认70 if (flag): #判断标志是否为1 c.Open(pin) #打开GPIO为pin值的口 time.sleep(0.5) #延时0.5秒 c.Stop(pin) #关闭GPIO为pin值的口 return 2 #返回值为2 else: cv2.putText(frame,"Open GPIO Failed!", ( 10, 10 ), cv2.FONT_HERSHEY_SIMPLEX, 0.3, ( 0, 0, 255 ), 1 ) #界面上方输出GPIO打开失败 return 1 #返回值为1 else: return 0 #返回值为0
def control(): # 1 2 className = index('start.jpg') if className == 'One': control = Control.Order() control.run('打开微信') if className == 'Five': screen()
def createRepresentationViewer(imagesDirectory, htmlPath, Reducer, h): try: os.mkdir(imagesDirectory) except: print "Error Creating folder" return Control.imageScaledViewGenerator( Reducer.reduction.objectsM.max(), Reducer.reduction.objectsM.min(), imagesDirectory, htmlPath, h, 10 )
def createBasisViewer(basisDirectory, htmlPath, Reducer, QLSA): try: os.mkdir(basisDirectory) except: print "Error Creating folder" return Control.imageViewGenerator( Reducer.reduction.basisM.max(), Reducer.reduction.basisM.min(), basisDirectory, htmlPath, 19, True, QLSA )
def main(argv): parser = argparse.ArgumentParser(description='RoboRinth Robot Explorer') parser.add_argument('--host', type=str, help='host of the mqtt broker to connect', default="192.168.0.200") parser.add_argument('--port', type=int, default=1883, help='port of the mqtt broker to connect') parser.add_argument('--roboName', type=str, default="robo-01", help='Robot MQTT topic/name to connect') parser.add_argument('--clientId', type=str, default="", help='MQTT client connection id') parser.add_argument( '--log', type=str, choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], default="INFO", help='Loglevel ') args = parser.parse_args() _initializeLogging(args.log) logger.debug("Main started") # Setup mqtt client client = MqttClient(args.host, args.port, args.clientId) client.startAsync() time.sleep(2) # Test code for MapMatcher roboName = args.roboName roboDriver = RoboDriver(roboName) client.subscribeTopics(roboName + '/notification/#') client.addMessageHandler(roboDriver.getMqttHandlerList()) roboDriver.setMqttClient(client) mapMatcher = MapMatcher() mapMatcher.registerRobotDriver(roboName, roboDriver) robots = {} robots[roboName] = Control(roboName, mapMatcher, roboDriver) robots[roboName].start() # End test code input("\n\nPress Enter to abort...\n\n") # Terminate client.stop() logger.debug("Terminate")
def __init__(self): #Game on board self.Game = Model.ChessGame(Control.initialBoard()) #set up grab issue self.isGrabbedOne = False #load picture self.bgImage = Image.open('newBoard.png') #open up an window self.window = tk.Tk() #New Game self.newGameButton = tk.Button(master = self.window, text = '开启新的棋局(Start a New Game)', font = ('Helvetica',20),command = self.startNewGame) self.newGameButton.grid(row = 0, column = 0,sticky = tk.N + tk.S + tk.E + tk.W) #Quit Button self.quitButton = tk.Button(master = self.window, text = '退出(Quit)', font = ('Helvetica',20),command = self.quitGame) self.quitButton.grid(row = 1, column = 0,sticky = tk.N + tk.S + tk.E + tk.W) #Game Type self.gameLable = tk.Label(master = self.window, text = '中国象棋(Chinese Chess)', font = ('Helvetica',20)) self.gameLable.grid(row = 2, column = 0,sticky = tk.W) #Turn Label self.turnLabel = tk.Label(master = self.window, text = f'玩家(Player): Red', font = ('Helvetica',20)) self.turnLabel.grid(row = 3, column = 0, sticky = tk.W) #Show Winner Label self.winnerLabel = tk.Label(master = self.window, text = '胜者(Winner): Have Not Been Decided Yet', font = ('Helvetica',20)) self.winnerLabel.grid(row = 4, column = 0, sticky = tk.W) #create canvas self.canvas = tk.Canvas(self.window,width = 670,height = 670, highlightthickness=0) self.canvas.grid(row=5,padx = 15, pady = 15, sticky=tk.W+tk.E+tk.N+tk.S) #stretch the game board self.window.rowconfigure(5, weight = 1) self.window.columnconfigure(0, weight = 1) #widght to resize window self.window.bind("<Configure>", self.resizeHandler) #widght to click on canvas self.canvas.bind('<Button-1>',self.clickedHandler)
def InitResource(): global database, resource datalist = [line.strip() for line in open(listfile)] database = Loader.LoadDataPair(datalist) resource = Loader.LoadLanguageResource() global TemplateLib, TopicLib, TreeState, Template TemplateLib = Loader.LoadTemplate(template_list) TopicLib = Loader.LoadTopic(topicfile) TreeState, Template = Control.Init()
def __init__(self): self.ctrl = Control(self.__class__.__name__) self.gridSize = 1.0 self.treshold_l = 0.4 self.treshold_s = 0.25 self.sonar = "" self.laser = "" self.running = True self.drive(0)
def get_response(user_input): global database, resource global TemplateLib, TopicLib, TreeState, Template engagement = sys.stdin relavance, answer = Control.FindCandidate(database, resource, user_input) state = Control.SelectState(relavance, engagement, TreeState) Log('DM STATE is [ %s ]' % (state)) print 'state:', state['name'] print "candidate answer ", relavance, answer output = NLG.FillTemplate(TemplateLib, TopicLib, Template[state['name']], answer) #output2 = unicodedata.normalize('NFKD',output).encode('ascii','ignore') Log('OUTPUT is [ %s ]' % (output)) #fileout = open('input_response_history.txt', 'a') #fileout.write(str(user_input) + '\n') #fileout.write(str(output) + '\n') #fileout.close() return output
def createHipShoudersControls( drvStart, drvEnd, jntList ): pymelLogger.debug('Starting: createHipShoudersControls()...') # Get drvStart Position drvS_pos = pm.xform(drvStart[0], query = True, translation = True) # Get drvEnd Position drvE_pos = pm.xform(drvEnd[0], query = True, translation = True) # Create Hip Control ctrl = jntList[0] + '_' + Names.suffixes['control'] rot = pm.xform(drvStart[0],q=1,ws=1,ro=1) rot = [-90,0,90] hips_cnt = Control.create( name= ctrl , offsets=2, shape='cube', size=[1,1,1], color='cyan', pos=drvS_pos, rot=rot, parent=None, typ='body' ) # Create Shoulder Ctrl #shoulder_cnt = Control.create() ######## fix this !!! top spine ctrl shoud b called SpineX_ctrl ctrl = jntList[-1]+ '_' + Names.suffixes['control'] rot = pm.xform(jntList[-1],ws=1,q=1,ro=1) shoulder_cnt = Control.create( name=ctrl, offsets=2, shape='circle_01', size=2, color='red', pos=drvE_pos,rot=rot, parent=None, typ='body' ) # Connect CC to Drv Jnts pm.parentConstraint(hips_cnt.listRelatives(ad=1)[0].getParent(), drvStart, maintainOffset = True) pm.parentConstraint(shoulder_cnt.listRelatives(ad=1)[0].getParent(), drvEnd, maintainOffset = True) # Clean Ctrls Attributes (Lock and Hide Scale and Visibility) hideLockAttr(hips_cnt, lockHideSV) hideLockAttr(shoulder_cnt, lockHideSV) hideLockAttr(drvStart[0], lockHideS) hideLockAttr(drvEnd[0], lockHideS) rList = [hips_cnt, shoulder_cnt] pymelLogger.debug('End: createHipShoudersControls()...') return rList
def InitResource(version): global TemplateLib, TopicLib, TreeState, Template, model, init_id, joke_id, more_id, dictionary_value, turn_id, wizard, isAlltag, engaged_input, engagement_mode global q_table, database, resource, socket, listflie, tfidfmodel, tfidfdict, table_state_strategy database = {} resource = {} listfile = None init_id = 0 joke_id = 0 more_id = 0 wizard = 3 isAlltag = 0 turn_id = 0 engaged_input = [] engagement_mode = 0 rescource_root = 'resource' template_list = [ 'template/template_new.txt', 'template/template_end.txt', 'template/template_open.txt', 'template/template_expand.txt', 'template/template_init.txt', 'template/template_joke.txt', 'template/template_back.txt', 'template/template_more.txt' ] template_list = [path.join(rescource_root, name) for name in template_list] topicfile = path.join(rescource_root, 'topic.txt') tfidfname = 'tfidf_reference' with open('dictionary_value.pkl') as f: dictionary_value = pickle.load(f) if version is 'v1': listfile = 'cnn_qa_human_response_name.list' elif version is 'v2': listfile = 'cnn_qa_human_response_name_high_app.list' elif version is 'v2.5': listfile = 'cnn_qa_human_response_name_high_app.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') elif version is 'v3': listfile = 'cnn_hr_v1_v2.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') elif version is 'v4': listfile = 'cnn_hr_v1_v2_v4.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') datalist = [line.strip() for line in open(listfile)] q_table = pickle.load(open('q_table.pkl')) database = Loader.LoadDataPair(datalist) resource = Loader.LoadLanguageResource() TemplateLib = Loader.LoadTemplate(template_list) TopicLib = Loader.LoadTopic(topicfile) TreeState, Template = Control.Init() model = models.Doc2Vec.load('/tmp/word2vec_50') if wizard is 2: context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") with open('table_state_strategy.pkl') as f: table_state_strategy = pickle.load(f)
class Main: m_Download_Data = Download_Data() m_Fromat_Data = Fromat_Data() m_Control = Control() m_Save_Biodata = Save_Biodata() m_show = show()
def clickedHandler(self,event): ''' click on canvas ''' width = self.canvas.winfo_width() height = self.canvas.winfo_height() turn = self.Game.returnTurn() player = lambda turn: 'Black' if turn%2 != 0 else 'Red' if not self.isGrabbedOne: if Control.grabChess(event,self.Game,player(turn),width,height,None): self.isGrabbedOne = True else: if Control.giveUpGrab(event,self.Game,player(turn),width,height,None): self.isGrabbedOne = False self.redrawAll()
def __init__(self): self.ctrl = Control(self.__class__.__name__) self.data = "" self.sensors = {"LASER" : "", # "SENS LASER" "ODOMETRY" : "", # "SENS ODOMETRY <float x> <float y> <float z>" "SONAR" : ""} # "SENS SONAR <float F1> <float F2> <float F3> <float F4> <float F5> <float F6> <float F7> <float F8>" self.running = True self.receive()
def setup(): ############################################################################### #import Data import Prediction import warnings import Control warnings.filterwarnings("ignore") Prediction_horizon = 60 # in minutes #Data.data_acquisition() DATA_LIST={} wb = openpyxl.load_workbook('DATA_LIST.xlsx') sheet = wb.get_sheet_by_name('Sheet1') for key in range(1, sheet.max_column+1): DATA_LIST[sheet.cell(row=1, column=key).value]=[] for v in range(2, sheet.max_row+1): DATA_LIST[sheet.cell(row=1, column=key).value].append(sheet.cell(row=v, column=key).value) # Model generation #SVR_model = Prediction.Support_Vector_Regression(DATA_LIST, Prediction_horizon) KNN_model = Prediction.kNN_Regression(DATA_LIST, Prediction_horizon) BRR_model = Prediction.Bayesian_Ridge_Regression(DATA_LIST, Prediction_horizon) # workbook = xlsxwriter.Workbook(os.path.dirname(os.path.abspath(__file__))+'\Control.xlsx') # workbook.add_worksheet() # workbook.close() alpha = 0.7 # Higher alpha means slower adaptation T_history={} try: for i in range(1,8): T_history[str(i)] = Control.max_T_history(Control.previous_date(i)) Mean_Running_Average = (1.0 - alpha) * sum( (alpha** (i-1) ) * int(T_history [str(i)]) for i in range(1,8) ) except Exception: Mean_Running_Average = 20 return DATA_LIST, KNN_model, BRR_model, Mean_Running_Average
def run(): english1 = input( "First Period: English" "\nYou open your schoolbag and grab the assigned reading. Will you..." "\n1.Read alone like a scrub" "\n2.Ask Edward to read with you\n") # Path 1 if english1 == "1": print( "\nYou decide to read by yourself. Its lonely, but you do get all your work done ahead of time.\n" ) english2 = input( "Glancing about the room, you notice Edward's supreme intellect has allowed him to finish early as well." "\nYou lingers on his form for too long, he looks up and meets your eyes!" "\n1.ABORT! ABORT! LOOK AWAY!" "\n2.Steel your resolve and give him a wave" "\n3.Bask unashamed in the glorious gaze of his dark chestnut brown eyes." ) if english2 == "1": print( "The shame of being caught hangs over you. You keep your head down and don't look up again until" "the bell rings. ") if english2 == "2": print("Not Finished") # edward waves back, small lp, leads to a conversation in the hallway if english2 == "3": print( "You stare longingly into Edward's eyes. Hoping that your deepest affections can be broadcast" "through this moment your sharing together." "\nInstead, Edward makes a face and looks away. Stupid! You lost track of time swimming in his" "chocolate fondue eyes and stared for way too long.") c.lp_down(1) # edward thinks its awkward # Path 2 elif english1 == "2": if c.LP > 30: print("Some mushy line about Edward :P") # Add more conversation options about reading with edward else: print("Edward rejects") c.lp_down(1) print("TESTING LovePoints: " + str(c.LP))
def __init__(self, dimension, master=None): Frame.__init__(self, master) self.master.title('Tediumrobo') self.pack() self.create_label(master) self.control = Control.Control(dimension) self.my_label = Label() self.my_label.pack() self.contents = StringVar() self.contents.set(self.control.refresh()) self.my_label["textvariable"] = self.contents
class Alert: #Initialises control class, and tresholds def __init__(self): self.ctrl = Control(self.__class__.__name__) self.TRESHOLD_S = 0.4 self.TRESHOLD_L = 0.25 self.RECOVERTIME = 3 self.running = True self.run() # Alternate between checkin Laser and Sonar distance def run(self): while self.running: self.check("LASER", self.TRESHOLD_L) self.check("SONAR", self.TRESHOLD_S) # Get sensor values, compare each to treshold, send out ALERT if below def check(self, sensor, treshold): data = "" self.ctrl.send("Sensors", "GET " + sensor) while not data[:5] == sensor: data = self.ctrl.receive() if data == None: break else: src, data = data if src == "main" and data == "STOP": self.running = False exit() vals = data[6:].split(' ') # Send out alert & sleep when on collision course for it in vals: if it < treshold: send("Steering", "ALERT") send("Logic", "ALERT") sleep(self.RECOVERTIME) continue
def __init__(self, robothost, robotport): self.ctr = Control(self.__class__.__name__) self.robot = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: self.robot.connect((robothost, robotport)) except socket.error: print "NO CONNECTION TO THE ROBOT, WTF ARE YOU DOING!" sleep(5) continue break self.mainloop() exit(0)
def TestFileLoading(): """ Routine to test the loading of the file #TODO: Make it fail by not finding the file #TODO: Make it fail by having corrupt data """ acr = Control.iCOG() oput = acr.SetAcroymnData() #TODO: Validate the response from the function print ("Response from function %s" %oput) return
def createReconstructionViewer(imagesDirectory, htmlPath, Reducer, QLSA): try: os.mkdir(imagesDirectory) except: print "Error Creating folder" return Control.imageViewGenerator( Reducer.reduction.reconstructed.max(), Reducer.reduction.reconstructed.min(), imagesDirectory, htmlPath, 19, True, QLSA, )
def _makeControls(): pymelLogger.debug('Starting: _makeControls()...') # Neck parent = 'head_controls' ctrl= Names.controls_neck[0] pos = pm.xform('Neck',ws=1,q=1,rp=1) rot = pm.xform('Neck',ws=1,q=1,ro=1) s = [['head_body_attach_space','head_world_space'],['local','world'],'orient'] Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, rot=rot, color=None, switch=s, pos=pos, parent=parent, typ='head' ) # Neck1 parent = Names.controls_neck[0] ctrl= Names.controls_neck[1] pos = pm.xform('Neck1',ws=1,q=1,rp=1) rot = pm.xform('Neck1',ws=1,q=1,ro=1) Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, rot=rot, color=None, pos=pos, parent=parent, typ='head' ) pymelLogger.debug('End: _makeControls()...')
def _makeIkControls(ikControls=None): pymelLogger.debug('Starting: _makeIkControls()...') for ctrl in ikControls: if 'IK' in ctrl: if Names.prefixes['left'] in ctrl: parent = '%s%s'%(Names.prefixes['left'],Names.joints_arm[-1]) if Names.prefixes['right'] in ctrl: parent = '%s%s'%(Names.prefixes['right'],Names.joints_arm[-1]) topNode = Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, color=None, pos=None, parent=parent, typ='body' ) pm.parent(topNode, 'controls') if 'PV' in ctrl: pass pymelLogger.debug('End: _makeIkControls()...')
def bodyCtrlSetUp( fkJnts, hips_cnt, shoulder_cnt, drvStart ): pymelLogger.debug('Starting: bodyCtrlSetUp()...') # Body control pos = pm.xform(hips_cnt, q=1, ws=1,rp=1) body_cnt_offset = Control.create( name= Names.controls_torso_cog , offsets=1, shape='circle_2_arrow', size=[1,1,1], color='darkBlue', pos=pos, parent=None, typ='body' ) body_cnt = body_cnt_offset.listRelatives(ad=1)[0].getParent() # position and freeze #rootPos = pm.xform(drvStart[0], query = True, translation = True) #body_cnt.setTranslation(rootPos) #pm.makeIdentity(body_cnt, apply=True) # Change rotation order cc_body #setRotateOrder(body_cnt, 2) # Lock and Hide Scale - Vis hideLockAttr(body_cnt, lockHideSV) # Parent torso_baseJnt to cc_body (CAREFUL!!! If no FKControls created this will not work now!!!!) pm.parent(fkJnts[0], body_cnt) # Group cc_jc_hip and parent it to torso_baseJnt (We group it first to keep de cc zeroed out) grp_cc_hip = pm.group(hips_cnt, name= Names.torso_hips_grp ) pm.parent(grp_cc_hip, fkJnts[0]) # Group cc_jc_shoulder and parent it to torso_endJnt (We group it first to keep de cc zeroed out) grp_cc_shoulder = pm.group(shoulder_cnt, name=Names.torso_shoulders_grp ) pm.parent(grp_cc_shoulder, fkJnts[-1]) # Lock and Hide Attr groups created hideLockAttr(grp_cc_hip, lockHideTRSV) hideLockAttr(grp_cc_shoulder, lockHideTRSV) pymelLogger.debug('End: bodyCtrlSetUp()...') return body_cnt_offset
def build_body(): pymelLogger.debug('Starting: build_body()...') Torso.build() # legs CanidaeLeg.build(side = Names.prefixes['left']) CanidaeLeg.build(side = Names.prefixes['right']) # arms Arm.build(side = Names.prefixes['left']) Arm.build(side = Names.prefixes['right']) # Hands and fingers Hand.build( side = Names.prefixes['left'] ) Hand.build( side = Names.prefixes['right'] ) # main ctrl main_cnt_name = Names.joints_torso[0] + '_' + Names.suffixes['control'] main_cnt = Control.create( name=main_cnt_name, offsets=0, shape='circle_4_arrow', size=1, color='yellow', pos=None, parent=None, typ='body' ) pm.parent(main_cnt, 'controls') ###################### ###################### # hard coded! fix! consGrp = [Names.torso_module, Names.legs_module] for grp in consGrp: try: pm.parentConstraint( main_cnt, grp, mo=1 ) except: print 'Could not constraint: ' + main_cnt + ' to ' + grp # constraint main to reference_jnt pm.parentConstraint(main_cnt, Names.joints_torso[0], mo=1) ###################### ###################### pymelLogger.debug('End: build_body()...')
def build( side=None ): pymelLogger.debug('Starting: build()...') if side == None: raise Exception('Make sure side: %s is valid '%side) if side != Names.prefixes['left'] and side != Names.prefixes['right']: raise Exception('Make sure side: %s is valid '%side) # create hand jnt handJntList = _createHandJnt( side ) # [handJnt, handJntName] handJnt = handJntList[0] handJntSH = handJntList[1] # create hand switch ctrl = handJntSH + '_' + Names.suffixes['switch'] hand_switch_offset = Control.create( name= ctrl , offsets=1, shape='cube', size=[1,1,1], color=_getSideColor(side), pos=None, parent=handJnt, typ='body' ) hand_switch_offset.setParent( world=1 ) hand_switch = hand_switch_offset.getChildren()[0] # it will work only with one offset hideLockAttr(hand_switch, lockHideTRSV) # add switch attr pm.addAttr( hand_switch, longName= Names.switchIkFk, k=True, min=0, max=1 ) # parentConstraint switch offset to sh handJnt !!!! Make sure it will work pm.parentConstraint(handJntSH, hand_switch_offset, mo=True) # build fingers Finger.build( side=side, label='Fingers', control=hand_switch, parentJnt = handJnt, curl='Z',twist='X',spread='Y', fkNormal=(1.0, 0.0, 0.0), radius=0.3 ) # group switch and hand hand_grp = pm.group(hand_switch_offset,handJnt,name = handJntSH + '_' + Names.suffixes['group']) _cleanUp( hand_grp ) pymelLogger.debug('End: build()...')
def _makeControls(): ''' Make Head and Face controls, parented to Neck ''' pymelLogger.debug('Starting: _makeControls()...') # Head parent = Names.controls_neck[1] ctrl= Names.controls_head[0] pos = pm.xform('Head',ws=1,q=1,rp=1) rot = pm.xform('Head',ws=1,q=1,ro=1) s = [['head_head_ctrl_space','head_world_space'],['local','world'],'orient'] Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, color=None, switch=s, pos=pos, rot=rot, parent=parent, typ='head' ) # Face controls parent = 'head_controls' ctrl= Names.controls_face[0] pos = pm.xform('Head',ws=1,q=1,rp=1) pos[0] += 3 Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, color=None, pos=pos, parent=parent, typ='head' ) pos[0] += 1 for ctrl in Names.controls_face: if ctrl == Names.controls_face[0]: continue pos[1] += 1 parent = Names.controls_face[0] ctrl= ctrl Control.create( name=ctrl, offsets=3, shape='circle_01', size=None, color=None, pos=pos, parent=parent, typ='head' ) pymelLogger.debug('End: _makeControls()...')
def createFKControls( jntList ): pymelLogger.debug('Starting: createFKControls()...') # for now creating based on current spline and same number # will not be oriented to the joint but world (analyze this!!) listJnts = [] for jnt in jntList: pm.select(clear=1) newJnt = pm.duplicate(jnt,rr=True,po=True, name=jnt+'_'+Names.suffixes['fk'])[0] try: newJnt.setParent(world=1) except: pass listJnts.append(newJnt) listJnts.reverse() index = 0 for jnt in listJnts: if index+1 == len(listJnts): break jnt.setParent(listJnts[index+1]) index = index + 1 listJnts.reverse() # Create controls for the fk spines fkSpines = listJnts[1:-1] # parent shape to joint #cc_torso01 = jcControl.circleControl('cc_'+torso01) offsetList = [] for fkJnt in fkSpines: jPos = pm.xform(fkJnt, query = True, translation = True, ws=1) rot = pm.xform(fkJnt, query = True, ro = True, ws=1) cName = fkJnt.split('_')[0] + '_' + Names.suffixes['control'] #rot = pm.xform(fkJnt.replace( '_' + Names.suffixes['fk'], '' ),ws=1,q=1,ro=1) offsetGrp = Control.create( name=cName, offsets=2, shape='circle_01', size=1.8, color='yellow', pos=jPos, parent=None,rot=rot, typ='body' ) offsetList.append(offsetGrp) # parent constraint print offsetGrp.listRelatives(ad=1)[0].getParent() pm.parentConstraint( offsetGrp.listRelatives(ad=1)[0].getParent(), fkJnt, mo=1 ) # parent offset grps topGrp = offsetList[0] if not len(offsetList) == 0: # parent groups offsetList.reverse() last = '' for offsetgrp in offsetList: if last: last.setParent(offsetgrp.listRelatives(ad=1)[0].getParent()) last = offsetgrp # parent top to hips_fk jnt topGrp.setParent(listJnts[0]) # hide chain """ for fkjnt in fkJntList: pm.hide(fkjnt) """ pymelLogger.debug('End: createFKControls()...') return listJnts
from Control import * import time import BrickPi_thread el,er=Engine.Engine('A'),Engine.Engine('B') thread = BrickPi_thread.BrickPi_Thread([el,er]) thread.on() control = Control(el,er) for i in range(100): control.drive(1,1,0.1) time.sleep(0.1)
recImgP = join(path, "reconstructionImages") htmlPath = join(path, "objects") html = Control.HTMLObjectsView( Reducer, path, createOriginalViewer(origImgP, htmlPath, Reducer, QLSA), createRepresentationViewer(repImgP, htmlPath, Reducer, np.ceil(np.sqrt(r))), createReconstructionViewer(recImgP, htmlPath, Reducer, QLSA), ) html.generate() del html del Reducer I = "/home/jecamargom/tmp/datasets/faces" M, Docs = Control.imagesMatrix(I, 361) DocsP = [join(I, f) for f in Docs] print "[DEBUG] Max number in ORL faces matrix", M.max() print "[DEBUG] Matrix Dimensions : ", M.shape p = "/home/jecamargom/tmp/experiments/faces1" r = 50 # generateFactorization("QLSA",Control.QLSA,M,Docs,DocsP,p,r) generateFactorization("QLSA2", Control.QLSA2, M, Docs, DocsP, p, r, True) # generateFactorization("NMF",Control.NMF,M,Docs,DocsP,p,r) # generateFactorization("VQ",Control.VQ,M,Docs,DocsP,p,r) # generateFactorization("PCA",Control.PCA,M,Docs,DocsP,p,r) p = "/home/jecamargom/tmp/experiments/faces2" r = 25
def createOriginalViewer(imagesDirectory, htmlPath, Reducer, QLSA): try: os.mkdir(imagesDirectory) except: print "Error Creating folder" return Control.imageOriginalViewGenerator(255, imagesDirectory, htmlPath, 19, True, QLSA)