コード例 #1
0
ファイル: bot.py プロジェクト: bbrouse/mumble-bots
  def on_channel_state(self, msg):
    if msg.channel_id not in self.channels_by_id:
      chan = Channel(self.bot, msg.channel_id)
      self.channels_by_id[msg.channel_id] = chan
    else:
      chan = self.channels_by_id[msg.channel_id]
    chan.update(msg)

    if msg.parent == msg.channel_id:
      if not msg.channel_id == 0:
        LOGGER.warning('Root channel not ID 0.')
      if self.root and self.root != chan:
        LOGGER.error('Received 2 different roots...?')
        raise Exception('Two roots.')
      self.root = chan
    elif chan.parent:
      if chan.parent.id != msg.parent:
        chan.parent.remove_child(chan)
        self.channels_by_id[msg.parent].add_child(chan)
    else:
      if not msg.parent in self.channels_by_id:
        LOGGER.error('Parent ID passed by server is not in the channel list.')
        raise Exception('Invalid Parent.')
      self.channels_by_id[msg.parent].add_child(chan)
    print msg
コード例 #2
0
ファイル: server.py プロジェクト: TheKipmaster/lab2redes
    def __init__(self):
        # Estruturas de clientes e canais
        self.clients = {}
        self.canais = {}

        self.canais["Canal 1"] = Channel("Canal 1")
        self.canais["Canal 2"] = Channel("Canal 2")
        self.canais["Canal 3"] = Channel("Canal 3")
        # Handlers para comandos
        self.handlers = {
            "NICK": self.nickClientHandler,
            "USUARIO": self.userClientHandler,
            "SAIR": self.quitClientHandler,
            "ENTRAR": self.subscribeChannelHandler,
            "SAIRC": self.quitChannelHandler,
            "LISTAR": self.listChannelHandler,
        }

        # requisita API do SO uma conexão AF_INET (IPV4) com protocolo de transporte SOCK_STREAM (TCP)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # requisita ao SO a posse de uma porta associada a um IP
        self.sock.bind((host, port))

        # requisita ao SO que a porta indicada de um dado IP seja reservado para escuta
        self.sock.listen(5)

        print("Conexão aberta porta: ", port)

        self.run()
コード例 #3
0
def single_compute(centroid, fn):
    map_func = lambda x: centroid[tuple(x)]
    mean_Es = np.average([np.sum(np.square(x)) for x in list(centroid.values())])

    ber_vals = []
    # EbN0 values
    for EbN0 in ebn0_values:
        # calculate N0 value to meet Eb/N0 requirement and add noise to sample
        EbN0_lin = 10**(0.1*EbN0)
        power = mean_Es/(EbN0_lin*n_bits)
        # Define channel
        channel = Channel(power)
        # Modulate signal
        mod_preamble = np.array(list(map(map_func, PREAMBLE)))
        mod_message = np.array(list(map(map_func, MESSAGE)))
        # Noisy signal
        mod_preamble_n = channel.AWGN(mod_preamble)
        mod_message_n = channel.AWGN(mod_message)
        # Demodulate signal
        demod_message = util.centroid_mapping(mod_preamble_n, PREAMBLE, mod_message_n)
        # Compute BER
        ber = np.sum(np.linalg.norm(demod_message - MESSAGE, ord=1, axis=1)) / (TEST_LEN*n_bits)
        # Add to list
        ber_vals.append(str(ber))
        print("    EbN0: %8f, ber: %8f" % (EbN0, ber))

    print("    done")

    with open(fn, "w") as f:
        f.write(init_string + ",".join(ber_vals) + "\n")
コード例 #4
0
ファイル: main.py プロジェクト: GeneFerneau/gc
def main():
    ### (Optional) Replace these addresses with others
    id_a = Id('e12048ff037a0f15bcf977c86181828f5e05dbfe6cf2efe9af6362c8d53a00b0') # addr: mwZ5RAPyv7NxHeeqq2zFo8xngHqWiB4Urb
    id_b = Id('e12048ff047a0f15bcf977c86171828f5e05dbfe6cf2efe9af6362c8d53a00b4') # addr: mgUd1ycGZ7GW66XqdjDFkhGNHmf38b6ATL

    ### Change these inputs to unspent transaction outputs, given the transaction id and the output index
    tx_in1 = TxInput('72ad77c50666676d0ca0a1f395a3ee4ba00acbaad9bcb281892c5ab2a78ff11c', 1) # A in ai
    tx_in2 = TxInput('f6e382f958dbf2e89303e16e4052185e8a30bd97517abc7d498f9c07260848bf', 0) # I in ai

    ### Change these values to carry the same amount as the outputs specified above
    val_a = 0.01
    val_b = 0.01985
    # Transaction fee
    fee = 0.00005

    # create channel between AB
    if lightning:
        print('TESTING LIGHTNING CHANNELS:')
        c_ab = Channel.from_inputs(id_a, id_b, tx_in1, tx_in2, val_a, val_b, fee, LIGHTNING_STATE)
    else:
        print('TESTING GENERALIZED CHANNELS:')
        c_ab = Channel.from_inputs(id_a, id_b, tx_in1, tx_in2, val_a, val_b, fee, GENERALIZED_STATE)
    print_tx(c_ab.ft, 'FT_AB')
    for name, tx in c_ab.state.get_state_transactions():
        print_tx(tx, name)

    c_ab.close(val_a, val_b)
    print_tx(c_ab.close_tx, 'FT_AB close')
コード例 #5
0
    def __init__(self):
        super().__init__()

        dial = ConnectDialog(self)
        dial.exec()

        # tmp!!!!! TODO:
        try:
            self.channel = Channel('192.168.1.11',
                                   8000 + int(dial.port_field.text()), '69420')
        except ValueError as _:
            self.channel = Channel('192.168.1.11', 8000, '69420')

        # self.channel = Channel(dial.host_field.text(), dial.port_field.text(), dial.password_field.text())

        self.move_buttons = dict()
        self.light_buttons = dict()
        self.distance_label = None
        self.speed_label = None
        self.line_label = None

        self.place_move_buttons()
        self.place_light_buttons()
        self.place_labels()

        self.widget_update_signal.connect(self.update_widgets)
        self.lock = Lock()
        self.update_active = True

        Thread(target=self.supervise_update).start()
