コード例 #1
0
ファイル: system.py プロジェクト: ogranada/pyqode.core
    def start(self, port=8080):
        """
        Starts the server. This will actually start the child process.

        :param port: Local TCP/IP port to which the underlying socket is
                     connected to.
        """
        self.__process = multiprocessing.Process(target=childProcess,
                                                 name=self.__name,
                                                 args=(port, ))
        self.__process.start()
        self.__running = False
        try:
            if sys.platform == "win32":
                self._client = Client(('localhost', port))
            else:
                try:
                    self._client = Client(('', port))
                except OSError:
                    # wait a second before starting, this occur if we were connected to
                    # previously running server that has just closed (we need to wait a
                    # little before starting a new one)
                    time.sleep(1)
                    self._client = Client(('', port))
            logger.info("Connected to Code Completion Server on 127.0.0.1:%d" %
                        port)
            self.__running = True
            self._lock = thread.allocate_lock()
            thread.start_new_thread(self._threadFct, ())
        except OSError:
            logger.exception("Failed to connect to Code Completion Server on "
                             "127.0.0.1:%d" % port)
        return self.__running
コード例 #2
0
ファイル: ramDB_c.py プロジェクト: d1ma/light_ramdb
class DBClient(object):
	def __init__(self, address=('localhost',6000), authkey='difficult password'):
		self.conn = Client(address, authkey=authkey)

	def get_batch(self, elements):
		self.conn.send(list(elements))
		to_ret = self.conn.recv()
		return to_ret

	def get(self, element):
		self.conn.send(element)
		to_ret = self.conn.recv()
		return to_ret

	def set(self, key, val):
		self.conn.send({key: val})

	def set_batch(self, key_val_dict):
		self.conn.send(key_val_dict)

	def __getitem__(self, key):
		return self.get(key)

	def __setitem__(self, key, val):
		self.set(key, val)
コード例 #3
0
ファイル: client.py プロジェクト: chengguozhen/iSDX
    def send(self, msg):
        #conn = Client((self.address, self.port), authkey=str(self.key))
        conn = Client((self.address, self.port))

        conn.send(json.dumps(msg))

        conn.close()
コード例 #4
0
ファイル: distproc.py プロジェクト: AmesianX/des
class Worker(object):

    def __init__(self, address, port, authkey=None):

        self.connection = Client((address, port), authkey=authkey)
        self.worker_id = self.connection.recv()

    def run(self):
        while True:

            task_data = self.connection.recv()
            if task_data is False:
                return

            result = self.do_task(task_data)
            self.connection.send((task_data, result))

    def log(self, *items):
        print "== Worker %s ==" % self.worker_id,
        for item in items:
            print item,
        print

    def do_task(self, data):
        raise NotImplementedError("A subclass must implement this.")
コード例 #5
0
ファイル: http_status.py プロジェクト: 1n5aN1aC/rainmeter-pi
def get_json():
    # Get the current values
    c = Client(("localhost", 25000))
    c.send("get")
    now = c.recv()

    # Now we parse all the data out of the results!
    data = {}
    data["IN_Temp"] = now.In_Temp
    data["IN_Humid"] = now.In_Humid
    data["OUT_Temp"] = now.Out_Temp
    data["OUT_Humid"] = now.Out_Humid
    data["Out_Wind_Now"] = now.Out_Wind_Now
    data["OUT_Wind_Avg"] = now.Out_Wind_Avg
    data["OUT_Wind_Max"] = now.Out_Wind_Max
    data["OUT_Rain_Today"] = now.Out_Rain_Today
    data["OUT_Rain_Last_24h"] = now.Out_Rain_Last_24h
    data["OUT_Rain_Since_Reset"] = now.Out_Rain_Since_Reset
    data["ATTIC_Temp"] = now.Attic_Temp
    data["ATTIC_Humid"] = now.Attic_Humid
    data["NOW_URL"] = now.Now_URL
    data["NOW_Feel"] = now.Now_Feel
    data["NOW_Feel_High"] = now.Now_Feel_High
    data["NOW_Feel_Low"] = now.NOW_Feel_Low
    data["SYSTEM_CPU"] = now.System_CPU
    data["SYSTEM_RAM"] = now.System_RAM

    # Now return the json as a string
    return json.dumps(data)
コード例 #6
0
 def process_data2(self, q):
     conn = Client(address, authkey="secret password")
     message = ""
     while True:
         message = conn.recv()
         # print "received", message[0],message[1]
         q.put(message)
コード例 #7
0
ファイル: notebook.py プロジェクト: Benhgift/note_study_tool
 def start_server(self, address, password):
     print("server waiting")
     listener = Listener()
     client = Client(address)
     client.send(listener.address)
     self._start_listener(listener)
     return listener.address
コード例 #8
0
class RsClient:

	def __enter__(self):
		"""no init"""

	def __exit__(self, type=None, value=None, tb=None):

		#self.conn may not exist so expect that it may fail.
		try:
			self.conn.close()
		except:
			pass

	def start(self, host='localhost', port=8000, key='8457#$%^&3648'):

		address = (host, port)
		self.conn = Client(address)

	def send(self, data):
		try:
			self.conn.send(data)
		except:
			self.stop()

	def stop(self):
		self.conn.close()
コード例 #9
0
ファイル: MetricValues.py プロジェクト: suttond/MODOI
def shutdown_metric(metric_server_addresses, authkey):
    """ This function tells all of the SimulationPotential instances running on the addresses in metric_server_addresses to shutdown. This is called when a SimulationClient instance shuts down.

    Args:
      metric_server_addresses: A list of tuples of the form (str, int) containing the hostnames and port numbers of the SimulationPotential instances.
      authkey (str): The password used in order to communicate with the SimulationPotential instances.

    Returns:
      float: The length of the curve with metric values in metric.

    """

    # For each SimulationPotential instance...
    for address in xrange(len(metric_server_addresses)):

        # Try making contact with the SimulationPotential instance...
        try:
            # Establish a connection with the SimulationPotential
            metric_server = Client(metric_server_addresses[address], authkey=authkey)

            # Send a status code indicating the SimulationPotential instance should stop running.
            metric_server.send({'status_code': comm_code('KILL')})

            # Close the connection.
            metric_server.close()

        # If contact with the SimulationPotential instance cannot be made then...
        except socket.error:
            # Make a note in the log which SimulationPotential couldn't be contacted.
            logging.warning('Failed to Make Connection to SimulationPotential at '
                          + str(metric_server_addresses[address]) + '.')
コード例 #10
0
ファイル: ipc.py プロジェクト: DarioGT/Zim-QDA
        def call(*args, **kwargs):
            global _recursive_conn_lock
            if _recursive_conn_lock:
                raise AssertionError, 'BUG: Recursive client connection'
                # Avoid hanging because we call the socket while the
                # server is blocking for our return value on the pipe.
                # If this is an issue blocking functionality,
                # re-route the call to the open pipe for which the
                # server is waiting.

            #~ if self._client_proxy_authkey is None:
                #~ self._client_proxy_authkey = AUTHKEY_FILE.raw()

            msg = RemoteMethodCall(self._obj, name, args, kwargs)
            logger.debug('Remote call from %i: %s', os.getpid(), msg)
            #~ print "CLIENT >>%s<<" % self._client_proxy_authkey
            #~ conn = Client(SERVER_ADDRESS, authkey=self._client_proxy_authkey)
            conn = Client(SERVER_ADDRESS, SERVER_ADDRESS_FAMILY)
            conn.send(msg)
            if not msg.async:
                re = conn.recv()
                logger.debug('Remote call returned to %i: %s', os.getpid(), re)
                if isinstance(re, Exception):
                    raise re
                else:
                    return re
コード例 #11
0
ファイル: lib.py プロジェクト: jeroen92/iSDX
 def send(self, msg):
     # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
     # TODO: then busy wait is probably inappropriate.
     if self.port == 5555:
         self.redis.rpush('flowqueue', msg)
     else:
         while True: # keep going until we break out inside the loop
             try:
                 self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                 conn = Client((self.address, self.port))
                 self.logger.debug('Connect to '+self.serverName+' successful.')
                 break
             except SocketError as serr:
                 if serr.errno == errno.ECONNREFUSED:
                     self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                 else:
                     # Not a recognized error. Treat as fatal.
                     self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                     raise serr
             except:
                 self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                 raise
         self.logger.debug('PCTRLSEND ' + str(msg))
         conn.send(msg)
         self.logger.debug('TRYCONNCLOSE trying to close the connection in pctrl')
         conn.close()
