Beispiel #1
0
def pushMsgToSingleDevice(channel_id, msg, opts):

    c = Channel()
    try:
        ret = c.pushMsgToSingleDevice(channel_id, msg, opts)
    except ChannelException as e:
        print e.getLastErrorMsg()
Beispiel #2
0
 def _manage_channels(self):
     assert self.state_lock.locked()
     for cid, channel in self.active_channels.items():
         message = 'Location channel management removing %r from active.'
         if not channel.accepting_requests():
             self.debugout(message % channel, 1)
             self.active_channels.pop(cid)
             self.parallel_channels.decrement()
     maxchannels = self.MAXPARALLELCHANNELS
     numpending = len(self.pending_transactions)
     numchannels = self.parallel_channels.value
     if numchannels == 0:
         createchannel = True
     elif numchannels >= maxchannels:
         createchannel = False
     elif (numpending / numchannels) > self.IDEALBACKLOG:
         createchannel = True
     else:
         createchannel = False
     if createchannel:
         channel = Channel(self.monitor, self.debug)
         channel.setup_connection(self.host, self.port, self.protocol)
         self.free_channels.append(channel)
         self.parallel_channels.increment()
     return
Beispiel #3
0
 def _manage_channels(self):
     assert self.state_lock.locked()
     for cid, channel in self.active_channels.items():
         message = 'Location channel management removing %r from active.'
         if not channel.accepting_requests():
             self.debugout(message % channel, 1)
             self.active_channels.pop(cid)
             self.parallel_channels.decrement()
     maxchannels = self.MAXPARALLELCHANNELS
     numpending = len(self.pending_transactions)
     numchannels = self.parallel_channels.value
     if numchannels == 0:
         createchannel = True
     elif numchannels >= maxchannels:
         createchannel = False
     elif (numpending / numchannels) > self.IDEALBACKLOG:
         createchannel = True
     else:
         createchannel = False
     if createchannel:
         channel = Channel(self.monitor, self.debug)
         channel.setup_connection(self.host, self.port, self.protocol)
         self.free_channels.append(channel)
         self.parallel_channels.increment()
     return
 def load_channel_catalog(self, channel_catalog_filename):
     if self.VERBOSE:
         print("* %s" % Channel.get_header_caps())
     with open(channel_catalog_filename, "r") as channel_file:
         for line in channel_file:
             channel_line = line.strip()
             # Skip empty lines.
             if not channel_line:
                 continue
             # Skip comments.
             if (channel_line[0] == ';') or (channel_line[0] == '#'):
                 continue
             # Retrieve the values from the file.
             try:
                 label, id, cost, size, energy, df_energy, energy_cost, delay, error, wireless, point_to_point = channel_line.split(
                 )
             except ValueError:
                 print("Error: Wrong line format '%s'" % channel_line)
                 return False
             # Create a new Channel.
             new_channel = Channel(label, int(id), int(cost), int(size),
                                   int(energy), int(df_energy),
                                   float(energy_cost), int(delay),
                                   int(error), int(wireless),
                                   int(point_to_point))
             # Append the channel to the list of channels.
             self.add_channel(new_channel)
             # Print the channel.
             if self.VERBOSE:
                 print("* %s" % new_channel.to_string())
     return True
Beispiel #5
0
def pushMsgToTag(tagName, msg, type, opts):

    c = Channel()
    try:
        ret = c.pushMsgToTag(tagName, msg, type, opts)
    except ChannelException as e:
        print e.getLastErrorMsg()
Beispiel #6
0
def pushMsgToAll(msg, opts):

    c = Channel()
    try:
        ret = c.pushMsgToAll(msg, opts)
    except ChannelException as e:
        print e.getLastErrorMsg()
Beispiel #7
0
def test_pushMessage_to_all():
    c = Channel(apiKey, secretKey)
    push_type = 3
    optional = dict()
    optional[Channel.MESSAGE_TYPE] = 1
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #8
0
def InsertChannelCallback(sender, query):
    Log("InsertChannelCallback ...")

    # For testing by reducing url typing
    if FAST_MY_CHANNEL_ENTRY:
        # query = "hdhomerun://DEVICE-0/tuner0?channel=8vsb:999999&program=%s" % query
        query = "hdhomerun://DEVICE-0/ch24-%s" % query

    try:
        myChannel = Channel.fromUrl(query)
        if not myChannel:
            deviceId = Prefs[DEVICE_ID]
            tunerId = Prefs[TUNER_ID]

            return MessageContainer(
                L('Error'), "%s\n%s" % (L('BadStreamUrl'), "\n".join(
                    Channel.getStreamUrlTemplates(deviceId, tunerId))))

        # default channel to verfied and enabled
        myChannel.GuideName = L('MyChannel')
        myChannel.Verified = True
        myChannel.Enabled = True

        myLineupList = NewMyLineupList(myChannel)
        UpdateLineupList(myLineupList)

        return MessageContainer(L('Success'),
                                "%s: %s" % (L('Added'), myChannel.toString()))

    except Exception, e:
        Log("Exception: %s" % e, False)
        return MessageContainer(
            L('Error'), "%s: %s" % (L('ProblemInsertingChannel'), query))
