get all the triggers that need to be handled
15884
def handle(self, *args, **options):
        
        from django.db import connection
        connection.close()
        failed_tries = settings.DJANGO_TH.get('failed_tries', 10)
        trigger = TriggerService.objects.filter(
            Q(provider_failed__lte=failed_tries) |
            Q(consumer_failed__lte=failed_tries),
            status=True,
            user__is_active=True,
            provider__name__status=True,
            consumer__name__status=True,
        ).select_related('consumer__name', 'provider__name')

        with ThreadPoolExecutor(max_workers=settings.DJANGO_TH.get('processes')) as executor:
            r = Read()
            for t in trigger:
                executor.submit(r.reading, t)
334135
def get_event_triggers(self):
        
        events = {}
        nvrflag = False
        event_xml = []

        url = '%s/ISAPI/Event/triggers' % self.root_url

        try:
            response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
            if response.status_code == requests.codes.not_found:
                # Try alternate URL for triggers
                _LOGGING.debug('Using alternate triggers URL.')
                url = '%s/Event/triggers' % self.root_url
                response = self.hik_request.get(url)

        except (requests.exceptions.RequestException,
                requests.exceptions.ConnectionError) as err:
            _LOGGING.error('Unable to fetch events, error: %s', err)
            return None

        if response.status_code != 200:
            # If we didn't recieve 200, abort
            return None

        # pylint: disable=too-many-nested-blocks
        try:
            content = ET.fromstring(response.text)

            if content[0].find(self.element_query('EventTrigger')):
                event_xml = content[0].findall(
                    self.element_query('EventTrigger'))
            elif content.find(self.element_query('EventTrigger')):
                # This is either an NVR or a rebadged camera
                event_xml = content.findall(
                    self.element_query('EventTrigger'))

            for eventtrigger in event_xml:
                ettype = eventtrigger.find(self.element_query('eventType'))
                # Catch empty xml defintions
                if ettype is None:
                    break
                etnotify = eventtrigger.find(
                    self.element_query('EventTriggerNotificationList'))

                etchannel = None
                etchannel_num = 0

                for node_name in CHANNEL_NAMES:
                    etchannel = eventtrigger.find(
                        self.element_query(node_name))
                    if etchannel is not None:
                        try:
                            # Need to make sure this is actually a number
                            etchannel_num = int(etchannel.text)
                            if etchannel_num > 1:
                                # Must be an nvr
                                nvrflag = True
                            break
                        except ValueError:
                            # Field must not be an integer
                            pass

                if etnotify:
                    for notifytrigger in etnotify:
                        ntype = notifytrigger.find(
                            self.element_query('notificationMethod'))
                        if ntype.text == 'center' or ntype.text == 'HTTP':
                            """
                            If we got this far we found an event that we want
                            to track.
                            """
                            events.setdefault(ettype.text, []) \
                                .append(etchannel_num)

        except (AttributeError, ET.ParseError) as err:
            _LOGGING.error(
                'There was a problem finding an element: %s', err)
            return None

        if nvrflag:
            self.device_type = NVR_DEVICE
        else:
            self.device_type = CAM_DEVICE
        _LOGGING.debug('Processed %s as %s Device.',
                       self.cam_id, self.device_type)

        _LOGGING.debug('Found events: %s', events)
        self.hik_request.close()
        return events
677416
public function getTriggered(array $data = array(), array $options = array())
    {
        $options += array('status' => 1);
        $triggers = (array) $this->getList($options);

        if (empty($triggers)) {
            return array();
        }

        $triggered = array();
        foreach ($triggers as $trigger) {
            if ($this->condition->isMet($trigger, $data)) {
                $triggered[] = $trigger['trigger_id'];
            }
        }

        return $triggered;
    }
5103
def _triggering_ctx(self):
        
        if self._is_triggering:
            raise RuntimeError('{} cannot be triggered while it is being handled'.format(self))
        self._is_triggering = True
        try:
            yield self
        finally:
            self._is_triggering = False
1354243
def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):
		
		pass
1278583
def handle(self, *args, **options):
        
        trigger_id = options.get('trigger_id')
        trigger = TriggerService.objects.filter(
            id=int(trigger_id),
            status=True,
            user__is_active=True,
            provider_failed__lt=settings.DJANGO_TH.get('failed_tries', 10),
            consumer_failed__lt=settings.DJANGO_TH.get('failed_tries', 10)
        ).select_related('consumer__name', 'provider__name')
        try:
            with Pool(processes=1) as pool:
                r = Read()
                result = pool.map_async(r.reading, trigger)
                result.get(timeout=360)
                p = Pub()
                result = pool.map_async(p.publishing, trigger)
                result.get(timeout=360)

                cache.delete('django_th' + '_fire_trigger_' + str(trigger_id))
        except TimeoutError as e:
            logger.warning(e)
43397
def if_sqlserver_disable_constraints_triggers(session: SqlASession,
                                              tablename: str) -> None:
    
    with if_sqlserver_disable_constraints(session, tablename):
        with if_sqlserver_disable_triggers(session, tablename):
            yield
