Пример #1
0
    def __init__(self, map_name):
        self.node_name = rospy.get_name()

        # Map
        self.map = dw.load_map(map_name)
        self.skeleton_graph = dw.get_skeleton_graph(self.map['tilemap'])

        # Dispatcher
        self.dispatcher = dispatcher.Dispatcher(self.skeleton_graph)
        self.state = {'seq': 0, 'duckies': {}, 'requests': []}

        # Subscribers
        self.sub_paths = rospy.Subscriber('/flock_simulator/state',
                                          FlockState,
                                          self.cbState,
                                          queue_size=1)

        # Publishers
        self.pub_commands = rospy.Publisher('/flock_simulator/commands',
                                            FlockCommand,
                                            queue_size=1)

        # Timer
        self.sim_frequency = 30.0  # Frequency of simulation in Hz
        self.request_timer = rospy.Timer(
            rospy.Duration.from_sec(1.0 / self.sim_frequency), self.cbTimer)
        self.isUpdating = False
Пример #2
0
 def connect(self, server=None, proxy=None, ssl=None, use_srv=None):
     """ Make a tcp/ip connection, protect it with tls/ssl if possible and start XMPP stream.
         Returns None or 'tcp' or 'tls', depending on the result."""
     if not server: server = (self.Server, self.Port)
     if proxy: sock = transports.HTTPPROXYsocket(proxy, server, use_srv)
     else: sock = transports.TCPsocket(server, use_srv)
     connected = sock.PlugIn(self)
     if not connected:
         sock.PlugOut()
         return
     self._Server, self._Proxy = server, proxy
     self.connected = 'tcp'
     if (ssl is None and self.Connection.getPort() in (5223, 443)) or ssl:
         try:  # FIXME. This should be done in transports.py
             transports.TLS().PlugIn(self, now=1)
             self.connected = 'ssl'
         except socket.sslerror:
             return
     dispatcher.Dispatcher().PlugIn(self)
     while self.Dispatcher.Stream._document_attrs is None:
         if not self.Process(1): return
     if self.Dispatcher.Stream._document_attrs.has_key(
             'version'
     ) and self.Dispatcher.Stream._document_attrs['version'] == '1.0':
         while not self.Dispatcher.Stream.features and self.Process(1):
             pass  # If we get version 1.0 stream the features tag MUST BE presented
     return self.connected
Пример #3
0
    def SASLHandler(self,conn,challenge):
        """ Perform next SASL auth step. Used internally. """
        if challenge.getNamespace()<>NS_SASL: return
        if challenge.getName()=='failure':
            self.startsasl='failure'
            try: reason=challenge.getChildren()[0]
            except: reason=challenge
            self.DEBUG('Failed SASL authentification: %s'%reason,'error')
            raise NodeProcessed
        elif challenge.getName()=='success':
            self.startsasl='success'
            self.DEBUG('Successfully authenticated with remote server.','ok')
            handlers=self._owner.Dispatcher.dumpHandlers()
            self._owner.Dispatcher.PlugOut()
            dispatcher.Dispatcher().PlugIn(self._owner)
            self._owner.Dispatcher.restoreHandlers(handlers)
            self._owner.User=self.username
            raise NodeProcessed
########################################3333
        incoming_data=challenge.getData()
        chal={}
        data=base64.decodestring(incoming_data)
        self.DEBUG('Got challenge:'+data,'ok')
        for pair in re.findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))',data):
            key,value=[x.strip() for x in pair.split('=', 1)]
            if value[:1]=='"' and value[-1:]=='"': value=value[1:-1]
            chal[key]=value
        if chal.has_key('qop') and 'auth' in [x.strip() for x in chal['qop'].split(',')]:
            resp={}
            resp['username']=self.username
            resp['realm']=self._owner.Server
            resp['nonce']=chal['nonce']
            cnonce=''
            for i in range(7):
                cnonce+=hex(int(random.random()*65536*4096))[2:]
            resp['cnonce']=cnonce
            resp['nc']=('00000001')
            resp['qop']='auth'
            resp['digest-uri']='xmpp/'+self._owner.Server
            A1=C([H(C([resp['username'],resp['realm'],self.password])),resp['nonce'],resp['cnonce']])
            A2=C(['AUTHENTICATE',resp['digest-uri']])
            response= HH(C([HH(A1),resp['nonce'],resp['nc'],resp['cnonce'],resp['qop'],HH(A2)]))
            resp['response']=response
            resp['charset']='utf-8'
            sasl_data=''
            for key in ['charset','username','realm','nonce','nc','cnonce','digest-uri','response','qop']:
                if key in ['nc','qop','response','charset']: sasl_data+="%s=%s,"%(key,resp[key])
                else: sasl_data+='%s="%s",'%(key,resp[key])