コード例 #12
0
ファイル: browser.py プロジェクト: edne/VimLiveHTML
    def run(self):
        while not self._stop:
            address = ('localhost', 6000)
            conn = Client(address)
            msg = conn.recv()
            conn.close()

            [cb() for k,cb in self.cbs.items() if msg==k]
コード例 #13
0
	def send(self, msg):

		try:
			connection = Client(self.address, authkey=self.auth)
			connection.send(msg)
			connection.close()
		except ConnectionRefusedError:
			print('Connection Refused')
コード例 #14
0
ファイル: nodemanager.py プロジェクト: eman89/bluesky
def run():
    global connection
    connection = Client(('localhost', 6000), authkey=b'bluesky')
    plugin.init()
    stack.init()
    bs.sim.doWork()
    connection.close()
    print('Node', nodeid, 'stopped.')
コード例 #15
0
def reset_rain():
    # Reset rain_since_reset in the table
    # (╯°□°)╯︵ ┻━┻
    c = Client( ('localhost', 25000) )
    c.send("reset_rain")
    result = c.recv()
    
    return "reset!"
コード例 #16
0
ファイル: rpc.py プロジェクト: nEDM-TUM/HimbeereCouch
class RPCProxy(RPCObject):
    """
    RPCProxy, object running in child processes that connects to an :class:`RPCServer`
    object.
    """
    def __init__(self, address, authkey):
        super(RPCProxy, self).__init__()
        self._functions = { }
        self._quitnotifiers = set()
        self._conn = Client(address, authkey=authkey)
        self._conn.send(json.dumps({"name" : _mp.current_process().name, "pid" : os.getpid()}))
        self._should_exit = False
        self.register_function(self.exit_now, "exit")
        def _exit(*args):
            self.exit_now()
        signal.signal(signal.SIGINT, _exit)
        signal.signal(signal.SIGTERM, _exit)

    def listen(self):
        def handle_client(client_c):
            while not self._should_exit:
                try:
                    func_name, args, kwargs = client_c.recv()
                except EOFError:
                    self.exit_now()
                    break
                try:
                    r = self._functions[func_name](*args,**kwargs)
                    client_c.send(r)
                except Exception as e:
                    client_c.send(e)
        self.t = Thread(target=handle_client, args=(self._conn,))
        self.t.daemon = True
        self.t.start()

    def register_exit_notification(self, func):
        self._quitnotifiers.add(func)

    def remove_exit_notification(self, func):
        try:
            self._quitnotifiers.remove(func)
        except KeyError: pass

    def exit_now(self):
        log("Exit requested")
        self._should_exit = True
        for f in self._quitnotifiers:
            f()
        return True

    def should_exit(self):
        return self._should_exit

    def register_function(self, func, name = None):
        if name is None:
            name = func.__name__
        self._functions[name] = func
コード例 #17
0
ファイル: Reflekt.py プロジェクト: likang/Reflekt
 def run(self):
     address = ("localhost", 6000)
     conn = Client(address, authkey="secret password")
     while True:
         command = conn.recv_bytes()
         if command == "quit":
             break
         self.animations[:] = parse_command(command, self.boxs, "receiver")
     conn.close()
コード例 #18
0
ファイル: reduction.py プロジェクト: webiumsk/WOT-0.9.15-CT
def rebuild_handle(pickled_data):
    address, handle, inherited = pickled_data
    if inherited:
        return handle
    sub_debug('rebuilding handle %d', handle)
    conn = Client(address, authkey=current_process().authkey)
    conn.send((handle, os.getpid()))
    new_handle = recv_handle(conn)
    conn.close()
    return new_handle
コード例 #19
0
 def __init__(self, portstr="/dev/m4_com", conn_type="serial"):
   self._pf = PacketFinder()
   self.conn_type = conn_type
   if self.conn_type == "serial":
     self._ser = serial.Serial(portstr, 115200, timeout=0)
     self._ser.flushInput()
   elif self.conn_type == "portal":
     conn = Client(address=('localhost', 50000), authkey='abracadabra')
     port = conn.recv()
     self.conn = Client(address=('localhost', port), authkey='abracadabra')
コード例 #20
0
ファイル: meteor.py プロジェクト: raingo/coco-caption
 def compute_score(self, gts, res):
     conn = Client(self.address, authkey=self.authkey)
     try:
         score = self._handle_client(gts, res, conn)
     except Exception as ioe:
         print ioe, '103'
         score = (0.0, [0.0])
     finally:
         conn.close()
     return score
コード例 #21
0
ファイル: cli.py プロジェクト: chrislyon/my-ordo-project
 def do_conn(self,line):
     global conn
     address = (params['SERVEUR'], params['PORT'])
     try:
         conn = Client(address, authkey=params['PASSWORD'])
         print "Connexion etablie"
     except:
         print "Erreur connexion"
     ## Reception de l'invite du serveur
     print conn.recv()
コード例 #22
0
ファイル: performance.py プロジェクト: gem/oq-hazardlib
 def send(self, *args):
     """
     Send a command to the listener. Add the .calc_id as last argument.
     """
     if self.address:
         client = Client(self.address, authkey=self.authkey)
         try:
             client.send(args + (self.calc_id,))
         finally:
             client.close()
コード例 #23
0
def triggerEvent( type, scheduleMethod, *args ):
    """
    This function inserts an event into CHOTestMonkey
    """
    host = "localhost"
    port = 6000
    address = ( host, port )
    conn = Client( address )
    request = []
    request.append( 2 )
    request.append( type )
    request.append( scheduleMethod )
    for arg in args:
        request.append( arg )
    conn.send( request )
    response = conn.recv()
    while response == 11:
        time.sleep( 1 )
        conn.send( request )
        response = conn.recv()
    if response == 10:
        print "Event inserted:", type, scheduleMethod, args
    elif response == 20:
        print "Unknown message to server"
    elif response == 21:
        print "Unknown event type to server"
    elif response == 22:
        print "Unknown schedule method to server"
    elif response == 23:
        print "Not enough argument"
    else:
        print "Unknown response from server:", response
    conn.close()
コード例 #24
0
ファイル: cliclient.py プロジェクト: benthomasson/pymud
class CliClient(cmd.Cmd):

    def __init__(self,address,id):
        self.id = id
        self.connection = Client(address, authkey='secret password')
        cmd.Cmd.__init__(self)

    def onecmd(self,line):
        self.connection.send(("creator",line))
        while self.connection.poll(0.1):
            print self.connection.recv()        
コード例 #25
0
ファイル: dspytbus.py プロジェクト: madprof/dspytbus
class Component(Base):
    """
    Components send and receive messages.

    Remember to call __init__() from your constructor! Subclass
    this and implement handle_message() to actually do stuff.
    Don't override anything but __init__() and handle_message()!
    """
    def __init__(self, bus=DEFAULT_ADDRESS, authkey=None, interests=None):
        """
        Initialize a new component.

        Connect to bus (host, port) with given authorization key and
        interests; interests can be a class, type, or tuple of these;
        if interests is None, the __interests__ attribute is used; if
        __interests__ does not exist, object is used.

        The constructor should always be called with keyword arguments.
        """
        super(Component, self).__init__()
        self._bus = Client(address=bus, authkey=authkey)
        assert self._bus is not None
        if interests is None:
            interests = getattr(self, "__interests__", object)
        self._bus.send(interests)
        self._bus_address = bus

    def send_message(self, message):
        """
        Send a message out of this component.

        Don't call this from the outside!
        """
        self._bus.send(message)

    @abstractmethod
    def handle_message(self, message):
        """
        Handle a message.

        You must override this!
        """
        assert False, "You must override this!"

    def run(self):
        """
        The component receives and dispatches messages here.

        Don't override this!
        """
        while True:
            msg = self._bus.recv()
            self.handle_message(msg)
