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)
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()
def main(): arguments = parse_arguments() normailze_inputs(arguments) first_chanel = Channel(mu1) second_chanel = Channel(mu2) generator = Generator(lmbd) ticks_number = 100000 * accuracy declined_claims = 0 generated_claims = 0 processed_claims = 0 for i in range(0, ticks_number): if generator.is_generated(): generator.start_generate() generated_claims += 1 if first_chanel.is_processed(): first_chanel.add() processed_claims += 1 elif second_chanel.is_processed(): second_chanel.add() processed_claims += 1 else: declined_claims += 1 first_chanel.tick() second_chanel.tick() generator.tick() print('Occupancy of first chanel: ', first_chanel.work_time / ticks_number) print('Occupancy of second chanel: ', second_chanel.work_time / ticks_number) print('Decline probability: ', declined_claims / generated_claims) print('Relative system capacity: ', processed_claims / generated_claims) print('Absolute system capacity: ', processed_claims * normalizing_factor / ticks_number)
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"))
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()
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
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")
def main(): request = Request(p) queue = Queue() channel_1 = Channel(p1) channel_2 = Channel(p2) count = 0 for i in range(iterations): request.generate() if request.was_request(): if queue.is_empty(): queue.add_item() calculate(channel_1, channel_2, queue, request) else: calculate(channel_1, channel_2, queue, request) if not queue.is_empty(): request.add_discard() else: queue.add_item() else: calculate(channel_1, channel_2, queue, request) count += channel_1.get_value() count += channel_2.get_value() count += queue.get_value() statistics(channel_1, channel_2, request, count)
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"))
def test_9_get_channel_from_test(self): """get_channel_from test: gets a channel from the channels list""" self.setup_channels_list_with([Channel("roger", "Pink"), Channel("dave", "Pink"), Channel("rick", "Pink"), Channel("nick", "Pink")]) channel_found = application.get_channel_from("dave") self.assertTrue("Pink" in channel_found.participants)
def test_channel_name_not_taken_multiple_entries_in_list(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.assertFalse(application.is_channel_name_taken("Syd"))
def getChannelFromFile(self, id): path = os.path.join(channelPath, id) if not sfile.exists(path): return None cfg = sfile.readlines(path) return Channel(cfg) ch = Channel(cfg[0], cfg[1], cfg[2], cfg[3], cfg[4], cfg[5], cfg[6]) return ch
def __init__(self): self.hw1 = StubHw(None) self.hw2 = StubHw(None) self.ch1 = Channel("Channel 1", 0, self.hw1) self.ch2 = Channel("Channel 2", 1, self.hw2) self.ch1.progs = [progdays.Progdays(), progdays.Progdays()] self.ch2.progs = [progdays.Progdays(), progdays.Progdays()] self.ch1.isenable = True self.ch1.progs[0].stime = stime.STime(hour=5, minute=0, duration=30) self.ch1.progs[0].isactive = True self.ch1.progs[0].set_days([True, True, True, True, True, True, True])
async def test_select_push(self): """Pushing on two channels should return the one with room""" sel = Selector() async with Channel(1) as chan1, Channel(1) as chan2: # Push to C2 first sel.push(chan1, 10) sel.push(chan2, 20) await chan1.push(11) val = await sel.gather() await chan1.close() self.assertEqual(val, (1, True)) self.assertEqual(await chan1.pop(), 11) self.assertEqual(await chan1.pop(), None) self.assertEqual(await chan2.pop(), 20)
async def __onPacket(self, packet): if packet.PacketID in self.packetDict: self.packetDict[packet.PacketID].set_result(packet) del self.packetDict[packet.PacketID] self.loop.create_task(self.onPacket(packet)) body = packet.toJsonBody() if packet.PacketName == "MSG": chatId = body["chatLog"]["chatId"] if "li" in body: li = body["li"] else: li = 0 channel = Channel(chatId, li, self.__writer) chat = Chat(channel, body) self.loop.create_task(self.onMessage(chat)) if packet.PacketName == "NEWMEM": chatId = body["chatLog"]["chatId"] if "li" in body: li = body["li"] else: li = 0 channel = Channel(chatId, li, self.__writer) self.loop.create_task(self.onJoin(packet, channel)) if packet.PacketName == "DELMEM": chatId = body["chatLog"]["chatId"] if "li" in body: li = body["li"] else: li = 0 channel = Channel(chatId, li, self.__writer) self.loop.create_task(self.onQuit(packet, channel)) if packet.PacketName == "DECUNREAD": chatId = body["chatId"] channel = Channel(chatId, 0, self.__writer) self.loop.create_task(self.onRead(channel, body))
def init(self): self.log.info('COMMUNICATION Establishing connection to remote target') self.log.info( 'COMMUNICATION Creation of control communication channel') self.channels.control_channel.create(ChannelType.CONTROL) self.channels.control_channel.connect(self._ip, self._port, attempts=10) self.log.info( 'COMMUNICATION Sending handshake message to remote target') init_msg = self.struct.FirstCommunicationMsg() self.channels.control_channel.send_structure(init_msg) status_msg = self.channels.control_channel.receive_structure( self.struct.TargetStatusMsg) self.check_status(status_msg) self.check_protocol(status_msg) self.num_cpus = status_msg.remote_hardware_info.num_cpus self.log.info('COMMUNICATION Creation of data communication channels') self.channels.cpu_data_channels.create(global_indexes=range( status_msg.remote_hardware_info.num_cpus), channel_type=ChannelType.CORE) self.tmp = Channel(index=self.channels.data_channels.length - 2, log=self.log) self.tmp.create(ChannelType.NONE) self.channels.data_channels.includes(self.tmp) self.tmp = Channel(index=self.channels.data_channels.length - 1, log=self.log) self.tmp.create(ChannelType.NONE) self.channels.data_channels.includes(self.tmp) self.channels.data_channels.connect(self._ip, self._port) self.log.info( 'COMMUNICATION Send handshake to data communication channels') for channel in self.channels.data_channels: channel.send_structure(init_msg) data_msg = channel.receive_structure(self.struct.FirstDataMsg) self.check_protocol(data_msg) if data_msg.data_type == ChannelType.MODULE: channel.set_type(ChannelType.MODULE) self.channels.module_data_channel = channel if data_msg.data_type == ChannelType.UNCORE: channel.set_type(ChannelType.UNCORE) self.channels.uncore_data_channel = channel
async def test_select_both_push(self): """Push and popping should perform the first available op""" sel1, sel2 = Selector(), Selector() async with Channel(1) as chan1, Channel(1) as chan2: # c1 will be empty (cannot pop) sel1.pop(chan1) sel1.push(chan2, 10) val = await sel1.gather() self.assertEqual(val, (1, True)) # c2 will be empty (cannot pop) self.assertEqual(await chan2.pop(), 10) sel2.push(chan1, 20) sel2.pop(chan2) val = await sel2.gather() self.assertEqual(val, (0, True))
def parse(game, content, index): track = Track() track.index = index track.name = content.get('name') track.topic_format = content.get('topic_format') puzzles = [game.puzzles[x] for x in content.get('puzzles', [])] for i in xrange(0, len(puzzles) + 1): puzzle = puzzles[i] if i < len(puzzles) else None # channel name: correct solution of the previous level: if i == 0: # start channel (without a previous puzzle) name = game.format_channel(content['start']['channel']) else: name = game.format_channel(puzzles[i - 1].get_correct()) # channel topic: current puzzle clue if not puzzle: # finish channel (without current puzzle) topic = track.format_finish_topic(content['finish']['topic'], game, i + 1, len(puzzles)) else: topic = track.format_puzzle_topic(puzzles[i], game, i + 1, len(puzzles)) channel = Channel(name, topic) # set cross reference to puzzle: channel.puzzle = puzzle # set incorrect channel list: if puzzle: for incorrect in puzzle.get_incorrect(): incorrect_channel = Channel(incorrect, puzzle.incorrect_topic) channel.next_incorrect.append(incorrect_channel) # also generate a per-track list of incorrect channel: track.channels_incorrect.append(incorrect_channel) track.channels.append(channel) # build internal links between channel: for i in xrange(0, len(track.channels)): track.channels[i].prev = track.channels[i - 1] if i > 0 else None track.channels[i].next = track.channels[ i + 1] if i < len(track.channels) - 1 else None return track
async def test_multi(self): """Test multiple push and pops""" result = [] async with Channel(2) as chan: async def pushers(chan: Channel): await asyncio.gather( TestChannel.pusher(chan, [1, 2, 3, 4, 5]), TestChannel.pusher(chan, [6, 7, 8, 9, 10]), TestChannel.pusher(chan, [11, 12, 13, 14, 15]), TestChannel.pusher(chan, [16, 17, 18, 19, 20]), TestChannel.pusher(chan, [21, 22, 23, 24, 25]), TestChannel.pusher(chan, [26, 27, 28, 29, 30]), TestChannel.pusher(chan, [31, 32, 33, 34, 35]), TestChannel.pusher(chan, [36, 37, 38, 39, 40]), TestChannel.pusher(chan, [41, 42, 43, 44, 45]), ) await chan.close() async def poppers(chan: Channel): await asyncio.gather( TestChannel.popper(chan, result), TestChannel.popper(chan, result), TestChannel.popper(chan, result), TestChannel.popper(chan, result), TestChannel.popper(chan, result), ) await asyncio.gather(pushers(chan), poppers(chan)) self.assertEqual(frozenset(result), frozenset(range(1, 46)))
def main(): print("Waiting for a connection.") try: ss.bind((host, port)) except socket.error as e: print(str(e)) exit() ss.listen(16) while True: conn, addr = ss.accept() nickname = conn.recv(2048).decode('utf-8') chan = conn.recv(2048).decode('utf-8') if chan not in channels.keys(): channels[chan] = Channel(conn, nickname, chan) else: channels[chan].adduser(conn, nickname) connections[conn] = nickname print("connected to: " + str(addr[0]) + ":" + str(addr[1])) start_new_thread(client_thread, (conn, ))
def __init__(self, node, num): self.node = node self.id = node.id + '.' + num self.running = True self.channel = Channel() self.link = None
def GetChannel_1C(self, configuration, acq, trk, tlm, channel, queue): "" aux = configuration.get( "Acquisition_1C" + str(channel) + ".implementation", "W") appendix1 = str(channel) if aux != "W" else "" aux = configuration.get( "Tracking_1C" + str(channel) + ".implementation", "W") appendix2 = str(channel) if aux != "W" else "" aux = configuration.get( "TelemetryDecoder_1C" + str(channel) + ".implementation", "W") appendix3 = str(channel) if aux != "W" else "" # default_item_type = "gr_complex" acq_item_type = configuration.get( "Acquisition_1C" + appendix1 + ".item_type", default_item_type) trk_item_type = configuration.get( "Tracking_1C" + appendix2 + ".item_type", default_item_type) assert acq_item_type == trk_item_type in_memory_configuration.d["Channel.item_type"] = acq_item_type self.acq_ = self.GetAcqBlock(configuration, "Acquisition_1C" + appendix1, acq, 1, 0) self.trk_ = self.GetTrkBlock(configuration, "Tracking_1C" + appendix2, trk, 1, 1) self.tlm_ = self.GetTlmBlock(configuration, "TelemetryDecoder_1C" + appendix3, tlm, 1, 1) self.channel_ = Channel(configuration, channel, self.acq_, self.trk_, self.tlm_, "Channel", "1C", queue) return self.channel_
def create_channel(self, params): """In Asterisk, originate a channel. Return the Channel.""" result = self._api.call('channels', http_method='POST', parameters=params) # Temporary until method is implemented result = Channel(self._api) return result
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)
async def test_push_nowait(self): """Push up to channel size should not block""" async with Channel(2) as chan: await chan.push(10) await chan.push(11) self.assertEqual(await chan.pop(), 10) self.assertEqual(await chan.pop(), 11)
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)
def ponderByUnionOfChannels(self): self.ls_recomendated = [] #Reseting list... for channel in tqdm(self.ls_channel): if channel.blocked is True: continue num_fol = self.api.get_followe(channel.id) mult = self.ponderByFollowers(num_fol) subs = self.api.get_followers(channel.id) mult = mult / len(subs) for subchannel in tqdm(subs): #Existe como un usuario que ya sigue? idx_temp = self.get_index_in_list(subchannel, False, self.ls_channel) if idx_temp is not -1: #Ya existe continue else: #No existe #Existe como ya recomendado? idx = self.get_index_in_list(subchannel, False, self.ls_recomendated) if idx is -1: #No existe try: temp_channel = Channel(id = subchannel, name = self.api.get_name(subchannel), ponderation = mult) self.ls_recomendated.append(temp_channel) except: print("ERROR", subchannel) else: #Ya existe self.ls_recomendated[idx].addPonderation(mult)
def test_response_success_for_channel_creation_request(self): """get_response_for_channel_creation_request test""" self.channel_registry.setup_channels_list_with([ Channel("roger", "Pink")]) self.assertEqual( self.channel_registry.get_response_for_channel_creation_request( "Dave"), "SUCCESS")
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))
def createchan(self, pkt, x, y): # Older clients first report version here self.version=pkt.p2 name=str(pkt.body).strip('\0') pv = self.server.GetPV(name) if pv is None: # PV does not exist log.debug("Can't create channel for non-existant PV %s",name) fail = CAmessage(cmd=26, p1=pkt.p1) self.send(fail.pack()) return chan=Channel(self.next_sid, pkt.p1, self.server, self, pv) self.channels[chan.sid]=chan dtype, maxcount = pv.info(chan) ok = CAmessage(cmd=18, dtype=dtype, count=maxcount, p1=pkt.p1, p2=chan.sid) rights = CAmessage(cmd=22, p1=pkt.p1, p2=chan.rights) self.send(ok.pack()+rights.pack()) self.next_sid=self.next_sid+1 while self.next_sid in self.channels: self.next_sid=self.next_sid+1