########################################3333
            node=Node('response',attrs={'xmlns':NS_SASL},payload=[base64.encodestring(sasl_data[:-1]).replace('\r','').replace('\n','')])
            self._owner.send(node.__str__())
        elif chal.has_key('rspauth'): self._owner.send(Node('response',attrs={'xmlns':NS_SASL}).__str__())
        else: 
            self.startsasl='failure'
            self.DEBUG('Failed SASL authentification: unknown challenge','error')
        raise NodeProcessed
Пример #4
0
 def StartTLSHandler(self, conn, starttls):
     if starttls.getNamespace() <> NS_TLS: return
     self.starttls = starttls.getName()
     if self.starttls == 'failure':
         self.DEBUG("Got starttls responce: " + self.starttls, 'error')
         return
     self.DEBUG("Got starttls proceed responce. Switching to SSL...", 'ok')
     self._startSSL()
     self._owner.Dispatcher.PlugOut()
     dispatcher.Dispatcher().PlugIn(self._owner)
Пример #5
0
def main():
    serial_port = os.getenv('LIBTHING_PORT', '/dev/ttyAMA0')
    baud_rate = 9600

    id_service = tags.DeploydTags('http://dev-laurip2.red-gate.com:2403/users')
    lib_service = books.DeploydBooks('http://10.120.200.158:2403/books')
    #lib_service = books.DeploydBooks('http://dev-laurip2.red-gate.com:2404/books')
    disp = dispatcher.Dispatcher(id_service, lib_service)
    ser = serializer.Serializer()
    serial = zigbee.ZigBee(serial_port, baud_rate, disp, ser)
    serial.run()
Пример #6
0
 def __init__(self):
     super().__init__()
     # window settings
     self.window_settings = {"view_grouped":True}
     # create instances
     self.dispatcher = Dispatcher.Dispatcher()
     self.visualization = Visualization.Visualization(self.dispatcher,self.window_settings)
     # get default values
     self.file_name_bom = self.dispatcher.get_cad_system().get_default_file()
     self.path_database = self.dispatcher.get_cad_system().get_default_directory()
     # buil UI
     self.init_ui()
Пример #7
0
 def StartTLSHandler(self, conn, starttls):
     """ Handle server reply if TLS is allowed to process. Behaves accordingly.
         Used internally."""
     if starttls.getNamespace()<>NS_TLS: return
     self.starttls=starttls.getName()
     if self.starttls=='failure':
         self.DEBUG("Got starttls response: "+self.starttls,'error')
         return
     self.DEBUG("Got starttls proceed response. Switching to TLS/SSL...",'ok')
     self._startSSL()
     self._owner.Dispatcher.PlugOut()
     dispatcher.Dispatcher().PlugIn(self._owner)
Пример #8
0
def main(stdscr):
    global menu_window, menu_panel, io_system, the_dispatcher

    curses.echo()
    panels = []
    menu_window = curses.newwin(2, (iosys.WINDOW_WIDTH + 2) * 2 + 3)
    menu_panel = curses.panel.new_panel(menu_window)
    menu_window.addstr(1, 0, "Stack of runnable processes")
    menu_window.addstr(1, iosys.WINDOW_WIDTH + 3, "Set of waiting processes")
    the_dispatcher = dispatcher.Dispatcher()
    io_system = iosys.IO_Sys(the_dispatcher, panels) # setup the windows
    the_dispatcher.set_io_sys(io_system)
    menu("(n)ew, (f)ocus, (t)op, (k)ill, (h)alt, (p)ause, (w)ait, (q)uit")
Пример #9
0
def main():
    _log("init")
    _log("main")
    # format = "[%(asctime)s][%(thread)-12s] %(message)s"
    # logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
    # logging.getLogger("main")
    # logging.info("Welcome")
    disp = dispatcher.Dispatcher()
    disp_thread = threading.Thread(target=disp.main)
    disp_thread.start()

    while True:
        time.sleep(1)
Пример #10
0
def train():

    # param_values = [v for v in parameters.values()]
    d = dispatcher.Dispatcher()
    model = d.get_model()
    print(f'model created on {d.device}')

    r = Run()
    e = Epoch()

    for run in r.get_runs(d.get_parameters()):

        # model = d.get_model()

        optimizer = optim.Adam(model.parameters(), lr=run.lr)
        batch_loader = d.get_data_batch(batch_size=run.bs)

        r.begin(run, model, batch_loader, device=d.device)
        for epoch in range(d.epochs):

            e.begin()
            for batch in batch_loader:

                images = batch[0].to(d.device)
                labels = batch[1].to(d.device)

                # images.to(d.device)
                # labels.to(d.device)

                preds = model(images)  # forward prop ==> get predictions
                loss = F.cross_entropy(preds, labels)  # calculate loss
                optimizer.zero_grad()  # zero the grads
                loss.backward()  # backward prop ==> calculate gradients
                optimizer.step()  # update weights

                e.track_loss(loss, run.bs)
                e.track_accuracy(preds, labels)

            # print(e.accuracy)
            e.end(run=r, model=model,
                  data=batch_loader)  ### continue from here

        r.end(e)
        print(
            f'#{r.count} lr: {run.lr}, bs: {run.bs} - accuracy: {e.accuracy} - run time: {r.duration}'
        )

    res_path = d.get_resource_path()
    r.save(fileName=f'{res_path}results')
    torch.save(model, f'{res_path}cnn1.pt')
