Create a callback used as the target of timer events.

A reference is kept to the callback for the lifetime of the loop
to prevent "Cannot destroy active lambda function" fatal error from
the event extension.
553725
private function createTimerCallback()
    {
        $this->timerCallback = function ($_, $_, $timer) {
            call_user_func($timer->getCallback(), $timer);

            // Timer already cancelled ...
            if (!$this->isTimerActive($timer)) {
                return;

                // Reschedule periodic timers ...
            } elseif ($timer->isPeriodic()) {
                event_add(
                    $this->timerEvents[$timer],
                    $timer->getInterval() * self::MICROSECONDS_PER_SECOND
                );

                // Clean-up one shot timers ...
            } else {
                $this->cancelTimer($timer);
            }
        };
    }
8012
function t(time, done) {
  if (arguments.length === 1) {
    done = time;
    time = 2000;
  }
  var error = new Error(`Callback took too long (max: ${time})`);
  var waiting = true;

  var timeout = setTimeout(function () {
    if (!waiting) return;
    waiting = false;
    done(error);
  }, time);

  function handler() {
    if (!waiting) return;
    clearTimeout(timeout);
    waiting = false;
    done.apply(this, arguments);
  }

  return handler;
}
207137
function attemptLock(lock, timeout, callback) {
  var lockPath;
  var sequenceNodeName;
  var timerId = null;
  var start = Date.now();

  createNode(lock, afterCreate);

  function afterCreate(err, nodePath) {
    if (err) {
      return exit(err);
    }

    lockPath = nodePath;

    sequenceNodeName = nodePath.substring(lock.basePath.length + 1);

    getSortedChildren(lock, afterGetChildren);
  }

  function afterGetChildren(err, list) {
    if (exited()) {
      return;
    }
    if (err) {
      return exit(err);
    }

    var result = lock.driver.getsTheLock(list, sequenceNodeName,
      lock.maxLeases);

    if (result.error) {
      return exit(result.error);
    }
    else if (result.hasLock) {
      return exit(null, lockPath);
    }

    var watchPath = utils.join(lock.basePath, result.watchPath);

    lock.client
      .getData()
      .usingWatcher(watcher)
      .forPath(watchPath, afterGetData);

    setTimer();
  }

  function afterGetData(err) {
    if (exited() || !err) {
      return;
    }

    if (err.getCode() === Exception.NO_NODE) {
      getSortedChildren(lock, afterGetChildren);
    }
    else {
      exit(err);
    }
  }

  function watcher(event) {
    if (!exited() && event.getType() === Event.NODE_DELETED) {
      getSortedChildren(lock, afterGetChildren);
    }
  }

  function setTimer() {
    if (timerId) {
      return;
    }

    if (timeout >= 0) {
      timeout -= Date.now() - start;

      if (timeout <= 0) {
        return sayBye();
      }

      timerId = setTimeout(sayBye, timeout);
    }
  }

  function sayBye() {
    exit(new TimeoutError('Could not acquire lock %s', lock.basePath));
  }

  function exit(err, path) {
    if (timerId) {
      clearTimeout(timerId);
      timerId = -1;
    }

    var cb = callback;
    callback = null;

    if (!err) {
      cb(null, path);
    }
    else if (lockPath) {
      deleteNode(lock, lockPath, proceed);
    }
    else {
      cb(err);
    }

    function proceed(deleteError) {
      if (deleteError) {
        cb(deleteError);
      }
      else {
        cb(err);
      }
    }
  }

  function exited() {
    return !callback;
  }
}
91569
def call_repeatedly(func, interval, *args, **kwargs):
    
    main_thead = threading.current_thread()
    stopped = threading.Event()

    def loop():
        while not stopped.wait(interval) and main_thead.is_alive():  # the first call is in `interval` secs
            func(*args, **kwargs)

        return

    timer_thread = threading.Thread(target=loop, daemon=True)
    timer_thread.start()

    atexit.register(stopped.set)

    return timer_thread, stopped.set
977671
function createMethodsManager() {
    var methods = {};

    return {
        addMethod: addMethod,
        setTarget: setTarget
    };

    /*
     * Adds a method that will be available to extend the object.
     *
     * @param {string} name The method name
     * @param {function} [method] The handler for the specified method name.
     * @return {function} The handler for the specified method name.
     */
    function addMethod(name, method) {
        if (method !== undefined) {
            methods[name] = method;
        }
        return methods[name];
    }

    /*
     * Sets the target object to extend.
     *
     * @param {object} target The target object.
     */
    function setTarget(target) {
        var targetMethods = {};
        for (var name in methods) {
            targetMethods[name] = wrapMethod(target, methods[name]);
        }
        return targetMethods;
    }

    /*
     * Wraps the method so that it is executed with the appropriate
     * arguments.
     *
     * @param {object} target The target object.
     * @param {function} method The method to wrap.
     */
    function wrapMethod(target, method) {
        return function() {

            // Put arguments into a real array.
            var methodArgs = [];
            for (var i = 0; i < arguments.length; i++) {
                methodArgs.push(arguments[i]);
            }

            var params = method(target, parseMethodArgs, methodArgs);

            modifyTarget(target,
                params.source,
                params.sourceKeys,
                params.filters,
                params.overrideKeys);
            return this;
        };
    }
}
636755
def _wrap(self, value, priority=0):
        

        if not callable(value):
            raise TypeError("Only callable values can be stored in CallbackContainer")

        elif self.is_bound_method(value):

            # We are dealing with a bound method. Method references aren't
            # persistent, so instead we store a reference to the function
            # and instance.

            value = (weakref.ref(value.__func__),
                     weakref.ref(value.__self__, self._auto_remove),
                     priority)

        else:

            value = (value, priority)

        return value
