Generate a Security Parameters object based on the instance's
        configuration.
        See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
972161
def get_auth_data(cls, instance):
        '''
        
        '''
        if "community_string" in instance:
            # SNMP v1 - SNMP v2

            # See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
            if int(instance.get("snmp_version", 2)) == 1:
                return hlapi.CommunityData(instance['community_string'], mpModel=0)
            return hlapi.CommunityData(instance['community_string'], mpModel=1)

        elif "user" in instance:
            # SNMP v3
            user = instance["user"]
            auth_key = None
            priv_key = None
            auth_protocol = None
            priv_protocol = None
            if "authKey" in instance:
                auth_key = instance["authKey"]
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
            if "privKey" in instance:
                priv_key = instance["privKey"]
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
                priv_protocol = hlapi.usmDESPrivProtocol
            if "authProtocol" in instance:
                auth_protocol = getattr(hlapi, instance["authProtocol"])
            if "privProtocol" in instance:
                priv_protocol = getattr(hlapi, instance["privProtocol"])
            return hlapi.UsmUserData(user, auth_key, priv_key, auth_protocol, priv_protocol)
        else:
            raise Exception("An authentication method needs to be provided")
1018185
def _validate_snmp(self):
        
        cred = self.snmp_credentials
        if cred is not None:
            if cred.get('snmp_inspection') is True:
                if not all([cred.get('auth_user'),
                           cred.get('auth_prot_pp'),
                           cred.get('auth_priv_pp')]):
                    msg = self._('Either few or all mandatory '
                                 'SNMP credentials '
                                 'are missing.')
                    LOG.error(msg)
                    raise exception.IloInvalidInputError(msg)
                try:
                    auth_protocol = cred['auth_protocol']
                    if auth_protocol not in ["SHA", "MD5"]:
                        msg = self._('Invalid SNMP auth protocol '
                                     'provided. '
                                     'Valid values are SHA or MD5')
                        LOG.error(msg)
                        raise exception.IloInvalidInputError(msg)
                except KeyError:
                    msg = self._('Auth protocol not provided by user. '
                                 'The default value of MD5 will '
                                 'be considered.')
                    LOG.debug(msg)
                    pass
                try:
                    priv_protocol = cred['priv_protocol']
                    if priv_protocol not in ["AES", "DES"]:
                        msg = self._('Invalid SNMP privacy protocol '
                                     'provided. '
                                     'Valid values are AES or DES')
                        LOG.error(msg)
                        raise exception.IloInvalidInputError(msg)
                except KeyError:
                    msg = self._('Privacy protocol not provided '
                                 'by user. '
                                 'The default value of DES will '
                                 'be considered.')
                    LOG.debug(msg)
                    pass
            else:
                LOG.debug(self._('snmp_inspection set to False. SNMP'
                                 'inspection will not be performed.'))
        else:
            LOG.debug(self._('SNMP credentials not provided. SNMP '
                             'inspection will not be performed.'))
502715
def _build_parameters(
    server_no_context_takeover: bool,
    client_no_context_takeover: bool,
    server_max_window_bits: Optional[int],
    client_max_window_bits: Optional[Union[int, bool]],
) -> List[ExtensionParameter]:
    
    params: List[ExtensionParameter] = []
    if server_no_context_takeover:
        params.append(("server_no_context_takeover", None))
    if client_no_context_takeover:
        params.append(("client_no_context_takeover", None))
    if server_max_window_bits:
        params.append(("server_max_window_bits", str(server_max_window_bits)))
    if client_max_window_bits is True:  # only in handshake requests
        params.append(("client_max_window_bits", None))
    elif client_max_window_bits:
        params.append(("client_max_window_bits", str(client_max_window_bits)))
    return params
