Ensure that the `definition_type` property of `marking-definition`
    objects is one of the values in the STIX 2.0 specification.
13189
def vocab_marking_definition(instance):
    
    if (instance['type'] == 'marking-definition' and
            'definition_type' in instance and not
            instance['definition_type'] in enums.MARKING_DEFINITION_TYPES):

        return JSONError("Marking definition `definition_type` should be one "
                         "of: %s." % ', '.join(enums.MARKING_DEFINITION_TYPES),
                         instance['id'], 'marking-definition-type')
792630
private void validateDefinesDeclaration(Node n, JSDocInfo info) {
    if (info != null && info.isDefine() && n.isLet()) {
      report(n, INVALID_DEFINE_ON_LET);
    }
  }
58980
protected static function ensureTypes()
    {
        if (self::$doneScanning && count(self::$types) > 0) {
            return;
        }

        foreach (self::types() as $t) {
        }
    }
146085
function(definition, client) {

  this.client = client;

  this.schema = null;

  this.ddlHelper = {
    tableName: null,
    pkAttrName: null,
    pkAutoIncrement: false,
    attrNamesToColNames: {},
    attrTypes: {},
    colNamesToAttrNames: {},
    colTypes: {},
    defaultValues: {},
    cqlCreateTable: null,
    indexes: {}
  };

  this._parseDefinition(definition);
}
622721
private void validateDefaultValue(Node n) {
    if (n.isDefaultValue() && n.getParent().isParamList()) {
      Node targetNode = n.getFirstChild();
      JSDocInfo info = targetNode.getJSDocInfo();
      if (info == null) {
        return;
      }

      JSTypeExpression typeExpr = info.getType();
      if (typeExpr == null) {
        return;
      }

      Node typeNode = typeExpr.getRoot();
      if (typeNode.getToken() != Token.EQUALS) {
        report(typeNode, DEFAULT_PARAM_MUST_BE_MARKED_OPTIONAL);
      }
    }
  }
253227
def is_type_factory(_type):
    

    def inner(x):
        if type(x) != _type:
            raise ValueError("Value must have type '%s'" % str(_type))

    return inner
1096542
def types_strict(instance):
    
    if instance['type'] not in enums.TYPES:
        yield JSONError("Object type '%s' is not one of those defined in the"
                        " specification." % instance['type'], instance['id'])

    if has_cyber_observable_data(instance):
        for key, obj in instance['objects'].items():
            if 'type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES:
                yield JSONError("Observable object %s is type '%s' which is "
                                "not one of those defined in the "
                                "specification."
                                % (key, obj['type']), instance['id'])
68761
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) {
	let fd = fieldDefine;
	// First phrase resolve fieldDefine is auto or function into final fieldDefine
	if (fd === 1) {
		if (isPrimitive(fieldValue)) {
			return "*";
		} else {
			fd = nextql.resolveType(fieldValue);
			nextql.afterResolveTypeHooks.forEach(
				hook => (fd = hook(fieldValue) || fd)
			);
		}
	}

	if (typeof fd == "function") {
		fd = fieldDefine(fieldValue);
	}

	// Second phrase resolve fieldDefine is explicit into fieldModel name;
	if (fd == undefined) {
		return new NextQLError(
			"Cannot resolve model: " + JSON.stringify(fieldDefine),
			{ path: fieldPath }
		);
	}

	// InlineModel
	if (fd.constructor && fd.constructor == Object) {
		return new InlineModel(fd);
	}

	// ScalarModel
	if (fd === "*") {
		return "*";
	}

	// NamedModel
	const model = nextql.model(fd);
	if (!model) {
		return new NextQLError("Model not found: " + fd, {
			path: fieldPath
		});
	}

	return model;
}
703450
def ensure_subclass(value, types):
    
    ensure_class(value)
    if not issubclass(value, types):
        raise TypeError(
            "expected subclass of {}, not {}".format(
                types, value))
1186307
public final boolean defineSynthesizedProperty(String propertyName,
      JSType type, Node propertyNode) {
    return defineProperty(propertyName, type, false, propertyNode);
  }