701769
function (opts) {
        if (!opts.target || !opts.method) {
            return
        }

        var target = opts.target,
            method = (typeof opts.method == 'function') ? opts.method : target[opts.method]

        var element = this.hashForMethods[opts.target.id]
        if (element) {
            for (var i=0; i<element.timers.length; i++) {
                // Compare callback function
                if (element.timers[i].callback == method.bind(target)) {
                    var timer = element.timers.splice(i, 1)
                    timer = null
                }
            }
        }
    }
1237447
def safe_callback(self, event, *args, **kwargs):
        # type: (str, *Any, **Any) -> Any
        
        if self.state == StoredInstance.KILLED:
            # Invalid state
            return None

        try:
            return self.__callback(event, *args, **kwargs)
        except FrameworkException as ex:
            # Important error
            self._logger.exception(
                "Critical error calling back %s: %s", self.name, ex
            )

            # Kill the component
            self._ipopo_service.kill(self.name)

            if ex.needs_stop:
                # Framework must be stopped...
                self._logger.error(
                    "%s said that the Framework must be stopped.", self.name
                )
                self.bundle_context.get_framework().stop()
            return False
        except:
            self._logger.exception(
                "Component '%s': error calling callback method for event %s",
                self.name,
                event,
            )
            return False
937435
def timerEvent( self, event ):
        
        self.killTimer(event.timerId())
        
        self.setMaximumWidth(10000)
        self.setMaximumHeight(10000)
775759
def addCallback(cls, eventType, func, record=None, once=False):
        
        callbacks = cls.callbacks()
        callbacks.setdefault(eventType, [])
        callbacks[eventType].append((func, record, once))
1131117
def set_callbacks(self, worker_start_callback: callable, worker_end_callback: callable, are_async: bool = False):
        
        # We are setting self.worker_start_callback and self.worker_end_callback
        # to lambdas instead of saving them in private vars and moving the lambda logic
        # to a member function for, among other reasons, making callback updates atomic,
        # ie. once a callback has been posted, it will be executed as it was in that
        # moment, any call to set_callbacks will only affect callbacks posted since they
        # were updated, but not to any pending callback.

        # If callback is async, execute the start callback in the calling thread
        scheduler = self.immediate if are_async else self.background
        self.worker_start_callback = lambda worker: scheduler(Work(
            lambda: worker_start_callback(worker), "worker_start_callback:" + worker.name
        ))

        # As the end callback is called *just* before the thread dies,
        # there is no problem running it on the thread
        self.worker_end_callback = lambda worker: self.immediate(Work(
            lambda: worker_end_callback(worker), "worker_end_callback:" + worker.name
        ))
601343
function(implementOn, event, callback, selector, context, once) {
	var self = this,

	stringy = callback.toString(),
	
	wrappedListener = function (e){

		var eventWrapper = new NWTEventInstance(e),

		selfCallee = arguments.callee,

		returnControl = function() {
			// Call the callback
			// Prepend the wrapped event onto the argument list so we can expect what arguments we get
			localnwt.event._eventData.unshift(eventWrapper);
			callback.apply(implementOn, localnwt.event._eventData);
			localnwt.event._eventData = [];

			if (once) {
				implementOn.removeEventListener(event, selfCallee);
			}
		};

		if (selector) {
			implementOn.all(selector).each(function(userEl) {
				if (userEl._node == eventWrapper.target._node) {
					returnControl();
				}
			});
			return;
		}
		returnControl();
	};

	// Push the callback onto the cached string
	self._cached[stringy] = self._cached[stringy] || [];
	self._cached[stringy].push({
		type: event,
		obj: implementOn,
		fn: wrappedListener,
		raw: callback
	})

	return wrappedListener;
}
573218
def create_with(
            cls, event: str = None, observable: T.Union[str, Observable] = None
    ) -> T.Callable[..., "ObservableProperty"]:
        """"""

        return functools.partial(cls, event=event, observable=observable)
1049064
def start(self, *args, **kwargs):
        

        @wraps(self.callback)
        def callback():
            os.read(self.timer, 8)
            repeat = self.callback(*args, **kwargs)
            if not repeat:
                self.stop()

        spec = timerfd.itimerspec(self.interval, self.interval)
        timerfd.settime(self.timer, 0, spec)

        self.loop.remove_watcher(self.timer)
        self.loop.add_watcher(self.timer, callback)
565509
def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
        
        self.loop.add_callback(callback, *args, **kwargs)
652471
function( e )
        {
            var event      = new Event( aType );
            event.target   = self;
            event.srcEvent = e;

            aHandler( event );
        }
122469
function createCallback(element,callback) {

    var fn = function(originalEvent) {

      !originalEvent && ( originalEvent = window.event );

      // create a normalized event object
      var event = {
        // keep a ref to the original event object
        originalEvent: originalEvent,
        target: originalEvent.target || originalEvent.srcElement,
        type: "wheel",
        deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
        deltaX: 0,
        delatZ: 0,
        preventDefault: function() {
          originalEvent.preventDefault ?
            originalEvent.preventDefault() :
            originalEvent.returnValue = false;
        }
      };

      // calculate deltaY (and deltaX) according to the event
      if ( support == "mousewheel" ) {
        event.deltaY = - 1/40 * originalEvent.wheelDelta;
        // Webkit also support wheelDeltaX
        originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
      } else {
        event.deltaY = originalEvent.detail;
      }

      // it's time to fire the callback
      return callback( event );

    };

    fns.push({
      element: element,
      fn: fn,
    });

    return fn;
  }