Пример #11
0
    def _parseTLSStanza(self, stanza):
        """ Handle server reply if TLS is allowed to process. Behaves accordingly.
			Used internally.
		"""
        if stanza.getName() == "proceed":
            self.state = TLS_SUCCESS
            self.printf("Got starttls proceed response. Switching to TLS...",
                        "ok")
            self._startSSL()
            self._owner.Dispatcher.plugOut()
            dispatcher.Dispatcher().plugIn(self._owner)
        else:
            self.state = TLS_FAILURE
            self.printf("Got starttls response: %s" % (self.state), "error")
Пример #12
0
def start( my_app_name ):
    ''' 
        params  tuple q_name
                string my_app_name   
                      同一台机器 不可有两个相同进程的my_app_name相同 
                string mq_addr  rabbitmq的amqp格式的字符串
    '''
    q_name  = ( GROUP_NAME, my_app_name )
    mq_addr = MD_ADDR
    
    init(q_name, my_app_name)
    global MONITOR_RBT_WRITE
    MONITOR_RBT_WRITE = dispatcher.Dispatcher()
    MONITOR_RBT_WRITE.init( q_name, '', mq_addr, 'write')
Пример #13
0
 def connect(self, server=None, proxy=None):
     if not server: server = (self.Server, self.Port)
     if proxy:
         connected = transports.HTTPPROXYsocket(proxy, server).PlugIn(self)
     else:
         connected = transports.TCPsocket(server).PlugIn(self)
     if not connected: return
     self._Server, self._Proxy = server, proxy
     self.connected = 'tcp'
     if self.Connection.getPort() == 5223:
         transports.TLS().PlugIn(self, now=1)
         self.connected = 'tls'
     dispatcher.Dispatcher().PlugIn(self)
     while self.Dispatcher.Stream._document_attrs is None:
         self.Process(1)
     return self.connected
Пример #14
0
	def connect(self, secureMode=SECURE_DISABLE, useResolver=True):
		""" Connect to jabber server. If you want TLS/SSL support to be discovered and enable automatically, 
			set third argument as SECURE_AUTO (SSL will be autodetected only if port is 5223 or 443)
			If you want to force SSL start (i.e. if port 5223 or 443 is remapped to some non-standard port) then set it to SECURE_FORCE.
			If you want to disable TLS/SSL support completely, set it to SECURE_DISABLE.
			Returns None or "TCP", "SSL" "TLS", depending on the result.
		"""
		sock = transports.TCPSocket(useResolver)
		connectType = sock.plugIn(self)
		if not connectType: 
			sock.plugOut()
			return None
		self.connectType = C_TCP
		isSSLPort = self.port in (5223, 443)
		if (secureMode == SECURE_AUTO and isSSLPort) or secureMode == SECURE_FORCE:
			# FIXME. This should be done in transports.py
			try:
				transports.TLS().plugIn(self, forceSSL=True)
				self.connectType = C_SSL
			except socket.sslerror:
				self.TLS.PlugOut()
				return None
		dispatcher.Dispatcher().plugIn(self)
		while self.Dispatcher.stream._document_attrs is None:
			if not self.process(1):
				return None
		# If we get version 1.0 stream the features tag MUST BE presented
		if self.Dispatcher.stream._document_attrs.get("version") == "1.0":
			while not self.Dispatcher.features and self.process(1):
				pass
		if secureMode == SECURE_AUTO and not isSSLPort:
			# If we get version 1.0 stream the features tag MUST BE presented
			if self.Dispatcher.stream._document_attrs.get("version") == "1.0":
				transports.TLS().plugIn(self)
				if transports.TLS_UNSUPPORTED == self.TLS.state:
					self.TLS.PlugOut()
					return self.connectType
				while not self.TLS.state and self.process(1):
					pass
				if self.TLS.state != transports.TLS_SUCCESS:
					self.TLS.plugOut()
					return None
				self.connectType = C_TLS
		return self.connectType