1051106
private void inlineDefinitions(MarkupDocBuilder markupDocBuilder, List<ObjectType> definitions, String uniquePrefix) {
        if (CollectionUtils.isNotEmpty(definitions)) {
            for (ObjectType definition : definitions) {
                addInlineDefinitionTitle(markupDocBuilder, definition.getName(), definition.getUniqueName());

                List<ObjectType> localDefinitions = new ArrayList<>();
                propertiesTableComponent.apply(markupDocBuilder, PropertiesTableComponent.parameters(
                        definition.getProperties(),
                        uniquePrefix,
                        localDefinitions
                ));
                for (ObjectType localDefinition : localDefinitions)
                    inlineDefinitions(markupDocBuilder, Collections.singletonList(localDefinition), localDefinition.getUniqueName());
            }
        }

    }

    private void buildConsumesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        List<String> consumes = operation.getOperation().getConsumes();
        if (CollectionUtils.isNotEmpty(consumes)) {
            consumesComponent.apply(markupDocBuilder, ConsumesComponent.parameters(consumes,
                    getSectionTitleLevel()));
        }

    }

    private void buildProducesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        List<String> produces = operation.getOperation().getProduces();
        if (CollectionUtils.isNotEmpty(produces)) {
            producesComponent.apply(markupDocBuilder, ProducesComponent.parameters(produces,
                    getSectionTitleLevel()));
        }
    }

    private void buildTagsSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            List<String> tags = operation.getOperation().getTags();
            if (CollectionUtils.isNotEmpty(tags)) {
                buildSectionTitle(markupDocBuilder, labels.getLabel(TAGS));
                if (config.getTagOrdering() != null) {
                    tags.sort(config.getTagOrdering());
                }
                markupDocBuilder.unorderedList(tags);
            }
        }
    }

    /**
     * Builds the security section of a Swagger Operation.
     *
     * @param operation the Swagger Operation
     */
    private void buildSecuritySchemeSection(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
        if (config.isPathSecuritySectionEnabled()) {
            securitySchemeComponent.apply(markupDocBuilder, SecuritySchemeComponent.parameters(
                    operation,
                    getSectionTitleLevel()
            ));
        }
    }

    /**
     * Retrieves the title level for sections
     */
    private int getSectionTitleLevel() {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            return 3;
        } else {
            return 4;
        }
    }

    /**
     * Builds the example section of a Swagger Operation.
     *
     * @param operation the Swagger Operation
     */
    private void buildExamplesSection(MarkupDocBuilder markupDocBuilder, PathOperation operation, List<PageBreakLocations> locations) {

        Map<String, Object> generatedRequestExampleMap = ExamplesUtil.generateRequestExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);
        Map<String, Object> generatedResponseExampleMap = ExamplesUtil.generateResponseExampleMap(config.isGeneratedExamplesEnabled(), operation, definitions, definitionDocumentResolver, markupDocBuilder);

        boolean beforeExampleRequestBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_REQUEST);
        boolean afterExampleRequestBreak = locations.contains(AFTER_OPERATION_EXAMPLE_REQUEST);
        boolean beforeExampleResponseBreak = locations.contains(BEFORE_OPERATION_EXAMPLE_RESPONSE);
        boolean afterExampleResponseBreak = locations.contains(AFTER_OPERATION_EXAMPLE_RESPONSE);

        exampleMap(markupDocBuilder, generatedRequestExampleMap, labels.getLabel(EXAMPLE_REQUEST), labels.getLabel(REQUEST), beforeExampleRequestBreak, afterExampleRequestBreak);
        exampleMap(markupDocBuilder, generatedResponseExampleMap, labels.getLabel(EXAMPLE_RESPONSE), labels.getLabel(RESPONSE), beforeExampleResponseBreak, afterExampleResponseBreak);
    }

    private void exampleMap(MarkupDocBuilder markupDocBuilder, Map<String, Object> exampleMap, String operationSectionTitle, String sectionTitle, boolean beforeBreak, boolean afterBreak) {
        if (exampleMap.size() > 0) {
            if (beforeBreak) markupDocBuilder.pageBreak();
            buildSectionTitle(markupDocBuilder, operationSectionTitle);
            for (Map.Entry<String, Object> entry : exampleMap.entrySet()) {

                // Example title, like "Response 200" or "Request Body"
                buildExampleTitle(markupDocBuilder, sectionTitle + " " + entry.getKey());

                if (NumberUtils.isNumber(entry.getKey())) {
                    // Section header is an HTTP status code (numeric)
                    JsonNode rootNode = parseExample(entry.getValue());
                    Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();



                    if (!fieldsIterator.hasNext()) {
                        // rootNode contains a single example, no need to further iterate.
                        String example = Json.pretty(rootNode);
//                        String example = Json.pretty(stripExampleQuotes(rootNode.toString()));
//                        example = Json.pretty(example);
                        markupDocBuilder.listingBlock(example, "json");
                    }
                    while (fieldsIterator.hasNext()) {
                        Map.Entry<String, JsonNode> field = fieldsIterator.next();

                        if (field.getKey().equals("application/json")) {
                            String example = Json.pretty(field.getValue());
                            example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example));

                            markupDocBuilder.listingBlock(example, "json");

                        } else if (field.getKey().equals("application/xml")) {

                            String example = stripExampleQuotes(field.getValue().toString());
                            example = StringEscapeUtils.unescapeJava(example);

                            //TODO: pretty print XML

                            markupDocBuilder.listingBlock(example, "xml");
                        } else {
                            String example = Json.pretty(entry.getValue());
                            markupDocBuilder.listingBlock(example, "json");
                            break; // No need to print the same example multiple times
                        }
                    }
                } else if (entry.getKey().equals("path")) {
                    // Path shouldn't have quotes around it
                    markupDocBuilder.listingBlock(entry.getValue().toString());
                } else if (entry.getKey().equals("header")){
                    // Header should have format: apikey:"string"
                    markupDocBuilder.listingBlock(entry.getValue().toString(), "json");
                } else {
                    
                    Object value = entry.getValue();
                    
                    if (value instanceof Map) {
                        
                        @SuppressWarnings("unchecked")
                        Map<String, String> examplesByContentType = (Map<String, String>) value;
                        
                        for (Entry<String, String> entryByType : examplesByContentType.entrySet()) {
                            if (entryByType.getKey().equals("application/json")) {
                                String example = Json.pretty(entryByType.getValue());
                                example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example));
    
                                markupDocBuilder.listingBlock(example, "json");
    
                            } else if (entryByType.getKey().equals("application/xml")) {
    
                                String example = stripExampleQuotes(entryByType.getValue().toString());
                                example = StringEscapeUtils.unescapeJava(example);
    
                                //TODO: pretty print XML
    
                                markupDocBuilder.listingBlock(example, "xml");
                            } else {
                                String example = Json.pretty(entry.getValue());
                                markupDocBuilder.listingBlock(example, "json");
                                break; // No need to print the same example multiple times
                            }
                        }
                    } else {
                        markupDocBuilder.listingBlock(Json.pretty(value), "json");
                    }
                }
            }
            if (afterBreak) markupDocBuilder.pageBreak();
        }
    }

    /**
     * Strip leading and trailing quotes from a string
     *
     * @param raw String containing leading or trailing quotes
     * @return parsed String
     */
    private String stripExampleQuotes(String raw) {
        return raw
                .replaceAll("^\"+", "")  // Strip leading quotes
                .replaceAll("\"+$", ""); // Strip trailing quotes
    }

    /**
     * Parse a JSON array
     *
     * @param raw Object containing a JSON string
     * @return JsonNode[contentType, example]
     * @throws RuntimeException when the given JSON string cannot be parsed
     */
    private JsonNode parseExample(Object raw) throws RuntimeException {
        try {
            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);
            return mapper.readTree(Json.pretty(raw));
        } catch (Exception ex) {
            throw new RuntimeException("Failed to read example", ex);
        }
    }

    /**
     * Adds a example title to the document.
     *
     * @param title the section title
     */
    private void buildExampleTitle(MarkupDocBuilder markupDocBuilder, String title) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            markupDocBuilder.sectionTitleLevel4(title);
        } else {
            markupDocBuilder.sectionTitleLevel5(title);
        }
    }

    /**
     * Apply extension context to all OperationsContentExtension.
     *
     * @param context context
     */
    private void applyPathsDocumentExtension(PathsDocumentExtension.Context context) {
        extensionRegistry.getPathsDocumentExtensions().forEach(extension -> extension.apply(context));
    }

    public static class Parameters {

        private final PathOperation operation;

        public Parameters(PathOperation operation) {
            this.operation = Validate.notNull(operation, "PathOperation must not be null");
        }
    }
}
105415
def validate_values(self, definition):
        

        if not self._strict_type_checks:
            return

        # Validate the scalar kind.
        scalar_kind = definition.get('kind')
        if scalar_kind not in SCALAR_TYPES_MAP.keys():
            raise ParserError(self._name + ' - unknown scalar kind: ' + scalar_kind +
                              '.\nSee: {}'.format(BASE_DOC_URL))

        # Validate the collection policy.
        collection_policy = definition.get('release_channel_collection', None)
        if collection_policy and collection_policy not in ['opt-in', 'opt-out']:
            raise ParserError(self._name + ' - unknown collection policy: ' + collection_policy +
                              '.\nSee: {}#optional-fields'.format(BASE_DOC_URL))

        # Validate the cpp_guard.
        cpp_guard = definition.get('cpp_guard')
        if cpp_guard and re.match(r'\W', cpp_guard):
            raise ParserError(self._name + ' - invalid cpp_guard: ' + cpp_guard +
                              '.\nSee: {}#optional-fields'.format(BASE_DOC_URL))

        # Validate record_in_processes.
        record_in_processes = definition.get('record_in_processes', [])
        for proc in record_in_processes:
            if not utils.is_valid_process_name(proc):
                raise ParserError(self._name + ' - unknown value in record_in_processes: ' + proc +
                                  '.\nSee: {}'.format(BASE_DOC_URL))

        # Validate the expiration version.
        # Historical versions of Scalars.json may contain expiration versions
        # using the deprecated format 'N.Na1'. Those scripts set
        # self._strict_type_checks to false.
        expires = definition.get('expires')
        if not utils.validate_expiration_version(expires) and self._strict_type_checks:
            raise ParserError('{} - invalid expires: {}.\nSee: {}#required-fields'
                              .format(self._name, expires, BASE_DOC_URL))
