Esempio n. 1
0
 def __init__(self, path, mask, callbacks, pending_delay):
     FileSystemEventHandler.__init__(self)
     self._path = path
     self._mask = mask
     self._callbacks = callbacks
     self._pending_delay = pending_delay
     self._pending = set()
Esempio n. 2
0
    def __init__(self):
        FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
        self.root = None
        self.currentdir = None		# The actual logdir that we're monitoring
        self.logfile = None
        self.observer = None
        self.observed = None		# a watchdog ObservedWatch, or None if polling
        self.thread = None
        self.event_queue = []		# For communicating journal entries back to main thread

        # Context for journal handling
        self.version = None
        self.is_beta = False
        self.mode = None
        self.group = None
        self.cmdr = None
        self.shipid = None
        self.shiptype = None
        self.shippaint = None
        self.body = None
        self.system = None
        self.station = None
        self.coordinates = None
        self.ranks = None
        self.credits = None
Esempio n. 3
0
    def __init__(self, window):
        super(Client, self).__init__()

        self.window = window
        self.width, self.height = glfw.get_window_size(window)

        self.gl = mg.create_context()
        self.compile()

        self.camerapos = vec4(0.0, 0.0, 20.0, 1.0)

        def on_modified(e):
            # restart python if python code is changed
            if e.src_path.endswith(".py"):
                glfw.set_window_should_close(window, glfw.TRUE)
                os.system(f"python {e.src_path}")

            # compile shaders if the change is not python code
            else:
                self.should_compile = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_modified
        observer = Observer()
        observer.schedule(handler, "./.", True)
        observer.start()

        self.is_drag_rot_cam = False
        self.prempos = vec2(0.0, 0.0)

        # wire glfw events
        glfw.set_mouse_button_callback(window, self.on_mouse_button)
        glfw.set_cursor_pos_callback(window, self.on_cursor_pos)
        glfw.set_scroll_callback(window, self.on_scroll)
        glfw.set_window_size_callback(window, self.on_window_size)
Esempio n. 4
0
    def run(self) -> None:
        self._logger.info("Started running the server")

        event_handler = FileSystemEventHandler()
        event_handler.on_created = self._process_file_system_event
        event_handler.on_modified = self._process_file_system_event

        observer = Observer()
        observer.schedule(event_handler,
                          self._configuration.upload_directory,
                          recursive=True)
        observer.start()

        try:
            while True:
                time.sleep(1)
        except Exception:
            self._logger.exception(
                "An unexpected exception occurred during watching file changes"
            )

            observer.stop()

        observer.join()

        self._logger.info("Finished running the server")
Esempio n. 5
0
 def __init__(self):
     FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
     self.root = None
     self.currentdir = None		# The actual logdir that we're monitoring
     self.observer = None
     self.observed = None		# a watchdog ObservedWatch, or None if polling
     self.status = {}		# Current status for communicating status back to main thread
Esempio n. 6
0
    def __init__(self, holder, configfile, *args, **kwargs):
        FileSystemEventHandler.__init__(self, *args, **kwargs)
        self._file = None
        self._filename = ""
        self._where = 0
        self._satellite = ""
        self._orbital = None
        cfg = ConfigParser()
        cfg.read(configfile)
        self._coords = cfg.get("local_reception", "coordinates").split(" ")
        self._coords = [float(self._coords[0]),
                        float(self._coords[1]),
                        float(self._coords[2])]
        self._station = cfg.get("local_reception", "station")
        logger.debug("Station " + self._station +
                     " located at: " + str(self._coords))
        try:
            self._tle_files = cfg.get("local_reception", "tle_files")
        except NoOptionError:
            self._tle_files = None

        self._file_pattern = cfg.get("local_reception", "file_pattern")
        
        self.scanlines = holder

        self._warn = True
 def __init__(self, *args, **kwargs):
     self.rate = 4
     self.surface = pygame.Surface((1, 1))
     self.size = (0, 0)
     self.fade = False
     self.screensize = kwargs.pop("screensize")
     FileSystemEventHandler.__init__(self, *args, **kwargs)
Esempio n. 8
0
def watchdog_monitor():
    def on_created(event):
        print(type(event))
        print(event.src_path)

        if event.src_path[-4:] == ".xls":
            print("true")
            time.sleep(1)
            confirm(event.src_path)

    json_f = json.load(open("tmp/config.json"))
    event_handler = FileSystemEventHandler()

    event_handler.on_created = on_created

    path = json_f['defaultPath']

    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