Пример #15
0
def main(stdscr):

    # ALL processes have some iosys and dispatcher
    global menu_window, menu_panel, io_system, the_dispatcher

    curses.echo()
    panels = []
    menu_window = curses.newwin(2, (iosys.WINDOW_WIDTH + 2) * 2 + 3)
    menu_panel = curses.panel.new_panel(menu_window)
    menu_window.addstr(1, 0, "Stack of runnable processes")
    menu_window.addstr(1, iosys.WINDOW_WIDTH + 3, "Set of waiting processes")

    # assigns a dispatcher object
    the_dispatcher = dispatcher.Dispatcher()

    # assigns the dispatcher to the iosys object. Also assigns the panels to allow manipulation
    io_system = iosys.IO_Sys(the_dispatcher, panels)  # setup the windows

    # give the dispatcher an iosys
    the_dispatcher.set_io_sys(io_system)
    menu("(n)ew, (f)ocus, (t)op, (k)ill, (h)alt, (p)ause, (w)ait, (q)uit")
Пример #16
0
def main():
    """Initialize GPIO and SPI and start clock functions."""

    if initialize() == 0:
        soc.bcm2835_close()
        sys.exit(1)

    clock_driver = dsp.Dispatcher(parameter_init)

    clock_driver.register('watchdog', watchdog, 4)
    clock_driver.register('time_display', time_display, 1)
    clock_driver.register('configuration', get_clock_config, 600)

    #clock_driver.show()

    while True:
        clock_driver.dispatch()

    # Will not get here ever
    soc.bcm2835_close()
    sys.exit(0)
Пример #17
0
    def __init__(self):

        h = Gdk.Screen().height()
        w = Gdk.Screen.width()

        Gtk.Window.__init__(self, title="Gitmarks")
        self.props.resizable = True
        self.props.default_width = w / 3
        self.props.default_height = h
        self.status_bar = Gtk.Statusbar.new()
        self.tree_view = None
        self.item_list = None

        gm_dispatcher = dispatcher.Dispatcher()
        ofh = OpenFileHandler(self, self.status_bar, gm_dispatcher)
        handlers = [ofh]
        gm_dispatcher.load_handlers(handlers)

        self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
        self.hbox = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)

        self.add(self.vbox)

        hb_factory = widgets.HeaderBar(gm_dispatcher)
        header_bar = hb_factory.make_headerbar("Gitmarks")
        self.profile_label = hb_factory.get_profile_label()
        self.set_titlebar(header_bar)

        self.vbox.pack_start(self.hbox, True, True, 0)
        self.vbox.pack_end(self.status_bar, False, True, 0)
        self.connect("delete-event", Gtk.main_quit)

        self.gio_settings = settings.GitmarksSettings().create_gio_settings(
            GLib.get_current_dir())

        if self.init_settings() is None:
            sys.exit(0)
Пример #18
0
def configure_and_start_server(config, options=None):
    """
    Configure and start the server.
    Command line options always take advantage over configuration read from file.
    The file is a way to define default command line options

    :param config: Configuration read from file
    :param options: option read from command line
    """

    ################################################################################################
    #                                           socket init                                        #
    ################################################################################################
    s = socket()                                    # Create a socket object
    #host = gethostname()            th                # Get local machine name
    host = gethostbyname(config['server_address'])
    #s.bind((host, int(config['port'])))             # Bind to the port
    s.bind((host, int(config['port'])))
    buffer_size = int(config['buffer_size'])        # sizing the buffer for reading from socket
    max_connection = int(config['max_connection'])  # define the max concurrent connection supported by the server

    s.listen(max_connection)      # Now wait for client connection.
    liblogging.log("Server is now waiting for connection", liblogging.INFO)

    ################################################################################################
    #                                           socket start                                       #
    ################################################################################################
    while True:
        c, addr = s.accept()     # Establish connection with client.
        liblogging.log("Got connection from (%s, %s)" % addr)
        c.send("cE %s\n" % config['msg_banner'])
        client_thread = dispatcher.Dispatcher(c, addr, buffer_size, options)
        client_thread.setDaemon(True)
        client_thread.start()

        #thread.start_new_thread(handler, (c, addr, buffer_size))
        # c.close()                # Close the connection
Пример #19
0
    def looper(self, args):
        except_count = 0
        history_file = '.hpirhist'
        exit_val = EXIT_OK
        d = None

        try:
            log.set_log_level(args.log)
            read_history_file(history_file)

            d = dispatcher.Dispatcher(args)
            d.start_transport()

            while not d.is_done():
                try:
                    d.read_and_exec()
                    except_count = 0
                except:
                    except_count += 1
                    log.i('') # Ensure the following error message starts on a new line.
                    log.e('{} : {}'.format(sys.argv[0], sys.exc_info()[1]))
                    if d.is_trace_on_error():
                        print traceback.format_exc()
                    if (except_count >= 2) or d.is_exit_on_error():
                        exit_val = EXIT_ERR
                        d.force_done()

            write_history_file(history_file)
        except:
            exit_val = EXIT_ERR
            print traceback.format_exc()
        finally:
            if d:
                d.stop_transport()

        return exit_val
