Validate the beacon configuration
343814
def validate(config):
    '''
    
    '''

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

        if 'emitatstartup' in _config:
            if not isinstance(_config['emitatstartup'], bool):
                return False, ('Configuration for load beacon option '
                               'emitatstartup must be a boolean.')

        if 'onchangeonly' in _config:
            if not isinstance(_config['onchangeonly'], bool):
                return False, ('Configuration for load beacon option '
                               'onchangeonly must be a boolean.')

        if 'averages' not in _config:
            return False, ('Averages configuration is required'
                           ' for load beacon.')
        else:

            if not any(j in ['1m', '5m', '15m'] for j
                       in _config.get('averages', {})):
                return False, ('Averages configuration for load beacon '
                               'must contain 1m, 5m or 15m items.')

            for item in ['1m', '5m', '15m']:
                if not isinstance(_config['averages'][item], list):
                    return False, ('Averages configuration for load beacon: '
                                   '1m, 5m and 15m items must be '
                                   'a list of two items.')
                else:
                    if len(_config['averages'][item]) != 2:
                        return False, ('Configuration for load beacon: '
                                       '1m, 5m and 15m items must be '
                                       'a list of two items.')

    return True, 'Valid beacon configuration'
44357
protected function registerBeacon()
    {
        $this->app->singleton(BeaconContract::class, function ($app) {
            $config = $app['config'];

            return new Beacon($config);
        });
    }
803497
def validate(config):
    '''
    
    '''
    # Must be a list of dicts.
    if not isinstance(config, list):
        return False, 'Configuration for napalm beacon must be a list.'
    for mod in config:
        fun = mod.keys()[0]
        fun_cfg = mod.values()[0]
        if not isinstance(fun_cfg, dict):
            return False, 'The match structure for the {} execution function output must be a dictionary'.format(fun)
        if fun not in __salt__:
            return False, 'Execution function {} is not availabe!'.format(fun)
    return True, 'Valid configuration for the napal beacon!'
1349368
def beacon(config):
    '''
    
    '''
    ret = []
    pkey = 'sh.vt'
    shells = _get_shells()
    ps_out = __salt__['status.procs']()
    track_pids = []
    for pid in ps_out:
        if any(ps_out[pid].get('cmd', '').lstrip('-') in shell for shell in shells):
            track_pids.append(pid)
    if pkey not in __context__:
        __context__[pkey] = {}
    for pid in track_pids:
        if pid not in __context__[pkey]:
            cmd = ['strace', '-f', '-e', 'execve', '-p', '{0}'.format(pid)]
            __context__[pkey][pid] = {}
            __context__[pkey][pid]['vt'] = salt.utils.vt.Terminal(
                    cmd,
                    log_stdout=True,
                    log_stderr=True,
                    stream_stdout=False,
                    stream_stderr=False)
            __context__[pkey][pid]['user'] = ps_out[pid].get('user')
    for pid in list(__context__[pkey]):
        out = ''
        err = ''
        while __context__[pkey][pid]['vt'].has_unread_data:
            tout, terr = __context__[pkey][pid]['vt'].recv()
            if not terr:
                break
            out += salt.utils.stringutils.to_unicode(tout or '')
            err += terr
        for line in err.split('\n'):
            event = {'args': [],
                     'tag': pid}
            if 'execve' in line:
                comps = line.split('execve')[1].split('"')
                for ind, field in enumerate(comps):
                    if ind == 1:
                        event['cmd'] = field
                        continue
                    if ind % 2 != 0:
                        event['args'].append(field)
                event['user'] = __context__[pkey][pid]['user']
                ret.append(event)
        if not __context__[pkey][pid]['vt'].isalive():
            __context__[pkey][pid]['vt'].close()
            __context__[pkey].pop(pid)
    return ret
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.'
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"]
                )
652319
def _validate(self, key, cls=None):
        """"""
        if key not in self.manifest:
            raise ValueError("Manifest %s requires '%s'."
                             % (self.manifest_path, key))
        if cls:
            if not isinstance(self.manifest[key], cls):
                raise TypeError("Manifest value '%s' should be %s, not %s"
                                % (key, cls, type(self.manifest[key])))