Esempio n. 9
0
 def __init__(self):
     FileSystemEventHandler.__init__(self)
     super().__init__()
     self.locked_groups = []
     try:
         pass
         self.load_state()
         self.displaygen()
     except:
         self.display = ""
         self.groups = []
         self.monitors = {}
         monitors = command("bspc query -M --names").strip().split("\n")
         for monitor in monitors:
             self.monitors[monitor] = []
             workspaces = command("bspc query -D -m " + monitor +
                                  " --names").strip().split("\n")
             command("bspc desktop -f " + workspaces[0])
             self.groups.append(Group())
             self.activegroup = self.groups[-1]
             self.activegroup.workspaces = [
                 workspace for workspace in workspaces
             ]
     try:
         command("rm {}*".format(config["command_folder"]))
     except:
         pass
     self.displaygen()
Esempio n. 10
0
 def __init__(self, file_path, host="192.168.1.25", port=1234):
     FileSystemEventHandler.__init__(self)
     self.file_path = file_path
     self._host = host
     self._port = port
     self._regex = re.compile(r"^(?P<artist>.*) - (?P<title>.*)$")
     self._last_sent = time.time()
Esempio n. 11
0
 def __init__(self):
     """
     Constructor
     :return:
     """
     FileSystemEventHandler.__init__(self)
     self.app = app._get_current_object()
Esempio n. 12
0
    def __init__(self, monitor_dir, config):
        FileSystemEventHandler.__init__(self)

        self.monitor_dir = monitor_dir
        if not config: config = {}

        self.scan_interval = config.get('scan_interval', 3) # If no updates in 3 seconds (or user specified option in config file) process file
Esempio n. 13
0
 def __init__(self, path, mask, callbacks, pending_delay):
     FileSystemEventHandler.__init__(self)
     self._path = path
     self._mask = mask
     self._callbacks = callbacks
     self._pending_delay = pending_delay
     self._pending = set()
Esempio n. 14
0
    def __init__(self, window):
        super(Client, self).__init__()

        self.window = window
        glfw.make_context_current(window)

        self.gl = mg.create_context()
        self.need_compile = False

        imgui.create_context()
        win_size = glfw.get_window_size(window)
        self.imgui = ModernGLRenderer(ctx=self.gl, display_size=win_size)

        quad = Quad(self.gl, vspath="./gl/quad.vs", fspath="./gl/quad.fs")

        self.children = []
        self.children.append(quad)

        def onmod(e):
            self.need_compile = True

        handler = FileSystemEventHandler()
        handler.on_modified = onmod
        shader_code_observer = Observer()
        shader_code_observer.schedule(handler, "./gl", True)
        shader_code_observer.start()

        self.wire_glfw_to_imgui_events()

        self.last_time = 0
        self.u_camera_rotation_xz = 0.0
        self.u_camera_zoom = 1.0
Esempio n. 15
0
 def __init__(self, project_id, handler_type='project'):
     # Initialize.
     self.project_id = project_id
     FileSystemEventHandler.__init__(self)
     # Handler is a project file handler...
     if handler_type == 'project':
         log_msg = ('PROJECT_EVENT_HANDLER initialized for project '
                    'with ID {project_id}')
         self.actions = {
             'Created': self._on_created_project,
             'Deleted': self._on_deleted_project,
             'Modified': self._on_modified_project,
             'Moved': self._on_moved_project
         }
     # Handler is a project scanner handler.
     elif handler_type == 'scanner':
         log_msg = ('Project image scan handler initialized for project '
                    'with ID {project_id}')
         self.actions = {'Created': self._on_created_scanner}
     # Undefined handler type.
     else:
         raise NotImplementedError()
     # Populate the log_mgs with data and log.
     log_msg = log_msg.format(**self.__dict__)
     _logger().debug(log_msg)
Esempio n. 16
0
    def __init__(self, window):
        super().__init__()

        self.window = window
        self.width, self.height = WIDTH, HEIGHT

        self.gl = mg.create_context()

        self.rotation = vec2(0.0, 0.0)
        self.u_campos = vec3(-2.0, 2.0, 5.0)

        self._prevpos = ivec2(0, 0)
        self._isdrag = False

        self.compile_shaders()

        def _on_mod(e):
            self.should_compile = True

        handler = FileSystemEventHandler()
        handler.on_modified = _on_mod
        observer = Observer()
        observer.schedule(handler, "./gl", True)
        observer.schedule(handler, "./tex", True)
        observer.start()

        imgui.create_context()
        self.imgui = ModernGLGLFWRenderer(ctx=self.gl,
                                          display_size=(WIDTH, HEIGHT))
        self.imgui.wire_events(self.gl, window)
        self.imgui.on_mouse_button = self.on_mouse_button
        self.imgui.on_cursor_pos = self.on_cursor_pos
 def run(self):
     observer = Observer()
     handler = FileSystemEventHandler()
     handler.on_modified = self.on_modified_event
     observer.schedule(handler, "./gl")
     observer.start()
     observer.join()