コード例 #6
0
    def test_get_how_many_days_ago_was_creation_7_days_ago(self):
        """should return 7 when the current date and the creation date are 
        7 days apart"""
        test_channel = Channel("My Ballad", "John Henry")
        test_channel.creation_time = datetime.today() - timedelta(7)

        self.assertEqual(test_channel._get_how_many_days_ago_was_creation(), 7)
コード例 #7
0
    def test_get_how_many_days_ago_was_creation_yesterday(self):
        """should return 1 if the creation day is the day before the current 
        day"""
        test_channel = Channel("Kérsz Taslit?", "Zuboly")
        test_channel.creation_time = datetime.today() - timedelta(1) 

        self.assertEqual(test_channel._get_how_many_days_ago_was_creation(), 1)
コード例 #8
0
    def test_get_how_many_days_ago_was_creation_6_days_ago(self):
        """should return 6 when the current date and the creation date are 
        6 days apart"""
        test_channel = Channel("Black Rock", "Joe Bonamassa")
        test_channel.creation_time = datetime.today() - timedelta(6)

        self.assertEqual(test_channel._get_how_many_days_ago_was_creation(), 6)
コード例 #9
0
    def test_get_day_of_creation_from_yesterday(self):
        """should return 'yesterday' if the creation date is a day before the
        current date"""
        test_channel = Channel("Cream", "Strange Brew")
        test_channel.creation_time = datetime.today() - timedelta(1)

        self.assertEqual(test_channel._get_day_of_creation(), "yesterday")
コード例 #10
0
    def test_get_time_of_creation_afternoon(self):
        """should return the creation time in the '24H' format"""
        test_channel = Channel("Scenes From a Memory", "Dream Theater")
        test_channel.creation_time = datetime.fromisoformat(
            '2020-02-10 14:30:00.000')

        self.assertEqual(test_channel._get_time_of_creation(), "14:30")
コード例 #11
0
    def subscribe(self, icepap_addr, signal_name):
        """
        Creates a new subscription for signal values.

        icepap_addr - IcePAP driver number.
        signal_name - Signal name.
        Return - A positive integer id used when unsubscribing.
        """
        for ch in self.channels_subscribed.values():
            if ch.equals(icepap_addr, signal_name):
                msg = 'Channel already exists.\nAddr: ' \
                      '{}\nSignal: {}'.format(icepap_addr, signal_name)
                raise Exception(msg)
        channel = Channel(icepap_addr, signal_name)
        sn = QString(signal_name)
        cond_1 = sn.endsWith('Tgtenc')
        cond_2 = sn.endsWith('Shftenc')
        cond_3 = sn == 'DifAxMeasure'
        if cond_1 or cond_2 or cond_3:
            try:
                cfg = self.icepap_system[icepap_addr].get_cfg()
            except RuntimeError as e:
                msg = 'Failed to retrieve configuration parameters ' \
                      'for driver {}\n{}.'.format(icepap_addr, e)
                raise Exception(msg)
            if (cond_1 and cfg['TGTENC'].upper() == 'NONE') or \
                    (cond_2 and cfg['SHFTENC'].upper() == 'NONE'):
                msg = 'Signal {} is not mapped/valid.'.format(sn)
                raise Exception(msg)
            if cond_3:
                channel.set_measure_resolution(cfg)
        self.channel_id += 1
        self.channels_subscribed[self.channel_id] = channel
        return self.channel_id
コード例 #12
0
ファイル: node.py プロジェクト: pylots/raft
 def run(self):
     logger.info(
         f'{self.index}: ClientQueue running, connect to {self.address}')
     self.retry = 0
     while True:
         self.channel = Channel(self.index)
         try:
             self.channel.connect(self.address)
         except Exception as e:
             logger.error(f'{self.index}: Channel connect exception {e}')
             continue
         logger.debug(f'{self.index}: Connected to {self.address}')
         message = None
         self.retry = 0
         while self.retry < 5:
             if not message:
                 message = self.queue.get()
             try:
                 self.channel.send(message)
                 message = None
                 self.retry = 0
                 continue
             except Exception as e:
                 logger.warning(
                     f'Exception sending: {message} {e} retry={self.retry}')
                 self.retry += 1
コード例 #13
0
ファイル: iface.py プロジェクト: Abengochea/Simu
    def __init__(self, node, num):
        self.node = node
        self.id = node.id + '.' + num
        self.running = True
        self.channel = Channel()

        self.link = None
コード例 #14
0
def GetAllChannelsTest():
    plex = getServer()
    # searchParams = {}
    # searchParams["studio"] = "TV Tokyo"
    # channel = searchShow(plex, 'Anime', **searchParams)

    indir = 'channels'
    for root, dirs, filenames in os.walk(indir):
        for f in filenames:
            channel = Channel(indir + '/' + f)
            searchParams = {}
            genParams = channel.getGeneralParams()
            for d in genParams:
                if d != 'library' and d != 'show_block':
                    searchParams[d] = genParams[d]
            # library = searchParams['library']
            # del searchParams["library"]
            # del searchParams["show_block"]
            shows = searchShow(plex, genParams['library'], **searchParams)
            show = shows[0]
            # show = shows[random.randint(0,len(shows)-1)]
            episodes = getEpisodeBlock(plex, genParams['library'], show.title,
                                       genParams['show_block'])
            print(episodes)
            print("Channel: %s\nDescription: %s" %
                  (channel.title, channel.description))
            for e in episodes:
                print(
                    "%s %s: %s\n%s\n" %
                    (e.grandparentTitle, e.seasonEpisode, e.title, e.summary))
コード例 #15
0
 def test_5_channel_name_taken(self):
     """channel_name_taken test: channel list with more entries"""
     self.setup_channels_list_with([Channel("roger", "Pink"), 
                                    Channel("dave", "Pink"),
                                    Channel("rick", "Pink"),
                                    Channel("nick", "Pink")])
     self.assertTrue(application.is_channel_name_taken("Dave"))
