def setUpClass(cls): os.chdir("%s/test_resources" % os.path.dirname(__file__)) cls.w = watcher.Watcher(meta_url="mock", hajson_path=cls.hajson_path, hacfg_path=cls.hacfg_path, habase_path=cls.habase_path, port=80)
def main(argv): if argv: zoo_ip = str(argv[0]) else: zoo_ip = ZOO_IP chunkserver = watcher.Watcher(zoo_ip=zoo_ip, port=PORT) s = zerorpc.Server(chunkserver) address = 'tcp://%s:%s' % (zutils.get_myip(), PORT) try: print 'Registering watcher at %s' % address s.bind(address) s.run() except ZMQError as e: print "Unable to start watcher: " + e.strerror s.close() sys.exit(2) except KeyboardInterrupt: pass finally: print 'Closing watcher on %s' % address s.close()
def cli(actual_patrol_module): """Command line interpreter for a patrol file.""" patrolpy_directory = os.path.dirname(os.path.realpath(sys.argv[0])) parser = optparse.OptionParser() parser.add_option("-r", "--run", type="str", dest="run", default=None, help="Specify a method in {} to run directly.".format( actual_patrol_module.__file__)) parser.add_option("-a", "--all", action="store_true", dest="all", help="Run all methods in {} in priority order.".format( actual_patrol_module.__file__)) parser.add_option("-p", "--post", type="str", dest="post", help="Command to run after a trigger (e.g. guake)") parser.add_option("-d", "--directory", type="str", dest="directory", help="Directory to run {} in (default: {}).".format( actual_patrol_module.__file__, patrolpy_directory)) options, _ = parser.parse_args(sys.argv[1:]) patrol_module = module.PatrolModule(actual_patrol_module, postcmd=options.post) # Use directory where patrol.py resides if no directory specified if options.directory: cwd = options.directory else: cwd = patrolpy_directory os.chdir(cwd) # Run all methods if options.all: patrol_module.run_all_methods() sys.exit() # Run specific method if options.run: if options.run in patrol_module.method_dict: patrol_module.run_method(options.run) sys.exit() else: sys.stderr.write("{} command not found.\n".format(options.run)) sys.stderr.flush() sys.exit(1) watch_obj = watcher.Watcher(cwd, patrol_module) watch_obj.run()
def run_with_state(self, state_manager, proc): info("running with %s affected and %s bad files... (%s files total)" % (len(state_manager.affected), len( state_manager.bad), len(state_manager.state))) debug("state is: %r" % (state_manager.state, )) args = self.nose_args[:] if self.test_id: args.append(self.test_id) # when only running a single test, we can't reliably update the state records listeners = [self.ui] else: listeners = [self.ui, self.state_listener] debug("args are: %r" % (args, )) watcher_plugin = watcher.Watcher(state_manager, *listeners) if self.opts.all: watcher_plugin.run_all() def run_tests(proc): nose.run(argv=args, addplugins=[watcher_plugin]) proc.terminate() runner = proc.spawn(target=run_tests, name="nose test runner", kind=pg.OSProcess) runner.wait() if runner.error: proc.terminate(runner.error)
def __init__(self, home, include_tests, exclude_tests, lib_path, verbose, log_path, process_timeout): self.__home = home self.__include_tests = include_tests self.__exclude_tests = exclude_tests self.__execution_id = "ltp:" + datetime.datetime.now().isoformat() self.__test_watcher = w.Watcher(log_path, self.__execution_id, verbose) self.__lib_path = lib_path self.__process_timeout = process_timeout
def setUpClass(cls): os.chdir("%s/test_resources" % os.path.dirname(__file__)) cls.w = watcher.Watcher(meta_url="mock", hajson_path=cls.hajson_path, hacfg_path=cls.hacfg_path, habase_path=cls.habase_path, port=80) with open("etc_haproxy_servers.json", 'w') as f: f.write('["192.168.1.101", "192.168.1.100"]')
def __init__(self, top_path, rescan_timeout=30): self.path = top_path self.rescan_timeout = rescan_timeout self.es = es_client.ElasticSearch("http://127.0.0.1:9200") self.index_name = "dqm_online_monitoring" try: os.makedirs(self.path) except OSError: pass self.mask = inotify.IN_CLOSE_WRITE | inotify.IN_MOVED_TO self.w = watcher.Watcher() self.w.add(self.path, self.mask)
def reiniciar_si_cambia(self, archivo): """Regista un archivo para hacer livecoding. Livecoding es un modo de pilas que se reinicia automáticamente si el archivo indicado cambia. Esto de termina programar mas rápido y prototipar con mayor fluidez.""" if not archivo: return if self.archivo_a_observar: raise Exception("Ya se estaba observando un archivo, imposible aceptar esta orden.") self.archivo_a_observar = archivo self.watcher = watcher.Watcher(archivo, callback=self._reiniciar_pilas_para_livecoding)
def __init__(self, parent, recursive = False, logger = None): threading.Thread.__init__(self) self.logger = logger or logging.getLogger(__name__) self.parent_ = parent self.w = None self.quit = False self.threshold_ = None self.timeout_ = None self.delay_ = None if recursive == True: self.logger.debug("RECURSIVE_MODE") self.w = watcher.AutoWatcher() else: self.logger.debug("NON-RECURSIVE_MODE") self.w = watcher.Watcher() self.recursiveMode = recursive
def __init__(self, socket, config_file, haproxy_file): """Parse the config file and create corresponding watchers and pools""" self._watchers = [] self._orchestrators = [] # Config parser self._configurator = configurator.Configurator(socket, config_file, haproxy_file) # Get list of services and their configs services = self._configurator.parse_config() # Write the initial configuration to file self._configurator.config_write() # If there is an existing HAProxy running that is using the same # pid file, take over the existing to avoid conflicts if haproxy_cmd.haproxy_proc(): haproxy_cmd.restart_haproxy() else: haproxy_cmd.start_haproxy() # Instantiate initial connection to haproxy socket only once haproxy_sock = haproxy.HAProxy(socket_dir=socket) # Share the single instance of haproxy socket and config parser for # efficiency for service_name, service in services.items(): self._watchers.append( watcher.Watcher(service_name, service, self._configurator)) # Only create orchestrators when the config is present if 'elasticity' in service: self._orchestrators.append( orchestrator.Orchestrator(service_name, service, haproxy_sock)) # Run self._cleanup on exit atexit.register(self._cleanup)
def __init__(self): """Initializes controller class.""" super(Controller, self).__init__() # Must pass the super to properly set up window # create the settings tab self.settings_tab = settings_tab.SettingsTab(self) self.ids.settings_tab.add_widget(self.settings_tab) # create the status tab self.status_tab = status_tab.StatusTab(self) self.ids.status_tab.add_widget(self.status_tab) # create the templates tab self.templates_tab = templates_tab.TemplatesTab(self) self.ids.templates_tab.add_widget(self.templates_tab) # Set up watchfolder self.watcher = watcher.Watcher() # register this controller with the watchfolder so the watchfolder can contact it self.watcher.register_observer_program(self) self.watcher.run()
import watcher import os import Myserver def print_ram(pidid): while (1): print(u'当前进程的内存使用:%.4f GB' % (psutil.Process(pidid).memory_info().rss / 1024 / 1024 / 1024)) time.sleep(0.1) nowpid = os.getpid() w = watcher.Watcher(nowpid) w.Start() model = torch.hub.load('pytorch/vision:v0.6.0', 'mobilenet_v2', pretrained=True) model.eval() from PIL import Image from torchvision import transforms input_image = Image.open("dog.jpg") preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,
def test_no_args(self): w = watcher.Watcher(self.dir, self.callback)
def test_args(self): w = watcher.Watcher(self.dir, self.callback, 1, 2, 3)
import watcher config = { "proc":watcher.PROCESS, "trigger":["python","main.py"], "mode":0, "path":"./", "files":[ "main.py" ], } watch = watcher.Watcher(**config) watch.start() watch.observe()
async def on_ready(): activity = discord.Game(name='Vibing on nova.vegova.si') await bot.change_presence(activity=activity) print(f'Logged in as {bot.user.name}') bot.add_cog(watcher.Watcher(bot))
sp = subplot(sp_ctr, title='Beam current', xlabel='t', ylabel='I [A]', scix=True, sciy=True, grid=False) xx, yy = watcher.get_current('t', bins=bins[0], charge=charge) sp.step(xx, yy) if show: plt.show() return fig if __name__ == '__main__': in_ = sys.argv[1] if not in_.endswith('.h5'): new_in = in_ + '.h5' watcher.sdds2hdf(in_, new_in) else: new_in = in_ try: watcher = watcher.Watcher(new_in) except: dist = match_particle_dist.h5_in_genesis(new_in) watcher = watcher.Watcher2({}, dist) inspect(watcher)
def start(self): self.event_manager = event_manager.EventManager() self.main_watcher = watcher.Watcher(self) self.event_manager.announcement_channels = self.config.get_json( "announcement_channels", default=[]) # TODO: probably event manager should take channels from client instead? # Game servers # see how regular this names are, it's asking for the loop self.game_servers['arma'] = game_server.ArmaServer( ip=self.config.get("arma_server_ip", section="Game Servers"), port=self.config.get("arma_server_port", section="Game Servers"), password=self.config.get("arma_server_password", section="Game Servers")) self.game_servers['arma_test'] = game_server.ArmaServer( ip=self.config.get("arma_test_server_ip", section="Game Servers"), port=self.config.get("arma_test_server_port", section="Game Servers"), password=self.config.get("arma_test_server_password", section="Game Servers")) self.game_servers['insurgency'] = game_server.InsurgencyServer( ip=self.config.get("insurgency_server_ip", section="Game Servers"), port=self.config.get("insurgency_server_port", section="Game Servers"), password=self.config.get("insurgency_server_password", section="Game Servers")) # TS3 self.TS3_address = self.config.get("teamspeak_server_ip", section="Communication Servers") self.TS3_port = self.config.get("teamspeak_server_port", section="Communication Servers") self.TS3_password = self.config.get("teamspeak_server_password", section="Communication Servers") # FAMDB self.FAMDB_API_key = self.config.get("API_key", section="FAMDB") self.FAMDB_app_id = self.config.get("application_id", section="FAMDB") # Discord client logging.info("Logging into Discord") self.discordClient = discord_client.Client(self) self.discordClient.channel_whitelist = self.config.get_json( "channel_whitelist", default=[]) self.discordClient.announcement_channels = self.config.get_json( "announcement_channels", default=[]) self.discordClient.welcome_pm = self.config.get( "welcome_pm", section="Announcements") self.discordClient.join_announcement = self.config.get( "join_announcement", section="Announcements") self.discordClient.leave_announcement = self.config.get( "leave_announcement", section="Announcements") self.client_email = self.config.get("email", section="Bot Account") self.client_pass = self.config.get("password", section="Bot Account") if self.client_email is None or self.client_pass is None: logging.critical("Could not find Discord authentication details " "in config file.") print("Could not find Discord authentication details.") exit(1) self.discordClient.login(self.client_email, self.client_pass) if not self.discordClient.is_logged_in: logging.critical("Logging into Discord failed") print('Logging in to Discord failed') exit(1) logging.info("Starting main watcher") self.main_watcher.start() logging.info("Entering main message event loop") self.discordClient.run()
def test_kwargs(self): w = watcher.Watcher(self.dir, self.callback, lol="rofl")
def test_bad_callback(self): with self.assertRaises(TypeError): w = watcher.Watcher(self.dir, 12345)
def run_watcher(): watcher_process = watcher.Watcher('mirrors.yml', data) watcher_thread = threading.Thread(target=watcher_process.start) watcher_thread.daemon = True watcher_thread.start()
def setUp(self): self.dir = tempfile.mkdtemp() self.callback = lambda: 1 self._watcher = watcher.Watcher(self.dir, self.callback)
def __init__(self, network, size=None, ui=None, play=False, update_frequency=30): self.dt = 0.001 self.tau_filter = 0.03 self.delay = 10 self.current_tick = 0 self.time_shown = 0.5 self.data_update_period = int( 1000.0 / update_frequency ) #minimum time between data updates (real-time, milliseconds) self.data_update_time = -1 self.autopause_at = None self.timelog = timelog.TimeLog() self.network = network self.watcher = watcher.Watcher(self.timelog) self.load_watches() self.requested_mode = None self.frame = JFrame(network.name) self.frame.visible = True self.frame.layout = BorderLayout() self.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.area = viewpanel.ViewPanel(network) self.area.background = Color.white self.area.layout = None self.area.addMouseListener(self) self.area.addMouseMotionListener(self) self.frame.add(self.area) self.time_control = timecontrol.TimeControl(self) self.frame.add(self.time_control, BorderLayout.SOUTH) self.forced_origins = {} self.forced_origins_prev = {} self.tick_queue = [] self.mapcache = neuronmap.MapCache() if size is None: size = (950, 600) if ui is not None: size = (max(int(ui.width), 950), max(int(ui.height), 500)) self.frame.size = (size[0], size[1] + 100) self.popup = JPopupMenu() self.area.add(self.popup) self.process_nodes(network.nodes, self.popup) restored = self.restore() if not restored: if ui is not None: p0 = ui.localToView(java.awt.geom.Point2D.Double(0, 0)) p1 = ui.localToView( java.awt.geom.Point2D.Double(ui.width, ui.height)) for n in ui.UINodes: x = (n.offset.x - p0.x) / (p1.x - p0.x) * size[0] y = (n.offset.y - p0.y) / (p1.y - p0.y) * size[1] self.add_item(n.name, location=(int(x), int(y))) self.restart = False self.paused = True self.simulating = False self.thread = java.lang.Thread(self) self.thread.priority = java.lang.Thread.MIN_PRIORITY self.thread.start() if play is True or play > 0: if isinstance(play, (int, float)): self.autopause_at = play self.time_control.pause(None)
import watcher import ctypes def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if __name__ == '__main__': if not is_admin(): input('Restart the program with admin privileges. ') else: w = watcher.Watcher() w.run()
#!python import sys import watcher if __name__ == '__main__': if len(sys.argv) != 2: print("usage: sonarr-extract.py <watch_directory>\n") else: w = watcher.Watcher(str(sys.argv[1])) w.run()
"headers" : [], "cache_dir" : "/var/mod_dsrc_cache", "azure_containers" : [ { "account_name" : "", "account_key" : "", "container" : "", "compression" : True, "decompression" : False , } ], } ################################################## queue = Queue.Queue() _obj_watcher = watcher.Watcher(_config_watcher, True) _obj_request = requester.Requester(_config_request, True) while True: _obj_watcher.set_test_loop(1) _obj_watcher.worker_init(queue) _obj_request.set_test_loop(7) _obj_request.worker_init(queue) queue.join()
if random.randint(0,1) == 0: player1 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) else: player2 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) elif num_humans == 0: player1 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) player2 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) if random.randint(0,1) == 0: player1 = player.RandomAI() print "Player 1 is random" else: player2 = player.RandomAI() print "Player 2 is random" if watch: movie = watcher.Watcher(game_file) movie.set_heuristic(heuristics.game_heuristic1) movie.set_show_eval(True) movie.watch() else: if not test: game = Board(player1, player2, game_file, history, load, show=show_board) game.play() else: if this_test == "draw1": player1 = player.RandomAI() player2 = player.RandomAI() max_turns = 0 counter = 0 while max_turns < 81: game = Board(player1, player2, game_file, history, load, True, show_board)
def test_bytes_path(self): # Eventually this will be supported. with self.assertRaises(TypeError): w = watcher.Watcher(os.getcwdb(), self.callback)