Пример #20
0
        if done:
            self.dispatch.stop()
            self.env.reset()

            self.solver.experience_replay(iteration, self.episodes)

            self.solver.save_model()
            if (self.episodes % 2 == 0):
                self.solver.update_model()

            self.episodes += 1


# #######################
# # Main control center #
# #######################

# This object centralizes everything
theDispatcher = dispatcher.Dispatcher()

# Provide a new environment (maze + agent)
theDispatcher.setEnvironment(env.Environment(12, 8, 15))

# Provide also the simulation stepper, which needs access to the
# agent and maze in the dispatcher.
theDispatcher.setStepper(TrainSolver(theDispatcher))

# Start the GUI and run it until quit is selected
# (Remember Ctrl+\ forces python to quit, in case it is necessary)
theDispatcher.run()
Пример #21
0
def make_schedule():
    mon_wed_fri = {
        'dates': [0, 2, 4],
        'times':
        [datetime.time(hour=10, minute=00),
         datetime.time(hour=18, minute=00)],
        'param':
        0
    }
    tue_thu_sat = {
        'dates': [1, 3, 5],
        'times':
        [datetime.time(hour=9, minute=00),
         datetime.time(hour=17, minute=00)],
        'param':
        0
    }
    thu_sun = {
        'dates': [3, 6],
        'times':
        [datetime.time(hour=22, minute=40),
         datetime.time(hour=14, minute=00)],
        'param':
        0
    }
    every_third_day = {
        'dates': [x for x in range(0, 31, 3)],
        'times': [
            datetime.time(hour=16, minute=25),
        ],
        'param': 1
    }
    every_fifth_day = {
        'dates': [x for x in range(0, 31, 5)],
        'times': [
            datetime.time(hour=8, minute=45),
        ],
        'param': 1
    }
    every_tenth_day = {
        'dates': [x for x in range(0, 31, 10)],
        'times': [
            datetime.time(hour=10, minute=00),
        ],
        'param': 1
    }
    flies_schedule = {
        'mon_wed_fri': dispatcher.Dispatcher(mon_wed_fri).make_fly_dates(),
        'tue_thu_sat': dispatcher.Dispatcher(tue_thu_sat).make_fly_dates(),
        'thu_sun': dispatcher.Dispatcher(thu_sun).make_fly_dates(),
        'every_third_day':
        dispatcher.Dispatcher(every_third_day).make_fly_dates(),
        'every_fifth_day':
        dispatcher.Dispatcher(every_fifth_day).make_fly_dates(),
        'every_tenth_day':
        dispatcher.Dispatcher(every_tenth_day).make_fly_dates()
    }

    departures = {
        'Москва': {
            'Лондон': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Берлин': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
            'Париж': flies_schedule['thu_sun'],  # чт вс 22:40 14:00
            'Мадрид': flies_schedule['every_fifth_day'],
            # 5 10 15 20 25 30 числа каждого месяца в 8:45
            'Мюнхен': flies_schedule[
                'every_tenth_day'],  # 10 20 30 числа каждого месяца в 8:00
            'Рим': flies_schedule['every_third_day'],  # каждые 3 дня в 16:25
        },
        'Лондон': {
            'Москва': flies_schedule['thu_sun'],  # чт вс 14:00 22:40
            'Берлин': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Париж': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
            'Мадрид': flies_schedule['every_third_day'],  # каждые 3 дня
            'Мюнхен': flies_schedule['every_fifth_day'],
            # 5 10 15 20 25 30 числа каждого месяца в 8:45
        },
        'Берлин': {
            'Лондон': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
            'Москва': flies_schedule['thu_sun'],  # чт вс 14:00 22:40
            'Париж': flies_schedule[
                'every_tenth_day'],  # 10 20 30 числа каждого месяца в 8:00
            'Мюнхен': flies_schedule['every_third_day'],  # каждые 3 дня
            'Рим': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
        },
        'Париж': {
            'Лондон': flies_schedule['thu_sun'],  # чт вс 14:00 22:40
            'Берлин': flies_schedule[
                'every_tenth_day'],  # 10 20 30 числа каждого месяца в 8:00
            'Москва': flies_schedule['every_third_day'],  # каждые 3 дня
            'Мадрид': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Мюнхен': flies_schedule['every_fifth_day'],
            # 5 10 15 20 25 30 числа каждого месяца в 8:45
            'Рим': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
        },
        'Мадрид': {
            'Лондон': flies_schedule['every_third_day'],  # каждые 3 дня
            'Берлин': flies_schedule['thu_sun'],  # чт вс 14:00 22:40
            'Париж': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Москва': flies_schedule[
                'every_tenth_day'],  # 10 20 30 числа каждого месяца в 8:00
            'Мюнхен': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
        },
        'Мюнхен': {
            'Лондон': flies_schedule[
                'every_tenth_day'],  # 10 20 30 числа каждого месяца в 8:00
            'Берлин': flies_schedule['every_fifth_day'],
            # 5 10 15 20 25 30 числа каждого месяца в 8:45
            'Париж': flies_schedule['thu_sun'],  # чт вс 14:00 22:40
            'Мадрид': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
            'Москва': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Рим': flies_schedule['every_third_day'],  # каждые 3 дня
        },
        'Рим': {
            'Берлин': flies_schedule['thu_sun'],  # чт вс 22:40 14:00
            'Париж': flies_schedule['every_fifth_day'],
            # 5 10 15 20 25 30 числа каждого месяца в 8:45
            'Мадрид': flies_schedule['tue_thu_sat'],  # вт чт сб 9:00 17:00
            'Мюнхен': flies_schedule['mon_wed_fri'],  # пн ср пт 10:00 18:00
            'Москва': flies_schedule['every_third_day'],  # каждые 3 дня
        },
    }

    with open('schedule.json', 'w', encoding='UTF8') as file:
        json.dump(departures, file, indent=4)