コード例 #16
0
ファイル: typer_old.py プロジェクト: jbrew/stereotype
 def get_master(self):
     keyboard = Frame(self, padx=10)
     header = Frame(keyboard)
     Label(header, text="master").pack()
     header.pack()
     mainkeys = Frame(keyboard)
     master_list = []
     for chnl in self.channels:
         channel_list = chnl.options
         for word in channel_list:
             break
     for i in range(len(wordlist)):
         optkey = Frame(mainkeys)
         num = (i + 1) % 10
         keylabel = '%s.' % Channel.optionmap()[i][0]
         keystroke = Channel.optionmap()[i][1]
         Label(optkey, text=keylabel, width=4, anchor=W,
               font=self.font).pack(side=LEFT)
         option = wordlist[i]
         label = option
         b = Button(optkey,
                    text=label,
                    font=self.font,
                    width=14,
                    anchor=W,
                    borderwidth=0,
                    command=lambda word=option: self.onAddWord(word),
                    pady=0)
         b.pack(side=LEFT)
         self.textframe.bind(keystroke,
                             lambda event, arg=option: self.onAddWord(arg))
         optkey.pack(side=TOP)
     mainkeys.pack()
コード例 #17
0
ファイル: iface.py プロジェクト: Abengochea/Simu
class Iface:
    def __init__(self, node, addr_iface):
        self.node = node
        self.addr_iface = addr_iface
        self.running = True
        self.channel = Channel()

    def __processQueue(self):
        """
        Funcio que s'executa tota la estona per tal de poder rebre missatges.
        """
        while self.running:
            message = self.channel.receive()
            self.node.receive(message, self.addr_iface)

    def send(self, msg):
        """
        Funci que serveix per enviar un missatge desde aquesta iface
        """
        self.channel.send(msg)

    def run(self):
        """
        Genera un thread per a cada interficie. Aquest thread creida a la funcio
        __processQueue, el qual esta pendent de rebre missatges.
        """
        self.thread = Thread(target=self.__processQueue)
        self.thread.start()
コード例 #18
0
 def get_channels(self):
     """Return a list of all Channels from Asterisk."""
     result = self._api.call('channels', http_method='GET')
     # Temporary until method is implemented
     result_list = [Channel(self._api), Channel(self._api)]
     #channels = [Channel(x) for x in result]
     return result_list
コード例 #19
0
ファイル: gui.py プロジェクト: 7Robot-Soft/atp
 def createProto(self, name, proto):
     scroll = QtGui.QScrollArea()
     scroll.setWidgetResizable(True)
     scroll.setFrameStyle(QtGui.QFrame.NoFrame)
     scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     layout = QtGui.QVBoxLayout()
     widget = QtGui.QWidget()
     sock = socket.socket()
     try:
         sock.connect((self.host, self.port + proto["id"]))
     except:
         print ("Failed to connect on %s %d" % (self.host, self.port))
         sys.exit(-1)
     file = sock.makefile(mode="rw")
     chan = Channel(file.buffer, print_packet, proto = name,
             transmitter = self.transmitter,
             symmetrical = self.symmetrical)
     chan._file_ = file # archi moche
     for packet in proto['packets']:
         if proto['packets'][packet]['transmitter'] == self.transmitter \
                 or proto['packets'][packet]['transmitter'] == 'both' \
                 or self.transmitter == 'both':
             layout.addWidget(self.createPacket(packet,
                 proto['packets'][packet], chan), 0)
     widget.setLayout(layout)
     scroll.setWidget(widget)
     return scroll
コード例 #20
0
def test_send_receive():
    channel = Channel()
    tx = channel.tx()
    rx = channel.rx()

    tx.put(1)
    assert rx.get() == 1
コード例 #21
0
async def _fetch(session, channel_id):
    url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
    channel = Channel(id = channel_id)
    retry_count = 0
    for retry_count in range(MAX_RETRY):
        try:
            async with session.get(url) as resp:
                text = await resp.text()
                try:
                    doc = xmltodict.parse(text)
                    channel.title = doc['feed']['title']
                    for m in doc['feed']['entry']:
                        channel.videos.append(m.get('yt:videoId'))
                except KeyError:
                    #チャンネル内動画がゼロ
                    pass
                except AttributeError:
                    #チャンネル内動画が一つだけ(feedの構造が変わっている)
                    m = doc['feed']['entry']
                    channel.videos.append(m.get('yt:videoId'))
                except xml.parsers.expat.ExpatError:
                    #チャンネルURLが削除されている
                    print(f'チャンネルが見つかりません:{channel_id}')

            return channel
        except (aiohttp.client_exceptions.ClientConnectorError,
            aiohttp.client_exceptions.ServerDisconnectedError) as e:
            print(f'[{channel_id}]通信エラー:リトライ {retry_count+1}回目/{MAX_RETRY}回中')
            await asyncio.sleep(3)            
コード例 #22
0
ファイル: tsmgr.py プロジェクト: sam210723/tsmgr
def create_channels(only_id=None):
    """
    Create channel objects
    """
    global channels

    # Get list of channel config files
    configs = os.listdir('tsmgr/channels')

    for c in configs:
        if not c.endswith('.ini'): continue

        # Parse channel config
        chan_config = configparser.ConfigParser()
        chan_config.read(f'tsmgr/channels/{c}')
        id = chan_config.get('channel', 'id')

        if only_id:
            if id == only_id:
                channels[id] = Channel(chan_config, config)
                print()
        else:
            # Check for channel ID conflicts
            try:
                channels[id]
                print(f"Channel ID conflict (ID: {id})\nExiting...")
                exit(1)
            except KeyError:
                # Create new channel object
                channels[id] = Channel(chan_config, config)
            print()
    if not only_id: print("--------------------------------\n")