Beispiel #9
0
class Turntable(Component):
    def __init__(self, cx, cy, width, height):
        super().__init__(cx, cy, width, height)
        self.image = PhotoImage(file="sources/turntable.gif")
        self.musicInfo = {}
        self.musicLoc = self.getLoc(self.musicInfo)
        self.channel = Channel(self.cx, self.cy, 100, self.musicLoc)

    def getLoc(self, info):
        locs = {}
        for key in info.keys():
            if isinstance(info[key], list):
                locs[key] = info[key]
        return locs

    def act(self):
        self.channel.isDisplayed = True

    def draw(self, canvas):
        canvas.create_image(self.cx, self.cy, image=self.image)
        self.channel.draw(canvas)

    def setInfo(self, info):
        self.musicInfo = info
        self.musicLoc = self.getLoc(self.musicInfo)
        self.channel.setInfo(self.musicLoc, self.musicInfo["duration"])

    pass
Beispiel #10
0
def test_pushMessage_to_all(message):
    c = Channel(apiKey, secretKey)
    push_type = 3
    optional = dict()
    optional[Channel.MESSAGE_TYPE] = 1
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #11
0
def test_pushMessage_to_tag():
    c = Channel(apiKey, secretKey)
    push_type = 2
    tag_name = 'push'
    optional = dict()
    optional[Channel.TAG_NAME] = tag_name
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #12
0
def test_pushMessage_to_tag():
    c = Channel(apiKey, secretKey)
    push_type = 2
    tag_name = 'push'
    optional = dict()
    optional[Channel.TAG_NAME] = tag_name
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #13
0
def test_pushMessage_to_tag():
    c = Channel(apiKey, secretKey)
    push_type = 2
    optional = dict()
    optional[Channel.TAG_NAME] = tagname
    optional[Channel.MESSAGE_TYPE] = 1
    #	print 'hi:::::', push_type, message, message_key, optional
    ret = c.pushMessage(push_type, message, message_key, optional)
Beispiel #14
0
def test_pushMessage_to_tag():
    c = Channel(apiKey, secretKey)
    push_type = 2
    optional = dict()
    optional[Channel.TAG_NAME] = tagname
    optional[Channel.MESSAGE_TYPE] = 1
    # 	print 'hi:::::', push_type, message, message_key, optional
    ret = c.pushMessage(push_type, message, message_key, optional)
Beispiel #15
0
def test_queryBindList():

    c = Channel(apiKey, secretKey)

    #optional = dict()

    #optional[Channel.CHANNEL_ID] =  channel_id

    c.queryBindList()
Beispiel #16
0
def test_queryBindList():
	
	c = Channel(apiKey, secretKey)
	
	#optional = dict()
	
	#optional[Channel.CHANNEL_ID] =  channel_id
	
	c.queryBindList()	
Beispiel #17
0
def test_pushMessage_to_user(user_id,channel_id,phone_system,secretKey,message):
	c = Channel(apiKey, secretKey)
	push_type = 1
	optional = dict()
	optional[Channel.USER_ID] = user_id
	optional[Channel.CHANNEL_ID] = channel_id
	optional[Channel.MESSAGE_TYPE] = 1
	ret = c.pushMessage(push_type, message, message_key, optional)
	print ret
Beispiel #18
0
def test_pushMessage_to_user():
    c = Channel(apiKey, secretKey)
    push_type = 1
    optional = dict()
    optional[Channel.USER_ID] = user_id
    optional[Channel.CHANNEL_ID] = channel_id
    # 推送通知类型
    optional[Channel.MESSAGE_TYPE] = 0
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #19
0
def test_pushMessage_to_user():
    c = Channel(apiKey, secretKey)
    push_type = 1
    optional = dict()
    optional[Channel.USER_ID] = user_id
    optional[Channel.CHANNEL_ID] = channel_id
    #推送通知类型
    optional[Channel.MESSAGE_TYPE] = 1
    ret = c.pushMessage(push_type, message, message_key, optional)
    print ret
Beispiel #20
0
    def __init__(self, dwf, hdwf):
        self.dwf = dwf
        self.hdwf = hdwf

        self.ch1 = Channel.Channel(self.dwf, self.hdwf, 0)
        self.ch2 = Channel.Channel(self.dwf, self.hdwf, 1)

        self.frequency = 100000.00
        self.buffersize = 512
        self.trigger = Trigger.Trigger(self.dwf, self.hdwf)
Beispiel #21
0
 def push_to_user(self, user, message):
     channel = Channel(self.__secret.apiKey, self.__secret.secretKey)
     push_type = 1
     optional = dict()
     optional[Channel.USER_ID] = user[0]
     optional[Channel.CHANNEL_ID] = user[1]
     optional[Channel.MESSAGE_TYPE] = 0
     alertMessage = "{'title':'%s', 'description':'%s', 'custom_content': { 'amber_alert_id':'%s', 'from_user_id':'%s' }}" % (message[0], message[1], message[2], message[3])
     #jsonMessage = json.dumps(updateMessage)
     ret = channel.pushMessage(push_type, alertMessage, message_key, optional)
     print (ret)
     return ret
 def __init__(self,
              callbackFunction=None,
              channels={},
              progressStepSeconds=0.1,
              progressStepSize=15):
     self.status = WScannerStatus.NOTSTARTED
     self.callbackFunction = callbackFunction
     self.channels = channels
     self.newChannels = {1: Channel('A'), 2: Channel('B'), 3: Channel('C')}
     self.progress = WScanner._WScanner__MINCHANNEL
     self.progressStepSeconds = progressStepSeconds
     self.progressStepSize = progressStepSize