Пример #22
0
#coding=gbk
''' 消息模块 '''
import dispatcher
import zlog as logging

import XmlConfig

GROUP_NAME    =  XmlConfig.get("/xml/Server_name/group_name")["value"]

LOCAL_ADDR    =  XmlConfig.get("/xml/Server_addr/local_addr")["value"]

MD_ADDR       =  XmlConfig.get("/xml/Server_addr/md_addr")["value"]

message_read  = dispatcher.Dispatcher()
message_write = dispatcher.Dispatcher()



def regist( server_name ):
    #初始化 
    logging.info( '注册地址为:%s'%str( (GROUP_NAME, server_name)) )
    ret = message_read.init( ( GROUP_NAME, server_name ), LOCAL_ADDR, MD_ADDR , 'read')
    if ret == 1:    
        logging.info( 'regist sucess!' )
    else:
        return False
                
    ret = message_write.init( ( GROUP_NAME, server_name ), LOCAL_ADDR, MD_ADDR , 'write')
    
    if ret == 1:
        logging.info( 'regist sucess!' )
Пример #23
0
    def _parseAuthStanza(self, stanza):
        """ Perform next SASL auth step. Used internally.
		"""
        if stanza.getXMLNS() != protocol.NS_SASL:
            return
        if stanza.getName() == "failure":
            self.state = AUTH_FAILURE
            reason = stanza.getFirstChild() or stanza
            self.printf("Failed SASL authentification: %s" % (reason), "error")
            raise protocol.NodeProcessed
        elif stanza.getName() == "success":
            self.state = AUTH_SUCCESS
            self.printf("Successfully authenticated with remote server", "ok")
            handlers = self._owner.Dispatcher.dumpHandlers()
            self._owner.Dispatcher.plugOut()
            dispatcher.Dispatcher().plugIn(self._owner)
            self._owner.Dispatcher.restoreHandlers(handlers)
            self._owner._user = self.username
            raise protocol.NodeProcessed

        incoming_data = stanza.getData()
        chal = {}
        data = base64.decodestring(incoming_data)
        self.printf("Got challenge: %s" % (data), "ok")
        for pair in re.findall(r'(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))', data):
            key, value = [x.strip() for x in pair.split("=", 1)]
            if value[:1] == "\"" and value[-1:] == "\"":
                value = value[1:-1]
            chal[key] = value
        if "qop" in chal and "auth" in [
                x.strip() for x in chal["qop"].split(", ")
        ]:
            resp = {}
            resp["username"] = self.username
            resp["realm"] = self._owner.server
            resp["nonce"] = chal["nonce"]
            cnonce = ""
            for i in range(7):
                cnonce += hex(int(random.random() * 65536 * 4096))[2:]
            resp["cnonce"] = cnonce
            resp["nc"] = ("00000001")
            resp["qop"] = "auth"
            resp["digest-uri"] = "xmpp/" + self._owner.server
            A1 = C([
                H(C([resp["username"], resp["realm"], self.password])),
                resp["nonce"], resp["cnonce"]
            ])
            A2 = C(["AUTHENTICATE", resp["digest-uri"]])
            response = HH(
                C([
                    HH(A1), resp["nonce"], resp["nc"], resp["cnonce"],
                    resp["qop"],
                    HH(A2)
                ]))
            resp["response"] = response
            resp["charset"] = "utf-8"
            data = ""
            for key in ("charset", "username", "realm", "nonce", "nc",
                        "cnonce", "digest-uri", "response", "qop"):
                if key in ("nc", "qop", "response", "charset"):
                    data += "%s=%s, " % (key, resp[key])
                else:
                    data += "%s=\"%s\", " % (key, resp[key])
            data = base64.encodestring(data[:-1]).replace("\r", "").replace(
                "\n", "")
            node = protocol.Node("response", attrs={"xmlns": protocol.NS_SASL})
            node.setData(data)
            self._owner.send(node.__str__())
        elif "rspauth" in chal:
            self._owner.send(
                protocol.Node("response", attrs={
                    "xmlns": protocol.NS_SASL
                }).__str__())
        else:
            self.state = AUTH_FAILURE
            self.printf("Failed SASL authentification: unknown challenge",
                        "error")
        raise protocol.NodeProcessed