コード例 #23
0
ファイル: gui.py プロジェクト: 7Robot-Soft/atp
 def createProto(self, name, proto):
     scroll = QtGui.QScrollArea()
     scroll.setWidgetResizable(True)
     scroll.setFrameStyle(QtGui.QFrame.NoFrame)
     scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
     layout = QtGui.QVBoxLayout()
     widget = QtGui.QWidget()
     sock = socket.socket()
     try:
         sock.connect((self.host, self.port + proto["id"]))
     except:
         print("Failed to connect on %s %d" % (self.host, self.port))
         sys.exit(-1)
     file = sock.makefile(mode="rw")
     chan = Channel(file.buffer,
                    print_packet,
                    proto=name,
                    transmitter=self.transmitter,
                    symmetrical=self.symmetrical)
     chan._file_ = file  # archi moche
     for packet in proto['packets']:
         if proto['packets'][packet]['transmitter'] == self.transmitter \
                 or proto['packets'][packet]['transmitter'] == 'both' \
                 or self.transmitter == 'both':
             layout.addWidget(
                 self.createPacket(packet, proto['packets'][packet], chan),
                 0)
     widget.setLayout(layout)
     scroll.setWidget(widget)
     return scroll
コード例 #24
0
ファイル: LocEnvs.py プロジェクト: lishengxiangzz/pyLocRL
    def step(self):
        self.channel = Channel(self.tran, self.recs)

        # for rec in receivers:
        #     rec.signal.plot()
        #     plt.show()

        receivers =[]
        dis = []
        est_num = 200
        for i in range(est_num):
            # Receive signals from the channel
            receivers = self.channel.propagate(duration=self.duration, Rs=self.Rs,
                                               symbol_wave_freq=self.symbol_wave_freq,
                                               carrier_freq=self.carrier_freq, fs=self.fs, amp=self.amp,
                                               noise_amp=self.noise_amp, wave_template='sine',
                                               data_seed=self.data_seed + i, noise_seed=self.noise_seed + i)

            dis_error = self.pos_mse(receivers)
            # print(dis_error)

            dis.append(dis_error)

        # mean of minimum 10 error
        dis = np.sort(dis)
        # print("soted:", dis)

        dis_error50 = dis[:int(est_num*0.68)] # (mu-sigma, mu+sigm) 2sigma: 0.9545
        # print(dis_error50[-1])

        return np.sqrt(np.mean(np.square(dis_error50))), [rec.SNR for rec in receivers ]
コード例 #25
0
ファイル: process.py プロジェクト: weiyangedward/cs425_MP
    def __init__(self, id, ordering):
        super(Process, self).__init__() # call __init__ from multiprocessing.Process
        self.id = id

        # Read config from file
        self.process_info, self.addr_dict = configreader.get_processes_info()
        address = self.process_info[id]
        ip, port = address[0], address[1]
        print(ip, port)

        # Init a socket
        self.socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(address)

        # Init channel

        # Causal Order Channel
        if ordering == 'causal':
            print 'causal ordering'
            self.channel = CausalOrderChannel(self, self.id, self.socket, self.process_info, self.addr_dict)
        elif ordering == 'total':
            print 'total ordering'
            # Total Order Channel
            if id == 1:
                # Select process 1 to be the sequencer
                self.channel = TotalOrderChannel(self, self.id, self.socket, self.process_info, self.addr_dict, True)
            else:
                self.channel = TotalOrderChannel(self, self.id, self.socket, self.process_info, self.addr_dict)
        else:
            # Regular channel
            print 'no ordering'
            self.channel = Channel(self, self.id, self.socket, self.process_info, self.addr_dict)
コード例 #26
0
class Client(object):
    def __init__(self, addr, coder=None):
        self.sock = Socket()
        self.addr = addr
        self.loop = Loop()
        self.ch = Channel(self.sock, self.loop, coder)
        self.ch.set_read_callback(self.on_msg_in)
        self.ch.set_write_callback(self.on_msg_sent)
        self.ch.set_error_callback(self.on_error)
    
    def start(self):
        self.ch.connect(self.addr)
        self.loop.loop()

    def on_msg_in(self, msg):
        pass
    
    def on_msg_sent(self):
        pass
    
    def on_error(self):
        pass
    
    def send(self, msg):
        self.ch.send(msg)
コード例 #27
0
def test_reproducability():
    c = Channel()
    c.send("Yes")
    r = c.receive_random_int(0, 2**20)
    d = Channel()
    d.send("Yes")
    assert r == d.receive_random_int(0, 2**20)
コード例 #28
0
ファイル: bot.py プロジェクト: hansl/mumble-bots
    def on_channel_state(self, msg):
        if msg.channel_id not in self.channels_by_id:
            chan = Channel(self.bot, msg.channel_id)
            self.channels_by_id[msg.channel_id] = chan
        else:
            chan = self.channels_by_id[msg.channel_id]
        chan.update(msg)

        if msg.parent == msg.channel_id:
            if not msg.channel_id == 0:
                LOGGER.warning('Root channel not ID 0.')
            if self.root and self.root != chan:
                LOGGER.error('Received 2 different roots...?')
                raise Exception('Two roots.')
            self.root = chan
        elif chan.parent:
            if chan.parent.id != msg.parent:
                chan.parent.remove_child(chan)
                self.channels_by_id[msg.parent].add_child(chan)
        else:
            if not msg.parent in self.channels_by_id:
                LOGGER.error(
                    'Parent ID passed by server is not in the channel list.')
                raise Exception('Invalid Parent.')
            self.channels_by_id[msg.parent].add_child(chan)
コード例 #29
0
    def __init__(self, directory, run_id, plot_every, restrict_energy,
                 num_iterations, len_preamble, n_bits, n_hidden, stepsize,
                 lambda_p, initial_logstd, k, noise_power):
        # System Parameters
        self.num_iterations = num_iterations
        self.preamble = util.generate_preamble(len_preamble, n_bits)
        self.restrict_energy = restrict_energy

        # Transmitter Parameters
        groundtruth = util.schemes[n_bits]
        t_args = [
            self.preamble, restrict_energy, groundtruth, n_bits, n_hidden,
            lambda_p, initial_logstd
        ]
        r_args = [self.preamble, k]

        # Receiver Parameters
        self.agent_one = actor.Actor(t_args, r_args, stepsize,
                                     directory + 'agent_1/')
        self.agent_two = actor.Actor(t_args, r_args, stepsize,
                                     directory + 'agent_2/')

        # Parameters to write in the plotted diagrams
        p_args_names = 'run_id total_iters len_preamble stepsize lambda_p initial_logstd noise_power restrict_energy'.split(
        )
        p_args_params = [
            run_id, num_iterations, len_preamble, stepsize, lambda_p,
            initial_logstd, noise_power, restrict_energy
        ]
        self.p_args = dict(zip(p_args_names, p_args_params))

        self.channel = Channel(noise_power)