1099064
def _generate_autoscaling_metadata(self, cls, args):
        
        assert isinstance(args, Mapping)
        init_config = self._create_instance(
            cloudformation.InitConfig,
            args['AWS::CloudFormation::Init']['config'])
        init = self._create_instance(
            cloudformation.Init, {'config': init_config})
        auth = None
        if 'AWS::CloudFormation::Authentication' in args:
            auth_blocks = {}
            for k in args['AWS::CloudFormation::Authentication']:
                auth_blocks[k] = self._create_instance(
                    cloudformation.AuthenticationBlock,
                    args['AWS::CloudFormation::Authentication'][k],
                    k)
            auth = self._create_instance(
                cloudformation.Authentication, auth_blocks)

        return cls(init, auth)
1345557
def __non_body_parameter_descriptor(self, param):
    
    descriptor = {}

    descriptor['name'] = param.name

    param_type, param_format = self.__field_to_parameter_type_and_format(param)

    # Required
    if param.required:
      descriptor['required'] = True

    # Type
    descriptor['type'] = param_type

    # Format (optional)
    if param_format:
      descriptor['format'] = param_format

    # Default
    default = self.__parameter_default(param)
    if default is not None:
      descriptor['default'] = default

    # Repeated
    if param.repeated:
      descriptor['repeated'] = True

    # Enum
    enum_descriptor = self.__parameter_enum(param)
    if enum_descriptor is not None:
      descriptor['enum'] = enum_descriptor

    return descriptor
781467
def __store_config(self, args, kwargs):
        
        signature = (
            'schema',
            'ignore_none_values',
            'allow_unknown',
            'require_all',
            'purge_unknown',
            'purge_readonly',
        )
        for i, p in enumerate(signature[: len(args)]):
            if p in kwargs:
                raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
            else:
                kwargs[p] = args[i]
        self._config = kwargs
        """ This dictionary holds the configuration arguments that were used to
            initialize the :class:`Validator` instance except the
            ``error_handler``. """
255446
def generate_parameters(self, parameter_id):
        
        if self.first_one:
            init_challenger = self.smbo_solver.nni_smac_start()
            self.total_data[parameter_id] = init_challenger
            return self.convert_loguniform_categorical(init_challenger.get_dictionary())
        else:
            challengers = self.smbo_solver.nni_smac_request_challengers()
            for challenger in challengers:
                self.total_data[parameter_id] = challenger
                return self.convert_loguniform_categorical(challenger.get_dictionary())
496185
def _generate_security_groups(config_key):
    
    raw_default_groups = validate_key_values(CONFIG, 'base', config_key, default='')
    default_groups = _convert_string_to_native(raw_default_groups)
    LOG.debug('Default security group for %s is %s', config_key, default_groups)

    entries = {}
    for env in ENVS:
        entries[env] = []

    if isinstance(default_groups, (list)):
        groups = _remove_empty_entries(default_groups)
        for env in entries:
            entries[env] = groups
    elif isinstance(default_groups, (dict)):
        entries.update(default_groups)

    LOG.debug('Generated security group: %s', entries)
    return entries
1304042
def create_security_group(self, name, desc=None):
        '''
        
        '''
        body = {'security_group': {'name': name,
                                   'description': desc}}
        return self.network_conn.create_security_group(body=body)
698096
def _generate_create_dict(self,
                              size=None,
                              hostname=None,
                              domain=None,
                              location=None,
                              os=None,
                              port_speed=None,
                              ssh_keys=None,
                              post_uri=None,
                              hourly=True,
                              no_public=False,
                              extras=None):
        """"""

        extras = extras or []

        package = self._get_package()
        location = _get_location(package, location)

        prices = []
        for category in ['pri_ip_addresses',
                         'vpn_management',
                         'remote_management']:
            prices.append(_get_default_price_id(package['items'],
                                                option=category,
                                                hourly=hourly,
                                                location=location))

        prices.append(_get_os_price_id(package['items'], os,
                                       location=location))
        prices.append(_get_bandwidth_price_id(package['items'],
                                              hourly=hourly,
                                              no_public=no_public,
                                              location=location))
        prices.append(_get_port_speed_price_id(package['items'],
                                               port_speed,
                                               no_public,
                                               location=location))

        for extra in extras:
            prices.append(_get_extra_price_id(package['items'],
                                              extra, hourly,
                                              location=location))

        hardware = {
            'hostname': hostname,
            'domain': domain,
        }

        order = {
            'hardware': [hardware],
            'location': location['keyname'],
            'prices': [{'id': price} for price in prices],
            'packageId': package['id'],
            'presetId': _get_preset_id(package, size),
            'useHourlyPricing': hourly,
        }

        if post_uri:
            order['provisionScripts'] = [post_uri]

        if ssh_keys:
            order['sshKeys'] = [{'sshKeyIds': ssh_keys}]

        return order
