def test_exec(self): auth = AuthManager("test/etc/users.auth") authkey = AuthKey(None, "my.pass") commander = Commander(auth) print commander.execute(self.command, self.data, authkey)
def test_acceptable_output(self): out = CommandOutputPipeBase(False, ["unacceptable"]) commander = Commander(out) try: commander.run_command(["echo", "some", "highly", "acceptable", "message"]) except: self.fail("run_command shouldn't have thrown an exception")
class MkrBot(telepot.helper.ChatHandler): _logger = None _commander = None def __init__(self, seed_tuple, timeout, log_path, log_level): super(MkrBot, self).__init__(seed_tuple, timeout) self._logger = Logger(log_path, log_level) self._commander = Commander() def on_message(self, msg): # check valid users # ... contents_type, chat_type, chat_id = telepot.glance(msg) if contents_type is 'text': self._handle_command(msg['text']) self.sender.sendMessage(msg['text']) return # self._logger.log('{0}, {1}, {2}'.format(contents_type, chat_type, chat_id)) def _handle_command(self, text): # parse text self._commander.handle_command(text)
def on_done(self, message): sublime.status_message("Sending new WorkingOn status") command = "granify send workingon \"%s\"" % message.encode('utf-8') queue = Queue.Queue() general = Commander(command, queue) general.start()
def main(): try: # Load system configuration conf = parse_arguments() # Send logging output to a file if specified configure_log(conf["log.file"]) # Look for available commands commands = find_commands("cmds/", conf["home.dir"]) # Core components auth = AuthManager(conf["home.dir"] + "/users.auth") commander = Commander(auth) scanner = MailScanner(Parsers(commands)) notifier = EmailNotifier(conf["smtp.host"], conf["smtp.port"]) # Read the email from stdin email = UnicodeParser().parse(sys.stdin) cmd_id, data, sprops, authkey = scanner.scan(email) auth_users = [key.user for key in auth.keys[cmd_id] if key.user] command = commands[cmd_id] output = commander.execute(command, data, authkey) if output: notifier.send(SuccessNotification(conf["notification.sender"], \ auth_users, command, sprops)) except AuthException, err: notifier.send(AuthNotification(cmd_id, conf["commander.address"], \ auth_users, email, data))
def main(): try: # Load system configuration conf = parse_arguments() # Send logging output to a file if specified configure_log(conf["log.file"]) # Look for available commands commands = find_commands("cmds/", conf["home.dir"]) # Core components auth = AuthManager(conf["home.dir"] + "/users.auth") commander = Commander(auth) scanner = MailScanner(Parsers(commands)) notifier = EmailNotifier(conf["smtp.host"], conf["smtp.port"]) # Read the email from stdin email = UnicodeParser().parse(sys.stdin) cmd_id, data, sprops, authkey = scanner.scan(email) auth_users = [ key.user for key in auth.keys[cmd_id] if key.user ] command = commands[cmd_id] output = commander.execute(command, data, authkey) if output: notifier.send(SuccessNotification(conf["notification.sender"], \ auth_users, command, sprops)) except AuthException, err: notifier.send(AuthNotification(cmd_id, conf["commander.address"], \ auth_users, email, data))
def test_commander(self): c = IMConfig("win32", "../", "../", "../os_defaults/") cmd = Cmd(c, "win32 ") assert ( cmd.start_vm() == "%PROGRAMFILES%\\Oracle\VirtualBox\\vboxmanage.exe startvm Island --type headless" )
class Window: def __init__(self): self.labels = [] top = Tkinter.Tk() self.commander = Commander() self.set_top(top) self.menu() top.geometry('{}x{}'.format(600, 600)) top.configure(bg='#445566') top.mainloop() def menu(self): mainmenu = Mainmenu(self.top) mainmenu.buttons(self) def set_top(self, top): self.top = top self.scrollbar = Scrollbar(self.top) self.scrollbar.pack(side=RIGHT, fill=Y) self.mylist = Listbox(self.top, yscrollcommand=self.scrollbar.set, width=600) def clean_labels(self): index = 0 for i in self.fileArray: self.fileArray.delete(index) index += 1 self.mylist.delete(0, END) def generate(self, files): self.fileArray = [] self.clean_labels() for index, i in enumerate(files): self.mylist.insert(END, files[index]) self.fileArray.append(files[index]) self.mylist.bind('<<ListboxSelect>>', lambda event, a=self.mylist: self.text_callback(a)) self.mylist.pack(side=LEFT, fill=BOTH) self.scrollbar.config(command=self.mylist.yview) def text_callback(self, fileCombo): fileCombo = self.fileArray[int(fileCombo.curselection()[0])] path = fileCombo if fileCombo.split('\t').count > 2: path = fileCombo.split('\t')[1] text = self.commander.examine_by_path(path) files = text.split('\n') self.generate(files) def start(self): text = self.commander.examine() files = text.split('\n') self.generate(files) def back(self): text = self.commander.back() files = text.split('\n') self.generate(files)
class SlackBot: def __init__(self): self._BOT_ID = os.environ.get("BOT_ID") self._AT_BOT = "<@" + str(self._BOT_ID) + ">" self._SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") self._slack_client = SlackClient(self._SLACK_TOKEN) self._parser = Parser(self._BOT_ID, self._AT_BOT) self._decoder = Decoder(self._SLACK_TOKEN) self._commander = Commander() def connect(self): """ Connect the slack bot to the chatroom """ READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose if self._slack_client.rtm_connect(): print("{} connected and running!".format(self._BOT_ID)) while True: json_list = self._slack_client.rtm_read() dictionary = self._parser.parse(json_list) if dictionary: dictionary = self._decoder.decode( dictionary) # Potentially encoded values self._commander.listen_message(dictionary) time.sleep(READ_WEBSOCKET_DELAY) else: print( "Connection failed. Are you connected to the internet? Invalid Slack token or bot ID?" )
def __init__(self): self._BOT_ID = os.environ.get("BOT_ID") self._AT_BOT = "<@" + str(self._BOT_ID) + ">" self._SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") self._slack_client = SlackClient(self._SLACK_TOKEN) self._parser = Parser(self._BOT_ID, self._AT_BOT) self._decoder = Decoder(self._SLACK_TOKEN) self._commander = Commander()
def test_register_and_execute(self): commander = Commander() def command(request_body): return True commander.register_command('command', command) result = commander.execute('command', {}) assert result == True
def test_execute_params(self): commander = Commander() def command(text): return text commander.register_command('com', command) result = commander.execute('com', 'shalom') assert result == 'shalom'
def test_run_cmd(sleep_cmd): out = ProgressOutputPipe() commander = Commander(out) commander.run_command( ["sh", "-c", "for x in {1..10}; do echo $x; %s done" % sleep_cmd]) for i in range(1, 10): assert i == int(out.stdout[i - 1])
def __init__(self): self.labels = [] top = Tkinter.Tk() self.commander = Commander() self.set_top(top) self.menu() top.geometry('{}x{}'.format(600, 600)) top.configure(bg='#445566') top.mainloop()
def __init__(self, t_group_id, t_long_poll, t_vk_api): self.m_group_id = t_group_id self.m_long_poll = t_long_poll self.m_vk_api = t_vk_api self.m_message_processor = MessageProcessor(self.m_group_id, self.m_long_poll, self.m_vk_api) self.m_commander = Commander()
def main(): sayer = GoogleSayer() txt = u""" Nemusí vám být osm let, abyste toužili na nějakou tu chvilku ponořit se do svého vlastního světa; do prostředí plného rozmanité fantazie, mírně zkrášlených představ a upravených realit. Jen tak pro radost, pro vlastní potěšení a pro pocit uspokojení. Takovou psychickou léčbou projde čas od času každý, někdo častěji a dokonaleji, jiný zřídka a povrchně. Přestože je v podobném „mini-světě“ většinou vše černobílé a občas i nemastné a neslané, stejně krátká exkurze potěší. Jednu podívanou stejného druhu připravil i režisér Rich Moore v animovaném trháku Raubíř Ralf. Povedlo se mu vytvořit skvělý film – odehrávající se v drobném, ale nesmírně zajímavém a chytře promyšleném světě herních automatů. Hlavní hrdina Ralf je typický záporák. Na rozdíl od dalších negativních postav však nevykrádá banky ani neplodí nemanželské děti; ke statusu toho špatného mu postačuje jeho každodenní práce. V herním automatu Fix-It Felix (tedy Oprav to, Felixi) vždy s vervou rozbije postavený dům, který po něm musí pracně opravit postavička Felix, ovládaná oním mladým stvořením stojícím před konzolí. Všechny vavříny, medaile a pochvalná gesta tak logicky sbírá právě Felix, což se Ralfovi příliš nelíbí. Proto se vydává na dobrodružnou výpravu do dalších her a v jejich prostředích se snaží získat ocenění a obdivná plácání po ramenou. Během devadesáti čtyř minut se několikrát zdá, že se vysněné odměny dočká – jenže pokaždé mu do toho „něco skočí“. A tak musí bojovat až do úplného konce. Happy end se přesto koná a Ralf se z něj neraduje sám, nýbrž s kamarádkou Vanellope, které tím vlastně také zachránil krk. Dle výše popsaného příběhu můžete usoudit, jak moc je zvláštní zápletka. Nic extra. Vše ale vynahrazuje excelentní zpracování a zasazení do světa skutečně existujících her. Já osobně nepatřím mezi milovníky konzolí různých druhů (po pravdě řečeno jsem nerozpoznal ani jeden název videohry); přesto mi neunikl nádech nostalgie, s jakou jsou všechny virtuality prezentovány. Důmyslný svět, v rámci něhož mohly postavičky po zavírací době přecházet mezi svými zaměstnáními a prožívat různorodá trápení, vás vskutku ohromí a nenechá přemýšlet nad tím, jestli by se tohle a tamto dalo udělat lépe či jinak. Nápad a prostředí v Raubíři Ralfovi jednoduše dělají víc než polovinu úspěchu. Diváckou náladu zvednou i hlášky hlavních postav. Jsou absurdní a svým způsobem dětinské – právě proto však vyvolají na tvářích diváků lehký úsměv podkreslený dávkou ironie. Onen úsměv a potěšení vydrží i při sledování product placementových vložek – sušenky Oreo v roli strážců hradu, kakao Nesquik jako hnědé lepkavé jezero nebo dietní coca-cola tvořící v kombinaci s mentoskami explodující sopku. Sice jde o klasickou reklamu; nicméně ta díky vcelku úsměvnému a komickému zakomponování do děje dodává potřebnou šťávu. Zmínku si neodpustím ani směrem k českému dabingu. Ten domácím tvůrcům víceméně vyšel, z normálu vybočovala pouze Veronika Žilková, která propůjčila svůj hlas dívčí hrdince Vanellope. Jakkoliv vynikající herečkou může Žilková být, rádoby roztomilý hlas v Raubíři Ralfovi spíše působil, jako by jí někdo na boky přilepil husí křídla, držel pistoli u hlavy a nutil ji napodobovat tóny opeřence. Možná jde jen o můj laický dojem – každopádně především laici do kin chodí. Dabing prostě udělal na kontě disneyovského snímku drobnou kaňku. Ve všem ostatním je Raubíř Ralf velmi kvalitní film – a rovněž i nesmírně chytré dílo. Nejedná se totiž o směsici toho „nejdětštějšího“ z širokého okolí, která má přinést nejvyšší tržby a hysterickou hladovost nejmenších diváků. Zápletka a hlavně prostředí snesou měřítka animáku, na nějž rádi přijdou diváci různých věkových kategorií. A takové obveselení se teď před Vánoci hodí všem. """ for sentence in txt.split("."): sayer.say(sentence) """rr = RSSReader(open("data/idnes.rss")) rr.retrieve_rss() newslist = rr.get_titles() newslist_links = rr.get_links() txt = idnes.get_text(newslist_links[1]) print txt exit(0)""" # start commander comm = Commander("localhost", 12345) comm.daemon = True comm.start() # start task stack ts = TaskStack() ts.daemon = True ts.start() mainop = MainOperator(comm, ts) mainop.daemon = True mainop.start() while 1: raw_input() #sayer = EposSayer() sayer = GoogleSayer() rr = RSSReader(open("data/idnes.rss")) rr.retrieve_rss() for i, title in enumerate(rr.get_titles()[:4]): sayer.say(u"%d. zpráva:" % (i + 1)) sayer.say(title) sayer.save_cache()
def run(self): LOG.debug('Leader.run()') ballot_num = (0,self.communicator.identity('leader')[0]) LOG.debug("BALLOT: " + str(ballot_num)) active = False proposals = [] # Spawn a scout. me = self.communicator.identity('leader') Scout(me, self.acceptors, ballot_num, self.communicator).start() while True: sender, msg = self.receive() LOG.debug('Leader.receive: (%s,%s)' % (sender, msg)) msg = msg.split(':') # Case 1 if msg[0] == 'propose': LOG.debug("Leader: Inside propose") sp = ast.literal_eval(msg[1]) s = sp[0] p = sp[1] if all([proposal[0] != s for proposal in proposals]): # proposals = proposals union [sp] if sp not in proposals: proposals.append(sp) if active: bsp = (ballot_num, s, p) LOG.debug("Leader spawning COM: " + str(bsp)) # Spawn commander. Commander(self.acceptors, self.replicas, bsp, self.communicator).start() # Case 2 if msg[0] == 'adopted': LOG.debug("--------------------ADOPTED-----------------") LOG.debug("PROPOSALS: " + str(proposals)) pvalues = ast.literal_eval(msg[2]) new_sp_list = self.pmax_op(pvalues) proposals = self.xor(proposals, new_sp_list) LOG.debug("After xor: " + str(proposals)) for proposal in proposals: bsp = (ast.literal_eval(msg[1]), proposal[0], proposal[1]) LOG.debug("Leader spawning COM: " + str(bsp)) Commander(self.acceptors, self.replicas, bsp, self.communicator).start() active = True # Case 3 if msg[0] == "preempted": b = ast.literal_eval(msg[1]) if b > ballot_num: active = False ballot_num[0] = b[0] + 1 # Spawn Scout. time.sleep(random.random()) me = self.communicator.identity('leader') Scout(me, self.acceptors, ballot_num, self.communicator).start()
def __init__(self, args=None, cmds = None, daemon = None): component.Component.__init__(self, "ConsoleUI", 2) # keep track of events for the log view self.events = [] try: locale.setlocale(locale.LC_ALL, '') self.encoding = locale.getpreferredencoding() except: self.encoding = sys.getdefaultencoding() log.debug("Using encoding: %s", self.encoding) # start up the session proxy self.sessionproxy = SessionProxy() client.set_disconnect_callback(self.on_client_disconnect) # Set the interactive flag to indicate where we should print the output self.interactive = True self._commands = cmds if args: args = ' '.join(args) self.interactive = False if not cmds: print "Sorry, couldn't find any commands" return else: from commander import Commander cmdr = Commander(cmds) if daemon: cmdr.exec_args(args,*daemon) else: cmdr.exec_args(args,None,None,None,None) self.coreconfig = CoreConfig() if self.interactive and not deluge.common.windows_check(): # We use the curses.wrapper function to prevent the console from getting # messed up if an uncaught exception is experienced. import curses.wrapper curses.wrapper(self.run) elif self.interactive and deluge.common.windows_check(): print """\nDeluge-console does not run in interactive mode on Windows. \n Please use commands from the command line, eg:\n deluge-console.exe help deluge-console.exe info deluge-console.exe "add --help" deluge-console.exe "add -p c:\\mytorrents c:\\new.torrent" """ else: reactor.run()
def test_silent_output_no_out(self): saved_stdout = sys.stdout try: out = StringIO() sys.stdout = out commander = Commander(None) commander.run_command(["echo", "Hello", "World!"]) output = out.getvalue().strip() assert output == '' finally: sys.stdout = saved_stdout
def test_run_chained_cmd(sleep_cmd): out = ProgressOutputPipe() commander = Commander(out) commander.run_chained_commands([([ "sh", "-c", "for x in {1..5} a b c d e; do echo $x; %s done" % sleep_cmd ], []), (["grep", "-e", "\\d"], [])]) assert len(out.stdout) == 5 for i in range(1, 5): assert i == int(out.stdout[i - 1])
def __init__(self, name): TestCase.__init__(self, name) self.commands = find_commands("test/cmds/") self.auth = AuthManager("test/etc/users.auth") self.commander = Commander(self.auth) self.scanner = MailScanner(Parsers(self.commands)) self.email = UnicodeParser().parse(open("test/data/cmd.email")) self.notifier = EmailNotifier("10.2.1.2", 25)
def test_config(self): c = IMConfig("win32", "../", "../", "../os_defaults/") cmd = Cmd(c) command = cmd.ip_a_eth1_onguest() res = Exec.exec_sync(command) response = [line for line in res[1].split("\n") if "eth1" in line] for line in response: search_res = re.search(r'(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)', line) if search_res: ip = search_res.group() print(ip)
def test_silent_output_nonverbose_out(self): saved_stdout = sys.stdout try: out = StringIO() sys.stdout = out pipe = CommandOutputPipeBase(False) commander = Commander(pipe) commander.run_command(["echo", "Hello", "World!"]) output = out.getvalue().strip() assert output == '' finally: sys.stdout = saved_stdout
def test_execute_other(self): cmndr = Commander() def other_command2(r, t): return 'command 2' def other_command1(r): return 'command 1' cmndr.register_command(cmndr.KEY_OTHER, other_command1) cmndr.register_command(cmndr.KEY_OTHER, other_command2) result = cmndr.execute_other('request_body', 'msg text') assert result == ['command 1', 'command 2']
def test_register_other_command(self): cmndr = Commander() def other_command_t(): return True def other_command_f(): return False cmndr.register_command(cmndr.KEY_OTHER, other_command_t) cmndr.register_command(cmndr.KEY_OTHER, other_command_f) assert cmndr.commands[cmndr.KEY_OTHER] == [ other_command_t, other_command_f ]
def __init__( self, resolution, K, commander, left_topic='/gi/simulation/left/image_raw', right_topic='/gi/simulation/right/image_raw', object_position_topic='/track_rect_pub', move_threshold=0.3, altitude=3000, stereo=None, baseline=None, ): self.fx = float(K[0][0]) self.fy = float(K[1][1]) # self.idx = 0 self.con = Commander() time.sleep(0.1) self.left_sub = message_filters.Subscriber(left_topic, Image) self.right_sub = message_filters.Subscriber(right_topic, Image) self.object_position_sub = message_filters.Subscriber( object_position_topic, Int32MultiArray) ts = message_filters.ApproximateTimeSynchronizer( [self.left_sub, self.right_sub, self.object_position_sub], 10, 0.1, allow_headerless=True) ts.registerCallback(self.update_new_position) self.prev_position = None self.cur_position = None self.width = resolution[0] self.hight = resolution[1] self.camera_center = self.get_center((0, 0, self.width, self.hight)) self.move_threshold = move_threshold self.altitude = altitude self.stereo = stereo if stereo is not None: assert baseline is not None self.baseline = baseline self.bridge = CvBridge() rospy.spin()
def test_set_max_cal_commander(self): cmndr = Commander() userstore.register_user_commands(cmndr) request_body = { 'message': { 'from': { 'first_name': 'igor', 'id': '777' } } } set_reply = cmndr.execute('/set_max_calories', request_body, ['2000']) get_reply = cmndr.execute('/show_max_calories', request_body) assert set_reply == 'igor, max calories were updated.' assert get_reply == 'igor, your max calories is 2000'
def run(self, edit): command = "granify test granify" queue = Queue.Queue() general = Commander(command, queue) general.start() command_executed, message = queue.get() if (command_executed): window = self.view.window() log_window = window.new_file() log_window.insert(edit, 0, message) log_window.set_name("Granify Spec Test Results") log_window.set_read_only(True) else: sublime.message_dialog(message)
def __reset(self): self.__toss_coin() self.__battlefield = ([], []) self.__commanders = (Commander(self.player_names[0], 20), Commander(self.player_names[1], 20)) self.__hands = ([], []) self.__decks = ([], []) self.__deck_priority = ([], []) for player in (self.__fp, self.__sp): for card_id in self.deck_lists[player]: self.__decks[player].append(copy(self.card_set[card_id])) shuffle(self.__decks[player]) self.__deck_priority[player].extend(list(self.deck_lists[player]))
def test_update_water(self): cmndr = Commander() waterstore.registerWaterCommands(cmndr) cmndr.execute( '/waterupd', { 'message': { 'date': 1542830400, 'from': { 'first_name': 'igor', 'id': '123' } } }, ['10']) key = waterstore.getWaterKey('123', '1542830400') water_amount = waterstore.getWaterAmount(key) assert water_amount.timesDrank == 10
def test_update_coffee(self): cmndr = Commander() coffeestore.registerCoffeeCommands(cmndr) cmndr.execute( '/coffeeupd', { 'message': { 'date': 1542830400, 'from': { 'first_name': 'igor', 'id': 123 } } }, ['10']) key = coffeestore.getCoffeeKey(123, '1542830400') coffee_amount = coffeestore.getCoffeeAmount(key) assert coffee_amount.timesDrank == 10
def init(): global game_map global hero global commander hero = Hero(10, 11.0, 11.0, math.pi / 2) commander = Commander() game_map = GameMap(20, 20, [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], hero, commander, [Unit(10, 10.5, 7.5, 0)]) game_map.generate_hostiles(5) game_map.generate_friendlies(3)
def dataReceived(self, data): if not '\n' in data: self.buf += data return full = (self.buf + data).split("\n") self.buf = full[-1] for line in full[:-1]: json_data = json.loads(line) if json_data["message_type"] == "hello": global game_map print "Hello message" units = [Unit.from_dict(u) for u in json_data["units"]] bullets = [Bullet.from_dict(b) for b in json_data["bullets"]] hero = Hero.from_dict(json_data["hero"]) commander = Commander.from_dict(json_data["commander"]) game_map = GameMap(json_data["rows"], json_data["cols"], json_data["map"], hero, commander, units, bullets) elif json_data["message_type"] == "update": # Drop any removed units/bullets, then update values for remaining if len(game_map.units) > len(json_data["units"]): game_map.units = game_map.units[:len(json_data["units"])] for i in xrange(len(json_data["units"]) - len(game_map.units)): game_map.units.append(Unit(1, 1999, 1999, 0, 0)) for u_old, u_new in zip(game_map.units, json_data["units"]): u_old.update_from_dict(u_new) if len(game_map.bullets) > len(json_data["bullets"]): game_map.bullets = game_map.bullets[:len(json_data["bullets"])] for i in xrange(len(json_data["bullets"]) - len(game_map.bullets)): game_map.bullets.append(Bullet(0, 999, 999, 0, 0)) for b_old, b_new in zip(game_map.bullets, json_data["bullets"]): b_old.update_from_dict(b_new) game_map.hero.update_from_dict(json_data["hero"]) game_map.commander.update_from_dict(json_data["commander"])
def buildProtocol(self, useless_addr): # Docs mislead, have to explicitly pass something to get persistent # state across protocol/transport invocations. As there is only # one server object per process instantion, that's not necessary. protobj = ProtocolIVSHMSGServer(self) Commander(protobj) return protobj
def run(self, edit): window = sublime.active_window() command = "granify github merged_today" queue = Queue.Queue() general = Commander(command, queue) general.start() command_executed, message = queue.get() if(command_executed): log_window = window.new_file() log_window.insert(edit, 0, message) log_window.set_name("Pull Requests Merged Today") log_window.set_scratch(True) log_window.set_status("granify_generated_on", "Generated on "+ str(datetime.datetime.now().strftime("%y-%m-%d @ %H:%M"))) else: sublime.message_dialog("No PRs were merged today!\n%s" % message)
def on_done(self, d_range): date_range = d_range.split(' to ') command = "granify github merged_between --start=%s --end=%s" % (date_range[0], date_range[1]) queue = Queue.Queue() general = Commander(command, queue) general.start() command_executed, message = queue.get() if(command_executed): window = sublime.active_window() log_window = window.new_file() log_window.insert(self.edit, 0, message) log_window.set_name("Pull Requests Merged Between %s and %s" % (date_range[0], date_range[1])) log_window.set_scratch(True) log_window.set_status("granify_generated_on", "Generated on "+ str(datetime.datetime.now().strftime("%y-%m-%d @ %H:%M"))) else: sublime.message_dialog("No PRs were merged in that range\n%s" % message)
def run(self, edit): sublime.status_message("Syncing granify/goliath") command = "granify recompile resync" queue = Queue.Queue() general = Commander(command, queue) general.start() settings = sublime.load_settings('Granify.sublime-settings') if settings.get('granify_always_wait_for_threads'): # The following code gets the response from the executed command, it's more # accurate but also requires you to wait for the thread to finish command_executed, message = queue.get() if(command_executed): sublime.message_dialog("Granify and Goliath are in sync") else: sublime.error_message("Problem syncing granify/goliath") else: sublime.message_dialog("Syncing in progress")
def run(self, edit): sublime.status_message("Compiling granify and goliath") command = "granify migrate test" queue = Queue.Queue() general = Commander(command, queue) general.start() settings = sublime.load_settings('Granify.sublime-settings') if settings.get('granify_always_wait_for_threads'): # The following code gets the response from the executed command, it's more # accurate but also requires you to wait for the thread to finish command_executed, message = queue.get() if(command_executed): sublime.message_dialog('Test environment migration completed successfully') else: sublime.error_message("An error occurred while migrating to test") else: sublime.message_dialog("Migration in progress")
class TestMailCommander(TestCase): def __init__(self, name): TestCase.__init__(self, name) self.commands = find_commands("test/cmds/") self.auth = AuthManager("test/etc/users.auth") self.commander = Commander(self.auth) self.scanner = MailScanner(Parsers(self.commands)) self.email = UnicodeParser().parse(open("test/data/cmd.email")) self.notifier = EmailNotifier("10.2.1.2", 25) def test_commander(self): cmd_id, data, sprops, authkey = self.scanner.scan(self.email) command = self.commands[cmd_id] self.commander.execute(command, data, authkey) print command.output["text"] def test_auth_notification(self): cmd_id, data, sprops, authkey = self.scanner.scan(self.email) command = self.commands[cmd_id] self.commander.execute(command, data, authkey) sender = "*****@*****.**" recipients = ["*****@*****.**"] notification = AuthNotification(cmd_id, sender, recipients, self.email, data) self.notifier.send(notification) def test_success_notification(self): cmd_id, data, sprops, authkey = self.scanner.scan(self.email) command = self.commands[cmd_id] self.commander.execute(command, data, authkey) sender = "*****@*****.**" recipients = [] notification = SuccessNotification(sender, recipients, command, sprops) self.notifier.send(notification)
def __init__(self, seed_tuple, timeout, log_path, log_level): super(MkrBot, self).__init__(seed_tuple, timeout) self._logger = Logger(log_path, log_level) self._commander = Commander()
c.t.do_run=False def do_eval(self,*args): '''run eval on parameter, any python command, one param only''' return eval(args[0]) def do_history(self,*args): '''dump list of command history''' return c.input.history def do_history_save(self,*args): import pickle with open('history_data.pkl', 'wb') as output: pickle.dump(c.input.history, output, pickle.HIGHEST_PROTOCOL) def do_clear_buffer(self,*args): '''empty time buffer''' c.times_table=[] c=Commander('SENTINEL - SpEed aNd revoluTIoN mEter tooL', cmd_cb=TestCmd()) PACKET_START=0xa5 RDM_UID=0x24 DMX_IN=0x04 DMX_SNIFFER=0x34 def make_buffer(type): buffer=bytearray(6) buffer[0]=PACKET_START buffer[1]=type buffer[2]=0x0 buffer[3]=0x0 buffer[4]=buffer[0]+buffer[1] buffer[5]=(sum(buffer)&0xff) return buffer
if not args.pwd: p=getpass.getpass('Password: '******':') s=map(lambda x: x.strip(),s) if len(s)>1: s[1]=int(s[1]) args.server=s logging.basicConfig(level=logging.DEBUG if args.debug else logging.ERROR, format='%(levelname)-8s %(message)s') xc=ChatClient(args.user, args.pwd, args.room) c=Commander('XMPP Test Client', cmd_cb=XMPPCommand(xc)) xc.print_fn=c.output if xc.connect(args.server or (), use_ssl=args.ssl): xc.process(block=False) else: print >>sys.stderr, 'Unable to connect' sys.exit(-1) xc.wait_ready( ) c.loop() xc.disconnect() sys.exit(0)