コード例 #30
0
ファイル: communication.py プロジェクト: opcm/aca
    class v3(Base):
        MAX_CORE_CHANNELS = 16

        def _init_channels(self):
            self.control_channel = Channel(index=0, log=self._log)

            self.cpu_data_channels = ChannelList(length=self.MAX_CORE_CHANNELS,
                                                 log=self._log)
            self.module_data_channel = Channel(index=self.MAX_CORE_CHANNELS,
                                               log=self._log)
            self.uncore_data_channel = Channel(index=self.MAX_CORE_CHANNELS +
                                               1,
                                               log=self._log)

            self.data_channels = ChannelList(length=self.MAX_CORE_CHANNELS + 2,
                                             log=self._log)
            self.data_channels.includes(*self.cpu_data_channels.reserved)
            self.data_channels.includes(self.module_data_channel)
            self.data_channels.includes(self.uncore_data_channel)

        def close(self):
            self._log.debug('COMMUNICATION CHANNELS - Closing')
            for channel in self.data_channels:
                channel.close()
            self.control_channel.close()
            self._init_channels()
コード例 #31
0
 def test_channel_name_taken_multiple_entries_in_list(self):
     """channel_name_taken test: channel list with more entries"""
     self.channel_registry.setup_channels_list_with([
         Channel("roger", "Pink"), 
         Channel("dave", "Pink"),
         Channel("rick", "Pink"),
         Channel("nick", "Pink")])
     self.assertTrue(self.channel_registry.is_channel_name_taken("Dave"))
コード例 #32
0
ファイル: knive.py プロジェクト: emmasteimann/knive
 def createChannel(self,channelName):
     """Factory function for Channel Objects. Registers the channel.
     Returns: new Channel Object"""
     
     channel = Channel()
     channel.name = channelName
     self.addChannel(channel)
     return channel
コード例 #33
0
 def __init__(self, addr, coder=None):
     self.sock = Socket()
     self.addr = addr
     self.loop = Loop()
     self.ch = Channel(self.sock, self.loop, coder)
     self.ch.set_read_callback(self.on_msg_in)
     self.ch.set_write_callback(self.on_msg_sent)
     self.ch.set_error_callback(self.on_error)
コード例 #34
0
 def process_new(self, sock):
     ch = Channel(Socket(sock), self.loop, self.coder)
     ch.set_read_callback(self.on_msg_in)
     ch.set_write_callback(self.on_msg_sent)
     ch.set_error_callback(self.on_error)
     ch.set_peer_closed(self.peer_closed)
     self.clients[ch.fd] = ch
     self.on_connect(ch)
コード例 #35
0
  def markStream(self, chId, status):
    ch = Channel()
    ch.findOne(chId)
    ch.setStatus(status)
    xbmc.executebuiltin("Container.Refresh")


    
コード例 #36
0
ファイル: universe.py プロジェクト: jketterl/pilight
 def __init__(self, channels = 512):
     self.channels = [None] * channels
     for i in range(0, channels):
         channel = Channel()
         channel.index = i
         channel.addListener(self)
         self.channels[i] = channel;
     self.output = Output()
     self.filters = []
コード例 #37
0
ファイル: readlineio.py プロジェクト: readlineio/readlineio
def run():
    page_id = random_page_id()
    page_channel = Channel('http://readline.io', page_id)
    print("Access your application by going to http://{}/{}".format(server_name, page_id))
    while True:
        message = page_channel.dequeue()
        if message:
            print("Message received: len={}".format(len(json.dumps(message))))
            handle_message(message)
        else:
            print("No message received, continuing long poll.")
コード例 #38
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
    def convert(self):
        """
        Convert the channel to the expected sample width and frame rate.
        
        """
        newchannel = Channel()
        newchannel.set_frames( self.__convert_frames( self.channel.frames ) )
        newchannel.sampwidth = self.sampwidth
        newchannel.framerate = self.framerate

        self.channel = newchannel
コード例 #39
0
ファイル: botstate.py プロジェクト: typoon/boteco
    def joined_channel(self, channel, who):

        # We just joined the channel
        if who == self._nick:
            c = Channel()
            c.users.append(who)
            c.channel = channel
            self._joined_channels.append(c)
        
        for i in self._joined_channels:
            if i.channel == channel:
                i.users.append(who)
コード例 #40
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def add_frames(self, frames, position):
     """
     Convert the channel by adding frames.
     
     @param position (int) the position where the frames will be inserted
     
     """
     newchannel = Channel()
     newchannel.set_frames( self.channel.frames[:position*self.sampwidth] + frames + self.channel.frames[position*self.sampwidth:] )
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     self.channel = newchannel
コード例 #41
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def remove_offset(self):
     """
     Remove the offset in the channel
     
     """
     newchannel = Channel()
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     avg = audioutils.avg(self.channel.frames, self.sampwidth)
     newchannel.set_frames(audioutils.bias(self.channel.frames, self.sampwidth, - avg))
     
     self.channel = newchannel
