Create a general "register watcher" system that will be ported out and directly accessable in the device_curator object.
162556
function createRegisterWatcher(curatedDevice) {
	this.watchers = {};

	this.getWatchers = function() {
		var defered = q.defer();
		var watcherKeys = Object.keys(self.watchers);
		defered.resolve(watcherKeys);
		return defered.promise;
	};
	
	var isValidWatcher = function(watcherName) {
		var isValid = true;
		if(typeof(self.watchers[watcherName]) === 'undefined') {
			isValid = false;
			return isValid;
		}
		return isValid;
	};
	// createWatcher is the function that creates a new watcher if one doesn't
	// already exist.
	this.createWatcher = function(watcherName, callback, options) {
		var defered = q.defer();

		var collectionFunction = 'iReadMany';
		if(options) {
			if(options.collectionFunction) {
				collectionFunction = options.collectionFunction;
			}
		}
		// If there aren't any watchers
		if(!isValidWatcher(watcherName)) {
			self.watchers[watcherName] = new createWatcherObject(
				watcherName,
				collectionFunction,
				callback,
				curatedDevice
			);
			defered.resolve(watcherName);
		} else {
			defered.reject({'err': 'Watcher already exists'});
		}
		return defered.promise;
	};

	this.configureWatcher = function(watcherName, newConfig) {
		if(isValidWatcher(watcherName)) {
			return self.watchers[watcherName].configureWatcher(newConfig);
		} else {
			var defered = q.defer();
			defered.reject({'err': 'Watcher does not exist'});
			return defered.promise;
		}
	};

	var deleteWatcher = function(watcherName) {
		var defered = q.defer();
		var statistics = {};
		var keys = Object.keys(self.watchers[watcherName].statistics);
		keys.forEach(function(key) {
			statistics[key] = self.watchers[watcherName].statistics[key];
		});
		self.watchers[watcherName] = null;
		self.watchers[watcherName] = undefined;
		delete self.watchers[watcherName];
		defered.resolve({'name': watcherName, 'statistics': statistics});
		return defered.promise;
	};
	this.stopWatcher = function(watcherName) {
		var defered = q.defer();
		if(isValidWatcher(watcherName)) {
			self.watchers[watcherName].stopWatcher()
			.then(deleteWatcher)
			.then(defered.resolve, defered.reject);
		} else {
			defered.reject({'err': 'Watcher does not exist'});
		}
		return defered.promise;
	};

	this.stopAllWatchers = function() {
		var defered = q.defer();
		var watcherKeys = Object.keys(self.watchers);
		if(watcherKeys.length > 0) {
			var promises = watcherKeys.map(self.stopWatcher);

			q.AllSettled(promises)
			.then(function(results) {
				defered.resolve(watcherKeys);
			});
		} else {
			defered.resolve([]);
		}
		return defered.promise;
	};
	
	var self = this;
}
702698
def register_callback(self, sensorid, callback, user_data=None):
        """"""
        if sensorid not in self._registry:
            self._registry[sensorid] = list()
        self._registry[sensorid].append((callback, user_data))
548744
def watch_record(indexer, use_polling=False):
    
    if use_polling:
        from watchdog.observers.polling import PollingObserver as Observer
        Observer  # fool pyflakes
    else:
        from watchdog.observers import Observer

    event_handler = RecordHandler(indexer)
    observer = Observer()
    observer.schedule(event_handler, path=indexer.record_path, recursive=True)
    indexer.logger.debug('Start observer.')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        indexer.logger.debug('Got KeyboardInterrupt. Stopping observer.')
        observer.stop()
    indexer.logger.debug('Joining observer.')
    observer.join()
    indexer.logger.debug('Finish watching record.')
114004
def add_watcher(self, fd, callback):
        """"""

        if not isinstance(fd, int):
            fd = fd.fileno()

        self.callbacks[fd] = callback
        self.epoll.register(fd, EPOLLIN)
837597
def remove_watchers(self, watcher_name = None):
        
        if watcher_name == None:
            self.device.watchers.remove()
        else:
            self.device.watchers.remove(watcher_name)
3243
function init(domainManager) {
    if (!domainManager.hasDomain("fileWatcher")) {
        domainManager.registerDomain("fileWatcher", {major: 0, minor: 1});
    }

    domainManager.registerCommand(
        "fileWatcher",
        "watchPath",
        watcherManager.watchPath,
        false,
        "Start watching a file or directory",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the file or directory to watch"
        }, {
            name: "ignored",
            type: "array",
            description: "list of path to ignore"
        }]
    );
    domainManager.registerCommand(
        "fileWatcher",
        "unwatchPath",
        watcherManager.unwatchPath,
        false,
        "Stop watching a single file or a directory and it's descendants",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the file or directory to unwatch"
        }]
    );
    domainManager.registerCommand(
        "fileWatcher",
        "unwatchAll",
        watcherManager.unwatchAll,
        false,
        "Stop watching all files and directories"
    );
    domainManager.registerEvent(
        "fileWatcher",
        "change",
        [
            {name: "event", type: "string"},
            {name: "parentDirPath", type: "string"},
            {name: "entryName", type: "string"},
            {name: "statsObj", type: "object"}
        ]
    );

    watcherManager.setDomainManager(domainManager);
    watcherManager.setWatcherImpl(watcherImpl);

}
547038
private void startWatcher() {

        if (m_watcher == null) {
            try {
                m_watcher = new CmsUploadTimeoutWatcher(this);
                m_watcher.start();
            } catch (Exception e) {
                LOG.info(
                    Messages.get().getBundle().key(Messages.LOG_UPLOAD_CREATE_WATCH_DOG_2, getId(), e.getMessage()));
            }
        }
    }