Beispiel #23
0
 def copyChannel(self, ch, labels):
     # making all labels 10/1 or 10/20 system
     label = self.system10_20.testLabel(labels[self.i])
     if label is None:
         '''This a label not in the system so we add
         it as additional information'''
         channel = Channel(labels[self.i], ch)
         self.additionalData.append(channel)
     else:
         channel = Channel(label, ch)
         self.channels.append(channel)
     self.i += 1
Beispiel #24
0
def test_pushMessage_to_user():
    c = Channel(apiKey, secretKey)
    c.DEFAULT_HOST=dev_host
    push_type = 1
    optional = dict()
    optional[Channel.USER_ID] = 815730795201756090
    #optional[Channel.USER_ID] = 665778416804465913
    #optional[Channel.CHANNEL_ID] = 4617656892525519033
    optional[Channel.CHANNEL_ID] = 4320553738754859600
    #推送通知类型
    optional[Channel.DEVICE_TYPE] = 4
    optional[Channel.MESSAGE_TYPE] = 1
    optional['phone_type'] = 'io'
    ret = c.pushMessage(push_type, message, hashlib.md5(str(datetime.datetime.now())).hexdigest(), optional)
    print ret
Beispiel #25
0
    def add_channels_to_server(self):

        with open(self.channels_file, 'r') as f:
            for line in f:
                if line != "":
                    channel_name = line.strip().split()[0]
                    self.channels[channel_name] = Channel.Channel(channel_name)
Beispiel #26
0
 def read(self):
     print("invoked read")
     ret = chnl._read(self.channel)
     print(ret)
     item = cPickle.loads(ret)
     print(item)
     return item
Beispiel #27
0
    def join_invite(self, client, channelName):
        isInSameRoom = False

        if client.get_clientName() in self.channels_client_map:
            if channelName in self.channels_client_map[
                    client.client.get_clientName()]:
                # User already on that channel
                client.send_message("\n> You are already in channel: " +
                                    channelName)
                isInSameRoom = True
            elif not channelName in self.channels_client_map[
                    client.client.get_clientName(
                    )] and channelName in self.channels:
                self.channels[channelName].clients[
                    client.get_clientName()] = client
                self.channels_client_map[client.get_clientName()].append(
                    channelName)

        if not isInSameRoom:
            if not channelName in self.channels:
                newChannel = Channel.Channel(channelName)
                self.channels[channelName] = newChannel
            self.channels[channelName].clients[
                client.get_clientName()] = client
            self.channels[channelName].welcome_client(client.get_clientName())
            self.channels_client_map[client.get_clientName()].append(
                channelName)
Beispiel #28
0
def main():
    global client, host, username, password, channel

    load_parameters()
    try:
        client = Client(host, username, password)
    except:
        print("Could not connect to remote host.")
    grid = ScreenGrid.ScreenGrid(2, 2)

    chans = []

    for counter, channel in enumerate(channels):
        chans.append(Channel.Channel(channel, counter, client, grid))

    while True:
        for chan in chans:
            chan.run()
            time.sleep(1)

        for event in pygame.event.get():
            if (event.type == pygame.KEYUP and event.key == pygame.K_c
                    and event.mod & pygame.KMOD_CTRL):
                pygame.quit()
                sys.exit()
Beispiel #29
0
 def ReDo(self, actions, es):
     # this redo's the filtering after forward
     self.GetParent().setStatus("Filtrando...", 1)
     self.eegs = es
     eegs = self.eegs
     new = []
     flag = False
     for eeg in eegs:
         # applying for each band
         bands = actions
         self.actions = bands
         if len(bands) > 0:
             flag = True
         for band in bands:
             channels = eeg.channels
             neweeg = deepcopy(eeg)
             neweeg.channels = []
             for ch in channels:
                 fourier = np.fft.rfft(ch.readings, len(ch.readings))
                 for i in range(len(fourier)):
                     if i < band.lowFrequency or i > band.hiFrequency:
                         fourier[i] = 0.0
                 # adding new filtered channel
                 filtered = np.fft.irfft(fourier)
                 fl = Channel(ch.label, filtered)
                 neweeg.channels.append(fl)
             # adding band limits to name
             neweeg.name += "~" + str(band.lowFrequency) + "~" + str(band.hiFrequency)
             new.append(neweeg)
     self.eegs.extend(new)
     self.pbutton.eegs = self.eegs
     self.GetParent().setStatus("", 0)
     if flag:
         self.exportButton.Enable()