コード例 #42
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def append_frames(self, frames):
     """
     Convert the channel by appending frames.
     
     @param frames (string) the frames to append
     
     """
     newchannel = Channel()
     newchannel.set_frames( self.channel.frames + frames )
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     self.channel = newchannel
コード例 #43
0
ファイル: server.py プロジェクト: emdash/todoserver
class List(object):

    def __init__(self, name, id=None):
        self.id = id if id else str(uuid4())
        self.channel = Channel(self.id)
        self.channel.onMessage = self.onMessage
        self.channel.onJoin = self.onJoin
        self.name = name
        self.items = []
        self.dirty = False

    def entitle(self, user):
        self.channel.entitle(user)

    def entitled(self, user):
        return user in self.channel.entitled

    def onJoin(self, socket):
        for i, item in enumerate(self.items):
            self.channel.sendTo(socket,
                {"type": "insert",
                 "index": i,
                 "attrs": item})

    def onMessage(self, socket, msg):
        require(msg, "index")

        if msg.type == "insert":
            require(msg, "attrs")
            self.items.insert(msg.index, msg.attrs)
            self.channel.broadcast(
                {"type": "insert",
                 "index": msg.index,
                 "attrs": msg.attrs})
            self.dirty = True

        elif msg.type == "delete":
            del self.items[msg.index]
            self.channel.broadcast(
                {"type": "delete",
                 "index": msg.index})
            self.dirty = True

        elif msg.type == "update":
            require(msg, "attrs")
            item = self.items[msg.index]
            item.update(msg.attrs)
            self.channel.broadcast(
                {"type": "update",
                 "index": msg.index,
                 "attrs": msg.attrs})
            self.dirty = True
コード例 #44
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def remove_frames(self, begin, end):
     """
     Convert the channel by removing frames.
     
     @param begin (int) the position of the beggining of the frames to remove
     @param end (int) the position of the end of the frames to remove
     
     """
     newchannel = Channel()
     newchannel.set_frames( self.channel.frames[:begin*self.sampwidth] + self.channel.frames[end*self.sampwidth:] )
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     self.channel = newchannel
コード例 #45
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def mul(self, factor):
     """
     Multiply the frames by the factor
     
     @param bias (int) the factor to multiply the frames
     
     """
     newchannel = Channel()
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     newchannel.set_frames(audioutils.mul(self.channel.frames, self.sampwidth, factor))
     
     self.channel = newchannel
コード例 #46
0
ファイル: channelformatter.py プロジェクト: drammock/sppas
 def bias(self, bias):
     """
     Apply a bias on the frames
     
     @param bias (int) the value to bias the frames
     
     """
     newchannel = Channel()
     newchannel.sampwidth = self.sampwidth
     newchannel.framerate = self.framerate
     newchannel.set_frames(audioutils.bias(self.channel.frames, self.sampwidth, bias))
     
     self.channel = newchannel
コード例 #47
0
ファイル: jsbot.py プロジェクト: 7Robot-Soft/jsbot
 def __init__(self, host, port):
     self.sock = socket.socket()
     self.sock.connect((HOST, PORT+5))
     self.asserv_file = self.sock.makefile(mode='rw')
     self.asserv = Channel(self.asserv_file.buffer,
             lambda name, args: name, proto = 'asserv')
     self.states = None
     self.speed = SpeedOrder(self.asserv)
     self.speed.start()
     self.sock2 = socket.socket()
     self.sock2.connect((HOST, PORT+6))
     self.mother_file = self.sock2.makefile(mode='rw')
     self.mother = Channel(self.mother_file.buffer,
             lambda name, args: name, proto = 'mother')
コード例 #48
0
ファイル: knive.py プロジェクト: cato-/knive
    def createChannelFromConfig(self,configObject):
        channel = Channel(configObject['name'],self.config)
        channel.slug = configObject['slug']            
        channel.url = configObject['url']

        
        # ================
        # = Inlet/Source =
        # ================

        if configObject['source']['type'] == 'kniveTCPSource':
            channel.inlet = TCPTSServer(
                                                secret=configObject['source']['sharedSecret'],
                                                port=configObject['source']['listenPort']
                                            )
        elif configObject['source']['type'] == 'GstInlet':
            channel.inlet = GstInlet(
                name = configObject['source']['name'],
                pipeline = configObject['source']['pipeline']
            )
        else:
            print "Unknown Inlet Type %s" % self.config['source']['type']
            sys.exit(1)

        # ===============
        # = Set outlets =
        # ===============
        for outletsectionname in configObject['outlets']:
            logging.debug('Setting up outlet: %s' % outletsectionname)
            outletConfig = configObject['outlets'][outletsectionname]
            if outletConfig['type'] == 'HTTPLive': 
                try:
                    httplivestream = HTTPLiveStream(channel=channel,destdir=outletConfig['outputLocation'],publishURL=outletConfig['publishURL'])
                    channel.addOutlet(httplivestream)
                except Exception, err:
                    logging.exception(err)
                    sys.exit(1)

                for qualityname in outletConfig.sections:
                    qualityConfig = outletConfig[qualityname]
                    httplivestream.createQuality(qualityname,qualityConfig,ffmpegbin=self.config['paths']['ffmpegbin'])
                
                

            elif outletConfig['type'] == 'StreamArchiver':
                
                archiver = FileWriter(
                        self.config[outletsectionname]['outputdir'],
                        suffix=self.config[outletsectionname]['suffix'],
                        keepFiles=self.config[outletsectionname]['keepfiles'],
                        filename=self.config[outletsectionname]['filename']
                )
                channel.addOutlet(archiver)
