Validate the beacon configuration
351746
def validate(config):
    '''
    
    '''
    if not isinstance(config, list):
        return False, ('Configuration for telegram_bot_msg '
                       'beacon must be a list.')

    _config = {}
    list(map(_config.update, config))

    if not all(_config.get(required_config)
               for required_config in ['token', 'accept_from']):
        return False, ('Not all required configuration for '
                       'telegram_bot_msg are set.')

    if not isinstance(_config.get('accept_from'), list):
        return False, ('Configuration for telegram_bot_msg, '
                       'accept_from must be a list of usernames.')

    return True, 'Valid beacon configuration.'
704006
def validate(config):
    '''
    
    '''

    VALID_MASK = [
        'access',
        'attrib',
        'close_nowrite',
        'close_write',
        'create',
        'delete',
        'delete_self',
        'excl_unlink',
        'ignored',
        'modify',
        'moved_from',
        'moved_to',
        'move_self',
        'oneshot',
        'onlydir',
        'open',
        'unmount'
    ]

    # Configuration for inotify beacon should be a dict of dicts
    if not isinstance(config, list):
        return False, 'Configuration for inotify beacon must be a list.'
    else:
        _config = {}
        list(map(_config.update, config))

        if 'files' not in _config:
            return False, 'Configuration for inotify beacon must include files.'
        else:
            for path in _config.get('files'):

                if not isinstance(_config['files'][path], dict):
                    return False, ('Configuration for inotify beacon must '
                                   'be a list of dictionaries.')
                else:
                    if not any(j in ['mask',
                                     'recurse',
                                     'auto_add'] for j in _config['files'][path]):
                        return False, ('Configuration for inotify beacon must '
                                       'contain mask, recurse or auto_add items.')

                    if 'auto_add' in _config['files'][path]:
                        if not isinstance(_config['files'][path]['auto_add'], bool):
                            return False, ('Configuration for inotify beacon '
                                           'auto_add must be boolean.')

                    if 'recurse' in _config['files'][path]:
                        if not isinstance(_config['files'][path]['recurse'], bool):
                            return False, ('Configuration for inotify beacon '
                                           'recurse must be boolean.')

                    if 'mask' in _config['files'][path]:
                        if not isinstance(_config['files'][path]['mask'], list):
                            return False, ('Configuration for inotify beacon '
                                           'mask must be list.')
                        for mask in _config['files'][path]['mask']:
                            if mask not in VALID_MASK:
                                return False, ('Configuration for inotify beacon '
                                               'invalid mask option {0}.'.format(mask))
    return True, 'Valid beacon configuration'
648003
function validate(config, source) {

  if (typeof config.rules === 'object') {
    Object.keys(config.rules).forEach(function(id) {
      validateRuleOptions(id, config.rules[id], source);
    });
  }
}
823274
def _validate_config(self, config):
        
        required_keys = [
            self.KEY_IDP_CONFIG,
            self.KEY_ENDPOINTS,
        ]

        if not config:
            raise ValueError("No configuration given")

        for key in required_keys:
            try:
                _val = config[key]
            except KeyError as e:
                raise ValueError("Missing configuration key: %s" % key) from e