Beispiel #30
0
    def join(self, clientSocket, chatMessage, clientName):
        isInSameRoom = False

        if len(chatMessage.split()) >= 2:
            channelName = chatMessage.split()[1]

            if clientName in self.channels_client_map:  # Here we are switching to a new channel.
                if self.channels_client_map[clientName] == channelName:
                    clientSocket.sendall(("\n> You are already in channel: " +
                                          channelName + "\n").encode('utf8'))
                    isInSameRoom = True
                else:  # switch to a new channel
                    oldChannelName = self.channels_client_map[clientName]
                    self.channels[oldChannelName].remove_client_from_channel(
                        clientName)  # remove them from the previous channel

            if not isInSameRoom:
                if not channelName in self.channels:
                    newChannel = Channel.Channel(channelName)
                    self.channels[channelName] = newChannel

                self.channels[channelName].clients[clientName] = clientSocket
                self.channels[channelName].welcome_client(clientName)
                self.channels_client_map[clientName] = channelName
        else:
            self.help(clientSocket)
Beispiel #31
0
 def loadFromCachedMode(self):
     import Channel
     import Playlist
     
     
     if not self._cachedMode:
         raise ValueError('Cannot load from cached mode. Pages are not in cached mode')
     
     
     
     #sourcesToUpdate = []
     
     for page in self._pages:
         if page.items:
             raise ValueError('In cached mode, yet page has original videosource items')
         
         items = []
         for cachedItem in page.cacheableItems:
             if cachedItem[0] == SourceType.CHANNEL:
                 channelId = cachedItem[1] 
                 ytVideoSource, needsInfoUpdate = Channel.fromUserOrId(channelId=channelId)
                 
             else:
                 playlistId = cachedItem[1]
                 ytVideoSource, needsInfoUpdate = Playlist.fromPlaylistId(playlistId)
                 
             items.append(ytVideoSource)
             if needsInfoUpdate:     #ignored here
                 pass
             
                 
         page.items = items
         
     self._cachedMode = False
Beispiel #32
0
 def concatenateWindows(self):
     if len(self.windows) == 0:
         return self
     self.SortWindows()
     channels = []
     for ch in self.channels:
         channels.append(Channel(ch.label, []))
     if len(self.windows) == 1:
         for i in range(len(channels)):
             reads = self.windows[0].readings[i]
             channels[i].readings.extend(reads)
     else:
         for w in range(len(self.windows)):
             for i in range(len(channels)):
                 reads = self.windows[w].readings[i]
                 if w < len(self.windows) - 1:
                     start, end = self.windows[w].GetSE()
                     s, e = self.windows[w+1].GetSE()
                     if start <= s <= end:
                         # there's overlapping
                         reads = self.windows[w].GetReadsUpTo(s)
                 channels[i].readings.extend(reads)
     concatenated = copy(self)
     concatenated.channels = channels
     concatenated.duration = len(channels[0].readings) / self.frequency
     return concatenated
Beispiel #33
0
    def join(self, user, chatMessage):
        isInSameRoom = False

        if len(chatMessage.split()) >= 2:
            channelName = chatMessage.split()[1]

            if user.username in self.users_channels_map:  # Here we are switching to a new channel.
                if self.users_channels_map[user.username] == channelName:
                    user.socket.sendall(
                        "\n> You are already in channel: {0}".format(
                            channelName).encode('utf8'))
                    isInSameRoom = True
                else:  # switch to a new channel
                    oldChannelName = self.users_channels_map[user.username]
                    self.channels[oldChannelName].remove_user_from_channel(
                        user)  # remove them from the previous channel

            if not isInSameRoom:
                if not channelName in self.channels:
                    newChannel = Channel.Channel(channelName)
                    self.channels[channelName] = newChannel

                self.channels[channelName].users.append(user)
                self.channels[channelName].welcome_user(user.username)
                self.users_channels_map[user.username] = channelName
        else:
            self.help(user.socket)
    async def end(self, context):
        """Command to archive a channel that has been finished."""
        user = context.author
        channel_id = context.channel.id
        guild_id = context.guild.id
        channel = Channel.get(user_id=user.id, id=channel_id, guild_id=guild_id)

        if not channel:
            await context.send(
                "This command must be sent from a proper playthrough room that you own."
            )
            return

        # TODO Check if already archived or not
        archival_category_obj = Category.get(
            guild_id=guild_id, game=channel.game, archival=True, full=False
        )
        if not archival_category_obj:
            await context.send(
                "No archival category is available for this game. Please contact an admin."
            )
            return

        archival_category = get(context.guild.categories, id=archival_category_obj.id)
        await context.channel.edit(category=archival_category, sync_permissions=True)

        completion_role_obj = CompletionRole.get(game=channel.game, guild_id=guild_id)
        if completion_role_obj:
            completion_role = get(context.guild.roles, id=completion_role_obj.id)
            await context.author.add_roles(completion_role)
            await context.send("You have been grantend the completion role.")

        await context.send("The channel has been moved to the archival category.")
    def __init__(self, serverFacade, comodo):

        screen_width = 640
        screen_height = 480
        screen_flag = 0
        screen_depht = 32

        self.colors = {}
        self.sprites = {}
        self.channels = {}

        pygame.init()
        self.screen = pygame.display.set_mode((screen_width, screen_height), screen_flag, screen_depht)
        self.clock = pygame.time.Clock()

        self.serverFacade = serverFacade
        self.comodo = comodo

        self.__loadColors()
        self.__loadSprites()
        self.__loadChannels()
        
        self.channel = Channel()
        #self.channel = self.channels.get(str(self.comodo.getTv().getChannel()))
        #self.resolution = self.channel.get_size()
        print (320-320*.27, 180-180*.27)