709314
def check_config(self, config):
        
        validation = ""
        required = ["name", "currency", "IBAN", "BIC"]

        for config_item in required:
            if config_item not in config:
                validation += config_item.upper() + "_MISSING "

        if not validation:
            return True
        else:
            raise Exception("Config file did not validate. " + validation)
569898
function validateConfig(config) {
    var timer = joi.object().keys({
        seconds: joi.number().integer().positive().default(60 * 5),
        handler: joi.alternatives().try(joi.func().arity(0), joi.string()).required()
    });

    var schema = joi.object().keys({
        debug:           joi.boolean().default(false),
        server:          joi.string().trim().uri().default(constants.TWITCH_IRC_SERVER),
        port:            joi.number().integer().positive().default(constants.TWITCH_IRC_PORT),
        secure:          joi.boolean().default(true),
        name:            joi.string().trim().required().lowercase(),
        password:        joi.string().trim().required(),
        channel:         joi.string().trim().required().regex(constants.CHANNEL_REGEX),
        commandPrefix:   joi.string().trim().default(constants.COMMAND_PREFIX),
        joinMessage:     joi.alternatives().try(joi.string().trim(), joi.boolean()).default(false),
        partMessage:     joi.alternatives().try(joi.string().trim(), joi.boolean()).default(false),
        commands:        joi.object().default({}),
        timers:          joi.array().items(timer).default([]),
        filterSpam:      joi.boolean().default(false),
        maxOffenses:     joi.number().integer().positive().default(constants.MAX_OFFENSES),
        autoExit:        joi.boolean().default(true),
        discordToken:    joi.alternatives().try(joi.string().trim(), joi.boolean()).default(false),
        discordChannels: joi.array().items(joi.string().trim()).default([]),
        log:             joi.alternatives().try(joi.string().trim(), joi.boolean()).default('chat_logs')
    });

    var validation = joi.validate(config, schema);

    if (validation.error) {
        var error = 'Your twitchcmd configuration is invalid.\n' +
            'Please consult the README.md for more information.\n' +
            validation.error.message;

        throw new Error(error);
    }

    return validation.value;
}
155782
def validate(config):
    '''
    
    '''
    # Configuration for pkg beacon should be a list
    if not isinstance(config, list):
        return False, ('Configuration for pkg beacon must be a list.')

    # Configuration for pkg beacon should contain pkgs
    pkgs_found = False
    pkgs_not_list = False
    for config_item in config:
        if 'pkgs' in config_item:
            pkgs_found = True
            if isinstance(config_item['pkgs'], list):
                pkgs_not_list = True

    if not pkgs_found or not pkgs_not_list:
        return False, 'Configuration for pkg beacon requires list of pkgs.'
    return True, 'Valid beacon configuration'
142618
def has_response(self, beacon_config, request, client_address):
		
		try:
			self._message_address_parse(request, invert_hello=self.__invert_hello)
			return True
		except ValueError:
			pass
		return False
1211475
protected function validateConfig()
    {
        $message = null;
        if (empty($this->config['api_key'])) {
            $message = 'Geocoder Config: Api Key is mandatory for using Google API.';
        }
        elseif (empty($this->config['request_url'])) {
            $message = 'Geocoder Config: Request URL is mandatory for using Google API.';
        }
        elseif (empty($this->config['output_format'])) {
            $message = 'Geocoder Config: Output Format is mandatory for using Google API.';
        }
        elseif ( ! in_array($this->config['output_format'], self::SUPPORTED_FORMATS)) {
            $message = 'Geocoder Config: Given Format is not supported.';
        }

        if ($message) {
            throw  new \InvalidArgumentException($message);
        }
    }