903319
function validateConfig(config) {
  var result = {}

  if (config.httpServer == null) throw Error("httpServer config property is null")
  result.httpServer = config.httpServer

  result.onRequest = config.onRequest || default_onRequest
  if (!_.isFunction(result.onRequest)) throw Error("onRequest config property is not a function")

  result.verbose = !!config.verbose

  return result

  //-----------------------------------
  function default_onRequest(request) {
    if (-1 == request.requestedProtocols.indexOf(exports.wsProtocol)) {
      return request.reject()
    }

    request.accept(exports.wsProtocol, request.origin)
  }
}
469395
def validate(args, config):
    
    profile = args.profile
    if not args.profile:
        if os.environ.get('AWS_PROFILE'):
            args.profile = os.environ.get('AWS_PROFILE')
        else:
            args.profile = 'default'

    if args.assume_role:
        role_msg = "with assumed role: %s" % (args.assume_role,)
    elif config.has_option(args.profile, 'assumed_role_arn'):
        role_msg = "with assumed role: %s" % (
            config.get(args.profile, 'assumed_role_arn'))
    else:
        role_msg = ""
    logging.info('Validating credentials for profile: %s %s' %
                (profile, role_msg))
    reup_message = "Obtaining credentials for a new role or profile."

    try:
        key_id = config.get(profile, 'aws_access_key_id')
        access_key = config.get(profile, 'aws_secret_access_key')
    except NoSectionError:
        log_error_and_exit("Credentials session '[%s]' is missing. "
                           "You must add this section to your credentials file "
                           "along with your long term 'aws_access_key_id' and "
                           "'aws_secret_access_key'" % (profile,))
    except NoOptionError as e:
        log_error_and_exit(e)

    # get device from param, env var or config
    if not args.device:
        if os.environ.get('MFA_DEVICE'):
            args.device = os.environ.get('MFA_DEVICE')
        elif config.has_option(profile, 'aws_mfa_device'):
            args.device = config.get(profile, 'aws_mfa_device')
        else:
            log_error_and_exit('You must provide --device or MFA_DEVICE or set '
                               '"aws_mfa_device" in ".aws/credentials"')

    # get assume_role from param or env var
    if not args.assume_role:
        if os.environ.get('MFA_ASSUME_ROLE'):
            args.assume_role = os.environ.get('MFA_ASSUME_ROLE')
        elif config.has_option(profile, 'assume_role'):
            args.assume_role = config.get(profile, 'assume_role')

    # get duration from param, env var or set default
    if not args.duration:
        if os.environ.get('MFA_STS_DURATION'):
            args.duration = int(os.environ.get('MFA_STS_DURATION'))
        else:
            args.duration = 3600 if args.assume_role else 43200

    # If this is False, only refresh credentials if expired. Otherwise
    # always refresh.
    force_refresh = False

    # Validate presence of profile-term section
    if not config.has_section(profile):
        config.add_section(profile)
        force_refresh = True
    # Validate option integrity of profile section
    else:
        required_options = ['assumed_role',
                            'aws_access_key_id', 'aws_secret_access_key',
                            'aws_session_token', 'aws_security_token',
                            'expiration']
        try:
            short_term = {}
            for option in required_options:
                short_term[option] = config.get(profile, option)
        except NoOptionError:
            logging.warn("Your existing credentials are missing or invalid, "
                        "obtaining new credentials.")
            force_refresh = True

        try:
            current_role = config.get(profile, 'assumed_role_arn')
        except NoOptionError:
            current_role = None

        if args.force:
            logging.info("Forcing refresh of credentials.")
            force_refresh = True
        # There are not credentials for an assumed role,
        # but the user is trying to assume one
        elif current_role is None and args.assume_role:
            logging.info(reup_message)
            force_refresh = True
        # There are current credentials for a role and
        # the role arn being provided is the same.
        elif (current_role is not None and
                args.assume_role and current_role == args.assume_role):
            pass
        # There are credentials for a current role and the role
        # that is attempting to be assumed is different
        elif (current_role is not None and
              args.assume_role and current_role != args.assume_role):
            logging.info(reup_message)
            force_refresh = True
        # There are credentials for a current role and no role arn is
        # being supplied
        elif current_role is not None and args.assume_role is None:
            logging.info(reup_message)
            force_refresh = True

    should_refresh = True

    # Unless we're forcing a refresh, check expiration.
    if not force_refresh:
        exp = datetime.strptime(
            config.get(profile, 'expiration'), '%Y-%m-%d %H:%M:%S')
        diff = exp - datetime.utcnow()
        if diff.total_seconds() <= 0:
            logging.info("Your credentials have expired, renewing.")
        else:
            should_refresh = False
            logging.info(
                "Your credentials are still valid for %s seconds"
                " they will expire at %s"
                % (diff.total_seconds(), exp))

    if should_refresh:
        get_credentials(profile, args, config)