コード例 #26
0
ファイル: listener.py プロジェクト: md1023/olivetti
def send_message_to_server(configuration):
    address = configuration.get('address')
    authkey = configuration.get('authkey')
    message = configuration.get('message')
    try:
        client = Client(address, authkey=authkey)
        client.send(message)
        client.close()
    except socket_error as serr:
        if serr.errno != errno.ECONNREFUSED:
            raise serr
        print('client couldn\'t connect')
コード例 #27
0
def worker(server_address):
    serv = Client(server_address, authkey=b'peekaboo')
    serv.send(os.getpid())
    while True:
        fd = recv_handle(serv)
        print('WĄTEK ROBOCZY: OTRZYMANO DESKRYPTOR', fd)
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd) as client:
            while True:
                msg = client.recv(1024)
                if not msg:
                    break
                print('WĄTEK ROBOCZY: OTRZYMANO {!r}'.format(msg))
                client.send(msg)
コード例 #28
0
ファイル: cli_sav.py プロジェクト: chrislyon/my-ordo-project
 def conn(self, serveur=None):
     address = (params['SERVEUR'], params['PORT'])
     print "Connecting : ", address
     print "Params = ", params
     try:
         conn = Client(address, authkey=params['PASSWORD'])
         print "Connexion etablie"
         ## Reception de l'invite du serveur
         print conn.recv()
         return conn
     except:
         print "Erreur connexion"
         return None
コード例 #29
0
ファイル: flask_web_api.py プロジェクト: lijianxin/Python-API
class ServiceConnect:
  def __delete__(self):
    if self.conn:
      self.conn.close()

  def conntect(self, host="localhost", port=6000):
    self.conn = Client((host, port))

  def request(self, req):
    self.conn.send(req)
    items = self.conn.recv_bytes()
    result = json.loads(items)
    return result
コード例 #30
0
def worker(server_address):
    serv = Client(server_address, authkey = b'peekaboo')
    serv.send(os.getpid())
    while True:
        fd = recv_handle(serv)
        print('WORER: GOT FD', fd)
        with socket(AF_INET, SOCK_STREAM, fileno=fd) as client:
            while True:
                msg = client.recv(1024)
                if not msg:
                    break
                print('WORKER: RECV {!r}'.format(msg))
                client.send(msg)
コード例 #31
0
ファイル: cliSend.py プロジェクト: TomAbrahams/prototypeSock
from multiprocessing.connection import Client
from array import array

address = ('localhost', 6001)     # family is deduced to be 'AF_INET'
choice = 'y'

with Client(address, authkey=b'go beyond Plus ULTRA!') as conn:
    while choice != 'n':
        choice = input("Would you like to send a message? (y/n)")
        if choice == 'y':
            messageToSend = input('Type what you want to send.\n')
            messageToSend = messageToSend.encode('utf-8')
            conn.send_bytes(messageToSend)
        elif choice == 'n':
            print('Thank you for using the multiprocessing client tester')
            print('Informing server that you wish to end your connection.')
            messageToSend = b'TM86'
            conn.send_bytes(messageToSend)
            conn.close()
        else:
            print('Invalid choice.')
print("the dream is program over...")
コード例 #32
0
ファイル: communicator.py プロジェクト: ufwt/kAFL
 def connect(self):
     sock = Client(self.address, 'AF_UNIX')
     return sock
コード例 #33
0
 def __init__(self):
     config = crawler._get_config()
     server_port = crawler.analysis_config(
         config, "LISTENER_PORT", 0, crawler.CONFIG_ANALYSIS_MODE_INTEGER)
     self.conn = Client((portListenerEvent.SERVER_IP, server_port))
コード例 #34
0
    # request2: ai_number
    # response2: ai_result:big,small,hit
    loop = True
    while loop:
        res = conn.recv()
        print res
        loop = ai.process(res)

    # for draw slowly
    play_back()


if __name__ == '__main__':
    # conn managerment
    address = ('localhost', 6000)
    conn = Client(address, authkey='secret password')

    # UI managerment
    f = simplegui.create_frame("猜数游戏 AI", 800, 600)
    f.add_button("new game [0,100)", new_game, 200)
    f.add_button("play back", play_back, 200)
    f.add_button("ai mid", ai_mid, 200)
    f.add_button("ai random", ai_random, 200)
    f.set_draw_handler(draw_handler)
    timer = simplegui.create_timer(200, tick)
    f.start()

    # conn end
    timer.stop()
    conn.close()
コード例 #35
0
    def train(self):
        address = ('localhost', 6000)
        conn = Client(address)
        try:
            plotter = Plotter()
            if self.plot:
                plotter.init_plot(self.env, self.policy)
            conn.send(ExpLifecycle.START)
            self.start_worker()
            self.init_opt()
            for itr in range(self.current_itr, self.n_itr):
                with logger.prefix('itr #{} | '.format(itr)):
                    conn.send(ExpLifecycle.OBTAIN_SAMPLES)
                    paths = self.sampler.obtain_samples(itr)
                    conn.send(ExpLifecycle.PROCESS_SAMPLES)
                    samples_data = self.sampler.process_samples(itr, paths)
                    self.log_diagnostics(paths)
                    conn.send(ExpLifecycle.OPTIMIZE_POLICY)
                    self.optimize_policy(itr, samples_data)
                    logger.log('saving snapshot...')
                    params = self.get_itr_snapshot(itr, samples_data)
                    self.current_itr = itr + 1
                    params['algo'] = self
                    if self.store_paths:
                        params['paths'] = samples_data['paths']
                    snapshotter.save_itr_params(itr, params)
                    logger.log('saved')
                    logger.log(tabular)
                    if self.plot:
                        conn.send(ExpLifecycle.UPDATE_PLOT)
                        plotter.update_plot(self.policy, self.max_path_length)
                        if self.pause_for_plot:
                            input('Plotting evaluation run: Press Enter to '
                                  'continue...')

            conn.send(ExpLifecycle.SHUTDOWN)
            plotter.close()
            self.shutdown_worker()
        finally:
            conn.close()
コード例 #36
0
class Logger(object):
    def __init__( self, din = {} ):
        self.dict = {
            'portname'        : '/dev/tty.usbserial-A601NO4K',
            'baudrate'        : 57600,
            'timeout_sec'     : 1,
            'sampling_time_ms': 5,
            'plotting_time_ms': 100,
            'n_data_sim'      : 4000,
            'verbose'         : False,
        }
        self.dict.update(din)
        
        # Simulate a logging at a predetermined sampling rate
        print "[LOG] Initialised simulation mode"
        self.ser = simulator(self.dict['n_data_sim'], self.dict['sampling_time_ms'])
       
        # Info on process used for data logging
        print "[IPC-C] Client process ID ", os.getpid()
        
        self.init_communication()
        self.__run__()
        self.close_communication()
        
    
    def init_communication(self):
        # Open the client-side of the communication for MultiProcessing
        print "[IPC-C] Opening client socket ... ",
        address = ('localhost', 6000)
        self.conn = Client(address)
        print "done!"
    
    def close_communication(self):
        # Tell to the server the data transfer is done
        self.conn.send('close')
        print "[IPC-C] Closing client ... ",
        # Close the client-side of the communication
        self.conn.close()
        print "done!"
    
    def write_msg(self, msg):
        self.conn.send( msg )
        
    def __run__(self):
        # Some initializations
        send_data = False
        avg       = [0, 0, 0]
        n         = 1
        time      = 0
        
        max_data = self.dict['n_data_sim']
            
        for i in range(1,max_data):
            # Read the data from the serial communication
            self.ser.log_data(self.dict['verbose'])
            
            # Calculate elapsed time from the sensor
            time = (time + self.ser.meas_ts_ms*1e-3) # (s)
            
            # Check if average or send data
            if n == round(self.dict['plotting_time_ms']/self.dict['sampling_time_ms']):
                send_data = True
            else:
                send_data = False
            
            # Average the data during a time span DT.
            # DT is chosen accordingly to the refresh rate of the plots (~100 ms)
            if send_data == False:
                # Calculate the cumulative average
                for j in range(0,3):
                    avg[j] = (avg[j]*(n-1)+self.ser.raw_data_A[j])/n
                    
                n = n+1
            else:
                msg = [os.getpid(), i, time, avg[0], avg[1], avg[2]]
                
                #print "Logger sent ", msg
                self.write_msg(msg)
                
                avg = [0, 0, 0]
                n   = 1