Esempio n. 18
0
    def __init__(self):
        FileSystemEventHandler.__init__(
            self)  # futureproofing - not need for current version of watchdog
        self.root = None
        self.currentdir = None  # The actual logdir that we're monitoring
        self.logfile = None
        self.observer = None
        self.observed = None  # a watchdog ObservedWatch, or None if polling
        self.thread = None
        self.event_queue = [
        ]  # For communicating journal entries back to main thread

        # On startup we might be:
        # 1) Looking at an old journal file because the game isn't running or the user has exited to the main menu.
        # 2) Looking at an empty journal (only 'Fileheader') because the user is at the main menu.
        # 3) In the middle of a 'live' game.
        # If 1 or 2 a LoadGame event will happen when the game goes live.
        # If 3 we need to inject a special 'StartUp' event since consumers won't see the LoadGame event.
        self.live = False

        self.game_was_running = False  # For generation the "ShutDown" event

        # Context for journal handling
        self.version = None
        self.is_beta = False
        self.mode = None
        self.group = None
        self.cmdr = None
        self.planet = None
        self.system = None
        self.station = None
        self.stationtype = None
        self.coordinates = None
        self.systemaddress = None
        self.started = None  # Timestamp of the LoadGame event
        self.missioncargo = {}  # For tracking cargo in wing missions

        # Cmdr state shared with EDSM and plugins
        self.state = {
            'Captain': None,  # On a crew
            'Cargo': defaultdict(int),
            'Credits': None,
            'Loan': None,
            'Raw': defaultdict(int),
            'Manufactured': defaultdict(int),
            'Encoded': defaultdict(int),
            'Rank': {},
            'Reputation': {},
            'Statistics': {},
            'Role': None,  # Crew role - None, Idle, FireCon, FighterCon
            'Friends': set(),  # Online friends
            'ShipID': None,
            'ShipIdent': None,
            'ShipName': None,
            'ShipType': None,
            'HullValue': None,
            'ModulesValue': None,
            'Rebuy': None,
            'Modules': None,
        }
Esempio n. 19
0
def watch(  # noqa: C901
        func: callable,
        path: str = None,
        *,
        poll_time=0.5,
        skip_first=False,
        name=None):
    """
    Execute function and re-execute if everytime a file under the given path
    changes.
    """

    import time
    from watchdog.observers import Observer
    from watchdog.events import (
        FileSystemEventHandler,
        FileCreatedEvent,
        FileDeletedEvent,
        FileModifiedEvent,
        FileMovedEvent,
    )

    # Create the dispatch function that throttles execution so func is
    # executed at most every poll_time seconds
    file_event = (FileCreatedEvent, FileDeletedEvent, FileModifiedEvent,
                  FileMovedEvent)
    last = time.time()

    def dispatch(ev):
        nonlocal last

        if (ev.src_path.endswith("__") or ev.src_path.startswith("__")
                or ev.src_path.startswith("~") or ev.src_path.startswith(".")):
            return

        if isinstance(ev, file_event):
            last = start = time.time()
            time.sleep(poll_time)
            if last == start:
                print(f"File modified: {ev.src_path}")
                func()

    # Initialize observer and mokey-match the instance dispatch method
    observer = Observer()
    handler = FileSystemEventHandler()
    handler.dispatch = dispatch
    observer.schedule(handler, path or os.getcwd(), recursive=True)
    observer.start()
    name = name or func.__name__

    # Starts execution loop
    print(f"Running {name} in watch mode.")
    if not skip_first:
        func()
    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
