Perform pre-transition tasks and construct the destination state.

        :param is_on: The on-off state to transition to.
        :param kwargs: The state to transition to.
        :return: The destination state of the transition.
183938
def _prepare_transition(self, is_on=None, **kwargs):
        
        # Handle transitions with changing on-off-state
        dest_state = kwargs.copy()
        if is_on is not None:
            if is_on and not self.is_on:
                if 'brightness' not in kwargs or kwargs['brightness'] is None:
                    dest_state['brightness'] = self.brightness
                self.set(brightness=0, cancel_transition=False)
            elif not is_on and self.is_on:
                dest_state['brightness'] = 0

        return dest_state
885511
def toggle(self):
        
        with self._lock:
            if self.is_active:
                self.off()
            else:
                self.on()
1209544
def on(  # pylint: disable=invalid-name
            self, event: str, *handlers: T.Callable
    ) -> T.Callable:
        """"""

        def _on_wrapper(*handlers: T.Callable) -> T.Callable:
            """wrapper for on decorator"""
            self._events[event].extend(handlers)
            return handlers[0]

        if handlers:
            return _on_wrapper(*handlers)
        return _on_wrapper
1037455
def callback(self, callback, *args, **kwds):
        
        _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)

        # We changed the signature, so using @wraps is not appropriate, but
        # setting __wrapped__ may still help with introspection.
        _exit_wrapper.__wrapped__ = callback
        self._push_exit_callback(_exit_wrapper)
        return callback
985109
def transition_running_state(target_state)
      state_transitions = {
        not_started: :running,
        running: :stopping,
        stopping: :stopped
      }
      if state_transitions[@running_state] == target_state
        @running_state = target_state
      else
        fail "Bad server state transition: #{@running_state}->#{target_state}"
      end
    end
969265
def transition(self, state, message=""):
        
        with self.changes_squashed:
            initial_state = self.state.value
            if self.state_set.transition_allowed(
                    initial_state=initial_state, target_state=state):
                self.log.debug(
                    "%s: Transitioning from %s to %s",
                    self.mri, initial_state, state)
                if state == ss.DISABLED:
                    alarm = Alarm.invalid("Disabled")
                elif state == ss.FAULT:
                    alarm = Alarm.major(message)
                else:
                    alarm = Alarm()
                self.update_health(self, HealthInfo(alarm))
                self.state.set_value(state)
                self.state.set_alarm(alarm)
                for child, writeable in self._children_writeable[state].items():
                    if isinstance(child, AttributeModel):
                        child.meta.set_writeable(writeable)
                    elif isinstance(child, MethodModel):
                        child.set_writeable(writeable)
            else:
                raise TypeError("Cannot transition from %s to %s" %
                                (initial_state, state))
794818
def on_train_begin(self, **kwargs:Any)->None:
        ""
        self.wait, self.opt = 0, self.learn.opt
        super().on_train_begin(**kwargs)
175706
def is_active(self, key, *instances, **kwargs):
        
        try:
            default = kwargs.pop('default', False)

            # Check all parents for a disabled state
            parts = key.split(':')
            if len(parts) > 1:
                child_kwargs = kwargs.copy()
                child_kwargs['default'] = None
                result = self.is_active(':'.join(parts[:-1]), *instances,
                                        **child_kwargs)

                if result is False:
                    return result
                elif result is True:
                    default = result

            try:
                switch = self[key]
            except KeyError:
                # switch is not defined, defer to parent
                return default

            if switch.status == GLOBAL:
                return True
            elif switch.status == DISABLED:
                return False
            elif switch.status == INHERIT:
                return default

            conditions = switch.value
            # If no conditions are set, we inherit from parents
            if not conditions:
                return default

            instances = list(instances) if instances else []
            instances.extend(self.context.values())

            # check each switch to see if it can execute
            return_value = False

            for namespace, condition in conditions.iteritems():
                condition_set = registry_by_namespace.get(namespace)
                if not condition_set:
                    continue
                result = condition_set.has_active_condition(condition,
                                                            instances)
                if result is False:
                    return False
                elif result is True:
                    return_value = True
        except:
            log.exception('Error checking if switch "%s" is active', key)
            return_value = False

        # there were no matching conditions, so it must not be enabled
        return return_value
431681
def status(self, **kwargs):
        
        self.services = dict(
            init_system=self.init_system,
            services=[]
        )