1357090
public function register()
    {
        $this->app->singleton('watcher', function ($app) {
            $tracker = new Tracker();

            return new Watcher($tracker, $app['files']);
        });
    }
1290765
def _setup_pyudev_monitoring(self):
        
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)
        self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event)
        self.udev_observer.start()
        self.py3_wrapper.log("udev monitoring enabled")
942867
def watch(ctx):
    
    watcher = Watcher(ctx)
    watcher.watch_directory(
        path='{pkg.source_less}', ext='.less',
        action=lambda e: build(ctx, less=True)
    )
    watcher.watch_directory(
        path='{pkg.source_js}', ext='.jsx',
        action=lambda e: build(ctx, js=True)
    )
    watcher.watch_directory(
        path='{pkg.docs}', ext='.rst',
        action=lambda e: build(ctx, docs=True)
    )
    watcher.start()
63365
def register(self, receiver_id, receiver):
        """"""
        assert receiver_id not in self.receivers
        self.receivers[receiver_id] = receiver(receiver_id)
186786
def assignBranchRegisters(inodes, registerMaker):
    
    for node in inodes:
        node.reg = registerMaker(node, temporary=True)
947806
def add_listener(registry, listener):
    
    if listener is None or listener in registry:
        return False

    registry.append(listener)
    return True
153563
def addObserver(self, observer):
        """"""
        Observable.addObserver(self, observer)

        # If self.startOnDemand is True, the reader monitoring
        # thread only runs when there are observers.
        if self.startOnDemand:
            if 0 < self.countObservers():
                if not self.rmthread:
                    self.rmthread = ReaderMonitoringThread(
                        self,
                        self.readerProc, self.period)

                    # start reader monitoring thread in another thread to
                    # avoid a deadlock; addObserver and notifyObservers called
                    # in the ReaderMonitoringThread run() method are
                    # synchronized
                    try:
                        # Python 3.x
                        import _thread
                        _thread.start_new_thread(self.rmthread.start, ())
                    except:
                        # Python 2.x
                        import thread
                        thread.start_new_thread(self.rmthread.start, ())
        else:
            observer.update(self, (self.rmthread.readers, []))
549115
def addMonitor(self, monitor):
    

    token = self.nextMonitorToken
    self.nextMonitorToken += 1

    self.monitors[token] = monitor

    return token
1289381
def run_watcher(self):
        
        # Create observer
        observer = Observer()

        # Start observer
        observer.start()

        # Dict that maps file path to `watch object`
        watche_obj_map = {}

        # Run change check in a loop
        while not self._watcher_to_stop:
            # Get current watch paths
            old_watch_path_s = set(watche_obj_map)

            # Get new watch paths
            new_watch_path_s = self._find_watch_paths()

            # For each new watch path
            for new_watch_path in new_watch_path_s:
                # Remove from the old watch paths if exists
                old_watch_path_s.discard(new_watch_path)

                # If the new watch path was not watched
                if new_watch_path not in watche_obj_map:
                    try:
                        # Schedule a watch
                        watch_obj = observer.schedule(
                            # 2KGRW
                            # `FileSystemEventHandler` instance
                            self,
                            # File path to watch
                            new_watch_path,
                            # Whether recursive
                            recursive=True,
                        )

                        # Store the watch obj
                        watche_obj_map[new_watch_path] = watch_obj

                    # If have error
                    except OSError:
                        # Set the watch object be None
                        watche_obj_map[new_watch_path] = None

            # For each old watch path that is not in the new watch paths
            for old_watch_path in old_watch_path_s:
                # Get watch object
                watch_obj = watche_obj_map.pop(old_watch_path, None)

                # If have watch object
                if watch_obj is not None:
                    # Unschedule the watch
                    observer.unschedule(watch_obj)

            # Store new watch paths
            self._watch_paths = new_watch_path_s

            # Sleep before next check
            time.sleep(self._interval)
398569
@SuppressWarnings("unchecked")
    private List<ListenerRegistration> addListenerToRegistry() {
        List<ListenerRegistration> registrationsBuilder = newArrayList();
        for (Pair<IdMatcher, Watcher> guiceWatcherRegistration : getRegisteredWatchers()) {
            Watcher watcher = guiceWatcherRegistration.right();
            IdMatcher idMatcher = guiceWatcherRegistration.left();
            Registration registration = registry.addWatcher(idMatcher, watcher);
            ListenerRegistration listenerRegistration = new ListenerRegistration(registration, idMatcher, watcher);
            registrationsBuilder.add(listenerRegistration);
        }
        return registrationsBuilder;
    }