Starts in the data file folder and recursively looks
    in parents for `schema_name`
12685
def _find_data_path_schema(data_path, schema_name):
    
    if not data_path or data_path == '/' or data_path == '.':
        return None
    directory = os.path.dirname(data_path)
    path = glob.glob(os.path.join(directory, schema_name))
    if not path:
        return _find_schema(directory, schema_name)
    return path[0]
1279251
def schema_term(self):
        """"""

        if not self.name:
            raise MetapackError("Resource for url '{}' doe not have name".format(self.url))

        t = self.doc.find_first('Root.Table', value=self.get_value('name'))
        frm = 'name'

        if not t:
            t = self.doc.find_first('Root.Table', value=self.get_value('schema'))
            frm = 'schema'

        if not t:
            frm = None

        return t
300766
def show_schemas(schemaname):
    

    ecode = 0
    try:
        schemas = {}
        schema_dir = os.path.join(contexts['anchore_config']['pkg_dir'], 'schemas')
        for f in os.listdir(schema_dir):
            sdata = {}
            try:
                with open(os.path.join(schema_dir, f), 'r') as FH:
                    sdata = json.loads(FH.read())
            except:
                anchore_print_err('found schema file but failed to parse: ' + os.path.join(schema_dir, f))

            if sdata and (not schemaname or f in schemaname):
                schemas[f] = sdata

        if not schemas:
            anchore_print_err("no specified schemas were found to show")
        else:
            anchore_print(json.dumps(schemas, indent=4))

    except Exception as err:
        anchore_print_err('operation failed')
        ecode = 1

    sys.exit(ecode)
176746
private Database readSingleSchemaFile(DatabaseIO reader, File schemaFile)
    {
        Database model = null;

        if (!schemaFile.isFile())
        {
            log("Path "+schemaFile.getAbsolutePath()+" does not denote a schema file", Project.MSG_ERR);
        }
        else if (!schemaFile.canRead())
        {
            log("Could not read schema file "+schemaFile.getAbsolutePath(), Project.MSG_ERR);
        }
        else
        {
            try
            {
                model = reader.read(schemaFile);
                log("Read schema file "+schemaFile.getAbsolutePath(), Project.MSG_INFO);
            }
            catch (Exception ex)
            {
                throw new BuildException("Could not read schema file "+schemaFile.getAbsolutePath()+": "+ex.getLocalizedMessage(), ex);
            }
        }
        return model;
    }
1120630
def _get_input_schema(self):
        """"""
        assert avro, 'avro module required'

        input_target = flatten(self.input())[0]
        input_fs = input_target.fs if hasattr(input_target, 'fs') else GCSClient()
        input_uri = self.source_uris()[0]
        if '*' in input_uri:
            file_uris = list(input_fs.list_wildcard(input_uri))
            if file_uris:
                input_uri = file_uris[0]
            else:
                raise RuntimeError('No match for ' + input_uri)

        schema = []
        exception_reading_schema = []

        def read_schema(fp):
            # fp contains the file part downloaded thus far. We rely on that the DataFileReader
            # initializes itself fine as soon as the file header with schema is downloaded, without
            # requiring the remainder of the file...
            try:
                reader = avro.datafile.DataFileReader(fp, avro.io.DatumReader())
                schema[:] = [reader.datum_reader.writers_schema]
            except Exception as e:
                # Save but assume benign unless schema reading ultimately fails. The benign
                # exception in case of insufficiently big downloaded file part seems to be:
                # TypeError('ord() expected a character, but string of length 0 found',).
                exception_reading_schema[:] = [e]
                return False
            return True

        input_fs.download(input_uri, 64 * 1024, read_schema).close()
        if not schema:
            raise exception_reading_schema[0]
        return schema[0]
925676
def schema_root(self) -> "SchemaTreeNode":
        """"""
        sn = self
        while sn.parent:
            sn = sn.parent
        return sn