Esempio n. 20
0
    def initialize_gl(self):
        self.gl = mg.create_context()
        self.gl.disable(mg.CULL_FACE)

        NUM_VERTICES = 8
        NUM_QUADS = 6

        self.vbo = self.gl.buffer(reserve=NUM_VERTICES * 3 * 4)
        self.vbo.bind_to_storage_buffer(0)
        self.normals_bo = self.gl.buffer(reserve=NUM_VERTICES * 3 * 4)
        self.normals_bo.bind_to_storage_buffer(1)

        self.ibo = self.gl.buffer(reserve=3 * 2 * NUM_QUADS * 4)
        self.ibo.bind_to_storage_buffer(2)

        self.vbo_content = self.regenerate_verts_content()

        self.recompile_vao()

        def on_mod(e):
            self.should_recompile_vao = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_mod
        observer = Observer()
        observer.schedule(handler, "./gl")
        observer.start()
Esempio n. 21
0
    def __init__(self, gl_win, width, height):
        super(Renderer, self).__init__()

        self.window = gl_win
        self.width, self.height = width, height
        self.gl = mg.create_context()

        self.vbo = self.gl.buffer(reserve=4 * 4 * 4)
        self.ibo = self.gl.buffer(reserve=6 * 4)

        self.vbo.bind_to_storage_buffer(0)
        self.ibo.bind_to_storage_buffer(1)

        self.const = self.gl.buffer(reserve=1024)
        self.const.bind_to_storage_buffer(15)

        self.build_vao()

        def onmod(e):
            self.should_compile = True

        h = FileSystemEventHandler()
        h.on_modified = onmod
        o = Observer()
        o.schedule(h, "./gl/", True)
        o.start()
Esempio n. 22
0
 def __init__(self, fun, publisher, pattern, attrs):
     """Initialize the processor."""
     FileSystemEventHandler.__init__(self)
     self.fun = fun
     self.publisher = publisher
     self.pattern = pattern
     self.attrs = attrs
Esempio n. 23
0
 def __init__(self, name, queue):
     FileSystemEventHandler.__init__(self)
     self.name = name
     self.queue = queue
     self.set = set()
     self.num = 0
     self.no = 0
Esempio n. 24
0
 def __init__(self, file_path, window):
     FileSystemEventHandler.__init__(self)
     self.file_path = os.path.normpath(file_path)
     self.last_position = 0
     self.signal = None
     self.signal = window.new_window
     self.ProcessCommands()
Esempio n. 25
0
def watch_note(note, handle_func):
    """watch a single note for changes,
    call `handle_func` on change"""
    ob = Observer()
    handler = FileSystemEventHandler()
    note_filename = path.basename(note)

    def handle_event(event):
        _, filename = path.split(event.src_path)
        if note_filename == filename or \
                path.normpath(event.src_path) == path.normpath(util.assets_dir(note)):
            print('compiling...')
            handle_func(note)
            print('done')
    handler.on_any_event = handle_event

    print('watching "{0}"...'.format(note_filename))
    ob.schedule(handler, path.dirname(note), recursive=True)
    ob.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('stopping...')
        ob.stop()
    ob.join()
Esempio n. 26
0
    def __init__(self, holder, configfile, *args, **kwargs):
        FileSystemEventHandler.__init__(self, *args, **kwargs)
        self._file = None
        self._filename = ""
        self._where = 0
        self._satellite = ""
        self._orbital = None
        cfg = ConfigParser()
        cfg.read(configfile)
        self._coords = cfg.get("local_reception", "coordinates").split(" ")
        self._coords = [
            float(self._coords[0]),
            float(self._coords[1]),
            float(self._coords[2])
        ]
        self._station = cfg.get("local_reception", "station")
        logger.debug("Station " + self._station + " located at: " +
                     str(self._coords))
        try:
            self._tle_files = cfg.get("local_reception", "tle_files")
        except NoOptionError:
            self._tle_files = None

        self._file_pattern = cfg.get("local_reception", "file_pattern")

        self.scanlines = holder

        self._warn = True
Esempio n. 27
0
    def init(self):
        self.gl = mg.create_context()

        self.vbo = [
            (
                self.gl.buffer(
                    np.array([-1.0, -1.0, -1.0, +1.0, +1.0, -1.0, +1.0, +1.0])
                    .astype(np.float32)
                    .tobytes()
                ),
                "2f",
                "in_pos",
            )
        ]

        self.ibo = self.gl.buffer(
            np.array([0, 1, 2, 2, 1, 3]).astype(np.int32).tobytes()
        )

        self.recompile()

        handler = FileSystemEventHandler()
        handler.on_modified = lambda e: self.set_recompile_flag(True)
        observer = Observer()
        observer.schedule(handler, "./gl/")
        observer.start()