438221
def member_create(self, params, member_id):
        
        member_config = params.get('rsParams', {})
        server_id = params.pop('server_id', None)
        version = params.pop('version', self._version)
        proc_params = {'replSet': self.repl_id}
        proc_params.update(params.get('procParams', {}))
        if self.enable_ipv6:
            enable_ipv6_single(proc_params)
        # Make sure that auth isn't set the first time we start the servers.
        proc_params = self._strip_auth(proc_params)

        # Don't pass in auth_key the first time we start the servers.
        server_id = self._servers.create(
            name='mongod',
            procParams=proc_params,
            sslParams=self.sslParams,
            version=version,
            server_id=server_id
        )
        member_config.update({"_id": member_id,
                              "host": self._servers.hostname(server_id)})
        return member_config
1354436
def create_config(cls, params, prefix=None, name=None):
        
        if isinstance(cls.cfg, Config):
            cfg = cls.cfg.copy(name=name, prefix=prefix)
        else:
            cfg = cls.cfg.copy()
            if name:
                cfg[name] = name
            if prefix:
                cfg[prefix] = prefix
            cfg = Config(**cfg)
        cfg.update_settings()
        cfg.update(params, True)
        return cfg
155447
public static void setupSecurityProperties(Hashtable<String,Object>  env,
   String userDN, char pwd[])

   {
	        
      if(userDN != null)
      {
          if (pwd == null)
              pwd = new char[0];

          env.put("java.naming.security.authentication", "simple");

          env.put("java.naming.security.principal", userDN);

          env.put("java.naming.security.credentials", new String(pwd));
    	  
      }
      
      boolean useSslConfigFactory = Config.getPropertyBoolean(LDAP_USE_SSL_CONFIG_FACTORY_PROP,false).booleanValue();
      
      String url = (String)env.get(LDAP.JAVA_NAMING_PROVIDER_URL);
      if(url != null && url.trim().toLowerCase().startsWith("ldaps")
         && useSslConfigFactory)
      {
    	  	env.put("java.naming.security.protocol","ssl");
    	  	env.put("java.naming.ldap.factory.socket", SSLConfigSocketFactory.class.getName());
      }

   }
882014
def _setup_subnet_parameters(self, params, data, is_create=True):
        
        is_update = not is_create
        params['enable_dhcp'] = data['enable_dhcp']
        if int(data['ip_version']) == 6:
            ipv6_modes = utils.get_ipv6_modes_attrs_from_menu(
                data['ipv6_modes'])
            if ipv6_modes[0] and is_create:
                params['ipv6_ra_mode'] = ipv6_modes[0]
            if ipv6_modes[1] and is_create:
                params['ipv6_address_mode'] = ipv6_modes[1]
        if data['allocation_pools']:
            pools = [dict(zip(['start', 'end'], pool.strip().split(',')))
                     for pool in data['allocation_pools'].splitlines()
                     if pool.strip()]
            params['allocation_pools'] = pools
        if data['host_routes'] or is_update:
            routes = [dict(zip(['destination', 'nexthop'],
                               route.strip().split(',')))
                      for route in data['host_routes'].splitlines()
                      if route.strip()]
            params['host_routes'] = routes
        if data['dns_nameservers'] or is_update:
            nameservers = [ns.strip()
                           for ns in data['dns_nameservers'].splitlines()
                           if ns.strip()]
            params['dns_nameservers'] = nameservers