483590
def export_schema(cls, recursive=True, include_parent_ref=False):
        """"""
        parent_excludes = {}
        if not include_parent_ref:
            parent_ref = cls.__mapper__.relationships.get(cls.export_parent)
            if parent_ref:
                parent_excludes = {c.name for c in parent_ref.local_columns}

        def formatter(c):
            return ('{0} Default ({1})'.format(
                str(c.type), c.default.arg) if c.default else str(c.type))

        schema = {c.name: formatter(c) for c in cls.__table__.columns
                  if (c.name in cls.export_fields and
                  c.name not in parent_excludes)}
        if recursive:
            for c in cls.export_children:
                child_class = cls.__mapper__.relationships[c].argument.class_
                schema[c] = [child_class.export_schema(recursive=recursive,
                             include_parent_ref=include_parent_ref)]
        return schema
380063
def load(self, schemafile=None):
        """"""
        if schemafile is not None:
            self._schemafile = schemafile

        try:
            self.data = json.load(open(self._schemafile))
        except (IOError, ValueError), e:
            msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
            raise jsonschema.SchemaError(msg)

        self.loaded = True
615442
protected function getSchema()
    {
        if (file_exists(__DIR__.'/../all.json')) {
            return json_decode(file_get_contents(__DIR__.'/../all.json'), true);
        }

        echo "Getting schema\n";

        $schema = [
            'datatypes' => [],
            'properties' => [],
            'types' => [],
        ];

        $client = new Client(['base_uri' => 'https://schema.org']);
        $response = $client->get('/docs/full.html');
        $crawler = new Crawler($response->getBody()->__toString());

        $dataTypes = $crawler->filter('#datatype_tree a');
        foreach ($dataTypes as $index => $dataType) {
            echo '['.($index + 1).'/'.$dataTypes->count().'] ';
            if (strpos($dataType->getAttribute('class'), 'ext') !== false) {
                echo 'Skipping extension datatype: '.$dataType->textContent."\n";
                continue;
            }

            echo 'Getting datatype: '.$dataType->textContent."\n";
            $schema['datatypes'][$dataType->textContent] = $this->getDataType($client, $dataType->getAttribute('href'));
        }

        $types = $crawler->filter('#thing_tree a');
        foreach ($types as $index => $type) {
            if (!isset($schema['types'][$type->textContent]) && substr($type->getAttribute('href'), 0, 1) !== '#') {
                echo '['.($index + 1).'/'.$types->count().'] ';
                if (strpos($type->getAttribute('class'), 'ext') !== false) {
                    echo 'Skipping extension type: '.$type->textContent."\n";
                    continue;
                }

                echo 'Getting type: '.$type->textContent."\n";
                $schema['types'][$type->textContent] = $this->getType($client, $type->getAttribute('href'));
            }
        }

        $specificProperties = [];
        foreach ($schema['types'] as $type) {
            foreach ($type['specific_properties'] as $specificProperty) {
                if (!isset($schema['properties'][$specificProperty])) {
                    $specificProperties[$specificProperty] = $specificProperty;
                }
            }
        }

        $specificPropertiesCount = count($specificProperties);
        foreach (array_values($specificProperties) as $index => $specificProperty) {
            echo '['.($index + 1).'/'.$specificPropertiesCount.'] Getting property: '.$specificProperty."\n";
            try {
                $schema['properties'][$specificProperty] = $this->getProperty($client, '/'.$specificProperty);
            } catch (\InvalidArgumentException $exception) {
                echo '   Failed: '.$exception->getMessage()."\n";
                echo "   Skipping...\n";
            }
        }

        $enumerationMembers = [];
        foreach ($schema['types'] as $type) {
            foreach ($type['enumeration_members'] as $enumerationMember) {
                if (!isset($schema['types'][$enumerationMember])) {
                    $enumerationMembers[$enumerationMember] = $enumerationMember;
                }
            }
        }

        $enumerationMembersCount = count($enumerationMembers);
        foreach (array_values($enumerationMembers) as $index => $enumerationMember) {
            echo '['.($index + 1).'/'.$enumerationMembersCount.'] Getting extra enumeration member: '.$enumerationMember."\n";
            $schema['types'][$enumerationMember] = $this->getType($client, '/'.$enumerationMember);
        }

        echo "Getting schema done!\n\n";

        file_put_contents(__DIR__.'/../all.json', json_encode($schema));

        return $schema;
    }