Beispiel #36
0
def get_section_channels(modeType):
    channelUrl = VVVVID_BASE_URL + getChannelsPath(modeType)
    response = getJsonDataFromUrl(channelUrl)
    data = json.loads(response.read().decode(
        response.info().getparam('charset') or 'utf-8'))
    channels = data['data']
    listChannels = []
    for channelData in channels:
        filter = ''
        path = ''
        listCategory = []
        listFilters = []
        listExtras = []
        if (channelData.has_key('filter')):
            for filter in channelData['filter']:
                listFilters.append(filter)
        if (channelData.has_key('category')):
            for category in channelData['category']:
                channelCategoryElem = ChannelCategory(category['id'],
                                                      category['name'])
                listCategory.append(channelCategoryElem)
        if (channelData.has_key('extras')):
            for extra in channelData['extras']:
                channelExtrasElem = ChannelExtra(extra['id'], extra['name'])
                listExtras.append(channelExtrasElem)

        channel = Channel(unicode(channelData['id']), channelData['name'],
                          listFilters, listCategory, listExtras)
        listChannels.append(channel)
    return listChannels
Beispiel #37
0
    def join(self, chatMessage, client):
        isInSameRoom = False

        if len(chatMessage.split()) >= 2:
            channelName = chatMessage.split()[1]

            if client.get_clientName() in self.channels_client_map:
                if channelName in self.channels_client_map[
                        client.client.get_clientName()]:
                    # User already on that channel
                    client.send_message("\n> You are already in channel: " +
                                        channelName)
                    isInSameRoom = True
                elif not channelName in self.channels_client_map[
                        client.client.get_clientName(
                        )] and channelName in self.channels:
                    self.channels[channelName].clients[
                        client.get_clientName()] = client
                    self.channels_client_map[client.get_clientName()].append(
                        channelName)

            if not isInSameRoom:
                if not channelName in self.channels:
                    newChannel = Channel.Channel(channelName)
                    self.channels[channelName] = newChannel
                self.channels[channelName].clients[
                    client.get_clientName()] = client
                self.channels[channelName].welcome_client(
                    client.get_clientName())
                self.channels_client_map[client.get_clientName()].append(
                    channelName)
        else:
            self.help(client.get_clientSocket())
Beispiel #38
0
    def _responseProcess(self, response):
        channels = []

        for item in response['items']:
            channel = Channel.fromChannelsRequest(item)
            channels.append(channel)

        return channels
Beispiel #39
0
 def is_selectable(self):
     #print ( "is_selectable has been called" )
     a = chnl.is_selectable(self.channel)
     #print ( "is_selectable got ", a )
     if a == 1:
         return True
     else:
         return False;
Beispiel #40
0
def test_pushMessage_to_user():
    c = Channel(apiKey, secretKey)
    c.DEFAULT_HOST=dev_host
    push_type = 1
    optional = dict()
    #optional[Channel.USER_ID] = 900581881515728799
    optional[Channel.USER_ID] = 654406316281477917
    #optional[Channel.USER_ID] = 665778416804465913
    #optional[Channel.CHANNEL_ID] = 4617656892525519033
    optional[Channel.CHANNEL_ID] = 3800664848253686124
    #optional[Channel.CHANNEL_ID] = 3800664848253686124
    #推送通知类型
    optional[Channel.DEVICE_TYPE] = 4
    optional[Channel.MESSAGE_TYPE] = 1
    optional['phone_type'] = 'ios'
    ret = c.pushMessage(push_type, message, hashlib.md5(str(datetime.datetime.now())).hexdigest(), optional)
    print ret
Beispiel #41
0
    def __init__(self):
        p = uuid.uuid4().int & 0xffffff
        av = uuid.uuid4().int & 0xffffff
        tak = uuid.uuid4().int & 0xffffff
        shm = uuid.uuid4().int & 0xffffff

        self.channel = chnl.getChannel(p,av,tak,shm)
        self.name = uuid.uuid1()
        return
Beispiel #42
0
 def _responseProcess(self, response):
     channels = []
             
     for item in response['items']:
         channel = Channel.fromChannelsRequest(item)
         channels.append(channel)            
         
         
     return channels
 def _responseProcess(response):  
     channels = []
     items = response['items']    
         
     for item in items:
         channel = Channel.fromSubscriptionsRequest(item)
         channels.append(channel)
         
     return channels
Beispiel #44
0
    def add_channel(self, channelName):
        targetChnl = Channel(channelName)
        self.channels[channelName] = targetChnl

        #send update
        for client in self.clients.values():
            client.send("/channel add {0}".format(targetChnl.name))

        return targetChnl
