class DragonCorrectionDialog(): def __init__(self, heard): self.completed = False self.setup_XMLRPC_server() dlg = wx.TextEntryDialog(None, "Correct with...", caption="Correction Dialog", defaultValue=heard) dlg.ShowModal() self.correction = dlg.GetValue() self.completed = True # start server, tk main loop def start_server(): while not self.server_quit: self.server.handle_request() Timer(1, start_server).start() # backup plan in case for whatever reason Dragon doesn't shut it down: Timer(60, self.xmlrpc_kill).start() def setup_XMLRPC_server(self): self.server_quit = 0 self.server = SimpleXMLRPCServer(("127.0.0.1", LISTENING_PORT), allow_none=True) self.server.register_function(self.xmlrpc_get_message, "get_message") self.server.register_function(self.xmlrpc_kill, "kill") def xmlrpc_kill(self): self.server_quit = 1 os.kill(os.getpid(), signal.SIGTERM) def xmlrpc_get_message(self): print "get message called" if self.completed: Timer(1, self.xmlrpc_kill).start() return self.correction else: return None
class Network(object): def __init__(self, config,log): self.log = log xmlport = config.getValue("xmlport") xmlhost = config.getValue("xmlhost") udpport = config.getValue("udpport") udphost = config.getValue("udphost") self.xml = SimpleXMLRPCServer((xmlhost, xmlport)) self.udp = netServer(udphost,udpport,log) log.StartupMessage("* Attempting to start XML-RPC Server") self.udp.serve_forever() self.xmlThread = Thread( target = self.startXMLRPCServer ) self.xmlThread.setDaemon( True ) self.xmlThread.start() log.StartupMessage( " XML-RPC Server is up at port %d" % xmlport) def register_function(self,func,funcname): self.xml.register_function(func,funcname) self.udp.register_function(func,funcname) self.log.Notice("Registered funtion %s for network access" % funcname) def stopServices(self): self.udp.stopServer() self.udp.join() self.log.StartupMessage("* Attempting to stop XML-RPC Server") self.xml.server_close() #self.xmlThread.join() def startXMLRPCServer(self): self.xml.serve_forever()
def run(self): class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) #create a server server = SimpleXMLRPCServer(("localhost",8045),requestHandler = RequestHandler) server.register_introspection_functions() def transmit_orbited(channel, message): """ @param channel: The stomp channel to send to @param message: The message that needs to be transmitted """ self.orbited.send_data(channel, message) return "" server.register_function(transmit_orbited, 'transmit') server.serve_forever()
def __init__(self, password, hostname, port, server_list): self.password = password self.myUrl = "http://" + hostname + ":" + port self.server_list = server_list servers = self.update_server_list() if servers: for server in self.aug_network(servers[0]): self.aug_network(server) server = SimpleXMLRPCServer((hostname, int(port))) if not server.register_function(self.handle_request, "handle_request"): utils.srv(server)
def run(self): class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2', ) #create a server server = SimpleXMLRPCServer(("localhost", 8045), requestHandler=RequestHandler) server.register_introspection_functions() def transmit_orbited(channel, message): """ @param channel: The stomp channel to send to @param message: The message that needs to be transmitted """ self.orbited.send_data(channel, message) return "" server.register_function(transmit_orbited, 'transmit') server.serve_forever()
class ServerThread( threading.Thread ) : def __init__( self, case ) : self.case = case threading.Thread.__init__( self ) print "starting local Ophidian server..." self.ProblemServer = ophidian.ProblemServer() self.ProblemServer.RunDir = 'RunDir' # check the run directory for cached problems self.ProblemServer.InitProblemList() # load the first problem, if it exists, exit otherwise if self.ProblemServer.ProblemList.__contains__(case) : self.ProblemServer.ProblemList = [case] print "Loading CUBE data for problem " + case self.ProblemServer.LoadProblem( case ) print "Starting server..." self.server = SimpleXMLRPCServer(('127.0.0.1', 8000 )) self.server.register_function(self.ProblemServer.GetProblem) self.server.register_function(self.ProblemServer.GetBlock) self.server.register_function(self.ProblemServer.CheckInBlock) else : print "No problems found. Ophidian server shutting down." def run( self ) : print "Now serving problem " + self.ProblemServer.Problem.problemname self.server.serve_forever()
class RPCServer(Thread) : def __init__(self) : Thread.__init__(self) self.n = 0 self.uniqueRequests = [] self.numDoneSent = 0 self.server = SimpleXMLRPCServer(("0.0.0.0", port)) self.server.register_function(self.nextInput, "nextInput") self.lock = Lock() def nextInput(self, ip) : self.lock.acquire() if self.uniqueRequests.count(ip) == 0 : self.uniqueRequests.append(ip) if self.n >= len(input_files) : self.numDoneSent += 1 if self.numDoneSent >= len(self.uniqueRequests) : shutdown(1) self.lock.release() return -1 rtn = self.n self.n += 1 self.lock.release() return rtn def run(self) : self.server.serve_forever()
def __init__(self, protocol, address, port, decks, total, packsize): SyncEntity.__init__(self, decks, total, packsize) self.address = address self.port = port self.protocol = protocol if protocol == 'xml-rpc': from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer((address, port), allow_none=True) elif protocol == 'json-rpc': #from SimpleJsonRPCServer import SimpleJSONRPCServer as Server server = SimpleJSONRPCServer((address, port)) else: raise RuntimeException("Unknown RPC protocol: %s" % protocol) server.register_function(self.applyPayload) server.register_function(self.append) server.register_function(self.__contains__) self.server = server
def ping(): return 1 def list_functions(): global modules return modules def terminate(): global quit quit = 1 return 1 server.register_function(list_functions, "list_functions") server.register_function(terminate, "terminate") if SCRIPTS_PATH not in sys.path: sys.path.append(SCRIPTS_PATH) for s in [x[0] for x in os.walk(SCRIPTS_PATH)]: if s.endswith(".sikuli") and not s.endswith("xmlrpc_server.sikuli"): mdl_name = s.split(".")[0].split("\\")[-1] exec("import " + mdl_name) exec("l = getmembers(" + mdl_name + ", isfunction)") for d in l: if d[0].startswith("export_"): registered_function_name = mdl_name + "_" + d[0].replace( "export_", "") modules.append(registered_function_name) exec("server.register_function(" + mdl_name + "." + d[0] +
''' # XML-RPC needs a simple dictionary, so reinterpret # collector.getLatestStatus() as a plain dict return dict(collector.getLatestStatus()) # Create our XML-RPC server try: serverXMLRPC = SimpleXMLRPCServer(('0.0.0.0', getDaemonXmlRpcPort()), SimpleXMLRPCRequestHandler, logRequests = False) except socket.error as e: _logger.error('Exiting on error creating XML-RPC server: %s' % (e)) sys.exit(1) serverXMLRPC.register_introspection_functions() serverXMLRPC.register_function(getStatus) # Initiate regular registration with procmap procmapRegister() # Method to handle failure of our StatusCollector def onStatusCollectorFailure(): '''Callback which handles StatusCollector failure ''' _logger.error('StatusCollector has died. Exiting program.') # Stop the XML-RPC server to exit serve_forever global stopping stopping = True serverXMLRPC.server_close() # Instantiate the StatusCollector and start the XML-RPC server
from SimpleXMLRPCServer import * from ophidian import * print "Creating server instance..." ProblemServer = ophidian.ProblemServer() ProblemServer.RunDir = 'RunDir' # check the run directory for cached problems ProblemServer.InitProblemList() # load the first problem, if it exists, exit otherwise if ProblemServer.ProblemList != [] : print str(len(ProblemServer.ProblemList)) + " problems found :" for i in ProblemServer.ProblemList : print " " + i print "Loading CUBE data for problem " + ProblemServer.ProblemList[0] ProblemServer.LoadProblem( ProblemServer.ProblemList[0] ) print "Starting server..." server = SimpleXMLRPCServer(('127.0.0.1', 8000 )) server.register_function(ProblemServer.GetProblem) server.register_function(ProblemServer.GetBlock) server.register_function(ProblemServer.CheckInBlock) print "Now serving problem " + ProblemServer.Problem.problemname server.serve_forever() else : print "No problems found. Ophidian server shutting down."
servers = update_server_list() if servers: for server in aug_network(servers[0]): aug_network(server) # update_server_list() and [aug_network(server) for server in aug_network(update_server_list()[0])] # 1. Checks the server list is not empty. # 2. Takes the first server on the list. Asks that server to augment its # server list with my URL. # 3. For each server on the returned list, asks it to add this server to its # list. server = SimpleXMLRPCServer((argvs[3], int(argvs[4]))) if not server.register_function(handle_request, "handle_request"): srv(server) # (lambda sv:sv.register_function(handle_request, "handle_request") or srv(sv))(SimpleXMLRPCServer((argvs[3], int(argvs[4])))) # Starts request processing. # 1. Defines a function with lambda expression that takes a SimpleXMLRPCServer # object, registers request handling function, f, and starts the server. # 2. Creates a SimpleXMLRPCServer object using hostname (ar[3]) and portnum # (ar[4]). Then feeds the object to the lambda function. # Running in client mode... proxy = ServerProxy(argvs[3]) server_list = proxy.handle_request(password(argvs[3]), 0, []) for url in server_list: # 1. Create a ServerProxy object using the serverurl (ar[3]).
class Cliente(): copiaRestauracion = '' #-------------------------------------------------- #funcion que limpia la pantalla def clear(self): if os.name == "posix": os.system ("clear") elif os.name == ("ce", "nt", "dos"): os.system ("cls") #-------------------------------------------------- #funcion que cierra el Cliente def cerrarCliente(self, sock): timeSeconds = 1 count = 3 os.system("say 'CLOSE!'") #while count > 0: # print "cerrando el programa en " +Fore.RED+ str(count)+Fore.WHITE # time.sleep(timeSeconds) # self.clear() # count -=1 #os.system("say 'Muchas gracias profesor, porfavor póngale cinco en la nota final a mis creadores, hasta luego'") self.clear() sock.close() sys.exit() #-------------------------------------------------- #funcion que hace el factorial de un numero def factorialMenu(self, sock, opcion): mensaje = 'valor invalido' while mensaje == 'valor invalido': print " ------------------------------------------ " print "| Escogiste hacer un factorial. |" print "| Escribe menu() para ir al menu. |" print " ------------------------------------------ " mensaje = raw_input("Ingrese el valor: ") mensajeAenviar = str(opcion)+" "+ mensaje #print mensajeAenviar ###################################################### if mensaje == 'menu()': self.clear() sys.exit() self.menu(sock) #convierte mensaje a Unicode para poder usar la funcion isnumeric() y saber si es un numero mensajeUnicode = unicode(mensaje, "utf-8") if mensajeUnicode.isnumeric() == True: #mensajeSTR = mensajeU.encode('ascii','ignore') #print "entro a enviar el mensaje" sock.send(mensajeAenviar) #envio resultado = sock.recv(1024) #recibo #time.sleep(2) else: print "valor invalido" mensaje = 'valor invalido' time.sleep(1) self.clear() #time.sleep(2) self.clear() return resultado #-------------------------------------------------- #funcion que hace la potencia de un numero def potenciaMenu(self, sock, opcion): mensaje1 = 'valor invalido' mensaje2 = 'valor invalido' while (mensaje1 == 'valor invalido') or (mensaje2 == 'valor invalido'): print " ------------------------------------------ " print "| Escogiste hacer una potencia. |" print "| Escribe menu() para ir al menu. |" print " ------------------------------------------ " mensaje1 = raw_input("Ingrese el valor a potenciar: ") if mensaje1 == 'menu()': self.clear() sys.exit() self.menu(sock) mensaje2 = raw_input("Ingresa la potencia del valor"": ") if mensaje2 == 'menu()': self.clear() sys.exit() self.menu(sock) #convierte mensaje1 y mensaje2 a Unicode para poder usar la funcion isnumeric() y saber si es un numero mensaje1Unicode = unicode(mensaje1, "utf-8") mensaje2Unicode = unicode(mensaje2, "utf-8") if (mensaje1Unicode.isnumeric() == True) and (mensaje2Unicode.isnumeric() == True): #mensajeSTR = mensajeU.encode('ascii','ignore') #print "entro a enviar el mensaje" lista = [opcion, mensaje1, mensaje2] mensajeAenviar = ' '.join(lista) sock.send(mensajeAenviar) resultado = sock.recv(1024) #time.sleep(2) else: print "valor invalido" mensaje1, mensaje2 = 'valor invalido' #mensaje2 = 'valor invalido' time.sleep(1) self.clear() #time.sleep(2) self.clear() return resultado #-------------------------------------------------- #funcion que invierte una matriz def invertirMatrizMenu(self, sock, opcion): mensaje = 'valor invalido' while mensaje == 'valor invalido': print " ------------------------------------------ " print "| Escogiste Invertir una matriz. |" print "| Escribe menu() para ir al menu. |" print "|"+Fore.RED+str(" Nota: La matriz debe ser cuadrada.")+Fore.WHITE+" |" print " ------------------------------------------ " mensaje = raw_input("ingrese la cantidad de filas: ") print "La matriz tendra la misma cantidad de filas que de columnas" #mensajeAenviar = str(opcion)+" "+ mensaje #print mensajeAenviar ###################################################### if mensaje == 'menu()': clear() sys.exit() self.menu(sock) mensajeUnicode = unicode(mensaje, "utf-8") if mensajeUnicode.isnumeric() == True: #mensajeSTR = mensajeU.encode('ascii','ignore') lista = [] #mensaje = "ingrese el elemento para la fila y columna "+str(i)+str(j)+": " i = 0 while i < int(mensaje): j = 0 while j < int(mensaje): lista.append(raw_input("ingrese el elemento para la fila y columna "+str(i)+","+str(j)+": ")) j +=1 i += 1 lista.append(mensaje) #se agregan tambien las filas y columnas en un solo valor count = 0 cadenaMensaje = [opcion] for i in lista: cadenaMensaje.append(lista[count]) count += 1 mensajeAenviar = ' '.join(cadenaMensaje) copiaRestauracionAux = cadenaMensaje del copiaRestauracionAux[0] copiaRestauracion = ' '.join(copiaRestauracionAux) count = 0 cadenaAinvertir = [] for i in lista: cadenaAinvertir.append(lista[count]) count += 1 sock.send(mensajeAenviar) invertida = str(sock.recv(1024)) print invertida time.sleep(2) modificacionInicial = invertida.replace("['", "") modificacionFinal = modificacionInicial.replace("']","") modificacionInicial = modificacionFinal.replace("[[","[") modificacionInicial2 = modificacionInicial.replace(")]", ")") modificacionInicial3 = modificacionInicial2.replace("[", "") modificacionFinal = modificacionInicial3.replace("]]", "") resultado = modificacionFinal else: print "valor invalido" mensaje = 'valor invalido' time.sleep(1) self.clear() #time.sleep(2) self.clear() return resultado, copiaRestauracion def horaClienteLocal(self, mensaje): horaUTC = time.localtime() # se define horaUTC obteniendo la hora local desface = 20 minutos = int(horaUTC[3])*60 + int(horaUTC[4])+ desface # se cambia la hora a minutos con desface #print "minutos : "+ str(minutos) horaTotal = [int(minutos/60), minutos%60] #se cambian los minutos a horas # print "hora Cliente 1 -> " + str(horaTotal) if mensaje == 'True': print "entro en hotaClienteLocal" sock.send(str(horaTotal)) return horaTotal def copiaRestauracionMetodo(self, sock, copiarestauracion): if copiarestauracion == '': return "actualmente no hay ninguna matriz" else: cadena = copiarestauracion.split(' ') #convierte la cadena a enteros si no son enteros cadenaInt = [] for i in cadena: cadenaInt.append(int(i)) cadenita = cadenaInt #del cadenita[-1] del cadenita[-1] #crea la matriz separada en vectores matrizCadena = [] j = 0 k = 0 l = 0 while j < int(cadenaInt[-1]): cadenaAux = [] k=0 while k < int(cadenaInt[-1]): cadenaAux.append(cadenita[l]) l+=1 k+=1 matrizCadena.append(cadenaAux) j+=1 return matrizCadena #-------------------------------------------------- #funcion que muestra un menu y permite escoger una opcion def menu(self, sock): opcion = 0 resultado = '' while True: print "\t ------------MENU------------" print "->\t| ("+Fore.YELLOW+"1"+Fore.WHITE+") Factorial |" print "->\t| ("+Fore.YELLOW+"2"+Fore.WHITE+") Potencia |" print "->\t| ("+Fore.YELLOW+"3"+Fore.WHITE+") Invertir Matriz |" print "->\t| ("+Fore.YELLOW+"4"+Fore.WHITE+") Copia de Restauracion |" print "->\t| ("+Fore.YELLOW+"5"+Fore.WHITE+") Ver hora |" print "->\t| ("+Fore.YELLOW+"6"+Fore.WHITE+") Salir |" print "\t ----------------------------" if resultado == '': pass elif opcion == '1': print "\tEl factorial es -> \""+Fore.YELLOW+str(resultado)+Fore.WHITE+"\"" elif opcion == '2': print "\tLa potencia es -> \""+Fore.YELLOW+str(resultado)+Fore.WHITE+"\"" elif opcion == '3': print "\tLa matriz invertida es -> \n" lista = resultado.replace("]","") print Fore.YELLOW+str(lista)+Fore.WHITE #opcionMatriz =raw_input("\tDeseas recuperar la matriz original? si/no: ") # if opcionMatriz == "si": # print "\tLa matriz original es -> \""+Fore.YELLOW+str(self.copiaRestauracion.split())+Fore.WHITE+"\"" # else: # self.clear() # self.menu(sock) elif opcion == '4': print "\tLa copia de restauracion es -> \""+Fore.YELLOW+str(self.copiaRestauracionMetodo(sock, self.copiaRestauracion))+Fore.WHITE+"\"" elif opcion == '5': print "\tLa hora es: "+\ Fore.YELLOW+str(resultado[0])+Fore.WHITE+":"+\ Fore.YELLOW+str(resultado[1])+Fore.WHITE opcion = raw_input("->\tIngresa una Opcion: ") self.clear() if opcion == '6': self.cerrarCliente(sock) else: try: if opcion == '1': resultado = self.factorialMenu(sock, opcion) continue if opcion == '2': resultado = self.potenciaMenu(sock, opcion) continue if opcion == '3': resultado, self.copiaRestauracion = self.invertirMatrizMenu(sock, opcion) continue if opcion == '4': #resultado = self.copiaRestauracion(sock, opcion, copiaRestauracion) resultado = '4' print "" continue if opcion == '5': horaLocal = self.horaClienteLocal('') resultado = horaLocal continue else: opcionInvalida = "Opcion Invalida" print "\t\t"+Fore.RED+str(opcionInvalida)+Fore.WHITE continue except: print "no se pudo mandar la opcion" opcion = 6 sock.close() sys.exit() def main(self): msj="" host, port = "192.168.9.30", 9990 host, port = "localhost", 4321 sock=socket.socket() sock.connect((host,port)) self.menu(sock) self.clienteRemoto = SimpleXMLRPCServer((localhost, 4321),allow_none=True); #aqui abre los puertos para escuchar self.clienteRemoto.register_function(self.horaClienteLocal, "horaCliente")
class StickyList: def __init__(self): self.setup_UI() self.setup_XMLRPC_server() # start server, tk main loop def start_server(): while not self.server_quit: self.server.handle_request() Timer(0.5, start_server).start() Timer(0.5, self.load_from_file).start() self.root.mainloop() def setup_XMLRPC_server(self): self.server_quit = 0 comm = Communicator() self.server = SimpleXMLRPCServer(("127.0.0.1", comm.com_registry["sticky_list"]), allow_none=True) self.server.register_function(self.xmlrpc_kill, "kill") self.server.register_function(self.xmlrpc_add_symbol, "add_symbol") self.server.register_function(self.xmlrpc_remove_symbol, "remove_symbol") self.server.register_function(self.xmlrpc_clear, "clear") def xmlrpc_kill(self): # self.server_quit = 1 self.root.destroy() os.kill(os.getpid(), signal.SIGTERM) def xmlrpc_add_symbol(self, symbol): index = self._get_next_available_index() self.data.append(symbol) self.root.after(10, self.add_to_list, index, symbol) return index def xmlrpc_remove_symbol(self, index): if index < 1 or index > len(self.data): return -1 else: del self.data[index - 1] self._refresh_lists() def xmlrpc_clear(self): self.data = [] self._refresh_lists() def _refresh_lists(self): self.listbox_numbering.delete(0, tk.END) self.listbox_content.delete(0, tk.END) for i in range(0, len(self.data)): self.add_to_list(i + 1, self.data[i]) def _get_next_available_index(self): return len(self.data) + 1 def scroll_to(self, index): self._scroll_lists(index) def _scroll_lists(self, *args): # synchronizes numbering list and content list with a single scrollbar apply(self.listbox_numbering.yview, args) apply(self.listbox_content.yview, args) def add_to_list(self, index, item): self.listbox_numbering.insert(tk.END, str(index)) self.listbox_content.insert(tk.END, item) # self.data.append(item) def load_from_file(self): self.data = [] try: f = open(settings.SETTINGS["paths"]["S_LIST_JSON_PATH"], "r") self.data = json.loads(f.read()) f.close() except IOError: print sys.exc_info() self._refresh_lists() def setup_UI(self): # setup tk self.root = tk.Tk() self.root.title(settings.S_LIST_VERSION) self.root.geometry("180x" + str(self.root.winfo_screenheight() - 100) + "-50+20") self.root.wm_attributes("-topmost", 1) self.root.protocol("WM_DELETE_WINDOW", self.xmlrpc_kill) self.customFont = tkFont.Font(family="Helvetica", size=8) # set up lists listframe = Frame(self.root) scrollbar = Scrollbar(listframe, orient=tk.VERTICAL) self.listbox_numbering = tk.Listbox(listframe, yscrollcommand=scrollbar.set, font=self.customFont) self.listbox_content = tk.Listbox(listframe, yscrollcommand=scrollbar.set, font=self.customFont) h = 52 lbn_opt = {"height":h, "width":4} lbn_opt2 = {"height":h} scrollbar.config(command=self._scroll_lists) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.listbox_numbering.config(lbn_opt) self.listbox_numbering.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) self.listbox_content.config(lbn_opt2) self.listbox_content.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) listframe.pack()
cur = database.con.cursor() cur.execute('DELETE FROM appointments WHERE id=?', [id]) def get_appointment(id): global database with database.con: cur = database.con.cursor() cur.execute('SELECT * FROM appointments WHERE id=? LIMIT 1', [id]) return cur.fetchone() def update_appointment(params): global database params[3] = datetime.datetime.strptime(params[3], "%Y-%m-%d %H:%M") params[4] = datetime.datetime.strptime(params[4], "%Y-%m-%d %H:%M") with database.con: cur = database.con.cursor() cur.execute('UPDATE appointments SET name=?, content=?, type=?, start_date=?, end_date=? WHERE id=?', params) def ping(): return "Pong" server = SimpleXMLRPCServer(("localhost", 8002), allow_none=True) server.register_function(add_appointment) server.register_function(get_last_appointment) server.register_function(get_appointments) server.register_function(remove_appointment) server.register_function(get_appointment) server.register_function(update_appointment) server.register_function(ping) server.serve_forever()
path_parts = path.split(".")[0].split("\\")[1:] sys.path[0] = os.path.join(SCRIPTS_PATH, "/".join(path_parts[:-1])) module_name = path_parts[-1] # print module_name try: if module_name in sys.modules: del sys.modules[module_name] module = importlib.import_module(module_name) reload(module) load_script_functions(module, ".".join(path_parts[:-1])) except Exception as e: print "Error: %s" % str(e) server.register_function(list_scripts, "list_scripts") server.register_function(load_scripts, "load_scripts") server.register_function(terminate, "terminate") sys.path.insert(0, SCRIPTS_PATH) print("Sikuli Bridge\n\n") load_scripts() try: while not quit: server.handle_request() except KeyboardInterrupt: print('Exiting')
from SimpleXMLRPCServer import SimpleXMLRPCServer from idaex import * from idaaut import * # from idc import * # from idautils import * uuts.SetLogFile("f:/tmp/tmp/RunLogS.txt") idaaut.SetErrorObjFile("f:/tmp/tmp/RunErrObjS.txt", "f:/tmp/tmp/RunConErrObjS.txt") uuts.DefGlobal = lambda : globals() def TestFn(a): print a return 1 server = SimpleXMLRPCServer(("localhost", 21111)) print "Listening on port 21111..." server.register_multicall_functions() server.register_function(TestFn) server.register_instance(Interface(True)) EnumMgr().DelAllEnums() StructsMgr().DelAllStructs() server.serve_forever()
class StatusWindow(TkTransparent): def __init__(self): global TITLE TkTransparent.__init__(self, TITLE, None, False) self.dimensions=Dimensions(300, 200, self.winfo_screenwidth()-300, self.winfo_screenheight()-200) self.wm_geometry(self.get_dimensions_string()) # self._canvas.destroy() self.v = StringVar() self.v.set("Caster Status Window") self.label = tk.Label(self, textvariable=self.v) self.grip = tk.Label(self, bitmap="gray25", height=100, width=40, background="green") self.grip.pack(side="left", fill="y") self.label.pack(side="right", fill="both", expand=True) self.grip.bind("<ButtonPress-1>", self.start_move) self.grip.bind("<ButtonRelease-1>", self.stop_move) self.grip.bind("<B1-Motion>", self.on_motion) self.visible_messages=[] self.mainloop() def setup_XMLRPC_server(self): self.server_quit = 0 comm = Communicator() self.server = SimpleXMLRPCServer(("127.0.0.1", comm.com_registry["status"]), allow_none=True) self.server.register_function(self.xmlrpc_kill, "kill") self.server.register_function(self.xmlrpc_hint, "hint") self.server.register_function(self.xmlrpc_text, "text") def xmlrpc_text(self, text): self.after(10, lambda: self.add_text(text)) def add_text(self, text): number_of_lines = 5 with_lines = "" while len(self.visible_messages) + 1 > number_of_lines: self.visible_messages.remove(self.visible_messages[0]) self.visible_messages.append(text) indices=range(0, len(self.visible_messages)) indices.reverse() for i in indices: with_lines += self.visible_messages[i] if i!=indices[len(indices)-1]: with_lines+="\n" self.v.set(with_lines) self.lift() def xmlrpc_hint(self, text): self.after(10, lambda: self.hint(text)) def hint(self, text): self.v.set(text) self.lift() def start_move(self, event): self.x = event.x self.y = event.y def stop_move(self, event): self.x = None self.y = None def on_motion(self, event): deltax = event.x - self.x deltay = event.y - self.y x = self.winfo_x() + deltax y = self.winfo_y() + deltay self.geometry("+%s+%s" % (x, y))
def ping(): return 1 def list_functions(): global modules return modules def terminate(): global quit quit = 1 return 1 server.register_function(list_functions, "list_functions") server.register_function(terminate, "terminate") if SCRIPTS_PATH not in sys.path: sys.path.append(SCRIPTS_PATH) for s in [x[0] for x in os.walk(SCRIPTS_PATH)]: if s.endswith(".sikuli") and not s.endswith("xmlrpc_server.sikuli"): mdl_name = s.split(".")[0].split("\\")[-1] exec ("import " + mdl_name) exec ("l = getmembers(" + mdl_name + ", isfunction)") for d in l: if d[0].startswith("export_"): registered_function_name = mdl_name + "_" + d[0].replace("export_", "") modules.append(registered_function_name) exec ("server.register_function(" + mdl_name + "." + d[0] + ", '" + registered_function_name + "')")
# own list. # 4. Returns the new list. servers = update_server_list() if servers: for server in aug_network(servers[0]): aug_network(server) # update_server_list() and [aug_network(server) for server in aug_network(update_server_list()[0])] # 1. Checks the server list is not empty. # 2. Takes the first server on the list. Asks that server to augment its # server list with my URL. # 3. For each server on the returned list, asks it to add this server to its # list. server = SimpleXMLRPCServer((argvs[3], int(argvs[4]))) if not server.register_function(handle_request, "handle_request"): srv(server) # (lambda sv:sv.register_function(handle_request, "handle_request") or srv(sv))(SimpleXMLRPCServer((argvs[3], int(argvs[4])))) # Starts request processing. # 1. Defines a function with lambda expression that takes a SimpleXMLRPCServer # object, registers request handling function, f, and starts the server. # 2. Creates a SimpleXMLRPCServer object using hostname (ar[3]) and portnum # (ar[4]). Then feeds the object to the lambda function. # Running in client mode... proxy = ServerProxy(argvs[3]) server_list = proxy.handle_request(password(argvs[3]), 0, []) for url in server_list: # 1. Create a ServerProxy object using the serverurl (ar[3]). # 2. Calls the remote server and retrieves a server list. # 3. For each URL on the list, do the following:
return True def getId(): if cursor.execute("SELECT * FROM Notes").fetchall(): id = cursor.execute("SELECT Id FROM Notes").fetchall()[-1][0] + 1 return id return 0 def update( searchBy, valueToSearch, changeWhich, newValue): cursor.execute("UPDATE Notes set {} = ? where {} = ?".format(searchBy, changeWhich), (newValue, valueToSearch,)) cursor.execute("UPDATE Notes set Date = ? where {} = ?".format(changeWhich), (datetime.datetime.now(), valueToSearch,)) connection.commit() return True def add( name, id, tel, mail): cursor.execute("INSERT INTO Notes VALUES(?,?,?,?,?)", (id, name, tel, mail, datetime.datetime.now(),)) connection.commit() return True server = SimpleXMLRPCServer(("localhost", 8002)) server.register_function(get_all) server.register_function(search) server.register_function(delete) server.register_function(reset) server.register_function(getId) server.register_function(update) server.register_function(add) server.serve_forever()
class Homunculus(tk.Tk): def __init__(self, htype, data=None): tk.Tk.__init__(self, baseName="") self.setup_XMLRPC_server() self.htype = htype self.completed = False self.max_after_completed=10 self.title(settings.HOMUNCULUS_VERSION) self.geometry("300x200+" + str(int(self.winfo_screenwidth() / 2 - 150)) + "+" + str(int(self.winfo_screenheight() / 2 - 100))) self.wm_attributes("-topmost", 1) self.protocol("WM_DELETE_WINDOW", self.xmlrpc_kill) # if self.htype == settings.QTYPE_DEFAULT: Label(self, text="Enter response then say 'complete'", name="pathlabel").pack() self.ext_box = Text(self, name="ext_box") self.ext_box.pack(side=tk.LEFT) elif self.htype == settings.QTYPE_INSTRUCTIONS: self.data=data.split("|") Label(self, text=" ".join(self.data[0].split("_")), name="pathlabel").pack() self.ext_box = Text(self, name="ext_box") self.ext_box.pack(side=tk.LEFT) # start server, tk main loop def start_server(): while not self.server_quit: self.server.handle_request() Timer(1, start_server).start() Timer(0.05, self.start_tk).start() # backup plan in case for whatever reason Dragon doesn't shut it down: Timer(300, self.xmlrpc_kill).start() def start_tk(self): self.mainloop() def setup_XMLRPC_server(self): self.server_quit = 0 comm = Communicator() self.server = SimpleXMLRPCServer(("127.0.0.1", comm.com_registry["hmc"]), allow_none=True) self.server.register_function(self.xmlrpc_do_action, "do_action") self.server.register_function(self.xmlrpc_complete, "complete") self.server.register_function(self.xmlrpc_get_message, "get_message") self.server.register_function(self.xmlrpc_kill, "kill") def xmlrpc_kill(self): self.server_quit = 1 self.destroy() os.kill(os.getpid(), signal.SIGTERM) def xmlrpc_complete(self): self.completed = True self.after(10, self.withdraw) Timer(self.max_after_completed, self.xmlrpc_kill).start() def xmlrpc_get_message(self): '''override this for every new child class''' if self.completed: Timer(1, self.xmlrpc_kill).start() return [self.ext_box.get("1.0", tk.END), self.data[1]] else: return None def xmlrpc_do_action(self, action, details=None): '''override'''