Decorator to assert that we're in a valid state.
541815
def valid_status(*valid):
  """"""
  def decorator(func):
    @functools.wraps(func)
    def _valid_status(self, *args, **kwargs):
      if self.status not in valid:
        raise protocol.ProtocolError(
            "`%s` called while in state: %s, valid: (%s)" % (
                func.__name__, self.status, ",".join(map(str, valid))))
      return func(self, *args, **kwargs)
    return _valid_status
  return decorator
1189294
def ok(no_exit, func, *args, **kwargs):
    """"""
    ret = func(*args, **kwargs)
    if no_exit or ret >= 0:
        return ret
    reason = errmsg[abs(ret)]
    error('{0}() returned {1} ({2})'.format(func.__name__, ret, reason))
767758
def is_state(self, status):
        
        if status == self.state:
            return True
        # Now low status
        if status == 'o' and self.state == u'UP':
            return True
        if status == 'd' and self.state == u'DOWN':
            return True
        if status in ['u', 'x'] and self.state == u'UNREACHABLE':
            return True
        return False
978885
def _valid(m, comment=VALID_RESPONSE, out=None):
    '''
    
    '''
    return _set_status(m, status=True, comment=comment, out=out)
1024203
def _check_states_enum(cls):
        """"""
        states_enum_name = cls.context.get_config('states_enum_name')
        try:
            cls.context['states_enum'] = getattr(
                cls.context.new_class, states_enum_name)
        except AttributeError:
            raise ValueError('No states enum given!')

        proper = True
        try:
            if not issubclass(cls.context.states_enum, Enum):
                proper = False
        except TypeError:
            proper = False

        if not proper:
            raise ValueError(
                'Please provide enum instance to define available states.')
1144650
def validate_statusline(self, valid_statusline):
        
        code = self.get_statuscode()
        try:
            code = int(code)
            assert(code > 0)
            return True
        except(ValueError, AssertionError):
            self.statusline = valid_statusline
            return False
1069300
def validate_normalized_state(state: np.ndarray,
                              num_qubits: int,
                              dtype: Type[np.number] = np.complex64) -> None:
    """"""
    if state.size != 1 << num_qubits:
        raise ValueError(
            'State has incorrect size. Expected {} but was {}.'.format(
                1 << num_qubits, state.size))
    if state.dtype != dtype:
        raise ValueError(
            'State has invalid dtype. Expected {} but was {}'.format(
                dtype, state.dtype))
    norm = np.sum(np.abs(state) ** 2)
    if not np.isclose(norm, 1):
        raise ValueError('State is not normalized instead had norm %s' % norm)
1234202
def assert_valid(self, instance, value=None):
        """"""
        valid = super(Union, self).assert_valid(instance, value)
        if not valid:
            return False
        if value is None:
            value = instance._get(self.name)
            if value is None:
                return True
        return self._try_prop_method(instance, value, 'assert_valid')
1342697
def grok_state(self, obj):
        """"""
        if 'state' in obj:
            my_state = obj['state'].lower()
            if my_state != 'absent' and my_state != 'present':
                raise aomi_excep \
                    .Validation('state must be either "absent" or "present"')

        self.present = obj.get('state', 'present').lower() == 'present'
278827
def _check_state(self, state):
        
        if not hasattr(state, '__iter__') or isinstance(state, six.string_types):
            raise ValueError('Start state must be a non-string iterable object.')
        state_vars = {s.var for s in state}
        if not state_vars == set(self.variables):
            raise ValueError('Start state must represent a complete assignment to all variables.'
                             'Expected variables in state: {svar}, Got: {mvar}.'.format(svar=state_vars,
                                                                                        mvar=set(self.variables)))
        for var, val in state:
            if val >= self.cardinalities[var]:
                raise ValueError('Assignment {val} to {var} invalid.'.format(val=val, var=var))
        return True
1188846
def check_application_state(self, request, callback):
        ""
        stored = request.session.get(self.session_key, None)
        returned = request.GET.get('state', None)
        check = False
        if stored is not None:
            if returned is not None:
                check = constant_time_compare(stored, returned)
            else:
                logger.error('No state parameter returned by the provider.')
        else:
            logger.error('No state stored in the sesssion.')
        return check
886983
def state=(value)
      return if @state == :closed
      unless PERMITTED_STATE_TRANSITIONS[@state].include?(value)
        raise ArgumentError, "Invalid state transition: #{@state.inspect} -> #{value.inspect}"
      end

      case value
      when :pending, :closed
        @stats["state"].update(value.to_s)
        @state = value
      when :authorized, :unauthorized, :expired, :failed
        if value != @state
          @stats["state"].update(value.to_s)
          @state = value
          (@status_callbacks || []).each do |callback|
            begin
              callback.call(:auth, @state)
            rescue StandardError => e
              ErrorTracker.log(self, "Failed status callback", e, nil, :caller)
            end
          end
        end
      else
        raise ArgumentError, "Unknown state: #{value.inspect}"
      end
      @state
    end
570094
def state(self):
    
    state = 'in progress'
    if self.is_complete:
      if self.failed:
        state = 'failed with error: %s' % str(self._fatal_error)
      elif self._errors:
        state = 'completed with some non-fatal errors'
      else:
        state = 'completed'
    return state
947060
def _assertsanity(self):
        """"""
        assert self.len >= 0
        assert 0 <= self._offset, "offset={0}".format(self._offset)
        assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset
        return True
20067
def _check_decorator(fct):
        """"""
        def wrapper(self, *args, **kw):
            if self.is_enable():
                ret = fct(self, *args, **kw)
            else:
                ret = self.stats
            return ret
        return wrapper
850017
def valid(self):
        """"""

        now = timezone.now()
        return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)
759336
def state(self, value):
        

        if value is not None:
            assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("state", value)
        self.__state = value