def openCalFrame(self): cv2.destroyAllWindows() self.hide() global iteration iteration = 0 Publisher.sendMessage("userFrameClosed", arg1="data") subFrame = CalibrationFrame()
def __init__(self): # Values and symbols of the card which will be created self.values = ['1','2','3','4','5','6','7','8','9','10','J','Q','K'] self.symbols = ['H', 'S', 'C', 'D'] # Generate the stock self.stock = [] for symbol in self.symbols: for value in self.values: self.stock.append(Card(symbol, value)) shuffle(self.stock) # Generate the waste self.waste = [] # generate empty piles for each color self.H = [] self.C = [] self.S = [] self.D = [] # generate empty waste self.waste = [] # generate tableau piles used to play self.PlayingStacks = [[], [], [], [], [], [], []] for stack in range (0, 7): for index in range (-1, stack): card = self.stock.pop() self.PlayingStacks[stack].append(card) self.PlayingStacks[stack][-1].setFaceDown(False) # Update GUI pub.sendMessage('refreshGUITopic')
def set_to_full(self): data = self.merge_blocks() if self.hash_is_correct(data): self.is_full = True self.raw_data = data self.write_piece_on_disk() pub.sendMessage('PiecesManager.PieceCompleted', piece_index=self.piece_index)
def connection_handler(self, fd, event): if fd == self.listener: (con,addr) = self.listener.accept() pub.sendMessage('TRACE.TCPSocket', msg=("Accepting connection from:" ,addr)) con.setblocking(0) self.rosie.add_io_handler(con, self.request_handler)
def test_commands_created(self): w = BaseMainWindow(None, None) cmd1 = Command(1, 'Name1', 'Desc1', lambda: 1, []) cmd2 = Command(2, 'Name2', 'Desc2', lambda: 1, []) cat1 = CommandCategory('Cat1') cat2 = CommandCategory('Cat2') cat1.append(cmd1) cat1.append(cat2) cat2.append(cmd2) tree = [cat1] pub.sendMessage('commands.created', command_tree=tree) self.assertEqual(1, w.main_menu.MenuCount) self.assertEqual(2, w.main_menu.GetMenu(0).MenuItemCount) self.assertEqual(1, w.main_menu.GetMenu(0).FindItemByPosition(1).SubMenu.MenuItemCount) cmd1.name = 'Nome1' cmd1.description = 'Descricao1' cmd2.name = 'Nome2' cmd2.description = 'Descricao2' cat1.name = 'Categoria1' cat2.name = 'Categoria2' pub.sendMessage('commands.changed', command_tree=tree, accel_table=wx.AcceleratorTable([])) self.assertEqual(cat1.name, w.main_menu.GetMenuLabel(0)) self.assertEqual(cmd1.name, w.main_menu.GetMenu(0).FindItemByPosition(0).ItemLabel) self.assertEqual(cat2.name, w.main_menu.GetMenu(0).FindItemByPosition(1).ItemLabel) self.assertEqual(cmd2.name, w.main_menu.GetMenu(0).FindItemByPosition(1).SubMenu.FindItemByPosition(0).ItemLabel)
def __init__(self, s_feats, cfg, cellclass = cell.DualCell): """ Initilization :param s_feats: the sensory features :type s_feats: tuple of ints :param s_bounds: bounds for each sensory features :type s_bounds: tuple of length 2 tuples of floats :param s_res: how many cell to create for each dimension :type s_res: tuple of ints """ self.dim = len(s_feats) self.s_feats = s_feats assert cfg.effect._get('s_bounds', None) != None, "{}you must define the s_bounds parameter for GridExplorer{}".format(gfx.red, gfx.end) assert len(cfg.effect.s_bounds) == self.dim self.bounds = cfg.effect.s_bounds self.cfg = cfg self.cfg._update(defcfg, overwrite = False) if type(cfg.effect.s_res) == int: self.s_res = [cfg.effect.s_res]*self.dim else: assert len(cfg.effect.s_res) == self.dim self.s_res = cfg.effect.s_res self.size = 0 pub.sendMessage('grid.init', grid = self, size = self.s_res, bounds = self.bounds) self.grid = {} self.cells = [] # list of cells for random choice self.active_cells = set() self.cellclass = cellclass self._build_grid()
def testSendTopicWithMessage(): class MyListener: def __init__(self): self.count = 0 self.heardTopic = False self.listen2Topics = [] def listen0(self): pass def listen1(self, **kwarg): self.count += 1 self.heardTopic = True def listen2(self, msgTopic=pub.AUTO_TOPIC, **kwarg): self.listen2Topics.append(msgTopic.getName()) my = MyListener() pub.subscribe(my.listen0, 'testSendTopic') pub.subscribe(my.listen1, 'testSendTopic') pub.subscribe(my.listen2, 'testSendTopic') pub.sendMessage('testSendTopic') assert my.count == 1 assert my.heardTopic == True pub.subscribe(my.listen0, 'testSendTopic.subtopic') pub.subscribe(my.listen1, 'testSendTopic.subtopic') pub.subscribe(my.listen2, 'testSendTopic.subtopic') pub.sendMessage('testSendTopic.subtopic') assert my.count == 3 assert [] == [topic for topic in my.listen2Topics if topic not in ('testSendTopic', 'testSendTopic.subtopic')]
def send( value, data, listeners ): """ Send takes the first listener off of the list listeners and sends the data to the next routine using the pubsub package. :param value: the value to send to the next routine :param data: additional data do pass along :param listeners: a list of subscribers that will get the data :Raises: ListenerSpecIncomplete Raised if there is a problem with the topic name. >>> from lib.common import Common >>> Common.send(999, {'device': 'xyz', 'port': 'abc'}, ()) Note: **This is a static method** """ if len( listeners ): # get the first item on the list listener = listeners.pop( 0 ) # test to see if the first item in the list is a list if ( ( type( listener ) == type( "" ) ) and ( len( listener ) > 0 ) ): pub.sendMessage( listener, value=value, data=data, listeners=listeners ) elif ( type( listener ) == type( [] ) ): Common.send( value, data, listener ) Common.send( value, data, listeners )
def finished_job(cls, job_id): """ Mark this job ID as finished, closing any open log handlers. :arg str job_id: The job ID we're done with. """ pub.sendMessage('job.close', job_id=job_id)
def on_message(self, message_string): # Only the first connected client can execute commands if not WebServer.clients or not self == WebServer.clients[0]: return if message_string: try: message = json.loads(message_string) except ValueError, e: print "Message is not in json format" return if "command" in message: if message["command"] == "set_frequency": frequency = message["args"]["frequency"] if isinstance(frequency, int): pub.sendMessage("set_frequency", frequency=frequency) elif message["command"] == "set_demodulation": demodulation = message["args"]["demodulation"] if demodulation: pub.sendMessage("set_demodulation", demodulation=demodulation) elif "notification" in message: if message["notification"] == "alive": WebServer.last_connectivity = time.time()
def lib_deregister(cat, name): del library[cat][name] debug("De-register %s command: %s" % (cat, name)) lib = {} for k in library: lib[k] = library[k].keys() pub.sendMessage("library", lib=lib)
def next_action(self): """The core of the guiding""" if not self.babble.finished or len(self.goalexplorer) < self.cfg.guide.min_orderbabble: babbling = self.babble.babble(self.t) action = Action(type = 'order', payload = babbling) path = 0 else: if random.random() < self.cfg.guide.ratio_orderbabble: babbling = self.babble.babble(self.t) action = Action(type = 'order', payload = babbling) path = 1 else: goal = self.goalexplorer.next_goal() if goal is None: babbling = self.babble.babble(self.t) action = Action(type = 'order', payload = babbling) path = 2 else: action = Action(type = 'goal', payload = goal) path = 3 pub.sendMessage('guide.next_action', guide = self, action = action, path = path) self.latest = action return action
def open_(self): if self.isClosed(): self.setClosed(False) pub.sendMessage("event.doorOpen", tile = self.tile) return True else: return False
def read(bot): global Bot Bot = bot if bot.remote['nick'] and bot.remote['nick'] != bot.nick: if bot.remote['message'].startswith(bot.prefix): bot._debug("Command received: %s" % bot.remote['message']) args = bot.remote['message'][1:].rstrip().split(" ") command = args[0].lower() if bot.remote['nick'].lower() not in bot.inv['banned']: if command in library['admin']: bot._debug('This is an admin-only command.') can_do = bot.remote['host'] in [host.strip() for host in bot.config.get(bot.network, 'admin_hostnames').split(',')] #can_do = can_do or bot.remote['nick'] in [nick.strip() for nick in bot.config.get(bot.network, 'admin').split(',')] if can_do: bot.previous['user'] = bot.remote['sendee'] pub.sendMessage("func.admin.%s" % library['admin'][command], bot=bot, args=args) else: if bot.voice: reply(bot.remote['sendee'], "%s: Can't do that, noob." % bot.remote['nick']) elif bot.voice and command in library['common']: bot._debug('This is a common command.') pub.sendMessage("func.common.%s" % library['common'][command], bot=bot, args=args) bot.previous['user'] = bot.remote['sendee'] elif bot.remote['message'].startswith("\x01") and bot.remote['message'].endswith("\x01"): type = bot.remote['message'][1:-1].split()[0] args = bot.remote['message'][1:-1].split()[1:] if type != "ACTION": ctcp(type, args) elif bot.remote['mid'] == "INVITE" and bot.remote['nick'].lower() not in bot.inv['banned']: join([bot.remote['mid'], bot.remote['message']]) else: if bot.init['registered'] and not bot.init['identified']: if bot.remote['nick'] == "NickServ": if "registered" in bot.remote['message']: bot._login() elif re.search("(accepted|identified)", bot.remote['message']): bot.init['identified'] = True __import__('time').sleep(3) autojoin() if bot.voice: #start scanning messages for certain data try: scanner.scan(bot) except (__import__('urllib2').URLError, __import__('socket').timeout): util.answer(bot, "fetch: response timeout exceeded.") else: if (bot.remote['mid'].startswith("4") or bot.remote['mid'].startswith("5")) and bot.remote['mid'] != "462": if bot.config.get(bot.network, 'traceback_notice_channel') == "yes" or bot.previous['user'][0] != "#": sendto = bot.previous['user'] or self.admin else: sendto = bot.admin reply(sendto, "Message from %s: Error #%s: %s" % (bot.remote['server'], bot.remote['mid'], bot.remote['message'])) if not bot.init['joined'] and not bot.init['registered']: autojoin()
def block_user(self, data): id = data["target"]["id"] if id in self.friends: self.friends.remove(id) if "blocks" in self.session.settings["general"]["buffer_order"]: self.session.db["blocked"]["items"].append(data["target"]) pub.sendMessage("blocked-user", data=data["target"], user=self.get_user())
def changeTimer(self, amount): print "Model:changeTimer amount: " + str(amount) self.timerValue = self.timerValue - amount #if self.timerValue > 0: # pub.sendMessage("timer_counting", amount=1) #pub.sendMessage("timer_counting", amount=1) # timer value is not zero, set another interrupt for 1s duration pub.sendMessage("timer_changed", money=self.timerValue)
def send_file(self, file_path): self.pauseState = False pub.sendMessage('programme-progress', progress=0) pub.sendMessage('queue-size', size=0) content = '' with open(file_path) as f: content = f.read() if bool(conf.get('common.filter_file_commands')): content = self.filter_file(content) # self.logger.debug('filtered file:' + content) if content is not None and content != '': self.commands_executed = 0 self.queue_size = 0 self.number_of_commands = 0 self.clear_command_queue() # wait for the sender to become ready while self.sender_thread is not None and \ self.sender_thread.isRunning(): time.sleep(0.3) self.tracking_progress = True self.timer() self.echo_back('start-of-file') self.sender(content) self.echo_back('end-of-file')
def save_settings(self, evt=None): """ Store the changes to the widgets to the settings.ini file This function should probably do some validation """ settings_dict = settings.settings.read_settings() for key, old_value in settings_dict.iteritems(): # This will help skip settings we don't change anyway group, item = key.split("/") if hasattr(self, item): if hasattr(getattr(self, item), "text"): new_value = getattr(self, item).text() else: new_value = getattr(self, item).currentText() if type(old_value) == int: new_value = int(new_value) if type(old_value) == float: new_value = float(new_value) if type(old_value) == QtGui.QKeySequence: new_value = QtGui.QKeySequence.fromString(new_value) if type(old_value) == bool: new_value = bool(new_value) if type(old_value) == unicode: new_value = str(new_value) if old_value != new_value: settings_dict[key] = new_value settings.settings.save_settings(settings_dict) # Notify the rest of the application that the settings have changed # TODO: changes here should propagate to the rest of the application (like the database screen) pub.sendMessage("changed_settings")
def afterUpdate(self): """ Called after a write (or batch of writes). Saves the current settings and notifies the bot. """ self.saveSettings() pub.sendMessage('settings:updated')
def save_configuration(self): if self.codes[self.dialog.general.language.GetSelection()] != config.app["app-settings"]["language"]: config.app["app-settings"]["language"] = self.codes[self.dialog.general.language.GetSelection()] languageHandler.setLanguage(config.app["app-settings"]["language"]) self.needs_restart = True if self.kmnames[self.dialog.general.km.GetSelection()] != config.app["app-settings"]["load_keymap"]: config.app["app-settings"]["load_keymap"] =self.kmnames[self.dialog.general.km.GetSelection()] kmFile = open(paths.config_path("keymap.keymap"), "w") kmFile.close() self.needs_restart = True if config.app["app-settings"]["use_invisible_keyboard_shorcuts"] != self.dialog.get_value("general", "use_invisible_shorcuts"): config.app["app-settings"]["use_invisible_keyboard_shorcuts"] = self.dialog.get_value("general", "use_invisible_shorcuts") pub.sendMessage("invisible-shorcuts-changed", registered=self.dialog.get_value("general", "use_invisible_shorcuts")) config.app["app-settings"]["voice_enabled"] = self.dialog.get_value("general", "disable_sapi5") config.app["app-settings"]["hide_gui"] = self.dialog.get_value("general", "hide_gui") config.app["app-settings"]["ask_at_exit"] = self.dialog.get_value("general", "ask_at_exit") config.app["app-settings"]["handle_longtweets"] = self.dialog.get_value("general", "handle_longtweets") config.app["app-settings"]["play_ready_sound"] = self.dialog.get_value("general", "play_ready_sound") config.app["app-settings"]["speak_ready_msg"] = self.dialog.get_value("general", "speak_ready_msg") if config.app["proxy"]["server"] != self.dialog.get_value("proxy", "server") or config.app["proxy"]["port"] != self.dialog.get_value("proxy", "port") or config.app["proxy"]["user"] != self.dialog.get_value("proxy", "user") or config.app["proxy"]["password"] != self.dialog.get_value("proxy", "password"): if self.is_started == True: self.needs_restart = True config.app["proxy"]["server"] = self.dialog.get_value("proxy", "server") config.app["proxy"]["port"] = self.dialog.get_value("proxy", "port") config.app["proxy"]["user"] = self.dialog.get_value("proxy", "user") config.app["proxy"]["password"] = self.dialog.get_value("proxy", "password") config.app.write()
def drawprobability(self, **kwargs): hometeam = json.loads(kwargs['hometeam']) awayteam = json.loads(kwargs['awayteam']) if (get_or_create_team(session=cherrypy.request.db, findplayers=awayteam) and get_or_create_team(session=cherrypy.request.db, findplayers=hometeam)): message={ 'awayNames':awayteam, 'homeNames':hometeam, 'strength':float(getStrength( session=cherrypy.request.db, homeNames=hometeam, awayNames=awayteam ))/100.0, 'winProbability':float(getWinProb(get_or_create_team(session=cherrypy.request.db, findplayers=awayteam).hitters,get_or_create_team(session=cherrypy.request.db, findplayers=hometeam).hitters))/100.0 } pub.sendMessage('currentgamedrawprobability', event='currentgamedrawprobability', message=message ) """ {'awayNames':["player1","player2","player3"], 'homeNames':["player4","player5","player6"], 'strength': '63.28', 'teamstrength':'64.30' """ else: print "invalid kwargs -> %s, %d, %d" % (kwargs, len(kwargs['awayteam']), len(kwargs['hometeam']))
def loadSettings(self): """ Called to populate all the settings into memory if necessary. Return True on Success, False on Failure. """ pub.sendMessage('settings:loaded') return True
def OnPaletteRequest(self, msg): """ Used to request the palette when a canvas is first drawn """ print 'Got palette request!' virtualPalette = self._updateVirtualPalette() pub.sendMessage('paletteResponse', msg=virtualPalette)
def addStory(self, story, save_extracted_text=False, save_raw_download=False, save_story_sentences=False): ''' Save a story (python object) to the database. Return success or failure boolean. ''' from pubsub import pub if self.storyExists(str(story['stories_id'])): return False story_attributes = { '_id': str(story['stories_id']), 'title': story['title'], 'url': story['url'], 'media_id': story['media_id'], 'collect_date': story['collect_date'], 'publish_date': story['publish_date'], 'description': story['description'], 'guid': story['guid'], 'fully_extracted': story['fully_extracted'], 'stories_id': story['stories_id'], } if( (save_extracted_text==True) and ('story_text' in story) ): story_attributes['story_text'] = story['story_text'] if( (save_raw_download==True) and ('first_raw_download_file' in story) ): story_attributes['first_raw_download_file'] = story['first_raw_download_file'] if('story_sentences' in story): story_attributes['story_sentences_count'] = len(story['story_sentences']) if( save_story_sentences==True ): story_attributes['story_sentences'] = story['story_sentences'] pub.sendMessage(self.EVENT_PRE_STORY_SAVE, db_story=story_attributes, raw_story=story) self._saveStory(story_attributes) saved_story = self.getStory( str(story['stories_id']) ) pub.sendMessage(self.EVENT_POST_STORY_SAVE, db_story=story_attributes, raw_story=story) return True
def variable_selected(self,event): # Find selected variable item = self.var_list.selection() if len(item) == 0: return # Get associated var_id var_id = self.var_dict[item[0]][0] self.displayed_var_id = var_id # If selected variable is writeable if self.var_dict[item[0]][4] == 1: self.variable.set(self.var_dict[item[0]][1]) # First, tell MCU to stop logging former variable ? # !!! Warning, if variable was requested by a plot, this is going to shut it down for the plot as well # Tell MCU to start logging new variable # Or other approach is to request the value a single time else: self.variable.set("** Variable not writeable **") pub.sendMessage("new_var_selected",varid=var_id,varname=self.var_dict[item[0]][1])
def testNotifyByPrint(): capture = captureStdout() def listener1(arg1): pass pub.subscribe(listener1, 'baz') pub.sendMessage('baz', arg1=123) pub.unsubscribe(listener1, 'baz') def doa(): def listener2(): pass pub.subscribe(listener2, 'bar') doa() # listener2 should be gc'd gc.collect() # for pypy: the gc doesn't work the same as cpython's topicMgr.delTopic('baz') expect = """\ PUBSUB: New topic "baz" created PUBSUB: Subscribed listener "listener1" to topic "baz" PUBSUB: Start sending message of topic "baz" PUBSUB: Sending message of topic "baz" to listener listener1 PUBSUB: Done sending message of topic "baz" PUBSUB: Unsubscribed listener "listener1" from topic "baz" PUBSUB: New topic "bar" created PUBSUB: Subscribed listener "listener2" to topic "bar" PUBSUB: Listener "listener2" of Topic "bar" has died PUBSUB: Topic "baz" destroyed """ captured = capture.getvalue() #print captured #print repr(expect) assert captured == expect, \ '\n'.join( unified_diff(expect.splitlines(), captured.splitlines(), n=0) )
def input_handler(self, fd, event): for ln in self.s: try: (key,val) = ln.split(':', 1) if (not self.last_values.has_key(key)): self.last_values[key] = 0; #if (val == self.last_values[key]): # continue # nevermind if (key == 'photo'): pub.sendMessage(key, level=int(val)) if (key == 'RH'): rounded = round(float(val),1) pub.sendMessage(key, humidity=rounded) if (key.startswith('temp.')): if (float(val) > 50): pub.sendMessage('debug', msg=ln) pub.sendMessage(key, \ tempC=float(val), tempF=float(val)*(9.0/5.0)+32 ) self.last_values[key] = val except ValueError: pub.sendMessage('debug', msg=ln) continue
def addStory(self, story, save_extracted_text=False, save_raw_download=True, save_story_sentences=False): """ Save a story (python object) to the database. Return success or failure boolean. """ if self.storyExists(str(story["stories_id"])): return False story_attributes = { "_id": str(story["stories_id"]), "title": story["title"], "url": story["url"], "media_id": story["media_id"], "collect_date": story["collect_date"], "publish_date": story["publish_date"], "description": story["description"], "guid": story["guid"], "fully_extracted": story["fully_extracted"], # TODO: look at this instead? "stories_id": story["stories_id"], "text": story["story_text"], } if (save_extracted_text == True) and ("story_text" in story): story_attributes["story_text"] = story["story_text"] if (save_raw_download == True) and ("first_raw_download_file" in story): story_attributes["first_raw_download_file"] = story["first_raw_download_file"] if "story_sentences" in story: story_attributes["story_sentences_count"] = len(story["story_sentences"]) if save_story_sentences == True: story_attributes["story_sentences"] = story["story_sentences"] pub.sendMessage(self.EVENT_PRE_STORY_SAVE, db_story=story_attributes, raw_story=story) self._db.save(story_attributes) saved_story = self.getStory(str(story["stories_id"])) pub.sendMessage(self.EVENT_POST_STORY_SAVE, db_story=story_attributes, raw_story=story) return True
def process_dm(self, data): if self.session.db["user_name"] == data["direct_message"]["sender"]["screen_name"]: self.put_data("sent_direct_messages", data["direct_message"]) pub.sendMessage("sent-dm", data=data["direct_message"], user=self.get_user()) else: self.put_data("direct_messages", data["direct_message"]) pub.sendMessage("direct-message", data=data["direct_message"], user=self.get_user())
def zabbix_push(self, key, val): # The Zabbix JSON parser is picky, so we have to build the # JSON by hand instead of letting the JSON module do it injson = '{"request":"sender data",\ "data":[\ {\ "host":"silentbob",\ "key":"%s",\ "value":"%s"}]}' % (key, val) #pub.sendMessage('zabbix', msg=injson) try: s = socket(AF_INET, SOCK_STREAM) s.settimeout(10) s.connect(('hmcgregor01.biggeeks.org', 10051)) s.send("ZBXD\x01") datalen = '%08x' % len(injson) datalen = datalen[6:8] + datalen[4:6] + datalen[2:4] + datalen[0:2] s.send(datalen) s.send(injson) #pub.sendMessage('zabbix', msg=s.recv(1024)) s.close() except Exception as e: pub.sendMessage('zabbix', msg='Zabbix push failed:'+str(e)) #nevermind pass
def unblock(self, data): if "blocks" in self.session.settings["general"]["buffer_order"] == True: item = utils.find_item(data["target"]["id"], self.session.db["blocked"]["items"]) self.session.db["blocked"]["items"].pop(item) pub.sendMessage("unblocked-user", item=item, user=self.get_user())
def on_timeout(self, *args, **kwargs): log.debug("Twitter timeout Error") pub.sendMessage("stream-error")
def on_success(self, data): try: if "direct_message" in data: self.process_dm(data) elif "friends" in data: self.friends = data["friends"] pub.sendMessage("friends-receibed") elif "text" in data and utils.is_allowed(data, self.session.settings["twitter"]["ignored_clients"]) == True: if data["user"]["id"] in self.muted_users: return self.check_mentions(data) self.check_send(data) if data["user"]["id"] in self.friends or data["user"]["screen_name"] == self.session.db["user_name"]: self.put_data("home_timeline", data) pub.sendMessage("item-in-home", data=data, user=self.get_user()) elif data.has_key("event"): if "favorite" == data["event"] and "favorites" in self.session.settings["general"]["buffer_order"]: self.check_favs(data) elif "unfavorite" == data["event"] and "favorites" in self.session.settings["general"]["buffer_order"]: self.remove_fav(data) elif "follow" == data["event"] and "followers" in self.session.settings["general"]["buffer_order"]: self.check_follower(data) elif "unfollow" == data["event"] and "friends" in self.session.settings["general"]["buffer_order"]: self.remove_friend(data) elif "block" == data["event"]: self.block_user(data) elif "unblock" == data["event"]: self.unblock(data) elif "list_created" == data["event"]: item = utils.find_item(data["target_object"]["id"], self.session.db["lists"]) if item != None: self.session.db["lists"].append(data["target_object"]) elif "list_destroyed" == data["event"]: item = utils.find_item(data["target_object"]["id"], self.session.db["lists"]) if item != None: self.session.db["lists"].pop(item) self.parent.remove_list(data["target_object"]["id"]) elif "list_member_added" == data["event"] and data["source"]["screen_name"] == self.get_user(): pub.sendMessage("new-list-member-added", **{"id":str(data["target"]["id"]), "list":data["target_object"], "user":self.get_user()}) elif "list_member_added" == data["event"] and data["target"]["screen_name"] == self.get_user(): self.session.db["lists"].append(data["target_object"]) elif "list_member_removed" == data["event"] and data["source"]["screen_name"] == self.get_user(): pub.sendMessage("list-member-deleted", **{"id":str(data["target"]["id"]), "list":data["target_object"], "user":self.get_user()}) elif "list_member_removed" == data["event"] and data["target"] == self.get_user(): id = data["target_object"]["id"] list = utils.find_item(id, self.session.db["lists"]) if list != None: self.session.db["lists"].pop(list) pub.sendMessage("list-deleted", **{"item":list, "user":self.get_user()}) elif "quoted_tweet" == data["event"]: self.set_quoted_tweet(data["target_object"]) if "events" in self.session.settings["general"]["buffer_order"]: pub.sendMessage("event", data= data, user= self.get_user()) # self.sound.play("new_event.ogg") except KeyboardInterrupt: pass
def EndLoadFile(self, bitmap_list): Publisher.sendMessage("End bitmap load", data=bitmap_list)
# print it correctly T: x,y,z R: x,y,z if data[0] == 1: # translation packet tx = data[1] + (data[2] * 256) ty = data[3] + (data[4] * 256) tz = data[5] + (data[6] * 256) if data[2] > 127: tx -= 65536 if data[4] > 127: ty -= 65536 if data[6] > 127: tz -= 65536 print("T: ", tx, ty, tz) pub.sendMessage('tx', val=NonLinear(tx)) pub.sendMessage('ty', val=NonLinear(ty)) pub.sendMessage('tz', val=NonLinear(tz)) if data[0] == 2: # rotation packet rx = data[1] + (data[2] * 256) ry = data[3] + (data[4] * 256) rz = data[5] + (data[6] * 256) if data[2] > 127: rx -= 65536 if data[4] > 127: ry -= 65536 if data[6] > 127: rz -= 65536
def movementlistener(self, message): sender = message[0] if sender in self.active_dict: if self.active_dict[sender]: pub.sendMessage("movement", message=message[1]) self.sendtime = time.time()
def save_entry(self, _): if self.entry is None: return self.entry.flags = self.flags.GetValue() pub.sendMessage('update_entry', item=self.item, entry=self.entry)
def on_save(self, event): """ Event handler that saves the data to disk """ pub.sendMessage('save_{}'.format(self.panel.page_id))
def on_add_node(self, event): pub.sendMessage(f'add_node_{self.page_id}')
def OnClickCancel(self, evt): Publisher.sendMessage("Cancel DICOM load")
def OnBrushSize(self, evt): """ """ # FIXME: Using wx.EVT_SPINCTRL in MacOS it doesnt capture changes only # in the text ctrl - so we are capturing only changes on text # Strangelly this is being called twice Publisher.sendMessage('Set watershed brush size', size=self.spin.GetValue())
def removeMoney(self, value): self.myMoney -= value #now tell anyone who cares that the value has been changed pub.sendMessage("MONEYCHANGED", money=self.myMoney)
def OnSelectColour(self, evt): colour = evt.GetValue()[:3] self.gradient.SetColour(colour) Publisher.sendMessage('Change mask colour', colour=colour)
def OnGradientChanged(self, evt): thresh_min = self.gradient_thresh.GetMinValue() thresh_max = self.gradient_thresh.GetMaxValue() if self.bind_evt_gradient: Publisher.sendMessage('Set edition threshold values', threshold_range=(thresh_min, thresh_max))
def OnDisableStyle(self): if (self.last_style == const.SLICE_STATE_EDITOR): Publisher.sendMessage('Disable style', style=const.SLICE_STATE_EDITOR)
def OnComboName(self, evt): mask_name = evt.GetString() mask_index = evt.GetSelection() Publisher.sendMessage('Change mask selected', index=mask_index) Publisher.sendMessage('Show mask', index=mask_index, value=True)
def OnCheckWWWL(self, evt): value = self.ww_wl_cbox.GetValue() Publisher.sendMessage('Set use ww wl', use_ww_wl=value)
def OnExpandWatershed(self, evt): Publisher.sendMessage('Expand watershed to 3D AXIAL')
def OnComboBrushOp(self, evt): brush_op = self.combo_brush_op.GetValue() Publisher.sendMessage('Set watershed operation', operation=brush_op)
def OnCheckOverwriteMask(self, evt): value = self.check_box.GetValue() Publisher.sendMessage('Set overwrite mask', flag=value)
def add_todo(self, e): with TodoFormDialog(note_id=self.note_id) as dlg: if dlg.ShowModal() == wx.ID_OK: todo = Todo.create(**self._get_dialog_detail(dlg)) self.append(todo) pub.sendMessage('on.todo.change', note_id=self.note_id)
# translation packet tx = data[1] + (data[2] * 256) ty = data[3] + (data[4] * 256) tz = data[5] + (data[6] * 256) if data[2] > 127: tx -= 65536 if data[4] > 127: ty -= 65536 if data[6] > 127: tz -= 65536 print("T: ", tx, ty, tz) tx = NonLinear(tx) ty = NonLinear(ty) tz = NonLinear(tz) pub.sendMessage('tx', val=tx) pub.sendMessage('ty', val=ty) pub.sendMessage('tz', val=tz) if data[0] == 2: # rotation packet rx = data[1] + (data[2] * 256) ry = data[3] + (data[4] * 256) rz = data[5] + (data[6] * 256) if data[2] > 127: rx -= 65536 if data[4] > 127: ry -= 65536 if data[6] > 127: rz -= 65536
def addMoney(self, value): self.myMoney += value #now tell anyone who cares that the value has been changed pub.sendMessage("money_changed", money=self.myMoney)
def __create_taxonomy(self): """Executes when the taxonomy is created (in the CreateTaxonomyWindow).""" self.__build_tree() pub.sendMessage(actions.TAXONOMY_EDITED)
def addState(self): pub.sendMessage("MAINWINDOW_ADD_STATE")
def hide_panels(self): for panel in self.panels.values(): panel.Hide() pub.sendMessage('clear_focus') self.current_panel = None self.Layout()
def addTransition(self): pub.sendMessage("MAINWINDOW_ADD_TRANSITION")
def remove_friend(self, data): if "friends" in self.session.settings["general"]["buffer_order"]: item = utils.find_item(data["target"]["id"], self.session.db["friends"]["items"]) if item > 0: self.friends.pop(item) pub.sendMessage("unfollowing", item=item, user=self.get_user())
def ClickOnHelp(self, evt): pub.sendMessage("MAIN_FRAME.CLICK_ON_HELP")
def UpdateLoadFileProgress(self, cont_progress): Publisher.sendMessage("Update bitmap load", data=cont_progress)