977696
def async_refresh(self, *args, **kwargs):
        
        # We trigger the task with the class path to import as well as the
        # (a) args and kwargs for instantiating the class
        # (b) args and kwargs for calling the 'refresh' method

        try:
            enqueue_task(
                dict(
                    klass_str=self.class_path,
                    obj_args=self.get_init_args(),
                    obj_kwargs=self.get_init_kwargs(),
                    call_args=args,
                    call_kwargs=kwargs
                ),
                task_options=self.task_options
            )
        except Exception:
            # Handle exceptions from talking to RabbitMQ - eg connection
            # refused.  When this happens, we try to run the task
            # synchronously.
            logger.error("Unable to trigger task asynchronously - failing "
                         "over to synchronous refresh", exc_info=True)
            try:
                return self.refresh(*args, **kwargs)
            except Exception as e:
                # Something went wrong while running the task
                logger.error("Unable to refresh data synchronously: %s", e,
                             exc_info=True)
            else:
                logger.debug("Failover synchronous refresh completed successfully")
1030304
def finish(self, *args, **kwargs):
        
        log.debug('finish(args={args}, kwargs={kwargs})'.format(args=args, kwargs=kwargs))
        self.on_finish(*args, **kwargs)
457039
def stop(self, *args, **kwargs):
        
        if self.status in (Status.stopping, Status.stopped):
            logger.debug("{} is already {}".format(self, self.status.name))
        else:
            self.status = Status.stopping
            self.onStopping(*args, **kwargs)
            self.status = Status.stopped
174907
def transition_state(state)
      authorize @contribution
      @initiative = @contribution.initiative
      @user = @contribution.user
      state = state.to_sym
      transition = @contribution.transition_by_state(state)
      initial_state = @contribution.state_name
      resource_name = @contribution.class.model_name.human
      if @contribution.send("can_#{transition}?")
        begin
          if @contribution.state_on_gateway != state
            if @contribution.update_state_on_gateway!(state)
              @contribution.send("#{transition}!")
            else
              flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
            end
          else
            @contribution.send("#{transition}!")
          end
        rescue
          flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
        end
      else
        flash[:alert] = t('flash.actions.update.alert', resource_name: resource_name)
      end
      if flash[:alert].present?
        render 'initiatives/contributions/show'
      else
        if initial_state == :pending
          flash[:notice] = t('flash.actions.create.notice', resource_name: resource_name)
        else
          flash[:notice] = t('flash.actions.update.notice', resource_name: resource_name)
        end
        redirect_to initiative_contribution_path(@contribution.initiative.id, @contribution)
      end
    end
161152
def _oneTransition(self, startState, inputToken, endState, outputTokens,
                       collector):
        
        # FIXME: tests for all of this (some of it is wrong)
        # if not isinstance(startState, MethodicalState):
        #     raise NotImplementedError("start state {} isn't a state"
        #                               .format(startState))
        # if not isinstance(inputToken, MethodicalInput):
        #     raise NotImplementedError("start state {} isn't an input"
        #                               .format(inputToken))
        # if not isinstance(endState, MethodicalState):
        #     raise NotImplementedError("end state {} isn't a state"
        #                               .format(startState))
        # for output in outputTokens:
        #     if not isinstance(endState, MethodicalState):
        #         raise NotImplementedError("output state {} isn't a state"
        #                                   .format(endState))
        self._automaton.addTransition(startState, inputToken, endState,
                                      tuple(outputTokens))
        inputToken.collectors[startState] = collector
368509
def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None):
        
        with _blocking(self.lock, self.power_state, self.light_state_event,
                       timeout):
            self.send(REQ_SET_POWER_STATE,
                      bulb, '2s', '\x00\x01' if is_on else '\x00\x00')
            self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
        return self.power_state
555465
def set_state(self, updater=None, **kwargs):
        
        if callable(updater):
            state_change = updater(self)
        elif updater is not None:
            state_change = updater
        else:
            state_change = kwargs

        return [callback_result
                for k, v in state_change.items()
                for callback_result in self.set(k, v)]
383016
def _onsuccess(self, result):
        
        if KSER_METRICS_ENABLED == "yes":
            KSER_TASKS_STATUS.labels(
                __hostname__, self.__class__.path, 'SUCCESS'
            ).inc()
        if result:
            result = self.result + result
        else:
            result = self.result
        logger.info(
            "{}.Success: {}[{}]: {}".format(
                self.__class__.__name__, self.__class__.path, self.uuid, result
            ),
            extra=dict(
                kmsg=Message(
                    self.uuid, entrypoint=self.__class__.path,
                    params=self.params, metadata=self.metadata
                ).dump(),
                kresult=ResultSchema().dump(result) if result else dict()
            )
        )
        return self.onsuccess(result)