Esempio n. 28
0
    def __init__(self):
        FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
        self.root = None
        self.currentdir = None		# The actual logdir that we're monitoring
        self.logfile = None
        self.observer = None
        self.observed = None		# a watchdog ObservedWatch, or None if polling
        self.thread = None
        self.event_queue = []		# For communicating journal entries back to main thread

        # On startup we might be:
        # 1) Looking at an old journal file because the game isn't running or the user has exited to the main menu.
        # 2) Looking at an empty journal (only 'Fileheader') because the user is at the main menu.
        # 3) In the middle of a 'live' game.
        # If 1 or 2 a LoadGame event will happen when the game goes live.
        # If 3 we need to inject a special 'StartUp' event since consumers won't see the LoadGame event.
        self.live = False

        self.game_was_running = False	# For generation the "ShutDown" event

        # Context for journal handling
        self.version = None
        self.is_beta = False
        self.mode = None
        self.group = None
        self.cmdr = None
        self.planet = None
        self.system = None
        self.station = None
        self.stationtype = None
        self.coordinates = None
        self.systemaddress = None
        self.started = None	# Timestamp of the LoadGame event

        # Cmdr state shared with EDSM and plugins
        self.state = {
            'Captain'      : None,	# On a crew
            'Cargo'        : defaultdict(int),
            'Credits'      : None,
            'FID'          : None,	# Frontier Cmdr ID
            'Horizons'     : None,	# Does this user have Horizons?
            'Loan'         : None,
            'Raw'          : defaultdict(int),
            'Manufactured' : defaultdict(int),
            'Encoded'      : defaultdict(int),
            'Engineers'    : {},
            'Rank'         : {},
            'Reputation'   : {},
            'Statistics'   : {},
            'Role'         : None,	# Crew role - None, Idle, FireCon, FighterCon
            'Friends'      : set(),	# Online friends
            'ShipID'       : None,
            'ShipIdent'    : None,
            'ShipName'     : None,
            'ShipType'     : None,
            'HullValue'    : None,
            'ModulesValue' : None,
            'Rebuy'        : None,
            'Modules'      : None,
        }
Esempio n. 29
0
 def __init__(self, library, path, xbmcif):
     FileSystemEventHandler.__init__(self)
     self.library = library
     self.path = path
     self.xbmcif = xbmcif
     self.supported_media = '|' + py2_decode(
         xbmc.getSupportedMedia(library)) + '|'
Esempio n. 30
0
    def init_gl(self):
        self.gl = mg.create_context()

        self.vbo = self.gl.buffer(
            np.array(
                [-1.0, -1.0, 0.0, -1.0, +1.0, 0.0, +1.0, -1.0, 0.0, +1.0, +1.0, 0.0]
            )
            .astype(np.float32)
            .tobytes()
        )
        self.ibo = self.gl.buffer(
            np.array([0, 1, 2, 2, 1, 3]).astype(np.int32).tobytes()
        )

        self.recompile()

        width, height = glfw.get_window_size(self.window)
        self.uniform("u_resolution", vec2(width, height))

        self.wire_events()

        def on_mod(e):
            self.should_recompile = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_mod
        self.observer = Observer()
        self.observer.schedule(handler, "./gl/", True)
        self.observer.start()
Esempio n. 31
0
    def __init__(self, args, callback=None):
        self._watchdog_observer = None
        self._path = args.config
        self._callback = callback
        self._config = {}

        # Load from file
        try:
            self.load_config_file()
        except FileNotFoundError:
            logger.info("No configuration file, creating a new one")
            self._config = CONF_SCHEMA({})

        # Overwrite with command line arguments
        args_keys = vars(args)
        for key in args_keys:
            if self._config.get(key) != args_keys[key]:
                self._config[key] = args_keys[key]

        self.save_config_file()

        self._watchdog_observer = Observer()
        watchdog_event_handler = FileSystemEventHandler()
        watchdog_event_handler.on_modified = lambda event: self.load_config_file(
        )
        self._watchdog_observer.schedule(watchdog_event_handler, self._path)
        self._watchdog_observer.start()
Esempio n. 32
0
def watch_note(note, handle_func):
    """watch a single note for changes,
    call `handle_func` on change"""
    ob = Observer()
    handler = FileSystemEventHandler()

    def handle_event(event):
        """update the note only if:
            - the note itself is changed
            - a referenced asset is changed
        """
        _, filename = os.path.split(event.src_path)

        # get all absolute paths of referenced images
        images = []
        for img_path in note.images:
            if not os.path.isabs(img_path):
                img_path = os.path.join(note.dir, img_path)
            images.append(img_path)

        if note.filename == filename or event.src_path in images:
            handle_func(note)
    handler.on_any_event = handle_event

    print('watching {0}...'.format(note.title))
    ob.schedule(handler, note.dir, recursive=True)
    ob.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('stopping...')
        ob.stop()
    ob.join()
