Pyramid tween for performing validation.

    Note this is very simple -- it validates requests, responses, and paths
    while delegating to the relevant matching view.
188506
def validation_tween_factory(handler, registry):
    
    settings = load_settings(registry)
    route_mapper = registry.queryUtility(IRoutesMapper)

    validation_context = _get_validation_context(registry)

    def validator_tween(request):
        # We don't have access to this yet but let's go ahead and build the
        # matchdict so we can validate it and use it to exclude routes from
        # validation.
        route_info = route_mapper(request)
        swagger_handler, spec = get_swagger_objects(settings, route_info,
                                                    registry)

        if should_exclude_request(settings, request, route_info):
            return handler(request)

        try:
            op_or_validators_map = swagger_handler.op_for_request(
                request, route_info=route_info, spec=spec)
        except PathNotMatchedError as exc:
            if settings.validate_path:
                with validation_context(request):
                    raise PathNotFoundError(str(exc), child=exc)
            else:
                return handler(request)

        def operation(_):
            return op_or_validators_map if isinstance(op_or_validators_map, Operation) else None

        request.set_property(operation)

        if settings.validate_request:
            with validation_context(request, response=None):
                request_data = swagger_handler.handle_request(
                    PyramidSwaggerRequest(request, route_info),
                    op_or_validators_map,
                )

            def swagger_data(_):
                return request_data

            request.set_property(swagger_data)

        response = handler(request)

        if settings.validate_response:
            with validation_context(request, response=response):
                swagger_handler.handle_response(response, op_or_validators_map)

        return response

    return validator_tween
10221
def validate_body!(response)
      return unless media_type
      return if media_type.kind_of? SimpleMediaType

      errors = self.media_type.validate(self.media_type.load(response.body))
      if errors.any?
        message = "Invalid response body for #{media_type.identifier}." +
          "Errors: #{errors.inspect}"
          raise Exceptions::Validation.new(message, errors: errors)
      end

    end
1197251
def validate(path):  # pragma: no cover
    """"""
    # reads the 'dynaconf_validators.toml' from path
    # for each section register the validator for specific env
    # call validate

    path = Path(path)

    if not str(path).endswith(".toml"):
        path = path / "dynaconf_validators.toml"

    if not path.exists():  # pragma: no cover  # noqa
        click.echo(
            click.style("{} not found".format(path), fg="white", bg="red")
        )
        sys.exit(1)

    validation_data = toml.load(open(str(path)))

    success = True
    for env, name_data in validation_data.items():
        for name, data in name_data.items():
            if not isinstance(data, dict):  # pragma: no cover
                click.echo(
                    click.style(
                        "Invalid rule for parameter '{}'".format(name),
                        fg="white",
                        bg="yellow",
                    )
                )
            else:
                data.setdefault("env", env)
                click.echo(
                    click.style(
                        "Validating '{}' with '{}'".format(name, data),
                        fg="white",
                        bg="blue",
                    )
                )
                try:
                    Validator(name, **data).validate(settings)
                except ValidationError as e:
                    click.echo(
                        click.style(
                            "Error: {}".format(e), fg="white", bg="red"
                        )
                    )
                    success = False

    if success:
        click.echo(click.style("Validation success!", fg="white", bg="green"))
512466
def _assemble_and_send_validation_request(self):
        

        # Fire off the query.
        return self.client.service.validateShipment(
                WebAuthenticationDetail=self.WebAuthenticationDetail,
                ClientDetail=self.ClientDetail,
                TransactionDetail=self.TransactionDetail,
                Version=self.VersionId,
                RequestedShipment=self.RequestedShipment)