81197
def v_type_if_feature(ctx, stmt, no_error_report=False):
    """"""
    stmt.i_feature = None
    # Verify the argument type
    expr = syntax.parse_if_feature_expr(stmt.arg)
    if stmt.i_module.i_version == '1':
        # version 1 allows only a single value as if-feature
        if type(expr) != type(''):
            err_add(ctx.errors, stmt.pos,
                    'BAD_VALUE', (stmt.arg, 'identifier-ref'))
            return

    def eval(expr):
        if type(expr) == type(''):
            return has_feature(expr)
        else:
            (op, op1, op2) = expr
            if op == 'not':
                return not eval(op1)
            elif op == 'and':
                return eval(op1) and eval(op2)
            elif op == 'or':
                return eval(op1) or eval(op2)

    def has_feature(name):
        # raises Abort if the feature is not defined
        # returns True if we compile with the feature
        # returns False if we compile without the feature
        found = None
        if name.find(":") == -1:
            prefix = None
        else:
            [prefix, name] = name.split(':', 1)
        if prefix is None or stmt.i_module.i_prefix == prefix:
            # check local features
            pmodule = stmt.i_module
        else:
            # this is a prefixed name, check the imported modules
            pmodule = prefix_to_module(stmt.i_module, prefix,
                                       stmt.pos, ctx.errors)
            if pmodule is None:
                raise Abort
        if name in pmodule.i_features:
            f = pmodule.i_features[name]
            if prefix is None and not is_submodule_included(stmt, f):
                pass
            else:
                found = pmodule.i_features[name]
                v_type_feature(ctx, found)
                if pmodule.i_modulename in ctx.features:
                    if name not in ctx.features[pmodule.i_modulename]:
                        return False

        if found is None and no_error_report == False:
            err_add(ctx.errors, stmt.pos,
                    'FEATURE_NOT_FOUND', (name, pmodule.arg))
            raise Abort
        return found is not None

    # Evaluate the if-feature expression, and verify that all
    # referenced features exist.
    try:
        if eval(expr) == False:
            # prune the parent.
            # since the parent can have more than one if-feature
            # statement, we must check if the parent
            # already has been scheduled for removal
            if stmt.parent not in stmt.i_module.i_prune:
                stmt.i_module.i_prune.append(stmt.parent)
    except Abort:
        pass