Esempio n. 33
0
def track_directories(directories, session, bucket_name):

    global aws_session, bucket
    aws_session = session
    bucket = bucket_name

    observer = Observer()

    # Create event handler and set the function to call when event occurs.
    event_handler = FileSystemEventHandler()
    event_handler.on_created = upload_file_to_S3


    # Schedule the observer to monitor every directory in the config file.
    for directory in directories:
        observer.schedule(event_handler, directory, recursive=True)
        write_to_log('Scheduled observer for ' + directory)

    # Start the observer.
    observer.start()

    try:

        write_to_log('Beginning to wait for events.')

        # Constantly wait for events.
        while True:
            time.sleep(1)

    # Stop when user presses Ctrl + C.
    except KeyboardInterrupt:
        write_to_log('Stopping observers...')
        observer.stop()
        observer.join()
        write_to_log('Stopped observers.')
 def __init__(self, paths, forkloop, minimum_wait=2.0):
     FileSystemEventHandler.__init__(self)
     self.forkloop = forkloop
     self.observers = []
     self.paths = paths
     self.minimum_wait = minimum_wait
     self.last_event = time.time()
Esempio n. 35
0
    def monitor(self):
        """Monitor current installation and log any changes"""
        print("Details at: " + LOGS_DIR + self.type + "-" + self.name +
              "-monitor.log")
        logging.basicConfig(filename=LOGS_DIR + self.type + "-" + self.name +
                            "-monitor.log",
                            level=logging.INFO,
                            format='%(asctime)s - %(message)s',
                            datefmt='%d-%m-%Y %H:%M:%S')
        # Monitor for changes and write details to a log
        event_handler = LoggingEventHandler()
        observer = Observer()
        observer.schedule(event_handler, self.path, recursive=True)
        observer.start()

        # Monitor for changes and trigger a event
        filesystem_event = FileSystemEventHandler()
        filesystem_event.on_modified = self.on_modified
        observer.schedule(filesystem_event, self.path, recursive=True)

        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()

        observer.join()
 def __init__(self, paths, forkloop, minimum_wait=2.0):
     FileSystemEventHandler.__init__(self)
     self.forkloop = forkloop
     self.observers = []
     self.paths = paths
     self.minimum_wait = minimum_wait
     self.last_event = time.time()
Esempio n. 37
0
    def __init__(self, width, height):
        super(Context, self).__init__()

        self.recorder = None

        self.GL = mg.create_context()

        self.width, self.height = width, height
        self.screenvbo = self.GL.buffer(reserve=4 * 4 * 4)
        self.screenibo = self.GL.buffer(reserve=6 * 4)
        self.screenvbo.bind_to_storage_buffer(0)
        self.screenibo.bind_to_storage_buffer(1)

        self.programs = []
        self.vertex_arrays = []

        self.recompile()

        def on_mod(e):
            self._should_recomile = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_mod
        observer = Observer()
        observer.schedule(handler, "./gl")
        observer.start()
Esempio n. 38
0
 def __init__(self):
     FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
     self.root = None
     self.logdir = self._logdir()
     self.logfile = None
     self.observer = None
     self.thread = None
     self.callback = None
     self.last_event = None	# for communicating the Jump event
	def __init__(self):
		self.watcher_pid_file = os.path.join(MONITOR_ROOT, "watcher.pid.txt")
		self.watcher_log_file = os.path.join(MONITOR_ROOT, "watcher.log.txt")

		self.annex_observer = Observer()
		self.netcat_queue = []
		self.cleanup_upload_lock = False

		FileSystemEventHandler.__init__(self)
Esempio n. 40
0
        def __init__(self, collectors, terminator, decoder, patterns, observer_class_name):
            FileSystemEventHandler.__init__(self)
            FileTrigger.__init__(self, collectors, terminator, decoder)
            self.input_dirs = []
            for pattern in patterns:
                self.input_dirs.append(os.path.dirname(pattern))
            self.patterns = patterns

            self.new_file = Event()
            self.observer = self.cases.get(observer_class_name, Observer)()
Esempio n. 41
0
 def on_modified(self, event):
     '''
     @summary:
     ファイル更新時イベント
     ファイルのときはインデックス更新
     ディレクトリのときはファイルが追加されたときとかそういうイベントなので、無視
     '''
     if not event.is_directory:
         self.refresh_file(event.src_path)
     FileSystemEventHandler.on_created(self, event)