Beispiel #45
0
    def join(self, user, chatMessage):
        print("Join executed")
        if len(chatMessage.split()) >= 2:
            channelName = chatMessage.split()[1]


            try:
                # detect if user is in the channel mentioned
                if channelName in self.users_channels_map2[user.username]:
                    print('inside')
                    # detect if user is currently in that channel
                    if self.users_channels_map[user.username] == channelName:
                        user.socket.sendall("\n> You are already in channel: {0}".format(channelName).encode('utf8'))
                    else:  # switch to channel the user is already in
                        # switch to channel
                        print('inside2')
                        self.users_channels_map[user.username] = channelName
                        self.channels[channelName].welcome_user(user.username)
                elif channelName not in self.users_channels_map2[user.username]:
                    print("not inside")
                    if not channelName in self.channels:
                        newChannel = Channel.Channel(channelName)
                        self.channels[channelName] = newChannel

                    self.channels[channelName].users.append(user)
                    self.channels[channelName].welcome_user(user.username)
                    self.users_channels_map[user.username] = channelName
                    self.users_channels_map2[user.username].append(channelName)
                    self.channels[channelName].update_channels(user, self.users_channels_map2[user.username])
            except:
                print('inside except')
                # if the user is not in any channel, do the next
                # if the channel does not exist, create a new one
                if not channelName in self.channels:
                    newChannel = Channel.Channel(channelName)
                    self.channels[channelName] = newChannel

                # append the user object in the channel object
                self.channels[channelName].users.append(user)
                # change GUI ??###
                self.channels[channelName].welcome_user(user.username)
                self.users_channels_map[user.username] = channelName
                self.users_channels_map2[user.username] = [channelName]
                self.channels[channelName].update_channels(user, self.users_channels_map2[user.username])
Beispiel #46
0
def InsertChannelCallback( sender, query ):
    Log( "InsertChannelCallback ..." )

    # For testing by reducing url typing
    if FAST_MY_CHANNEL_ENTRY:
        # query = "hdhomerun://DEVICE-0/tuner0?channel=8vsb:999999&program=%s" % query
        query = "hdhomerun://DEVICE-0/ch24-%s" % query
    
    try:
        myChannel = Channel.fromUrl( query )
        if not myChannel:
            deviceId = Prefs[DEVICE_ID]
            tunerId = Prefs[TUNER_ID]

            return MessageContainer(
                L('Error'),
                "%s\n%s" % ( L('BadStreamUrl'),
                           "\n".join( Channel.getStreamUrlTemplates(deviceId, tunerId)))
                )

        # default channel to verfied and enabled
        myChannel.GuideName = L('MyChannel')
        myChannel.Verified = True
        myChannel.Enabled = True

        myLineupList = NewMyLineupList( myChannel )
        UpdateLineupList( myLineupList )
        
        return MessageContainer(
            L('Success'),
            "%s: %s" % ( L('Added'), myChannel.toString() )
            )

    except Exception, e:
        Log( "Exception: %s" % e, False )
        return MessageContainer(
            L('Error'),
            "%s: %s" % ( L('ProblemInsertingChannel'), query )
            )
Beispiel #47
0
 def send_request(self):
     channel = Channel(self.tm._monitor)
     self.set_channel(channel)
     channel.socket = None
     channel.setup_connection(
         self.request.get_host(),
         self.request.get_port(),
         self.request.get_type()
         )
     channel.send_request(self.request)
     self.send_time = uptime.secs()
     return
Beispiel #48
0
 def _responseProcess(self, response):
     results = []        
     
     items = response['items']
     
     for item in items:
         kind = item['id']['kind']
         
         if kind == 'youtube#channel':
             channel = Channel.fromSearchRequest(item)
             results.append(channel)
             
         elif kind == 'youtube#playlist':
             playlist = Playlist.fromSearchRequest(item)
             results.append(playlist)
             
         else:
             raise ValueError('Unknown kind in youtube search: %s' %kind)
             
     
                     
     return results
Beispiel #49
0
def fromXml( lineupXml ):
    Log( "Lineup.py fromXml ..." )
    """
    Parses a snippet of the XML returned from the SiliconDust site for a
    given country and postal code. The XML for a single channel looks like
    this:

    <Lineup>
        <DisplayName>Grande Cable: Austin, TX, 78750</DisplayName>
        <ProviderName>Grande Cable</ProviderName>
        <DatabaseID>2262080</DatabaseID>
        <Program>
              ....
          </Program>
     </Lineup>
    """
    
    lineup = Lineup()

    lineup.DisplayName = Util.XPathSelectOne( lineupXml, 'DisplayName' )
    lineup.ProviderName = Util.XPathSelectOne( lineupXml, 'ProviderName' )
    lineup.DatabaseId = Util.XPathSelectOne( lineupXml, 'DatabaseID' )

    # ProvideName is used for equality comparison, so we want to work hard
    # to make sure it has some value.
    if not lineup.ProviderName:
        prefixRe = re.compile( r'^([^\:]+)\:' )
        reMatch = prefixRe.match( lineup.DisplayName )
        if reMatch:
            lineup.ProviderName = reMatch.group(1)
    if not lineup.ProviderName:
        lineup.ProviderName = lineup.DisplayName
    if not lineup.ProviderName:
        lineup.ProviderName = lineup.DatabaseId
          
    for programXml in lineupXml.xpath('Program'):
        lineup.channelList.append( Channel.fromXml( programXml ))

    return lineup