コード例 #37
0
import numpy as np
import math
import time
import subprocess

from multiprocessing.connection import Client

import signal
import json

import tornado.ioloop
import tornado.web

subprocess.Popen("python rocket_mpc_graph.py")
address = ('localhost', 6000)
conn = Client(address, authkey=bytes('mpc', 'utf-8'))

transform_dae = TransformationFactory('dae.finite_difference')
solver = SolverFactory('ipopt')
solver.options['tol'] = 1 * 10**-3

def perform_mpc(u_init, v_init, w_init,
				p_init, q_init, r_init,
				phi_init, theta_init, psi_init,
				x_init, y_init, h_init,
				goal_x, goal_y, goal_h):
    # start mpc
	mpc_time = 1.0
	mpc_samples = 20

	m = ConcreteModel()
コード例 #38
0
                    root.quit()
                elif s[0] == 'board':
                    gameboard.delete(0, END)
                    gameboard.insert(0, s[1])
                elif s[0] == 'answer':
                    message.delete(0, END)
                    message.insert(0, s[1])
            root.update()
    except TclError:
        pass


"apatir de aqui seria lo que es el main"
print 'Trying to connect'

conn = Client(address=('localhost', 6000), authkey='secret')
team = conn.recv()
gameboard = conn.recv()
window_queue = Queue()
input_queue = Queue()
gameboard_window = Process(target=graphical_interface,
                           args=(window_queue, team, input_queue, conn))
gameboard_window.start()
show_board(window_queue, gameboard)

i = 0
while i == 0:
    movement = read_movement(input_queue)
    print movement
    conn.send((team, movement))
    done = False
コード例 #39
0
def main():
    pipe = Client(sys.argv[1])
    proto, target = pipe.recv()

    try:
        s = lightblue.socket(proto)
        s.connect(target)
        s.settimeout(1 / 100.)
        pipe.send(None)
        while True:
            if pipe.poll():
                b = pipe.recv()
                print "sending", b
                s.send(b)
            try:
                o = s.recv(4096)
                pipe.send(o)
            except Exception, err:
                pass

    except Exception, err:
        pipe.send(err)
        raise
コード例 #40
0
    remote_conn = listener.accept()
    print('Got client ' + listener.last_accepted[0] + ':%d' %
          (listener.last_accepted[1]))

    try:
        while True:
            if remote_conn.poll():
                msg = remote_conn.recv()
                print('msg: ' + msg)
                if msg == 'quit':
                    keep_running = False
                    break
            else:
                time.sleep(0.01)
    except EOFError:
        print('Lost connection to client')
        listener.close()

## Client code ----------------------------------
from multiprocessing.connection import Client

address = ('', 6000)
conn = Client(address, authkey='test')

keep_running = True
while keep_running:
    msg = input('Enter string ')
    conn.send(msg)
    if msg == 'quit':
        keep_running = False