Esempio n. 42
0
        def __init__(self, patterns, observer_class_name="Observer"):
            FileSystemEventHandler.__init__(self)
            self.input_dirs = []
            for pattern in patterns:
                self.input_dirs.append(os.path.dirname(pattern))
                LOG.debug("watching " + str(os.path.dirname(pattern)))
            self.patterns = patterns

            self.new_file = Event()
            self.observer = self.cases.get(observer_class_name, Observer)()
Esempio n. 43
0
 def __init__(self):
     FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
     self.root = None
     self.logdir = self._logdir()
     self.logfile = None
     self.logging_enabled = self._logging_enabled
     self._restart_required = False
     self.observer = None
     self.thread = None
     self.last_event = None	# for communicating the Jump event
Esempio n. 44
0
 def on_deleted(self, event):
     '''
     @summary: ファイル削除イベント
     '''
     if event.is_directory:
         pass
     else:
         self.watcher.index.remove([event.src_path])
     logger.debug("DELETE %s" % event.src_path)
     FileSystemEventHandler.on_deleted(self, event)
Esempio n. 45
0
 def on_created(self, event):
     '''
     @summary:
         新規作成時イベント
         新規ファイルのインデックスを追加する
     '''
     if event.is_directory:
         self.watcher.analyze_dir(event.src_path, True)
     else:
         self.watcher.analyze_file(event.src_path)
     FileSystemEventHandler.on_created(self, event)
Esempio n. 46
0
 def __init__(self, dirname, record_source, loglevel):
     FileSystemEventHandler.__init__(self)
     self.dirname = dirname
     if not os.path.isdir(self.dirname + constants.TMP_FOLDER): 
         os.mkdir(self.dirname + constants.TMP_FOLDER)
     self.changes = {}
     self.just_changed = {}
     self.valid = re.compile(r'^(\./)?([^/]+/)*(?!\.)[^/]*[^~]$') #PE test this, should work
     #self.valid = re.compile(r'^(.+/)*[^\./][^/~]*$')
     self.record_source = record_source
     self.loglevel = loglevel
Esempio n. 47
0
    def __init__(self, exit, input_directory, output_directory, output_directory_tmp, loop=None, **kwargs):
        self._exit = exit
        self._loop = loop
        self._input_directory = input_directory
        self._output_directory = (output_directory_tmp, output_directory)

        logging.info('From directory is ' + input_directory)
        logging.info('To directory is ' + output_directory)

        AIOEventHandler.__init__(self, loop)
        FileSystemEventHandler.__init__(self, **kwargs)
Esempio n. 48
0
 def __init__(self, folder, callback=lambda x: None):
     self.callback = callback 
     event_handler = FileSystemEventHandler()
     def handler(e):
         path = e.src_path
         if path.endswith('.txt'):
             self.callback(path, read_text_file(path))
     # this happens also when file is created
     event_handler.on_modified = handler
     self.observer = Observer()
     self.observer.schedule(event_handler, folder)
Esempio n. 49
0
    def start(self):
        from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler

        handler = FileSystemEventHandler()
        handler.on_modified = self.compile_sass

        watch = Observer()
        watch.schedule(handler, self.assets_dir, recursive=True)
        watch.start()
        app.logger.info('Watching \'{}\' for changes'.format(self.assets_dir))
Esempio n. 50
0
 def __init__(self):
     FileSystemEventHandler.__init__(self)	# futureproofing - not need for current version of watchdog
     self.root = None
     self.logdir = self._logdir()	# E:D client's default Logs directory, or None if not found
     self.currentdir = None		# The actual logdir that we're monitoring
     self.logfile = None
     self.observer = None
     self.observed = None
     self.thread = None
     self.callbacks = { 'Jump': None, 'Dock': None }
     self.last_event = None	# for communicating the Jump event