Пример #24
0
 def __init__(self, protocol, message_types, socket, addr):
     self.connection = connection.Connection(protocol, socket, addr)
     self.sender = sender.Sender(self.connection, message_types)
     self.dispatcher = dispatcher.Dispatcher(message_types)
Пример #25
0
 def get_dispatcher(cls):
     if not cls._dispatcher:
         cls._dispatcher = dispatcher.Dispatcher()
     return cls._dispatcher
Пример #26
0
#coding=gbk
''' ÏûϢģ¿é '''
import dispatcher
import time
import JsonUtil as json

message_write  = dispatcher.Dispatcher()
message_write.init( ( 'F**K', 'FUCK001' ), '', 'amqp://192.168.0.252:5672/' , 'read')
num = 10000

st_time = time.time()
for i in range(num):
    message_write.send( ('F**K','FUCK001'), json.write('f**k'), 0 )

en_time = time.time()

print (en_time - st_time)/num 
Пример #27
0
 def __init__(self, token, url):
     self.token = token
     self.url = url
     self.coordinator = dispatcher.Dispatcher()
     return
Пример #28
0
    def __init__(self, parent=None):
        super(Protocol, self).__init__(parent)

        # -- Read settings --
        smhost = rigsettings.STATE_MACHINE_SERVER

        # -- Add widgets --
        self.dispatcher = dispatcher.Dispatcher(host=smhost, connectnow=False)
        self.savedata = savedata.SaveData()
        self.params = []
        for ind in range(6):
            self.params.append(
                paramgui.NumericParam('Param%d' % ind, value=1.1 * ind))
        self.param3 = paramgui.MenuParam('MenuParam', ('One', 'Two', 'Three'))
        self.evplot = eventsplot.EventsPlot()

        layoutMain = QtGui.QVBoxLayout()
        layoutTop = QtGui.QVBoxLayout()
        layoutBottom = QtGui.QHBoxLayout()
        layoutCol0 = QtGui.QVBoxLayout()
        layoutCol1 = QtGui.QVBoxLayout()
        layoutCol2 = QtGui.QVBoxLayout()
        groupBox1 = QtGui.QGroupBox('Group 1')
        layoutBox1 = QtGui.QVBoxLayout()

        layoutMain.addLayout(layoutTop)
        layoutMain.addStretch()
        layoutMain.addLayout(layoutBottom)

        layoutTop.addWidget(self.evplot)
        layoutBottom.addLayout(layoutCol0)
        layoutBottom.addLayout(layoutCol1)
        layoutBottom.addLayout(layoutCol2)
        #layoutBottom.setStretch(0,1)
        #layoutBottom.setStretch(1,0)

        layoutCol0.addWidget(self.savedata)
        layoutCol0.addWidget(self.dispatcher)
        #layoutCol2.addStretch()
        layoutCol2.addWidget(groupBox1)
        groupBox1.setLayout(layoutBox1)
        for param in self.params:
            layoutBox1.addWidget(param)
        layoutBox1.addWidget(self.param3)
        self.setLayout(layoutMain)

        # -- Set state matrix --
        tmin = 0.001  # Very small time
        Sdur = 0.2  # Duration of sound
        RewAvail = 4  # Length of time reward is available
        Rdur = 0.1  # Duration of reward
        Lw = rigsettings.LEFT_WATER  # Left water valve
        Rw = rigsettings.RIGHT_WATER  # Right water valve
        #Corr =
        #Err  =
        '''
        mat = []
        #           Ci  Co  Li  Lo  Ri  Ro  Tout  t  CONTo TRIGo
        mat.append([ 0,  0,  0,  0,  0,  0,  2, tmin,  0,   0   ]) # 0: State 0
        mat.append([ 1,  1,  1,  1,  1,  1,  1,   0,   0,   0   ]) # 1: PrepareNextTrial
        mat.append([ 3,  2,  2,  2,  2,  2,  2,   0,   0,   0   ]) # 2: WaitForCpoke
        mat.append([ 3,  3,  3,  3,  3,  3,  4, Sdur,  1,   1   ]) # 3: PlayTarget
        mat.append([ 4,  4,  5,  4,  1,  4,  1, Tout,  0,   0   ]) # 4: WaitForApoke
        mat.append([ 5,  5,  5,  5,  5,  5,  1, Rdur, Lw,   0   ]) # 5: Reward
        '''

        sm = statematrix.StateMatrix(readystate=('ready_next_trial', 1))
        sm.addState(name='wait_for_cpoke',
                    selftimer=4,
                    transitions={'Cin': 'play_target'})
        sm.addState(name='play_target',
                    selftimer=Sdur,
                    transitions={
                        'Cout': 'wait_for_apoke',
                        'Tout': 'wait_for_apoke'
                    },
                    actions={'DOut': 7})
        sm.addState(name='wait_for_apoke',
                    selftimer=RewAvail,
                    transitions={
                        'Lin': 'reward',
                        'Rin': 'punish',
                        'Tout': 'ready_next_trial'
                    })
        sm.addState(name='reward',
                    selftimer=Rdur,
                    transitions={'Tout': 'ready_next_trial'},
                    actions={'DOut': 2})
        sm.addState(name='punish',
                    selftimer=Rdur,
                    transitions={'Tout': 'ready_next_trial'},
                    actions={'DOut': 4})

        #prepareNextTrialStates = ('ready_next_trial','reward','punish')
        prepareNextTrialStates = ('ready_next_trial')
        self.dispatcher.setPrepareNextTrialStates(prepareNextTrialStates,
                                                  sm.getStatesDict())
        self.dispatcher.setStateMatrix(sm.getMatrix())

        # QUESTION: what happens if signal 'READY TO START TRIAL'
        #           is sent while on JumpState?
        #           does it jump to new trial or waits for timeout?

        print sm

        # -- Setup events plot --
        #self.evplot.setStatesColor(np.random.rand(6))
        '''
        statesColor = [ [255,0,0],[0,255,0],[0,0,255],\
                        [255,255,0],[255,0,255],[0,255,255] ]  
        self.evplot.setStatesColor(statesColor)
        '''
        statesColorDict = {
            'wait_for_cpoke': [127, 127, 255],
            'play_target': [255, 255, 0],
            'wait_for_apoke': [191, 191, 255],
            'reward': [0, 255, 0],
            'punish': [255, 0, 0],
            'ready_next_trial': [0, 0, 0]
        }
        self.evplot.setStatesColor(statesColorDict, sm.getStatesDict())

        # -- Connect signals from dispatcher --
        self.connect(self.dispatcher, QtCore.SIGNAL('PrepareNextTrial'),
                     self.prepareNextTrial)
        self.connect(self.dispatcher, QtCore.SIGNAL('StartNewTrial'),
                     self.startNewTrial)
        self.connect(self.dispatcher, QtCore.SIGNAL('TimerTic'), self.timerTic)