916259
def getParamFromEnv(self, var, default=''):
        
        if self.getParam(var):
            return self.getParam(var)
        if self.hostgroup:
            if self.hostgroup.getParam(var):
                return self.hostgroup.getParam(var)
        if self.domain.getParam('password'):
            return self.domain.getParam('password')
        else:
            return default
665636
def _build_netengine_arguments(self):
        
        arguments = {
            "host": self.host
        }

        if self.config is not None:
            for key, value in self.config.iteritems():
                arguments[key] = value

        if self.port:
            arguments["port"] = self.port

        return arguments
1126633
def _generate_create_dict(
            self, cpus=None, memory=None, hourly=True,
            hostname=None, domain=None, local_disk=True,
            datacenter=None, os_code=None, image_id=None,
            dedicated=False, public_vlan=None, private_vlan=None,
            private_subnet=None, public_subnet=None,
            userdata=None, nic_speed=None, disks=None, post_uri=None,
            private=False, ssh_keys=None, public_security_groups=None,
            private_security_groups=None, boot_mode=None, **kwargs):
        
        required = [hostname, domain]

        flavor = kwargs.get('flavor', None)
        host_id = kwargs.get('host_id', None)

        mutually_exclusive = [
            {'os_code': os_code, 'image_id': image_id},
            {'cpu': cpus, 'flavor': flavor},
            {'memory': memory, 'flavor': flavor},
            {'flavor': flavor, 'dedicated': dedicated},
            {'flavor': flavor, 'host_id': host_id}
        ]

        if not all(required):
            raise ValueError("hostname, and domain are required")

        for mu_ex in mutually_exclusive:
            if all(mu_ex.values()):
                raise ValueError(
                    'Can only specify one of: %s' % (','.join(mu_ex.keys())))

        data = {
            "startCpus": cpus,
            "maxMemory": memory,
            "hostname": hostname,
            "domain": domain,
            "localDiskFlag": local_disk,
            "hourlyBillingFlag": hourly,
            "supplementalCreateObjectOptions": {
                "bootMode": boot_mode
            }
        }

        if flavor:
            data["supplementalCreateObjectOptions"]["flavorKeyName"] = flavor

        if dedicated and not host_id:
            data["dedicatedAccountHostOnlyFlag"] = dedicated

        if host_id:
            data["dedicatedHost"] = {"id": host_id}

        if private:
            data['privateNetworkOnlyFlag'] = private

        if image_id:
            data["blockDeviceTemplateGroup"] = {"globalIdentifier": image_id}
        elif os_code:
            data["operatingSystemReferenceCode"] = os_code

        if datacenter:
            data["datacenter"] = {"name": datacenter}

        if private_vlan or public_vlan or private_subnet or public_subnet:
            network_components = self._create_network_components(public_vlan, private_vlan,
                                                                 private_subnet, public_subnet)
            data.update(network_components)

        if public_security_groups:
            secgroups = [{'securityGroup': {'id': int(sg)}}
                         for sg in public_security_groups]
            pnc = data.get('primaryNetworkComponent', {})
            pnc['securityGroupBindings'] = secgroups
            data.update({'primaryNetworkComponent': pnc})

        if private_security_groups:
            secgroups = [{'securityGroup': {'id': int(sg)}}
                         for sg in private_security_groups]
            pbnc = data.get('primaryBackendNetworkComponent', {})
            pbnc['securityGroupBindings'] = secgroups
            data.update({'primaryBackendNetworkComponent': pbnc})

        if userdata:
            data['userData'] = [{'value': userdata}]

        if nic_speed:
            data['networkComponents'] = [{'maxSpeed': nic_speed}]

        if disks:
            data['blockDevices'] = [
                {"device": "0", "diskImage": {"capacity": disks[0]}}
            ]

            for dev_id, disk in enumerate(disks[1:], start=2):
                data['blockDevices'].append(
                    {
                        "device": str(dev_id),
                        "diskImage": {"capacity": disk}
                    }
                )

        if post_uri:
            data['postInstallScriptUri'] = post_uri

        if ssh_keys:
            data['sshKeys'] = [{'id': key_id} for key_id in ssh_keys]

        return data