Esempio n. 51
0
  def __init__(self, options):

    # print options

    # Store the command line args
    self.options = options
    self.channel = Channel.objects.get(slug=self.options['channel_name'])

    # Init ourselves some redis
    pool = redis.ConnectionPool(host='localhost', port=6379, db=self.channel.redis_db)
    r = redis.Redis(connection_pool=pool)
    self.pipe = r.pipeline()
    self.redis_index = 0

    # If the overwrite flag is set, flush the redis db, 
    # set the channel line count to 0, and set the date
    # context to the channel start date, else grab the latest
    # date from the scores
    if self.options['overwrite']:
      r.flushdb()
      self.channel.set_line_count(0)
      self.date = self.channel.start_date
    else:
      self.date = self.channel.get_latest_date()

    # Define the nick handling members
    self.nicks = dict()
    nick_regex_string = '[a-zA-Z0-9_-\{\}\^\`\|]+'
    self.nick_regex_strings = [
      '<(?P<nick>%s)>' % nick_regex_string,
      'Action: (?P<nick>%s) ' % nick_regex_string,
      'Nick change: (?P<nick>%s) ' % nick_regex_string,
      'Topic changed on [#&][[a-zA-Z0-9]+ by (?P<nick>%s)\!' % nick_regex_string,
      '%s kicked from [#&][[a-zA-Z0-9]+ by (?P<nick>%s)' % (nick_regex_string, nick_regex_string),
      '(?P<nick>%s) \(.*\) [left|joined]' % nick_regex_string,
      '[#&][[a-zA-Z0-9]+: mode change \'.*\' by (?P<nick>%s)\!' % nick_regex_string
    ]

    #Grab a list of files in the target directory, sort and stick in a deque for optimized access (lists are slow)
    self.dir = deque()
    for f in sorted(filter(lambda x: self.options['filter_string'] in x, os.listdir(self.options['path']))):
      self.dir.append('%s%s' % (self.options['path'], f))

    # Open the first file in the queue
    self.file = open(self.dir.popleft(), 'r')

    # Set the initial file position
    self.where = self.file.tell()

    # Run the initial feed of the logs
    self.ReadLog()
    FileSystemEventHandler.__init__(self)
    def __init__(self, cfg_path=None, sharing_path=None):
        FileSystemEventHandler.__init__(self)
        # Just Initialize variable the Daemon.start() do the other things
        self.daemon_state = 'down'  # TODO implement the daemon state (disconnected, connected, syncronizing, ready...)
        self.running = 0
        self.client_snapshot = {}  # EXAMPLE {'<filepath1>: ['<timestamp>', '<md5>', '<filepath2>: ...}
        self.local_dir_state = {}  # EXAMPLE {'last_timestamp': '<timestamp>', 'global_md5': '<md5>'}
        self.listener_socket = None
        self.observer = None
        self.cfg = self._load_cfg(cfg_path, sharing_path)
        self.password = self._load_pass()
        self._init_sharing_path(sharing_path)

        self.conn_mng = ConnectionManager(self.cfg)
Esempio n. 53
0
    def __init__(self, monitor_dir, config, archive=False, initial_scan=False,
                 archive_suffix="_orig.pdf"):
        FileSystemEventHandler.__init__(self)

        self.monitor_dir = monitor_dir
        self.archive_suffix = archive_suffix
        self.archive = archive

        if not config: config = {}

        # Scan initial folder
        if initial_scan:
            self.scan_folder()

        self.scan_interval = config.get('scan_interval', 3) # If no updates in 3 seconds (or user specified option in config file) process file
Esempio n. 54
0
    def __init__(self, paper_filename, publish_url, paper_id):
        FileSystemEventHandler.__init__(self)  # super init

        self.paper_filename = paper_filename
        self.is_pdf = paper_filename.endswith('pdf')

        self.publish_url = publish_url
        self.paper_id = paper_id

        self.reset_stats()

        logging.info(
            "Creating a GamificationHandler with paper: " + paper_filename +
            " publish_url: " + publish_url +
            " and paper id: " + paper_id
        )
Esempio n. 55
0
def start_fs_loop():
    init()
    try:
        os.makedirs("albums")
    except:
        None
    ev_handler = FileSystemEventHandler()
    ev_handler.dispatch = handle_fs_events

    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(ev_handler, "albums/", recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
Esempio n. 56
0
  def __init__(self):
    # Grab a list of files in the target directory, sort and stick in a deque for optimized access (lists are slow)
    self.dir = deque()
    for f in sorted(filter(lambda x: args.filter_string in x, os.listdir(args.path))):
      self.dir.append('%s%s' % (args.path, f))

    # Open the first file in the queue
    self.file = open(self.dir.popleft(), 'r')

    # Init ourselves some redis
    self.r = redis.Redis(host='localhost', port=6379, db=args.db_index)
    self.redis_index = 0

    # Set the initial file position
    self.where = self.file.tell()

    # Run the initial feed of the logs
    self.ReadLog()
    FileSystemEventHandler.__init__(self)