Пример #29
0
            self._lock.acquire()
            self._isRelease = False

    def release(self):
        self._lock.release()
        self._isRelease = True

    def __del__(self):
        if not self._isRelease :
            self._lock.release()

import dispatcher

from Config import *

msg_queue_rec = dispatcher.Dispatcher()
msg_queue_send = dispatcher.Dispatcher()
local_address = None

def init(serv_name):
    global local_address
    local_address = (LOCAL_GROUP_NAME, serv_name)
    logging.info( "local_address = %s"%str(local_address) )
    msg_queue_send.init(local_address, LOCAL_IP, MD_ADDRESS, 'write')
    return msg_queue_rec.init(local_address, LOCAL_IP, MD_ADDRESS, 'read')

def receive( timeout=0 ):
    group, name, data = msg_queue_rec.receive(timeout)
    if None != data:
        logging.info( "receive from %s, msg is %s"%( (group, name), data ) )
    return group, name, data
Пример #30
0
                           Attr(name='url', selector='.usernameLink',
                                parse_func=sel_attr, func_kws={'attr': 'href'}),
                       ], getter=Getter(suffix='/subscriptions')),
            ]),
    Phase(templates=[
        Template(name='user',
                        store=StoreObject(
                            store_func=store_mongo, func_kws={'db': 'pornhub', 'collection': 'users'}),
                        attrs=[
                            Attr(name='url', selector='.profileUserName', parse_func=sel_attr,
                                        func_kws={'attr': 'href'})
                        ])
        Template(name='subscription', selector='.userWidgetWrapperGrid',
                        attrs=[
                            Attr(name='urls', selector='.userLink',
                                         parse_func=sel_attr, func_kws={'attr': 'href'}),
                        ], store=StoreObject(store_func=store_mongo,
                                                    func_kws={'db': 'pornhub', 'collection': 'users',
                                                              'query':

                        )
    ])

        ]
        )

disp = dispatcher.Dispatcher()
disp.add_scraper(marktplaats)

disp.run()