183081
def _validate(self):
        
        # This could be done with a default config

        # Check that specific keys exist
        sections = odict([
                ('catalog',['dirname','basename',
                            'lon_field','lat_field','objid_field',
                            'mag_1_band', 'mag_1_field', 'mag_err_1_field',
                            'mag_2_band', 'mag_2_field', 'mag_err_2_field',
                            ]),
                ('mask',[]),
                ('coords',['nside_catalog','nside_mask','nside_likelihood',
                           'nside_pixel','roi_radius','roi_radius_annulus',
                           'roi_radius_interior','coordsys',
                           ]),
                ('likelihood',[]),
                ('output',[]),
                ('batch',[]),
                ])  

        keys = np.array(list(sections.keys()))
        found = np.in1d(keys,list(self.keys()))

        if not np.all(found):
            msg = 'Missing sections: '+str(keys[~found])
            raise Exception(msg)

        for section,keys in sections.items():
            keys = np.array(keys)
            found = np.in1d(keys,list(self[section].keys()))
            if not np.all(found):
                msg = 'Missing keys in %s: '%(section)+str(keys[~found])
                raise Exception(msg)
578388
def check
      raise Errors::ConfigurationInvalid, config.errors.join("; ") unless config.valid?
      distribution.check
    end
246722
def response(self, beacon_config, request, client_address):
		
		return self._message(beacon_config, invert_hello=self.__invert_hello)
480932
private void validateBeforeStart() {
        LibraryUtils.checkArgumentNotNull(config, "Configuration is null.");
        config.validate();

        LibraryUtils.checkArgumentNotNull(sourceFilter, "sourceFilter is null.");
        LibraryUtils.checkArgumentNotNull(eventFilter, "eventFilter is null.");
        LibraryUtils.checkArgumentNotNull(eventsProcessor, "eventsProcessor is null.");
        LibraryUtils.checkArgumentNotNull(progressReporter, "progressReporter is null.");
        LibraryUtils.checkArgumentNotNull(exceptionHandler, "exceptionHandler is null.");

        LibraryUtils.checkArgumentNotNull(scheduledThreadPool, "scheduledThreadPool is null.");
        LibraryUtils.checkArgumentNotNull(mainThreadPool, "mainThreadPool is null.");
        LibraryUtils.checkArgumentNotNull(readerFactory, "readerFactory is null.");
    }
876662
def beacon(config):
    '''
    
    '''
    ret = []

    # NOTE: lookup current images
    current_vms = __salt__['vmadm.list'](
        keyed=True,
        order='uuid,state,alias,hostname,dns_domain',
    )

    # NOTE: apply configuration
    if VMADM_STATE['first_run']:
        log.info('Applying configuration for vmadm beacon')

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

        if 'startup_create_event' not in _config or not _config['startup_create_event']:
            VMADM_STATE['vms'] = current_vms

    # NOTE: create events
    for uuid in current_vms:
        event = {}
        if uuid not in VMADM_STATE['vms']:
            event['tag'] = "created/{}".format(uuid)
            for label in current_vms[uuid]:
                if label == 'state':
                    continue
                event[label] = current_vms[uuid][label]

        if event:
            ret.append(event)

    # NOTE: deleted events
    for uuid in VMADM_STATE['vms']:
        event = {}
        if uuid not in current_vms:
            event['tag'] = "deleted/{}".format(uuid)
            for label in VMADM_STATE['vms'][uuid]:
                if label == 'state':
                    continue
                event[label] = VMADM_STATE['vms'][uuid][label]

        if event:
            ret.append(event)

    # NOTE: state change events
    for uuid in current_vms:
        event = {}
        if VMADM_STATE['first_run'] or \
           uuid not in VMADM_STATE['vms'] or \
           current_vms[uuid].get('state', 'unknown') != VMADM_STATE['vms'][uuid].get('state', 'unknown'):
            event['tag'] = "{}/{}".format(current_vms[uuid].get('state', 'unknown'), uuid)
            for label in current_vms[uuid]:
                if label == 'state':
                    continue
                event[label] = current_vms[uuid][label]

        if event:
            ret.append(event)

    # NOTE: update stored state
    VMADM_STATE['vms'] = current_vms

    # NOTE: disable first_run
    if VMADM_STATE['first_run']:
        VMADM_STATE['first_run'] = False

    return ret