989151
function tween(a, b){
	var string = []
	var keys = []
	var from = []
	var to = []
	var cursor = 0
	var m

	while (m = number.exec(b)) {
		if (m.index > cursor) string.push(b.slice(cursor, m.index))
		to.push(Number(m[0]))
		keys.push(string.length)
		string.push(null)
		cursor = number.lastIndex
	}
	if (cursor < b.length) string.push(b.slice(cursor))

	while (m = number.exec(a)) from.push(Number(m[0]))

	return function frame(n){
		var i = keys.length
		while (i--) string[keys[i]] = from[i] + (to[i] - from[i]) * n
		return string.join('')
	}
}
146357
async def validation_middleware(request: web.Request, handler) -> web.Response:
    
    orig_handler = request.match_info.handler
    if not hasattr(orig_handler, "__schemas__"):
        if not issubclass_py37fix(orig_handler, web.View):
            return await handler(request)
        sub_handler = getattr(orig_handler, request.method.lower(), None)
        if sub_handler is None:
            return await handler(request)
        if not hasattr(sub_handler, "__schemas__"):
            return await handler(request)
        schemas = sub_handler.__schemas__
    else:
        schemas = orig_handler.__schemas__
    kwargs = {}
    for schema in schemas:
        data = await parser.parse(
            schema["schema"], request, locations=schema["locations"]
        )
        if data:
            kwargs.update(data)
    kwargs.update(request.match_info)
    request[request.app["_apispec_request_data_name"]] = kwargs
    return await handler(request)
594890
def parse_simplersp(self, tup_tree):
        

        self.check_node(tup_tree, 'SIMPLERSP')

        child = self.one_child(tup_tree, ('METHODRESPONSE', 'IMETHODRESPONSE'))

        return name(tup_tree), attrs(tup_tree), child
993056
function getValidChildrenTypes( desc, client ) {
            var node = client.getNode( desc.id );
            var validChildTypes = {};

            // figure out what the allowable range is
            var validChildren = node.getValidChildrenTypesDetailed(null, true);
            Object.keys( validChildren ).map(function( metaId ) {
                var child = client.getNode( metaId );
                var childType = child.getAttribute("name");
                var canCreateMore = validChildren[ metaId ];
                if ( canCreateMore &&
                     !child.isAbstract() )
                    validChildTypes[ childType ] = metaId;
            });
            return validChildTypes;
        }
1357946
def _build_validation_payload(self, request):
        
        parsed = urlparse(request.url)
        path = parsed.path
        query_string = parsed.query or ''

        return ValidationPayload(
            method=request.method,
            path=path,
            query_string=query_string,
            all_headers=request.headers,
            signed_headers=ValidationClient.__SIGNED_HEADERS,
            body=request.body or ''
        )
1266319
function buildErrorResponse(params) {
  params = params || {};
  params.error = params.error || {};
  var ERROR_CODES = models.CONSTANTS.ERROR_CODES;

  if (params.error.userDetail) {
    return params.error;
  }

  if (params.error) {
    var message = params.error.message || "";
    //If the message is about validation, the return a validation http response
    if (message.indexOf("validation") > -1) {
      params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
    }
  }

  //Mongoose Validation Failed
  if (params.error && params.error.errors) {
    var fieldKey = _.keys(params.error.errors)[0];
    params.userDetail = params.userDetail || params.error.errors[fieldKey].message;
    params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS;
  }

  var userDetail = params.userDetail || params.error.userDetail || params.error.message || "An Unexpected Error Occurred";
  var systemDetail = params.systemDetail || params.error.systemDetail || params.error.stack || "";
  var code = params.code || ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR;

  return {
    userDetail: userDetail,
    systemDetail: systemDetail,
    code: code
  };
}
816248
def validate(context = Attributor::DEFAULT_ROOT_CONTEXT)
      raise AttributorException, 'validation conflict' if @validating
      @validating = true

      context = [context] if context.is_a? ::String
      keys_with_values = []
      errors = []

      self.class.attributes.each do |sub_attribute_name, sub_attribute|
        sub_context = self.class.generate_subcontext(context, sub_attribute_name)

        value = __send__(sub_attribute_name)
        keys_with_values << sub_attribute_name unless value.nil?

        if value.respond_to?(:validating) # really, it's a thing with sub-attributes
          next if value.validating
        end

        errors.concat sub_attribute.validate(value, sub_context)
      end
      self.class.requirements.each do |req|
        validation_errors = req.validate(keys_with_values, context)
        errors.concat(validation_errors) unless validation_errors.empty?
      end

      errors
    ensure
      @validating = false
    end
1128821
def validate_api_call(schema, raw_request, raw_response):
    
    request = normalize_request(raw_request)

    with ErrorDict() as errors:
        try:
            validate_request(
                request=request,
                schema=schema,
            )
        except ValidationError as err:
            errors['request'].add_error(err.messages or getattr(err, 'detail'))
            return

        response = normalize_response(raw_response, raw_request)

        try:
            validate_response(
                response=response,
                request_method=request.method,
                schema=schema
            )
        except ValidationError as err:
            errors['response'].add_error(err.messages or getattr(err, 'detail'))