コード例 #49
0
ファイル: client.py プロジェクト: weiyangedward/cs425_MP
    def __init__(self, client_id, serverID):
        super(Client, self).__init__() # call __init__ from multiprocessing.Process

        self.server_id = multiprocessing.Value('i', 0)
        with self.server_id.get_lock():
            self.server_id.value = serverID + 1 # (1,10)

        self.socket_status = multiprocessing.Value('i', 0)
        with self.socket_status.get_lock():
            self.socket_status.value = 0

        """
            Read config from file
            process_info[id] = (ip, port)
            addr_dict[(ip, port)] = id
        """
        self.process_info, self.addr_dict = configreader.get_processes_info()
        self.total_server = configreader.get_total_servers()
        self.batch_cmd = ''
        self.reconnect_try = 0
        self.client_id = client_id
        # self.exit = sys.exit()

        """
            init TCP connect to server
        """
        with self.server_id.get_lock():
            self.address = self.process_info[self.server_id.value]
        self.ip, self.port = self.address[0], self.address[1]
        # print(self.ip, self.port)
        for res in socket.getaddrinfo(self.ip, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.socket = socket.socket(af, socktype, proto) # build a socket
                with self.socket_status.get_lock():
                    self.socket_status.value = 1
            except socket.error as msg:
                self.socket = None
                with self.socket_status.get_lock():
                    self.socket_status.value = 0
                continue
            try:
                self.socket.connect(sa) # connect to socket 
            except socket.error as msg:
                self.socket.close()
                self.socket = None
                with self.socket_status.get_lock():
                    self.socket_status.value = 0
                continue
            break
        if self.socket is None:
            print('could not open socket')
            sys.exit(1)

        """
            Init unicast channel
        """
        print("client, no ordering")
        # pass Client obj as arg to Channel
        self.channel = Channel(self, self.client_id, self.socket, self.process_info, self.addr_dict)
コード例 #50
0
ファイル: tcp_client.py プロジェクト: Tehnix/Voixer
    def join_channel(self, chan):
        """
        Notify the client that he has joined the channel, and supply the 
        client with a userlist.

        """
        try:
            chan = Channel(chan)
        except NameError:
            chan = Channel.channels[chan]
        if chan not in self.user.channels:
            logging.debug("Putting user '%s' in channel '%s'" % (self.user.nickname, chan.name))
            chan.add_user(self.user)
            self.user.add_channel(chan)
            self.server.queue_message("JOINED: %s\r\n" % chan.name, self.sock)
            self.server.queue_message("USERLIST %s: %s\r\n" % (chan.name, chan.userlist()), self.sock)
コード例 #51
0
ファイル: server.py プロジェクト: emdash/todoserver
 def __init__(self, name, id=None):
     self.id = id if id else str(uuid4())
     self.channel = Channel(self.id)
     self.channel.onMessage = self.onMessage
     self.channel.onJoin = self.onJoin
     self.name = name
     self.items = []
     self.dirty = False
コード例 #52
0
ファイル: utils.py プロジェクト: Josele33/TDTChannels
def get_tv_channels_from_part(text):
    line_where_first_channel_starts = 15
    attributes_per_item = 6
    list_to_iterate = text.split("|")[line_where_first_channel_starts:-1]
    while "\n" in list_to_iterate:
        list_to_iterate.remove("\n")
    channel_list = []
    for i in range(0, len(list_to_iterate), attributes_per_item):
        item_name = list_to_iterate[i].strip()

        item_options = list_to_iterate[i + 1].strip()

        item_web = list_to_iterate[i + 2].strip()
        if len(item_web) > 0 and item_web[0] != "-":
            item_web = stringbetweenparantheses(item_web)
        if len(item_web) == 1:
            item_web = ""

        if "HD" in item_name:
            item_resolution = "HD"
        else:
            item_resolution = "SD"

        item_logo = list_to_iterate[i + 3].strip()
        if len(item_logo) > 0 and item_logo[0] != "-":
            item_logo = stringbetweenparantheses(item_logo)
        if len(item_logo) == 1:
            item_logo = ""

        item_epg = list_to_iterate[i + 4].strip()
        if len(item_epg) == 1:
            item_epg = ""

        item_extra_info = list_to_iterate[i + 5].strip()
        if len(item_extra_info) == 1:
            item_extra_info = ""

        channel = Channel(item_name, item_web, item_resolution, item_logo, item_epg, item_extra_info)
        item_options = item_options.split(" - ")
        if len(item_options) > 0 and item_options[0] != "-":
            for option in item_options:
                format = (option[1:5]).replace("]", "")
                url = stringbetweenparantheses(option)
                channel.add_option(format, url)
        channel_list.append(channel)
    return channel_list
コード例 #53
0
ファイル: SubMaster.py プロジェクト: jketterl/pilight
    def __init__(self, channelNames = [], count = 512, id = "submaster"):
        self.id = id
        super(SubMaster, self).__init__(count)
        master = Channel()
        master.addListener(ChannelListener('master', self))

        masterMap = MultiChannelMapping(master)
        self.channelMap = {}
        self.targetMap = {}
        for index, name in enumerate(channelNames):
            channel = self[index]
            self.channelMap[name] = channel
            self.targetMap[name] = MultiChannelMapping(channel)
            masterMap.addTarget(channel) 

            channel.addListener(ChannelListener(name, self))
        self.channelMap['master'] = master
        self.selectChannel('master')
コード例 #54
0
    def addChannel(self, variableName, regions, nBins, binLow, binHigh):
        """
        Build a channel object from this fitConfig

        @param variableName The variable name to use in this channel
        @param regions Region to use
        @param nBins Number of bins
        @param binLow Left edge of lower bin
        @param binHight Right edge of upper bin
        """
        if variableName == "cuts":
            nBins = len(regions)
            #binLow = 0.5
            binHigh = nBins + binLow
            pass
        chanObj = Channel(variableName, regions, self.prefix, nBins,
                             binLow, binHigh, self.statErrThreshold)

        # Verify that this name is not already used
        for chan in self.channels:
            if chan.name == chanObj.name:
                log.info("Not gonna add the region, because it exists in fitConfig --> channel-List follows:" )
                for chan in self.channels:
                    print "      chan.name = ", chan.name
                raise RuntimeError("Channel %s already exists in fitConfig %s. Please use a different name." % (chanObj.name, self.name))

        #set channel parent
        chanObj.parentTopLvl = self

        #set stat error type
        chanObj.statErrorType = self.statErrorType

        # Channel doesn't have weights so add them
        chanObj.setWeights(self.weights)

        # Propagate systematics into channel
        for (systName, syst) in self.systDict.items():
            chanObj.addSystematic(syst)

        # Put samples owned by this fitConfig into the channel
        for s in self.sampleList:
            chanObj.addSample(s.Clone())

        # Add channel to the list
        self.channels.append(chanObj)

        return self.channels[len(self.channels) - 1]
コード例 #55
0
ファイル: bus.py プロジェクト: juanchitot/domo
 def __init__(self,bus_number,simulation_mode=False):
     Channel.__init__(self,bus_number)
     
     self.bus_number = bus_number
     self.bus_id = bus_number
     self.cards = {}
     self.in_ports = {}
     self.out_ports = {}        
     
     self.serial = serial.Serial()
     self.serial.port = self.bus_id
     self.serial.baudrate = Bus.baud_rate
     self.simulation_mode = False
     
     if simulation_mode : 
         self.start_simulation_mode()
     else :
         self.connect()     
     
     self.set_default_probabilitys()        
コード例 #56
0
ファイル: client.py プロジェクト: skiddling/DoubanFM
	def __init__(self):
		self.url = 'http://douban.fm/j/mine/playlist?type=n&channel=%d&from=mainsite'
		self.current_song = None
		self.player = Player()
		self.channel = Channel()
		self.current_channel = self.channel.current_channel
		self.view = View(self.channel)
		self.update_current_song()
		self.is_playing = False
		self.seconds = 0
		self.length = self.current_song.length
コード例 #57
0
    def connect(self, conn):
        '''
            Nawiazywanie polaczenia, inicjalizujace eventy
        '''
        #jesli uzytkonik zalogowany id -> pk usera
        #if conn.request.user.is_authenticated():
        #    conn.id = conn.request.user.pk

        conn.id = self.id_gen.next()
        user_id = conn.get_user_id()

        logger.debug("New connection; user %s; path %s; conn_id %s " % (user_id,
                conn.request.path_info, conn.id))

        if user_id not in self.users:
            self.users[user_id] = {}

        #tworzymy kanaly dla wspieranych eventow i doklejamy zdarzenia
        for event in conn.events:
            if active_events.has_key(event):
                #niezalogowani uzytkownicy moga odbierac tylko broadcasty
                if active_events[event].is_init_event():
                    Channel.init_event(conn, event, shared=self.shared)

                if self.history.has_key(event):
                    self.history[event].send_history(conn)

                if not (active_events[event].is_broadcast_event() or
                        conn.request.user.is_authenticated()):
                    continue

                #XXX: nadmiarowe, w konstruktorze wszystkie kanaly sa inicjalizowane
                if not self.channels.has_key(event):
                    logger.error('Brak kanalu %s, to niepowinno miec miejsca' % event)
                    self.channels[event] = Channel(event, tracker=self,
                                        history=self.history.get(event, None))

                if not self.users[user_id].has_key(event):
                    self.users[user_id][event] = True

                self.channels[event].new_connection(conn)
コード例 #58
0
ファイル: server.py プロジェクト: emdash/todoserver
    def __init__(self):
        Router = SockJSRouter(ChannelDispatcher, '/todo')
        self.app = web.Application(Router.urls)

        self.control = Channel("control")
        self.control.onMessage = self.controlMessageHandler
        ChannelDispatcher.addChannel(self.control)

        self.lists = []
        self.byId = {}
        self.init()
        self.dirty = True
コード例 #59
0
ファイル: parsers.py プロジェクト: mstipanov/hrpodcasts
    def parseChannel(self, showName):
        baseUrl = "http://radio.hrt.hr"
        data = self.readUrl(baseUrl + "/emisije/?" + urllib.urlencode({"q": showName.encode("utf-8")}))

        urls = re.findall(
            r'<div class="col-md-4 col-sm-6 item split">.*?<div class="thumbnail thumbnail-shows">.*?<a href="(.+?)">.*?<img src="(.+?)" alt=".*?" title="(.+?)" class="normal_size">.*?</a>.*?<div class="caption">.*?<h4><a href=".*?">.*?</a></h4>.*?<p>.*?</p>.*?<p>.*?</p>.*?</div>.*?</div>.*?</div>',
            data,
            re.DOTALL,
        )

        if not urls:
            return None

        showLink = baseUrl + urls[0][0]
        image = baseUrl + urls[0][1]
        title = urls[0][2]

        data = self.readUrl(showLink)

        searchItems = re.findall(r'<meta name="description" content="(.+?)" />', data, re.DOTALL)

        description = searchItems[0]

        channel = Channel()
        channel.link = showLink.strip()
        channel.title = title.strip()
        channel.description = description.strip()
        channel.image = image.strip()
        # channel.lastBuildDate = lastBuildDate.strip()
        channel.articles = self.parseArticles(baseUrl, showLink)
        return channel
コード例 #60
0
    def __init__(self, client_id, server_id):
        super(Client, self).__init__() # call __init__ from multiprocessing.Process

        # a shared variable to show serverID
        self.server_id = multiprocessing.Value('i', 0)
        with self.server_id.get_lock():
            self.server_id.value = server_id + 1 # (1,10)

        # a shared variable to show socket status
        self.socket_status = multiprocessing.Value('i', 0)
        with self.socket_status.get_lock():
            self.socket_status.value = 0

        # read process config from file
        self.process_info, self.addr_dict = configreader.get_processes_info()
        self.total_server = configreader.get_total_servers()
        self.batch_cmd = ''
        self.reconnect_try = 0
        self.client_id = client_id

        # init a TCP socket to connect to server
        with self.server_id.get_lock():
            self.address = self.process_info[self.server_id.value]
        self.ip, self.port = self.address[0], self.address[1]

        # robust way to find an available port
        for res in socket.getaddrinfo(self.ip, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.socket = socket.socket(af, socktype, proto) # init TCP socket
                with self.socket_status.get_lock():
                    self.socket_status.value = 1
            except socket.error as msg:
                self.socket = None
                with self.socket_status.get_lock():
                    self.socket_status.value = 0
                continue
            try:
                self.socket.connect(sa) # connect to TCP socket
            except socket.error as msg:
                self.socket.close()
                self.socket = None
                with self.socket_status.get_lock():
                    self.socket_status.value = 0
                continue
            break
        if self.socket is None:
            print('could not open socket')
            sys.exit(1)

        # init a unicast channel with delayed function, reuse code from MP1
        self.channel = Channel(self, self.client_id, self.socket, self.process_info, self.addr_dict)