コード例 #41
0
@Contact :   [email protected]
@License :   (C)Copyright 2018-2019, RCD_OS
'''

import json
from multiprocessing.connection import Client


class RPCProxy():
    """RPC client for json
    
    Attributes:
    
    To use:
    """
    def __init__(self, connection):
        self._connection = connection

    def __getattr__(self, name):
        def do_rpc(*args, **kwargs):
            self._connection.send(json.dumps((name, args, kwargs)))
            result = json.loads(self._connection.recv())
            return result

        return do_rpc


if __name__ == "__main__":
    c = Client(('localhost', 17000), authkey=b'peekaboo')
    proxy = RPCProxy(c)
    print(proxy.add(4, 3))
コード例 #42
0
import pickle


class RPCProxy:
    def __init__(self, connection):
        self._connection = connection

    def __getattr__(self, name):
        def do_rpc(*args, **kwargs):
            self._connection.send(pickle.dumps((name, args, kwargs)))
            result = pickle.loads(self._connection.recv())
            if isinstance(result, Exception):
                raise result
            return result

        return do_rpc


# Example use
from multiprocessing.connection import Client
c = Client(('beowulf.ucsd.edu', 1234), authkey=b'peekaboo')
proxy = RPCProxy(c)
print(proxy.fibo(123))
print(proxy.add(234, 789))
print(proxy.sub(2, 3))
try:
    proxy.sub([1, 2], 4)
except Exception as e:
    print(e)
コード例 #43
0
 def init_communication(self):
     # Open the client-side of the communication for MultiProcessing
     print "[IPC-C] Opening client socket ... ",
     address = ('localhost', 6000)
     self.conn = Client(address)
     print "done!"
コード例 #44
0
ファイル: computer.py プロジェクト: PreDarkness/HPC_homework
# print(conf.sections())
port = conf.getint('server','port')
host = conf.get('server','host')
addr = (host,port+node)


# 读取配置文件,用于开启第二个socket,用于等待其他节点的结果,并规约
conf2 = cp()
conf2.read('conf_computer.ini')
# print(conf2.sections())
port2 = conf2.getint('compute', 'port')
host2 = conf2.get('compute', 'host')
addr2 = (host2, port2)

#建立与控制节点的连接
cpter = Client(addr)
total_node = cpter.recv()
role = cpter.recv()
# print('角色分配:'+role)
cpter.send(role)

def rec_data():
    #接收文件
    data = cpter.recv()
    with open('data' + role + '.csv', 'wb') as f:
        f.write(data)
    # print("--------------数据文件" + role + "已收到-----------")
    task = cpter.recv()
    with open('task.py', 'wb') as f:
        f.write(task)
    # print("--------------计算任务文件已收到--------------")
コード例 #45
0
ファイル: __init__.py プロジェクト: rayleyva/wdb
class Wdb(object):
    """Wdb debugger main class"""
    _instances = {}
    _sockets = []
    enabled = True
    breakpoints = set()
    watchers = defaultdict(list)

    @staticmethod
    def get(no_create=False):
        """Get the thread local singleton"""
        pid = os.getpid()
        thread = threading.current_thread()
        wdb = Wdb._instances.get((pid, thread))
        if not wdb and not no_create:
            wdb = object.__new__(Wdb)
            Wdb.__init__(wdb)
            wdb.pid = pid
            wdb.thread = thread
            Wdb._instances[(pid, thread)] = wdb
        return wdb

    @staticmethod
    def pop():
        """Remove instance from instance list"""
        pid = os.getpid()
        thread = threading.current_thread()
        Wdb._instances.pop((pid, thread))

    def __new__(cls):
        return cls.get()

    def __init__(self):
        log.debug('New wdb instance %r' % self)
        self.obj_cache = {}
        self.tracing = False
        self.begun = False
        self.connected = False
        self.stepping = False
        self.extra_vars = {}
        self.last_obj = None
        self.reset()
        self.uuid = str(uuid4())
        self.state = Running(None)
        self.full = False
        self.below = False
        self._socket = None

    def run_file(self, filename):
        """Run the file `filename` with trace"""
        import __main__
        __main__.__dict__.clear()
        __main__.__dict__.update({
            "__name__": "__main__",
            "__file__": filename,
            "__builtins__": __builtins__,
        })
        with open(filename, "rb") as fp:
            statement = "exec(compile(%r, %r, 'exec'))" % (fp.read(), filename)
        self.run(statement, filename)

    def run(self, cmd, fn=None, globals=None, locals=None):
        """Run the cmd `cmd` with trace"""
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        if isinstance(cmd, str):
            cmd = compile(cmd, fn or "<wdb>", "exec")
        self.start_trace()
        self.breakpoints.add(Breakpoint(fn, temporary=True))
        try:
            execute(cmd, globals, locals)
        finally:
            self.stop_trace()

    def reset(self):
        """Refresh linecache"""
        import linecache
        linecache.checkcache()

    def connect(self):
        """Connect to wdb server"""
        log.info('Connecting socket on %s:%d' % (SOCKET_SERVER, SOCKET_PORT))
        tries = 0
        while not self._socket and tries < 10:
            try:
                self._socket = Client((SOCKET_SERVER, SOCKET_PORT))
            except socket.error:
                tries += 1
                log.warning('You must start wdb.server. '
                            '(Retrying on %s:%d) [Try #%d]' %
                            (SOCKET_SERVER, SOCKET_PORT, tries))

        if not self._socket:
            log.error('Could not connect to server')
            sys.exit(2)

        Wdb._sockets.append(self._socket)
        self._socket.send_bytes(self.uuid.encode('utf-8'))

    def trace_dispatch(self, frame, event, arg):
        """This function is called every line,
        function call, function return and exception during trace"""
        fun = getattr(self, 'handle_' + event)
        if fun and ((event == 'line' and self.breaks(frame)) or
                    (event == 'exception' and
                     (self.full or frame == self.state.frame or
                      (self.below and frame.f_back == self.state.frame)))
                    or self.state.stops(frame, event)):
            fun(frame, arg)
        if event == 'return' and frame == self.state.frame:
            # Upping state
            if self.state.up():
                # No more frames
                self.stop_trace()
                return
            # Threading / Multiprocessing support
            co = self.state.frame.f_code
            if ((co.co_filename.endswith('threading.py')
                 and co.co_name.endswith('_bootstrap_inner'))
                    or (self.state.frame.f_code.co_filename.endswith(
                        os.path.join('multiprocessing', 'process.py'))
                        and self.state.frame.f_code.co_name == '_bootstrap')):
                # Thread / Process is dead
                self.stop_trace()
                self.die()
                return
        if (event == 'call' and not self.stepping and not self.full
                and not (self.below and frame.f_back == self.state.frame)
                and not self.get_file_breaks(frame.f_code.co_filename)):
            # Don't trace anymore here
            return
        return self.trace_dispatch

    def trace_debug_dispatch(self, frame, event, arg):
        """Utility function to add debug to tracing"""
        trace_log.info('Frame:%s. Event: %s. Arg: %r' %
                       (pretty_frame(frame), event, arg))
        trace_log.debug('state %r breaks ? %s stops ? %s' %
                        (self.state, self.breaks(frame, no_remove=True),
                         self.state.stops(frame, event)))
        if event == 'return':
            trace_log.debug(
                'Return: frame: %s, state: %s, state.f_back: %s' %
                (pretty_frame(frame), pretty_frame(
                    self.state.frame), pretty_frame(self.state.frame.f_back)))
        if self.trace_dispatch(frame, event, arg):
            return self.trace_debug_dispatch
        trace_log.debug("No trace %s" % pretty_frame(frame))

    def start_trace(self, full=False, frame=None, below=False):
        """Start tracing from here"""
        if self.tracing:
            return
        self.reset()
        log.info('Starting trace on %r' % self.thread)
        frame = frame or sys._getframe().f_back
        # Setting trace without pausing
        self.set_trace(frame, break_=False)
        self.tracing = True
        self.below = below
        self.full = full

    def set_trace(self, frame=None, break_=True):
        """Break at current state"""
        # We are already tracing, do nothing
        trace_log.info('Setting trace %s (stepping %s) (current_trace: %s)' %
                       (pretty_frame(frame or sys._getframe().f_back),
                        self.stepping, sys.gettrace()))
        if self.stepping:
            return
        self.reset()
        trace = (self.trace_dispatch
                 if trace_log.level >= 30 else self.trace_debug_dispatch)
        trace_frame = frame = frame or sys._getframe().f_back
        while frame:
            frame.f_trace = trace
            frame = frame.f_back
        self.state = Step(trace_frame) if break_ else Running(trace_frame)
        sys.settrace(trace)

    def stop_trace(self, frame=None):
        """Stop tracing from here"""
        self.tracing = False
        self.full = False
        frame = frame or sys._getframe().f_back
        while frame:
            del frame.f_trace
            frame = frame.f_back
        sys.settrace(None)
        log.info('Stopping trace on %r' % self.thread)

    def set_until(self, frame, lineno=None):
        """Stop on the next line number."""
        self.state = Until(frame, frame.f_lineno)

    def set_step(self, frame):
        """Stop on the next line."""
        self.state = Step(frame)

    def set_next(self, frame):
        """Stop on the next line in current frame."""
        self.state = Next(frame)

    def set_return(self, frame):
        """Stop when returning from the given frame."""
        self.state = Return(frame)

    def set_continue(self, frame):
        """Don't stop anymore"""
        self.state = Running(frame)
        if not self.tracing and not self.breakpoints:
            # If we were in a set_trace and there's no breakpoint to trace for
            # Run without trace
            self.stop_trace()

    def get_break(self, filename, lineno, temporary, cond, funcname):
        if lineno and not cond:
            return LineBreakpoint(filename, lineno, temporary)
        elif cond:
            return ConditionalBreakpoint(filename, lineno, cond, temporary)
        elif funcname:
            return FunctionBreakpoint(filename, funcname, temporary)
        else:
            return Breakpoint(filename, temporary)

    def set_break(self,
                  filename,
                  lineno=None,
                  temporary=False,
                  cond=None,
                  funcname=None):
        """Put a breakpoint for filename"""
        log.info('Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
                 (filename, lineno, temporary, cond, funcname))
        breakpoint = self.get_break(filename, lineno, temporary, cond,
                                    funcname)
        self.breakpoints.add(breakpoint)
        if not temporary:
            self._socket.send_bytes(b'Server|AddBreak|' +
                                    pickle.dumps(breakpoint))

        log.info('Breakpoint %r added' % breakpoint)

    def clear_break(self,
                    filename,
                    lineno=None,
                    temporary=False,
                    cond=None,
                    funcname=None):
        """Remove a breakpoint"""
        log.info('Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
                 (filename, lineno, temporary, cond, funcname))

        breakpoint = self.get_break(filename, lineno, temporary or False, cond,
                                    funcname)
        if temporary is None and breakpoint not in self.breakpoints:
            breakpoint = self.get_break(filename, lineno, True, cond, funcname)

        try:
            self.breakpoints.remove(breakpoint)
            if not temporary:
                self._socket.send_bytes(b'Server|RmBreak|' +
                                        pickle.dumps(breakpoint))
            log.info('Breakpoint %r removed' % breakpoint)
        except:
            log.info('Breakpoint %r not removed: not found' % breakpoint)

    def safe_repr(self, obj):
        """Like a repr but without exception"""
        try:
            return repr(obj)
        except Exception as e:
            return '??? Broken repr (%s: %s)' % (type(e).__name__, e)

    def safe_better_repr(self, obj):
        """Repr with inspect links on objects"""
        try:
            rv = self.better_repr(obj)
        except Exception:
            rv = None
        if rv:
            return rv

        self.obj_cache[id(obj)] = obj
        return '<a href="%d" class="inspect">%s</a>' % (id(obj),
                                                        escape(repr(obj)))

    def better_repr(self, obj):
        """Repr with html decorations"""
        if isinstance(obj, dict):
            if type(obj) != dict:
                dict_repr = type(obj).__name__ + '({'
                closer = '})'
            else:
                dict_repr = '{'
                closer = '}'
            if len(obj) > 2:
                dict_repr += '<table>'
                dict_repr += ''.join([
                    '<tr><td>' + self.safe_repr(key) + '</td><td>:</td>'
                    '<td>' + self.safe_better_repr(val) + '</td></tr>'
                    for key, val in sorted(obj.items(), key=lambda x: x[0])
                ])
                dict_repr += '</table>'
            else:
                dict_repr += ', '.join([
                    self.safe_repr(key) + ': ' + self.safe_better_repr(val)
                    for key, val in sorted(obj.items(), key=lambda x: x[0])
                ])
            dict_repr += closer
            return dict_repr

        if any([
                isinstance(obj, list),
                isinstance(obj, set),
                isinstance(obj, tuple)
        ]):
            if type(obj) == list:
                iter_repr = '['
                closer = ']'
            elif type(obj) == set:
                iter_repr = '{'
                closer = '}'
            elif type(obj) == tuple:
                iter_repr = '('
                closer = ')'
            else:
                iter_repr = escape(obj.__class__.__name__) + '(['
                closer = '])'

            splitter = ', '
            if len(obj) > 2:
                splitter += '\n'
                iter_repr += '\n'
                closer = '\n' + closer

            iter_repr += splitter.join(
                [self.safe_better_repr(val) for val in obj])

            iter_repr += closer
            return iter_repr

    @contextmanager
    def capture_output(self, with_hook=True):
        """Steal stream output, return them in string, restore them"""
        self.hooked = ''

        def display_hook(obj):
            # That's some dirty hack
            self.hooked += self.safe_better_repr(obj)
            self.last_obj = obj

        stdout, stderr = sys.stdout, sys.stderr
        if with_hook:
            d_hook = sys.displayhook
            sys.displayhook = display_hook

        sys.stdout, sys.stderr = StringIO(), StringIO()
        out, err = [], []
        try:
            yield out, err
        finally:
            out.extend(sys.stdout.getvalue().splitlines()[1:])
            err.extend(sys.stderr.getvalue().splitlines())
            if with_hook:
                sys.displayhook = d_hook

            sys.stdout, sys.stderr = stdout, stderr

    def dmp(self, thing):
        """Dump the content of an object in a dict for wdb.js"""
        def safe_getattr(key):
            """Avoid crash on getattr"""
            try:
                return getattr(thing, key)
            except Exception as e:
                return 'Error getting attr "%s" from "%s" (%s: %s)' % (
                    key, thing, type(e).__name__, e)

        return dict((escape(key), {
            'val': self.safe_better_repr(safe_getattr(key)),
            'type': type(safe_getattr(key)).__name__
        }) for key in dir(thing))

    def get_file(self, filename):
        """Get file source from cache"""
        import linecache
        return to_unicode_string(''.join(linecache.getlines(filename)),
                                 filename)

    def get_stack(self, f, t):
        """Build the stack from frame and traceback"""
        stack = []
        if t and t.tb_frame == f:
            t = t.tb_next
        while f is not None:
            stack.append((f, f.f_lineno))
            f = f.f_back
        stack.reverse()
        i = max(0, len(stack) - 1)
        while t is not None:
            stack.append((t.tb_frame, t.tb_lineno))
            t = t.tb_next
        if f is None:
            i = max(0, len(stack) - 1)
        return stack, i

    def get_trace(self, frame, tb):
        """Get a dict of the traceback for wdb.js use"""
        import linecache
        frames = []
        stack, _ = self.get_stack(frame, tb)
        current = 0

        for i, (stack_frame, lno) in enumerate(stack):
            if frame == stack_frame:
                current = i
                break

        for i, (stack_frame, lno) in enumerate(stack):
            code = stack_frame.f_code
            filename = code.co_filename
            linecache.checkcache(filename)
            line = linecache.getline(filename, lno, stack_frame.f_globals)
            line = to_unicode_string(line, filename)
            line = line and line.strip()
            startlnos = dis.findlinestarts(code)
            lastlineno = list(startlnos)[-1][1]
            frames.append({
                'file': filename,
                'function': code.co_name,
                'flno': code.co_firstlineno,
                'llno': lastlineno,
                'lno': lno,
                'code': line,
                'level': i,
                'current': current == i
            })

        # While in exception always put the context to the top
        current = len(frames) - 1

        return stack, frames, current

    def send(self, data):
        """Send data through websocket"""
        log.debug('Sending %s' % data)
        self._socket.send_bytes(data.encode('utf-8'))

    def receive(self, pickled=False):
        """Receive data through websocket"""
        log.debug('Receiving')
        data = self._socket.recv_bytes()
        if pickled:
            data = pickle.loads(data)
            log.debug('Got pickled %r' % data)
            return data
        log.debug('Got %s' % data)
        return data.decode('utf-8')

    def interaction(self,
                    frame,
                    tb=None,
                    exception='Wdb',
                    exception_description='Stepping',
                    init=None):
        """User interaction handling blocking on socket receive"""
        log.info('Interaction for %r -> %r %r %r %r' %
                 (self.thread, frame, tb, exception, exception_description))
        self.stepping = True

        if not self.connected:
            self.connect()
            log.debug('Launching browser and wait for connection')
            web_url = 'http://%s:%d/debug/session/%s' % (
                WEB_SERVER or 'localhost', WEB_PORT or 1984, self.uuid)

            server = WEB_SERVER or '[wdb.server]'
            if WEB_PORT:
                server += ':%s' % WEB_PORT

            if WDB_NO_BROWSER_AUTO_OPEN:
                log.warning('You can now launch your browser at '
                            'http://%s/debug/session/%s' % (server, self.uuid))

            elif not webbrowser.open(web_url):
                log.warning('Unable to open browser, '
                            'please go to http://%s/debug/session/%s' %
                            (server, self.uuid))

            self.connected = True

        interaction = Interaction(self,
                                  frame,
                                  tb,
                                  exception,
                                  exception_description,
                                  init=init)

        # For meta debugging purpose
        self._ui = interaction

        if self.begun:
            # Each new state sends the trace and selects a frame
            interaction.init()
        else:
            self.begun = True
        interaction.loop()

    def handle_call(self, frame, argument_list):
        """This method is called when there is the remote possibility
        that we ever need to stop in this function."""
        fun = frame.f_code.co_name
        log.info('Calling: %r' % fun)
        init = 'Echo|%s' % dump({'for': '__call__', 'val': fun})
        self.interaction(frame,
                         init=init,
                         exception_description='Calling %s' % fun)

    def handle_line(self, frame, arg):
        """This function is called when we stop or break at this line."""
        log.info('Stopping at line %s' % pretty_frame(frame))
        self.interaction(frame)

    def handle_return(self, frame, return_value):
        """This function is called when a return trap is set here."""
        self.obj_cache[id(return_value)] = return_value
        self.extra_vars['__return__'] = return_value
        fun = frame.f_code.co_name
        log.info('Returning from %r with value: %r' % (fun, return_value))
        init = 'Echo|%s' % dump({'for': '__return__', 'val': return_value})
        self.interaction(
            frame,
            init=init,
            exception_description='Returning from %s with value %s' %
            (fun, return_value))

    def handle_exception(self, frame, exc_info):
        """This function is called if an exception occurs,
        but only if we are to stop at or just below this level."""
        type_, value, tb = exc_info
        # Python 3 is broken see http://bugs.python.org/issue17413
        _value = value
        if not isinstance(_value, BaseException):
            _value = type_(value)
        fake_exc_info = type_, _value, tb
        log.error('Exception during trace', exc_info=fake_exc_info)
        self.obj_cache[id(exc_info)] = exc_info
        self.extra_vars['__exception__'] = exc_info
        exception = type_.__name__
        exception_description = str(value)
        init = 'Echo|%s' % dump(
            {
                'for': '__exception__',
                'val': escape('%s: %s') % (exception, exception_description)
            })
        # User exception is 4 frames away from exception
        log.warning(pretty_frame(frame))
        frame = frame or sys._getframe().f_back.f_back.f_back.f_back
        self.interaction(frame,
                         tb,
                         exception,
                         exception_description,
                         init=init)

    def breaks(self, frame, no_remove=False):
        """Return True if there's a breakpoint at frame"""
        for breakpoint in set(self.breakpoints):
            if breakpoint.breaks(frame):
                if breakpoint.temporary and not no_remove:
                    self.breakpoints.remove(breakpoint)
                return True
        return False

    def get_file_breaks(self, filename):
        """List all file `filename` breakpoints"""
        return [
            breakpoint for breakpoint in self.breakpoints
            if breakpoint.on_file(filename)
        ]

    def get_breaks_lno(self, filename):
        """List all line numbers that have a breakpoint"""
        return list(
            filter(lambda x: x is not None, [
                getattr(breakpoint, 'line', None)
                for breakpoint in self.breakpoints
                if breakpoint.on_file(filename)
            ]))

    def die(self):
        """Time to quit"""
        log.info('Time to die')
        if self.connected:
            try:
                self.send('Die')
            except:
                pass
            self._socket.close()
        self.pop()
コード例 #46
0
def run_main(func):
    from multiprocessing.connection import Client
    from contextlib import closing
    address, key = cPickle.loads(eintr_retry_call(sys.stdin.read))
    with closing(Client(address, authkey=key)) as conn:
        raise SystemExit(func(conn))
コード例 #47
0
            ''' example: announce route 1.2.3.4 next-hop 5.6.7.8 as-path [ 100 200 ] '''

        except:
            pass


''' main '''
if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--port",
                        type=int,
                        help="port to connect to route server")
    parser.add_argument("--key",
                        help="authentication key to connect to route server")
    args = parser.parse_args()

    port = args.port if args.port else 6000
    key = args.key if args.key else 'xrs'

    conn = Client(('localhost', port), authkey=key)

    sender = Thread(target=_sender, args=(conn, sys.stdin))
    sender.start()

    receiver = Thread(target=_receiver, args=(conn, sys.stdout))
    receiver.start()

    sender.join()
    receiver.join()
コード例 #48
0
import numpy as np
from multiprocessing.connection import Client
import serial.tools.list_ports
import sys

#TODO stop IMUs and close connection to serial port and server on exit

# Connect to the server
connection = False
calib = False

try:
    address = ('localhost', 50001)
    # server = socket.socket()
    # server.connect(address)
    server = Client(address)
    server.send('imus')
    connection = True
except:
    print('No server found in address {}'.format(address))

addresses = [1, 2, 3, 4, 5, 6, 7, 8]

# Command the IMUs are to perform
command = [255, 255, 255, 255, 255, 255, 255, 255]
command[0] = 0
command[1] = 41
command[2] = 255
command[3] = 255
command[4] = 255
command[5] = 255
コード例 #49
0
from prediction_utils import nearestNeighbour, twoOpt, aggressiveNeighbour, random
#from random_neighbour import random
from hyperX import hyperXprediction
import sys

#def init(csv_path):
global csv_file_path, df, id
csv_file_path = sys.argv[1]
df = pd.read_csv(csv_file_path)
id = df.id
#runAll()
print("HEY I AM IN CONTRLLER")
#def runAll():

address = ('localhost', 6000)
conn = Client(address, authkey=b'secret password')
print("trying")
address2 = ('localhost', 7000)
conn2 = Client(address2, authkey=b'secret password')

#set policy for other agent....
otherAgentPolicyForDemo = str(sys.argv[2])
hyperXPolicy = "nn"

conn2.send(
    otherAgentPolicyForDemo)  #send other agent's policy to write log in csv.

moves = []

agent1_state = 0
agent2_state = 0
コード例 #50
0
John Eslick, Carnegie Mellon University, 2014
See LICENSE.md for license and copyright details.
"""
import numpy as np
import time
import sys
from multiprocessing.connection import Client

if __name__ == '__main__':
    inputFile = 'input.txt'
    outputFile = 'output.txt'
    # Set the socket address, maybe someday this will change or
    # have some setting option, but for now is hard coded
    address = ('localhost', 56001)
    # Open the connection
    conn = Client(address)
    # Read the samples from the input file made by ALAMO
    samples = []
    with open(inputFile, 'r') as f:
        print("Reading Input File {}".format(inputFile))
        line = f.readline()  # read and ignore first line
        line = f.readline()
        while (line):
            line = line.strip()
            line = line.split()
            if line[0] == 'T': break
            for i in range(len(line)):
                try:
                    line[i] = float(line[i])
                except:
                    # failed to convert to float I guess is not a number
コード例 #51
0
from multiprocessing.connection import Client
client = Client(('localhost', 1234))
run = True
while run:
    x = int(input('enter x: '))
    y = int(input('enter y: '))
    client.send(x)
    client.send(y)
#este script sends
コード例 #52
0
    SpellBinds,
    SpellsForCategory,
    State,
)
from spells import (
    DamType,
    getSpellByName,
    getSpellByType,
    Spell,
    SpellType,
)
from tfutils import tfprint
from utils import flatten, NoValue

SOCKET_FILE = "/var/run/user/{0}/bcproxy-tf-scripts-caster".format(getuid())
CONN = Client(SOCKET_FILE, "AF_UNIX")


def changeCategory(category_raw: str):
    global state
    cat = category_raw.upper()
    category = Category[cat]
    state = state._replace(category=category)
    CONN.send_bytes(dill.dumps(state))


def castString(spell: Spell, atTarget: bool, target: Optional[str]):
    # spell can't have target, cast always without
    if spell.withTarget == False:
        return spell.name
コード例 #53
0
ファイル: ouuSetupFrame.py プロジェクト: kesibe/FOQUS
    def analyze(self):
        dir = os.getcwd()
        for f in os.listdir(dir):
            if re.search('psuadeEval.out', f):
                os.remove(os.path.join(dir, f))

        if self.run_button.text() == 'Run OUU': # Run OUU
            names, indices = self.input_table.getPrimaryVariables()
            if len(names) == 0:
                QMessageBox.information(self, 'No Primary Variables',
                                              'At least one input must be a primary variable!')
                return

            valid, error = self.input_table.checkValidInputs()
            if not valid:
                QMessageBox.information(self, 'Input Table Distributions',
                                              'Input table distributions are either not correct or not filled out completely! %s' % error)
                return

            if self.compressSamples_chk.isChecked() and not self.scenariosCalculated:
                QMessageBox.information(self, 'Compress Samples Not Calculated',
                                              'You have elected to compress samples for discrete random variables (Z3), but have not selected the sample size to use!')
                return

            M1 = len(self.input_table.getPrimaryVariables()[0])
            M2 = len(self.input_table.getRecourseVariables()[0])
            M3 = len(self.input_table.getUQDiscreteVariables()[0])
            M4 = len(self.input_table.getContinuousVariables()[0])

            Common.initFolder(OUU.dname)

            self.managePlots()
            self.clearPlots()
            self.manageBestValueTable()
            self.summary_group.setTitle('Best So Far')

            xtable = self.input_table.getTableValues()

            # get arguments for ouu()
            model = copy.deepcopy(self.model)
            inputNames = model.getInputNames()
            inputTypes = list(model.getInputTypes())
            defaultValues = model.getInputDefaults()
            for row in xtable:
                if row['type'] == 'Fixed':
                    modelIndex = inputNames.index(row['name'])
                    inputTypes[modelIndex] = Model.FIXED
                    defaultValues[modelIndex] = row['value']
            #print inputTypes
            #print defaultValues
            model.setInputTypes(inputTypes)
            model.setInputDefaults(defaultValues)
            data = SampleData(model)
            fname = 'ouuTemp.dat'
            data.writeToPsuade(fname)

            # Outputs
            numOutputs = self.outputs_table.rowCount()
            y = []
            self.useAsConstraint = [False] * numOutputs
            self.useAsDerivative = [False] * numOutputs
            for r in range(numOutputs):
                type = self.outputs_table.cellWidget(r,0).currentText()
                if type == ouuSetupFrame.ObjFuncText:
                    y.append(r + 1)
                elif type == ouuSetupFrame.ConstraintText:
                    self.useAsConstraint[r] = True
                elif type == ouuSetupFrame.DerivativeText:
                    self.useAsDerivative[r] = True

            if self.mean_radio.isChecked():
                phi = {'type':1}
            elif self.meanWithBeta_radio.isChecked():
                beta = self.betaDoubleSpin.value()
                phi = {'type':2, 'beta':beta}
            elif self.alpha_radio.isChecked():
                alpha = self.alphaDoubleSpin.value()
                phi = {'type':3, 'alpha':alpha}
            x3sample = None
            if M3 > 0:
                if self.compressSamples_chk.isChecked():
                    selectedSamples = int(self.scenarioSelect_combo.currentText())
                    sfile = self.scenarioFiles[selectedSamples][0]
                else:
                    sfile = 'z3Samples.smp'
                    success = self.writeTableToFile(self.z3_table, sfile, M3)
                    if not success:
                        return
                    if sfile.endswith('.csv'): # Convert .csv file to simple file
                        newFileName = OUU.dname + os.sep + os.path.basename(fname)[:-4] + '.smp'
                        inData = LocalExecutionModule.readDataFromCsvFile(sfile, askForNumInputs=False)
                        LocalExecutionModule.writeSimpleFile(newFileName, inData[0])
                        sfile = newFileName

                #print 'x3 file is', sfile
                x3sample = {'file':sfile}                           # x3sample file
                data,_, numInputs, _ = LocalExecutionModule.readDataFromSimpleFile(sfile, hasColumnNumbers=False)
                if numInputs != M3:
                    QMessageBox.critical(self, "Number of variables don't match",
                                              'The number of variables from the file (%d) does not match the number of Z3 discrete variables (%d).  You will not be able to perform analysis until this is corrected.' % (numInputs, M3))
                    return
            useRS = self.x4RSMethod_check.isChecked()
            x4sample = None
            if self.z4NewSample_radio.isChecked():
                method = self.x4SampleScheme_combo.currentText()
                method = SamplingMethods.getEnumValue(method)
                N = self.x4SampleSize_spin.value()
                if method in [SamplingMethods.LH,SamplingMethods.LPTAU]:
                    x4sample = {'method':method, 'nsamples':N}  # number of samples (range: [M1+1,1000])
                elif method == SamplingMethods.FACT:
                    x4sample = {'method':method, 'nlevels':N}   # number of levels (range: [3,100])
            else:
                sfile = 'z4Samples.smp'
                success = self.writeTableToFile(self.z4_table, sfile, M4)
                if not success:
                    return
                if len(sfile) == 0:
                    QMessageBox.critical(self, 'Missing file',
                               'Z4 sample file not specified!')
                    return

                if sfile.endswith('.csv'): # Convert .csv file to simple file
                    newFileName = OUU.dname + os.sep + os.path.basename(fname)[:-4] + '.smp'
                    inData = LocalExecutionModule.readDataFromCsvFile(sfile, askForNumInputs=False)
                    LocalExecutionModule.writeSimpleFile(newFileName, inData[0])
                    sfile = newFileName

                inData, outData, numInputs, numOutputs = LocalExecutionModule.readDataFromSimpleFile(sfile, hasColumnNumbers=False)
                numSamples = inData.shape[0]
                if numInputs != M4:
                    QMessageBox.critical(self, "Number of variables don't match",
                                              'The number of input variables from the file (%d) does not match the number of Z4 continuous variables (%d).  You will not be able to perform analysis until this is corrected.' % (numInputs, M4))
                    return
                if numSamples <= M4:
                    QMessageBox.critical(self, 'Not enough samples',
                               'Z4 sample file must have at least %d samples!' % (M4 + 1))
                    return

                x4sample = {'file': sfile}                      # x4sample file, must have at least M4+1 samples

                if useRS:
                    Nrs = self.z4SubsetSize_spin.value()     # add spinbox to get number of samples to generate RS
                    x4sample['nsamplesRS'] = Nrs               # TO DO: make sure spinbox has M4+1 as min and x4sample's sample size as max

            #  TODO: Get rid of usebobyqa option. Behavior should be as if usebobyqa is always false
            # TODO: Change GUI to display optimizer and optimizing with bobyqa
            # TODO: Get rid of primarySolver_combo completely
            useBobyqa = False
            method = self.primarySolver_combo.currentText()
            if method == "BOBYQA":
                pass
            elif method == "NEWUOA":
                pass
            if 'simulator' in self.secondarySolver_combo.currentText():
                useBobyqa = True  # use BOBYQA if driver is a simulator, not an optimizer

            self.run_button.setText('Stop')
            optDriver = None
            ensembleOptDriver = None
            if self.node_radio.isChecked():
                ensembleOptDriver = self.setupPSUADEClient()
                optDriver = ensembleOptDriver
                listener = listen.foqusListener(self.dat)
                variableNames = []
                fixedNames = []
                for row in xtable:
                    #print row
                    if row['type'] == 'Fixed':
                        fixedNames.append(row['name'])
                    else:
                        variableNames.append(row['name'])
                #print fixedNames, variableNames
                #print variableNames + fixedNames
                listener.inputNames = variableNames + fixedNames
                outputNames = self.model.getOutputNames()
                listener.outputNames = [outputNames[yItem-1] for yItem in y]
                listener.failValue = -111111
                self.listenerAddress = listener.address
                listener.start()

            # print M1, M2, M3, M4, useBobyqa
            self.OUUobj = OUU()
            try:
                results = self.OUUobj.ouu(fname,y,self.useAsConstraint,self.useAsDerivative,xtable,phi,
                                          x3sample=x3sample,x4sample=x4sample,useRS=useRS,useBobyqa=useBobyqa,
                                          optDriver = optDriver, ensOptDriver = ensembleOptDriver, plotSignal = self.plotSignal,
                                          endFunction=self.finishOUU)
            except:
                import traceback
                traceback.print_exc()
                if self.node_radio.isChecked():
                    # stop the listener
                    conn = Client(self.listenerAddress)
                    conn.send(['quit'])
                    conn.close()

                # enable run button
                self.run_button.setEnabled(True)
                return
        else: # Stop OUU
            self.OUUobj.stopOUU()
            self.run_button.setEnabled(False)
            self.freeze()
コード例 #54
0
#!/usr/bin/env python
# -*- coding: utf8 -*-

from multiprocessing.connection import Client


c = Client(("127.0.0.1", 8080), authkey="password")
print c.recv()
c.close()
コード例 #55
0
ファイル: 3_client.py プロジェクト: tayebzaidi/PPLL_Spr_16
from multiprocessing.connection import Client

print 'trying to connect'
conn = Client(address=('127.0.0.1', 6000), authkey='secret password')
print 'connection accepted'

answer = ''
while answer != 'adios':   
    message = raw_input('Message to send? ')
    print 'sending message'
    conn.send(message)
    answer = conn.recv() 
    print 'received message', answer 

conn.close()

コード例 #56
0
ファイル: parallel.py プロジェクト: vhmar/oq-engine
def main(hostport):
    host, port = hostport.split(':')
    conn = Client((host, int(port)))
    func, args = conn.recv()
    safely_call(func, args, False, conn)
コード例 #57
0
import rsa
import hashlib
from multiprocessing.connection import Client

first_adress = ('localhost', 6002)

public_key, private_key = rsa.newkeys(512)


def generate_password(length):
    return "".join(
        random.choices(string.ascii_uppercase + string.digits,
                       k=length)).encode("UTF-8")


broker_connection = Client(first_adress)
try:
    broker_connection.send(public_key)
    broker_public_key = broker_connection.recv()
    half_pass = generate_password(50)
    encrypted = rsa.encrypt(half_pass, broker_public_key)
    broker_connection.send(encrypted)
    password = half_pass + rsa.decrypt(broker_connection.recv(), private_key)
finally:
    broker_connection.close()
print(password)

broker_connection = Client(first_adress, authkey=password)
# print("aaaaa")
try:
    broker_connection.send("aici")
コード例 #58
0
        key_pressed = event.keysym
        if key_pressed == 'Up' or key_pressed == 'w':
            movement = 1
        elif key_pressed == 'Right' or key_pressed == 'd':
            movement = 2
        elif key_pressed == 'Down' or key_pressed == 's':
            movement = 3
        elif key_pressed == 'Left' or key_pressed == 'a':
            movement = 4

    canvas.bind("<Motion>", aiming)
    canvas.bind("<Button-1>", shooting)
    canvas.bind_all("<Key>", moving)

    print ('trying to connect')
    conn = Client(address=('127.0.0.1', 6000), authkey=b'secret')
    print ('connection accepted')

    def normal_act():
        global shoot, shooted, last_time_shooted, reload
        global movement, bullets
        if shoot and bullets>0:
            bullets -= 1
            last_time_shooted = time.time()
            shooted = True
        elif shooted:
            current_time = time.time()
            diff = current_time - last_time_shooted
            if diff >= 3:
                bullets = 3
                reload = True
コード例 #59
0
import errno
from socket import error as socket_error

from multiprocessing.connection import Client
from array import array

import subprocess

address = '/home/pi/raspberry-predator-gauntlet/connection-loc'
addressT = ('localhost', 8333)

# if server is not running: ConnectionRefusedError: [Errno 111] Connection refused
successfullySent = False
while not successfullySent:
    try:
        with Client(addressT) as connection:
            connection.send(['gameEnd', None, 1])
            successfullySent = True
    except socket_error as thisError:
        if thisError.errno != errno.ECONNREFUSED:
            raise thisError
        print('server not running')
        # try to start the server
        pipeHolder = subprocess.Popen([
            '/usr/bin/python3.5',
            '/home/pi/raspberry-predator-gauntlet/predator-display-serv.py'
        ])
        # wait for a little
        time.sleep(2)
コード例 #60
0
 def create_connect_client(self):
     address = (self.host, self.port_num)
     conn = Client(address, authkey=b'secret password A')
     return conn