Beispiel #50
0
def create_cell(ChanDict,name,pfile):
  comp_names=list()
  Ch=Channel.chanlib(ChanDict)
  cell= moose.loadModel(pfile,name)
  moose.Neutral(name)
  for comp in moose.wildcardFind('%s/#[TYPE=Compartment]'%(name)):
    print comp
    #comp=moose.element('/cell/soma')
    nachan=moose.copy('/library/NaF',comp,'NaF')
    kchan=moose.copy('/library/kDr',comp,'kDr')
    #skchan=moose.copy('/library/SKCa',comp,'SKCa')
    len =comp.length
    dia = comp.diameter
    SA= np.pi * len * dia
    #print SA
    kchan.Gbar= SA * 200e-2
    nachan.Gbar=SA * 30e-2
    #skchan.Gbar=SA*10
    moose.connect(nachan,'channel',comp,'channel')
    moose.connect(kchan,'channel',comp,'channel')
    #moose.connect(skchan,'channel',comp,'channel')
    #comp_names.append(comp.name)
    #print comp_names
  return comp
Beispiel #51
0
def test_queryUserTag():
	c = Channel(apiKey, secretKey)
	ret = c.queryUserTag(user_id)
	print ret
class ComodoUI:
    time_loading = 0
    cursorBluetooth = False
    clickBluetooth = False

    def __init__(self, serverFacade, comodo):

        screen_width = 640
        screen_height = 480
        screen_flag = 0
        screen_depht = 32

        self.colors = {}
        self.sprites = {}
        self.channels = {}

        pygame.init()
        self.screen = pygame.display.set_mode((screen_width, screen_height), screen_flag, screen_depht)
        self.clock = pygame.time.Clock()

        self.serverFacade = serverFacade
        self.comodo = comodo

        self.__loadColors()
        self.__loadSprites()
        self.__loadChannels()
        
        self.channel = Channel()
        #self.channel = self.channels.get(str(self.comodo.getTv().getChannel()))
        #self.resolution = self.channel.get_size()
        print (320-320*.27, 180-180*.27)
        #self.image_surface = pygame.Surface((320-320*.27, 180-180*.27))
        #self.image_surface.fill(self.colors.get("black"))
        #self.channel.set_display(self.image_surface)
        #self.channel.play()

    def __loadColors(self):
        self.colors["black"] = (0, 0, 0)
        self.colors["strong_orange"] = (255, 120, 0)
        self.colors["light_orange"] = (255, 173, 11)
        self.colors["white"] = (255, 255, 255)
        self.colors["green"] = (0, 255, 0)
        self.colors["light_green"] = (140, 220, 130)
        self.colors["blue"] = (0, 50, 255)

    def __loadSprites(self):
        self.sprites["tv_off"] = pygame.image.load("images/tv/desligada.png").convert()
        self.sprites["tv_on"] = pygame.image.load("images/tv/ligada.png").convert()
        self.sprites["som_off"] = pygame.image.load("images/som/sony.png").convert()
        self.sprites["som_on"] = pygame.image.load("images/som/sonyLigado.png").convert()
        self.sprites["people"] = pygame.image.load("images/people.png").convert()
        self.sprites["background"] = pygame.image.load("images/background.jpg").convert()
        self.sprites["bluetooth_deactive"] = pygame.image.load("images/bluetooth/deactive.png")
        self.sprites["bluetooth_active"] = pygame.image.load("images/bluetooth/active.png")

        for sprite in self.sprites.values():
            sprite.set_colorkey(self.colors["green"])

    def __loadChannels(self):
        self.channels["1"] = pygame.movie.Movie("channels/channel1.mpg")

    def run(self):
        while True:
            self.clock.tick(30)
            self.sprites["tv_off"].set_colorkey(self.colors["green"])
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    self.serverFacade.exit()
                    
                if pygame.mouse.get_cursor()[0] and 530 < pygame.mouse.get_pos()[0] < 570 and 10 < pygame.mouse.get_pos()[1] < 65:
                    self.cursorBluetooth = True
                    
                    if self.cursorBluetooth and pygame.mouse.get_pressed()[0] and 530 < pygame.mouse.get_pos()[0] < 570 and 10 < pygame.mouse.get_pos()[1] < 65:
                        self.clickBluetooth = True
                        self.__sendSignalBluetooth()
                        
                        if self.clickBluetooth == True:
                            self.clickBluetooth = False
                        
                else:
                    self.cursorBluetooth = False
                
            self.screen.blit(self.sprites["background"], (0, 0))
            if (self.serverFacade.getConnected()):
                self.__drawTV()
                #self.__drawSom()
                self.__printText(self.comodo.getNome(), "Arial", 35, 240, 10, self.colors["strong_orange"])
                self.__drawNumberPeople()
            else:
                self.__loadingScreen()
            pygame.display.flip()
    inverterVolume = False
    inverterCanal = False

    def __loadingScreen(self):
        if (self.time_loading < 10):
            self.__printText("Conectando", "Arial", 60, 150, 40, self.colors["white"])
            self.time_loading += 1
        elif (self.time_loading >= 10 and self.time_loading < 40):
            self.__printText("Conectando.", "Arial", 60, 150, 40, self.colors["white"])
            self.time_loading += 1
        elif (self.time_loading >= 40 and self.time_loading < 70):
            self.__printText("Conectando..", "Arial", 60, 150, 40, self.colors["white"])
            self.time_loading += 1
        elif (self.time_loading >= 70 and self.time_loading < 100):
            self.__printText("Conectando...", "Arial", 60, 150, 40, self.colors["white"])
            self.time_loading += 1
        else:
            self.__printText("Conectando", "Arial", 60, 150, 40, self.colors["white"])
            self.time_loading = 0

    def __drawTV(self):
        if (not(self.comodo.getTv().getEstado())):
            self.__drawEquipment(self.sprites.get("tv_off"), (20, 80))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((23, 260), (250, 50)))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((0, 10), (800, 50)))
        else:
            self.__drawEquipment(self.sprites.get("tv_on"), (20, 80))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((23, 260), (250, 50)))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((23, 260), (250, 50)))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((0, 10), (800, 50)))
            self.__drawTvDisplay(self.comodo.getTv())
            pygame.draw.rect(self.screen, self.colors["light_green"], Rect((56, 205), (self.comodo.getTv().getVolume() * 1.8, 10)))
            self.screen.blit(self.channel.play(str(self.comodo.getTv().getChannel())), (31, 98))
        self.__showInfo("TV", self.comodo.getTv(), (159, 285))

    def __drawSom(self):
        if (not(self.comodo.getSom().getEstado())):
            self.__drawEquipment(self.sprites.get("som_off"), (20 * 17, 80))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((23 * 15, 260), (250, 50)))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((0, 10), (800, 50)))
        else:
            self.__drawEquipment(self.sprites.get("som_on"), (20 * 17, 80))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((23 * 15, 260), (250, 50)))
            pygame.draw.rect(self.screen, self.colors["white"], Rect((0, 10), (800, 50)))

        self.__showInfo("SOM", self.comodo.getSom(), (159 * 3, 285))

    def __drawTvDisplay(self, equipment):
        pygame.draw.rect(self.screen, self.colors["white"], Rect((200, 112), (50, 20)))
        self.__printText("CH " + str(equipment.getChannel()), "Arial", 15, 205, 113, self.colors["blue"])
        self.__printText("+", "Arial", 20, 243, 195, (140, 220, 130))
        self.__printText("-", "Arial", 20, 40, 195, (140, 220, 130))

    def __drawEquipment(self, image, position):
        self.screen.blit(image, position)

    def __drawNumberPeople(self):
        pygame.draw.rect(self.screen, self.colors["white"], Rect((20, 400), (150, 63)))
        self.screen.blit(self.sprites["people"], (23, 400))
        self.__printText(str(self.comodo.getNumeroDePessoas()),"Arial",40,110,405,self.colors["black"])

    def __showChannel(self):
        self.screen.blit(self.image_surface, (31, 98))
        

    def __showInfo(self, equipmentName, equipment, position):
        self.__printText(equipmentName, "Arial", 40, position[0] - 125, position[1] - 25, self.colors["black"])
        self.__printText("Volume: " + str(equipment.getVolume()), "Arial", 20, position[0], position[1] - 23, self.colors["black"])
        self.__printText("Canal: " + str(equipment.getChannel()), "Arial", 20, position[0] + 15, position[1], self.colors["black"])

    def __printText(self, txtText, Textfont, Textsize, Textx, Texty, Textcolor):
        myfont = pygame.font.SysFont(Textfont, Textsize)
        label = myfont.render(txtText, 1, Textcolor)
        self.screen.blit(label, (Textx, Texty))
    
    def __drawDeviceBluetooth(self):
        if not self.cursorBluetooth:
            self.sprites["bluetooth_deactive"].set_colorkey((0, 255, 0))
            self.screen.blit(self.sprites["bluetooth_deactive"], (530, 10))
        else:
            self.sprites["bluetooth_active"].set_colorkey((0, 255, 0))
            self.screen.blit(self.sprites["bluetooth_active"], (530, 10))
            
    def __sendSignalBluetooth(self):
        if self.clickBluetooth:
            sendSignal = ClienteBluetooth()
            sendSignal.setComannd(self.comodo.getNome())
            sendSignal.start()
Beispiel #53
0
def test_verifyBind():
	c = Channel(apiKey, secretKey)
	optional = dict()
	optional[Channel.DEVICE_TYPE] = 3;
	ret = c.verifyBind(user_id, optional)
	print ret
Beispiel #54
0
def test_queryDeviceType():
	c = Channel(apiKey, secretKey)
	ret = c.queryDeviceType(channel_id)
	print ret
Beispiel #55
0
def test_fetchMessage():
	c = Channel(apiKey, secretKey)
	ret = c.fetchMessage(user_id)
	print ret	
Beispiel #56
0
def test_deleteTag():
	c = Channel(apiKey, secretKey)
	optional = dict()
	optional[Channel.USER_ID] = user_id
	ret = c.deleteTag(tagname, optional)
	print ret
Beispiel #57
0
def test_fetchTag():
	c = Channel(apiKey, secretKey)
	ret = c.fetchTag()
	print ret
Beispiel #58
0
def test_deleteMessage():
	c = Channel(apiKey, secretKey)
	msg_id = "111"
	ret = c.deleteMessage(user_id, msg_id)
	print ret