952613
function getHandlers (name, callback, context) {
    var events = [];
    if (!callback && !context) {
        if (name) {
            return (this._events && this._events[name]) || [];
        } else {
            return this._events;
        }
    }
    _.each(this._events, function (value, key) {
        if (!name || key === name) {
            value.forEach(function (event) {
                if ((!callback || event.callback === callback) && (!context || event.context === context)) {
                    events.push(event);
                }
            });
        }
    });
    return events;
}
790391
function(db) {
		var queries = [
		'DROP TRIGGER IF EXISTS documents_tcn_trigger ON documents',
		'CREATE TRIGGER documents_tcn_trigger AFTER INSERT OR UPDATE OR DELETE ON documents FOR EACH ROW EXECUTE PROCEDURE triggered_change_notification()',
		'DROP TRIGGER IF EXISTS dbversions_tcn_trigger ON dbversions',
		'CREATE TRIGGER dbversions_tcn_trigger AFTER INSERT OR UPDATE OR DELETE ON dbversions FOR EACH ROW EXECUTE PROCEDURE triggered_change_notification()',
		'DROP TRIGGER IF EXISTS types_tcn_trigger ON types',
		'CREATE TRIGGER types_tcn_trigger AFTER INSERT OR UPDATE OR DELETE ON types FOR EACH ROW EXECUTE PROCEDURE triggered_change_notification()',
		'DROP TRIGGER IF EXISTS attachments_tcn_trigger ON attachments',
		'CREATE TRIGGER attachments_tcn_trigger AFTER INSERT OR UPDATE OR DELETE ON attachments FOR EACH ROW EXECUTE PROCEDURE triggered_change_notification()',
		'DROP TRIGGER IF EXISTS libs_tcn_trigger ON libs',
		'CREATE TRIGGER libs_tcn_trigger AFTER INSERT OR UPDATE OR DELETE ON libs FOR EACH ROW EXECUTE PROCEDURE triggered_change_notification()'
		];
		return queries.map(function(q) {
			return db.query(q);
		}).reduce(_Q.when, _Q(db));
	}
1123750
def manage_action(self,
                      stat_name,
                      trigger,
                      header,
                      action_key):
        """"""
        # Here is a command line for the current trigger ?
        try:
            command, repeat = self.get_limit_action(trigger, stat_name=stat_name)
        except KeyError:
            # Reset the trigger
            self.actions.set(stat_name, trigger)
        else:
            # Define the action key for the stats dict
            # If not define, then it sets to header
            if action_key is None:
                action_key = header

            # A command line is available for the current alert
            # 1) Build the {{mustache}} dictionnary
            if isinstance(self.get_stats_action(), list):
                # If the stats are stored in a list of dict (fs plugin for exemple)
                # Return the dict for the current header
                mustache_dict = {}
                for item in self.get_stats_action():
                    if item[self.get_key()] == action_key:
                        mustache_dict = item
                        break
            else:
                # Use the stats dict
                mustache_dict = self.get_stats_action()
            # 2) Run the action
            self.actions.run(
                stat_name, trigger,
                command, repeat, mustache_dict=mustache_dict)
185202
def triggers(self):
        
        self._triggers, value = self.get_attr_set(self._triggers, 'trigger')
        return value
642918
def trigger_revisions(self, trigger_id, **kwargs):
        ""
        api_path = "/api/v2/triggers/{trigger_id}/revisions.json"
        api_path = api_path.format(trigger_id=trigger_id)
        return self.call(api_path, **kwargs)
596275
def get_handlers(self, event: str) -> T.List[T.Callable]:
        """"""

        return list(self._events.get(event, []))
285709
def trigger_show_by_trigger_name(self, trigger_name, **kwargs):
        ""
        api_path = "/api/v2/triggers/{trigger_name}"
        api_path = api_path.format(trigger_name=trigger_name)
        return self.call(api_path, **kwargs)
944663
function triggerEvents (list, args, context) {
  var pass = true

  if (list) {
    var i = 0
    var l = list.length
    var a1 = args[0]
    var a2 = args[1]
    var a3 = args[2]
    // call is faster than apply, optimize less than 3 argu
    // http://blog.csdn.net/zhengyinhui100/article/details/7837127
    switch (args.length) {
      case 0: for (; i < l; i += 2) {pass = list[i].call(list[i + 1] || context) !== false && pass} break
      case 1: for (; i < l; i += 2) {pass = list[i].call(list[i + 1] || context, a1) !== false && pass} break
      case 2: for (; i < l; i += 2) {pass = list[i].call(list[i + 1] || context, a1, a2) !== false && pass} break
      case 3: for (; i < l; i += 2) {pass = list[i].call(list[i + 1] || context, a1, a2, a3) !== false && pass} break
      default: for (; i < l; i += 2) {pass = list[i].apply(list[i + 1] || context, args) !== false && pass} break
    }
  }
  // trigger will return false if one of the callbacks return false
  return pass
}
1213724
public static TriggerContext on(Trigger trigger) {
        List<Trigger> addedTriggers = new ArrayList<Trigger>();
        if (trigger != null) {
            addedTriggers.add(trigger);
        }
        return new TriggerContext(addedTriggers);
    }
894629
def _trigger(self):
        """"""
        if _debug: IOQController._debug("_trigger")

        # if we are busy, do nothing
        if self.state != CTRL_IDLE:
            if _debug: IOQController._debug("    - not idle")
            return

        # if there is nothing to do, return
        if not self.ioQueue.queue:
            if _debug: IOQController._debug("    - empty queue")
            return

        # get the next iocb
        iocb = self.ioQueue.get()

        try:
            # hopefully there won't be an error
            err = None

            # let derived class figure out how to process this
            self.process_io(iocb)
        except:
            # extract the error
            err = sys.exc_info()[1]

        # if there was an error, abort the request
        if err:
            self.abort_io(iocb, err)

        # if we're idle, call again
        if self.state == CTRL_IDLE:
            deferred(IOQController._trigger, self)