592009
def validate_configs(self):
        
        # Check required arguments, validate values
        for conf in self.REQUIRED_CONFIGS:
            if conf not in self._config:
                raise MissingConfigError('Missing required configuration %s' % conf)
1207389
def _validate_time_range(trange, status, msg):
    '''
    
    '''
    # If trange is empty, just return the current status & msg
    if not trange:
        return status, msg

    if not isinstance(trange, dict):
        status = False
        msg = ('The time_range parameter for '
               'wtmp beacon must '
               'be a dictionary.')

    if not all(k in trange for k in ('start', 'end')):
        status = False
        msg = ('The time_range parameter for '
               'wtmp beacon must contain '
               'start & end options.')

    return status, msg
591004
def validate(self, config):
        
        if not isinstance(config, ConfigObject):
            raise Exception("Config object expected")

        if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):
            raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"])

        if config["output"]["layout"] not in ("default", "content-only"):
            raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"])

        if config["input"]["locations"] is not None:
            unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)]
            if len(unknown_locations) > 0:
                raise ValueError(
                    "Location%s \"%s\" does not exists"
                    % ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations))
                )

            config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]]

        if config["input"]["arguments"] is not None:
            if not isinstance(config["input"]["arguments"], dict):
                raise ValueError(
                    "Sources arguments \"%s\" are not a dict" % config["input"]["arguments"]
                )
39598
def validate():
    """"""

    errors = dict()
    for test in (test_architecture,
                 test_pyqt_availability,
                 test_pyblish_availability,
                 test_qtconf_availability,
                 test_qtconf_correctness,
                 test_qt_availability):
        try:
            test()
        except Exception as e:
            errors[test] = e

    if not errors:
        print("=" * 78)
        print()
        print(""" - Success!

{exe} is well suited to run Pyblish QML""".format(exe=sys.executable))
        print()
        print("=" * 78)

        return True

    print("=" * 78)
    print()
    print(" - Failed")
    print()
    for test, error in errors.iteritems():
        print(test.__name__)
        print("    %s" % error)
    print()
    print("=" * 78)

    return False
748918
def validate(self):
        """"""
        if not isinstance(self.location, Location):
            raise TypeError(u'Expected Location location, got: {} {}'
                            .format(type(self.location).__name__, self.location))

        if self.location.field is None:
            raise AssertionError(u'Received Location without a field: {}'
                                 .format(self.location))

        if not is_graphql_type(self.field_type):
            raise ValueError(u'Invalid value of "field_type": {}'.format(self.field_type))