510564
def _schema_options(p):
    

    p.add_argument(
        'resource', metavar='selector', nargs='?',
        default=None).completer = _schema_tab_completer
    p.add_argument(
        '--summary', action="store_true",
        help="Summarize counts of available resources, actions and filters")
    p.add_argument('--json', action="store_true", help=argparse.SUPPRESS)
    p.add_argument("-v", "--verbose", action="count", help="Verbose logging")
    p.add_argument("-q", "--quiet", action="count", help=argparse.SUPPRESS)
    p.add_argument("--debug", default=False, help=argparse.SUPPRESS)
1162842
def fill_schema_from_xsd_file(filename, schema):
    
    ifmap_statements = _parse_xsd_file(filename)
    properties_all = []

    for v in ifmap_statements.values():
        if (isinstance(v[0], IDLParser.Link)):
            src_name = v[1]
            target_name = v[2]
            src = schema._get_or_add_resource(src_name)
            target = schema._get_or_add_resource(target_name)
            if "has" in v[3]:
                src.children.append(target_name)
                target.parent = src_name
            if "ref" in v[3]:
                src.refs.append(target_name)
                target.back_refs.append(src_name)
        elif isinstance(v[0], IDLParser.Property):
            target_name = v[1][0]
            prop = ResourceProperty(v[0].name, is_list=v[0].is_list, is_map=v[0].is_map)
            if target_name != 'all':
                target = schema._get_or_add_resource(target_name)
                target.properties.append(prop)
            else:
                properties_all.append(prop)

    for r in schema.all_resources():
        schema.resource(r).properties += properties_all
283074
def _get_schema_file(extension, path):
        
        for file in os.listdir(path):
            if file.endswith(extension):
                return os.path.join(path, file)
727124
def _read_schema(self):
        """"""
        cache_filename = os.path.join(
            CACHE_ROOT, "%s.smt" % self._representation)
        log.info("Attempting to read local schema at %s" % cache_filename)
        try:
            if time.time() - os.stat(cache_filename).st_mtime > CACHE_EXPIRY:
                log.warning("Cache expired, re-pulling")
                self._pull_schema_definition(cache_filename)
        except OSError:
            log.warning("Local schema not found. Pulling from web.")
            self._pull_schema_definition(cache_filename)
        else:
            log.info("Success")

        return cache_filename
1243533
def load_config(conf_dir=DEFAULT_CONFIG_DIR, schema=CLIENT_SCHEMA):
    
    data = default_config(schema)
    config = read_config(conf_dir)
    if config:
        recursive_update(data, config)
    return data
79845
def import_schema(self, definitions, d):
        
        if not len(definitions.types):
            types = Types.create(definitions)
            definitions.types.append(types)
        else:
            types = definitions.types[-1]
        types.root.append(d.root)
        log.debug('imported (XSD):\n%s', d.root)
778399
def root(self, parts):
        
        result = None
        name = parts[0]
        log.debug('searching schema for (%s)', name)
        qref = self.qualify(parts[0])
        query = BlindQuery(qref)
        result = query.execute(self.schema)
        if result is None:
            log.error('(%s) not-found', name)
            raise PathResolver.BadPath(name)
        log.debug('found (%s) as (%s)', name, Repr(result))
        return result
1178323
def print_schemas(self):
        '''
        
        '''
        self.indent_depth += 1
        for i in self.definitions:
            def_name = i.split('/')[-1]
            self.write('.. _{}:'.format(def_name))
            self.write('')
            self.write('{} Schema'.format(def_name))
            self.write('{}'.format('`' * (len(def_name) + 7)))
            self.write('')
            self.write('.. code-block:: json', self.indent_depth)
            self.indent_depth += 1
            self.write('')
            self.definition_rst(def_name)
            self.indent_depth -= 1
            self.write('')
            self.write('')
        self.indent_depth -= 1