1205616
def _begin_validation(
        session: UpdateSession,
        loop: asyncio.AbstractEventLoop,
        downloaded_update_path: str,
        robot_name: str) -> asyncio.futures.Future:
    
    session.set_stage(Stages.VALIDATING)

    validation_future \
        = asyncio.ensure_future(loop.run_in_executor(
            None, validate_update,
            downloaded_update_path, session.set_progress))

    def validation_done(fut):
        exc = fut.exception()
        if exc:
            session.set_error(getattr(exc, 'short', str(type(exc))),
                              str(exc))
        else:
            rootfs_file, bootfs_file = fut.result()
            loop.call_soon_threadsafe(_begin_write,
                                      session,
                                      loop,
                                      rootfs_file,
                                      robot_name)
    validation_future.add_done_callback(validation_done)
    return validation_future
313705
def basic_auth_tween_factory(handler, registry):
    
    def basic_auth_tween(request):
        remote_user = get_remote_user(request)
        if remote_user is not None:
            request.environ['REMOTE_USER'] = remote_user[0]
        return handler(request)
    return basic_auth_tween
117153
def _do_validate_resourcescenario(resourcescenario, template_id=None):
    
    res = resourcescenario.resourceattr.get_resource()

    types = res.types

    dataset = resourcescenario.dataset

    if len(types) == 0:
        return

    if template_id is not None:
        if template_id not in [r.templatetype.template_id for r in res.types]:
            raise HydraError("Template %s is not used for resource attribute %s in scenario %s"%\
                             (template_id, resourcescenario.resourceattr.attr.name,
                             resourcescenario.scenario.name))

    #Validate against all the types for the resource
    for resourcetype in types:
        #If a specific type has been specified, then only validate
        #against that type and ignore all the others
        if template_id is not None:
            if resourcetype.templatetype.template_id != template_id:
                continue
        #Identify the template types for the template
        tmpltype = resourcetype.templatetype
        for ta in tmpltype.typeattrs:
            #If we find a template type which mactches the current attribute.
            #we can do some validation.
            if ta.attr_id == resourcescenario.resourceattr.attr_id:
                if ta.data_restriction:
                    log.debug("Validating against %s", ta.data_restriction)
                    validation_dict = eval(ta.data_restriction)
                    dataset_util.validate_value(validation_dict, dataset.get_val())
854508
function createChainableTypeChecker(validate) {
        function checkType(isRequired, props, propName, componentName, location, propFullName) {
            for (var _len = arguments.length, rest = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
                rest[_key - 6] = arguments[_key];
            }

            return mobx.untracked(function () {
                componentName = componentName || '<<anonymous>>';
                propFullName = propFullName || propName;
                if (props[propName] == null) {
                    if (isRequired) {
                        var actual = props[propName] === null ? 'null' : 'undefined';
                        return new Error('The ' + location + ' `' + propFullName + '` is marked as required ' + 'in `' + componentName + '`, but its value is `' + actual + '`.');
                    }
                    return null;
                } else {
                    return validate.apply(undefined, [props, propName, componentName, location, propFullName].concat(rest));
                }
            });
        }

        var chainedCheckType = checkType.bind(null, false);
        chainedCheckType.isRequired = checkType.bind(null, true);
        return chainedCheckType;
    }
137702
def conditional_http_tween_factory(handler, registry):
    
    settings = registry.settings if hasattr(registry, 'settings') else {}
    if 'generate_etag_for.list' in settings:
        route_names = settings.get('generate_etag_for.list').split()
        GENERATE_ETAG_ROUTE_NAMES.update(route_names)

    def conditional_http_tween(request):
        response = handler(request)

        if request.matched_route.name in GENERATE_ETAG_ROUTE_NAMES:

            # If the Last-Modified header has been set, we want to enable the
            # conditional response processing.
            if response.last_modified is not None:
                response.conditional_response = True

            # We want to only enable the conditional machinery if either we
            # were given an explicit ETag header by the view or we have a
            # buffered response and can generate the ETag header ourself.
            if response.etag is not None:
                response.conditional_response = True
            elif (isinstance(response.app_iter, Sequence) and
                          len(response.app_iter) == 1) and response.body is not None:
                response.conditional_response = True
                response.md5_etag()

        return response

    return conditional_http_tween