279368
function validateConfig(config) {
    // appId and versionId are not validated here since
    // not all operations require these to be present.
    // Validation of specific params are done in the
    // ServiceBase.js
    const { authoringKey, region } = config;
    const messageTail = `is missing from the configuration.\n\nDid you run ${chalk.cyan.bold('luis init')} yet?`;

    assert(typeof authoringKey === 'string', `The authoringKey  ${messageTail}`);
    assert(typeof region === 'string', `The region ${messageTail}`);
    assert(args.region == 'westus' || args.region == 'westeurope' || args.region == 'australiaeast' || args.region == 'virginia', `${args.region} is not a valid authoring region.  Valid values are [westus|westeurope|australiaeast|virginia]`);
}
857476
function validateConfig(config) {
    // appId and versionId are not validated here since
    // not all operations require these to be present.
    // Validation of specific params are done in the
    // ServiceBase.js
    const {subscriptionKey} = config;
    const messageTail = `is missing from the configuration.\n\nDid you run ${chalk.cyan.bold('qnamaker init')} yet?`;
    assert(typeof subscriptionKey === 'string', `The subscriptionKey ${messageTail}`);
}
466016
def ValidateEndConfig(self, config_obj, errors_fatal=True):
    """"""
    errors = []

    if not config.CONFIG["Client.fleetspeak_enabled"]:
      location = config_obj.Get("Client.server_urls", context=self.context)
      if not location:
        errors.append("Empty Client.server_urls")

      for url in location:
        if not url.startswith("http"):
          errors.append("Bad Client.server_urls specified %s" % url)

    key_data = config_obj.GetRaw(
        "Client.executable_signing_public_key",
        default=None,
        context=self.context)
    if key_data is None:
      errors.append("Missing Client.executable_signing_public_key.")
    elif not key_data.startswith("-----BEGIN PUBLIC"):
      errors.append(
          "Invalid Client.executable_signing_public_key: %s" % key_data)
    else:
      rsa_key = rdf_crypto.RSAPublicKey()
      rsa_key.ParseFromHumanReadable(key_data)

    if not config.CONFIG["Client.fleetspeak_enabled"]:
      certificate = config_obj.GetRaw(
          "CA.certificate", default=None, context=self.context)
      if certificate is None or not certificate.startswith("-----BEGIN CERTIF"):
        errors.append("CA certificate missing from config.")

    for bad_opt in ["Client.private_key"]:
      if config_obj.Get(bad_opt, context=self.context, default=""):
        errors.append("Client cert in conf, this should be empty at deployment"
                      " %s" % bad_opt)

    if errors_fatal and errors:
      for error in errors:
        logging.error("Build Config Error: %s", error)
      raise RuntimeError("Bad configuration generated. Terminating.")
    else:
      return errors
474373
def beacon(config):
    '''
    
    '''
    log.debug(config)
    ctime = datetime.datetime.utcnow().isoformat()

    if not config:
        config = [{
            'loadavg': ['all'],
            'cpustats': ['all'],
            'meminfo': ['all'],
            'vmstats': ['all'],
            'time': ['all'],
        }]

    if not isinstance(config, list):
        # To support the old dictionary config format
        config = [config]

    ret = {}
    for entry in config:
        for func in entry:
            ret[func] = {}
            try:
                data = __salt__['status.{0}'.format(func)]()
            except salt.exceptions.CommandExecutionError as exc:
                log.debug('Status beacon attempted to process function %s '
                          'but encountered error: %s', func, exc)
                continue
            if not isinstance(entry[func], list):
                func_items = [entry[func]]
            else:
                func_items = entry[func]
            for item in func_items:
                if item == 'all':
                    ret[func] = data
                else:
                    try:
                        try:
                            ret[func][item] = data[item]
                        except TypeError:
                            ret[func][item] = data[int(item)]
                    except KeyError as exc:
                        ret[func] = 'Status beacon is incorrectly configured: {0}'.format(exc)

    return [{
        'tag': ctime,
        'data': ret,
    }]
252914
def validate(config):
    '''
    
    '''
    if not isinstance(config, list):
        return False, ('Configuration for network_settings '
                       'beacon must be a list.')
    else:
        _config = {}
        list(map(_config.update, config))

        interfaces = _config.get('interfaces', {})
        if isinstance(interfaces, list):
            #Old syntax
            return False, ('interfaces section for network_settings beacon'
                           ' must be a dictionary.')

        for item in interfaces:
            if not isinstance(_config['interfaces'][item], dict):
                return False, ('Interface attributes for network_settings beacon'
                               ' must be a dictionary.')
            if not all(j in ATTRS for j in _config['interfaces'][item]):
                return False, ('Invalid attributes in beacon configuration.')
    return True, 'Valid beacon configuration'
1222063
def validate_config(cls, config):
        
        if "discovery" not in config:
            raise ValueError("No discovery method defined.")

        if not any([item in config for item in ["port", "ports"]]):
            raise ValueError("No port(s) defined.")

        cls.validate_check_configs(config)