1029397
def _validate_collections_have_default_values(class_name, property_name, property_descriptor):
    """"""
    # We don't want properties of collection type having "null" values, since that may cause
    # unexpected errors during GraphQL query execution and other operations.
    if property_descriptor.type_id in COLLECTION_PROPERTY_TYPES:
        if property_descriptor.default is None:
            raise IllegalSchemaStateError(u'Class "{}" has a property "{}" of collection type with '
                                          u'no default value.'.format(class_name, property_name))
688183
function (fieldDefinition, fieldName) {
    const fieldType = propertyHelper.getFieldType(fieldDefinition);

    let checks;
    if (fieldType === 'number' || fieldType === 'integer' || fieldType === 'float') {
      checks = createChecks(fieldDefinition, fieldName, fieldType);
    }

    return checks;
  }
381804
def _validate_type(self, data_type, field, value):
        
        if not data_type:
            return

        types = (data_type,) if isinstance(data_type, _str_type) else data_type

        for _type in types:
            # TODO remove this block on next major release
            # this implementation still supports custom type validation methods
            type_definition = self.types_mapping.get(_type)
            if type_definition is not None:
                matched = isinstance(value, type_definition.included_types) \
                    and not isinstance(value, type_definition.excluded_types)
            else:
                type_handler = self.__get_rule_handler('validate_type', _type)
                matched = type_handler(value)
            if matched:
                return

            # TODO uncomment this block on next major release
            #      when _validate_type_* methods were deprecated:
            # type_definition = self.types_mapping[_type]
            # if isinstance(value, type_definition.included_types) \
            #         and not isinstance(value, type_definition.excluded_types):  # noqa 501
            #     return

        self._error(field, errors.BAD_TYPE)
        self._drop_remaining_rules()
735651
def visitValueType(self, ctx: jsgParser.ValueTypeContext):
        
        if ctx.idref():
            self._typeid = as_token(ctx)
        else:
            self.visitChildren(ctx)