Generates a basic confirm schema file from a configuration file.
495708
def generate_schema_file(config_file):
    

    config = utils.load_config_from_ini_file(config_file)
    schema = {}

    for section_name in config:
        for option_name in config[section_name]:
            schema.setdefault(section_name, {}).setdefault(option_name, {})
            schema[section_name][option_name]['description'] = 'No description provided.'

    return utils.dump_schema_file(schema)
1099866
def create(file_path):
    """"""
    if os.path.exists(file_path):
        raise IOError("There is already a configuration file at %s" %
                      file_path)
    with open(file_path, 'w') as f:
        config = configparser.ConfigParser()
        config.add_section('misc')
        config.set('misc', 'config-version', '1.0')
        default_nb_name = os.path.split(os.path.dirname(file_path))[1]
        config.set('misc', 'nb-name', default_nb_name)
        config.add_section('root')
        config.set('root', 'path', '.')
        config.add_section('models')
        config.set('models', 'module', 'models')
        config.add_section('tests')
        config.set('tests', 'module', 'tests')
        config.add_section('suites')
        config.set('suites', 'module', 'suites')
        config.write(f)
324231
def get_schema(schema_type):
    '''
    '''

    schema_file = "{}-schema.json".format(schema_type)
    file_path = os.path.join(_default_schema_dir, schema_file)

    if not os.path.isfile(file_path):
        raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path))

    return fileio.read_schema(file_path)
404042
def schema():
        """"""
        return Schema({
            'script': And(Or(type(' '), type(u' ')), len),
            Optional('title', default=''): str,
            Optional('model', default={}): {Optional(And(str, len)): object},
            Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
            Optional('item', default=None): object,
            Optional('dry_run', default=False): bool,
            Optional('debug', default=False): bool,
            Optional('strict', default=False): bool,
            Optional('variables', default={}): {
                Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
                    Or(type(' '), type(u' '))
            },
            Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
            Optional('internal', default=False): bool
        })
1167715
def AddDescriptorFromSchema(self, schema_name, schema):
        """"""
        # TODO(craigcitro): Is schema_name redundant?
        if self.__GetDescriptor(schema_name):
            return
        if schema.get('enum'):
            self.__DeclareEnum(schema_name, schema)
            return
        if schema.get('type') == 'any':
            self.__DeclareMessageAlias(schema, 'extra_types.JsonValue')
            return
        if schema.get('type') != 'object':
            raise ValueError('Cannot create message descriptors for type %s' %
                             schema.get('type'))
        message = extended_descriptor.ExtendedMessageDescriptor()
        message.name = self.__names.ClassName(schema['id'])
        message.description = util.CleanDescription(schema.get(
            'description', 'A %s object.' % message.name))
        self.__DeclareDescriptor(message.name)
        with self.__DescriptorEnv(message):
            properties = schema.get('properties', {})
            for index, (name, attrs) in enumerate(sorted(properties.items())):
                field = self.__FieldDescriptorFromProperties(
                    name, index + 1, attrs)
                message.fields.append(field)
                if field.name != name:
                    message.field_mappings.append(
                        type(message).JsonFieldMapping(
                            python_name=field.name, json_name=name))
                    self.__AddImport(
                        'from %s import encoding' % self.__base_files_package)
            if 'additionalProperties' in schema:
                self.__AddAdditionalProperties(message, schema, properties)
        self.__RegisterDescriptor(message)
115324
def load_schema(file_or_fp):
    
    fp = open(file_or_fp, 'r') if isinstance(file_or_fp, str) else file_or_fp
    obj = json.load(fp)
    schema = Schema(obj)
    return schema
1298432
def generate_schema(table, export_fields, output_format, output_fobj):
    

    if output_format in ("csv", "txt"):
        from rows import plugins

        data = [
            {
                "field_name": fieldname,
                "field_type": fieldtype.__name__.replace("Field", "").lower(),
            }
            for fieldname, fieldtype in table.fields.items()
            if fieldname in export_fields
        ]
        table = plugins.dicts.import_from_dicts(
            data, import_fields=["field_name", "field_type"]
        )
        if output_format == "txt":
            plugins.txt.export_to_txt(table, output_fobj)
        elif output_format == "csv":
            plugins.csv.export_to_csv(table, output_fobj)

    elif output_format == "sql":
        # TODO: may use dict from rows.plugins.sqlite or postgresql
        sql_fields = {
            rows.fields.BinaryField: "BLOB",
            rows.fields.BoolField: "BOOL",
            rows.fields.IntegerField: "INT",
            rows.fields.FloatField: "FLOAT",
            rows.fields.PercentField: "FLOAT",
            rows.fields.DateField: "DATE",
            rows.fields.DatetimeField: "DATETIME",
            rows.fields.TextField: "TEXT",
            rows.fields.DecimalField: "FLOAT",
            rows.fields.EmailField: "TEXT",
            rows.fields.JSONField: "TEXT",
        }
        fields = [
            "    {} {}".format(field_name, sql_fields[field_type])
            for field_name, field_type in table.fields.items()
            if field_name in export_fields
        ]
        sql = (
            dedent(
                """
                CREATE TABLE IF NOT EXISTS {name} (
                {fields}
                );
                """
            )
            .strip()
            .format(name=table.name, fields=",\n".join(fields))
            + "\n"
        )
        output_fobj.write(sql)

    elif output_format == "django":
        django_fields = {
            rows.fields.BinaryField: "BinaryField",
            rows.fields.BoolField: "BooleanField",
            rows.fields.IntegerField: "IntegerField",
            rows.fields.FloatField: "FloatField",
            rows.fields.PercentField: "DecimalField",
            rows.fields.DateField: "DateField",
            rows.fields.DatetimeField: "DateTimeField",
            rows.fields.TextField: "TextField",
            rows.fields.DecimalField: "DecimalField",
            rows.fields.EmailField: "EmailField",
            rows.fields.JSONField: "JSONField",
        }
        table_name = "".join(word.capitalize() for word in table.name.split("_"))

        lines = ["from django.db import models"]
        if rows.fields.JSONField in [
            table.fields[field_name] for field_name in export_fields
        ]:
            lines.append("from django.contrib.postgres.fields import JSONField")
        lines.append("")

        lines.append("class {}(models.Model):".format(table_name))
        for field_name, field_type in table.fields.items():
            if field_name not in export_fields:
                continue

            if field_type is not rows.fields.JSONField:
                django_type = "models.{}()".format(django_fields[field_type])
            else:
                django_type = "JSONField()"
            lines.append("    {} = {}".format(field_name, django_type))

        result = "\n".join(lines) + "\n"
        output_fobj.write(result)
1360596
def generate(env):
    """"""
    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    for suffix in ASSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASAction)
        shared_obj.add_action(suffix, SCons.Defaults.ASAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
        shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)

    for suffix in ASPPSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
        shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
        shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)

    env['AS']        = 'ml'
    env['ASFLAGS']   = SCons.Util.CLVar('/nologo')
    env['ASPPFLAGS'] = '$ASFLAGS'
    env['ASCOM']     = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES'
    env['ASPPCOM']   = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES'
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
609267
def validation_schema(name):
    """"""
    schemas = {
        'processor': 'processSchema.json',
        'descriptor': 'descriptorSchema.json',
        'field': 'fieldSchema.json',
        'type': 'typeSchema.json',
    }

    if name not in schemas:
        raise ValueError()

    field_schema_file = finders.find('flow/{}'.format(schemas['field']), all=True)[0]
    with open(field_schema_file, 'r') as fn:
        field_schema = fn.read()

    if name == 'field':
        return json.loads(field_schema.replace('{{PARENT}}', ''))

    schema_file = finders.find('flow/{}'.format(schemas[name]), all=True)[0]
    with open(schema_file, 'r') as fn:
        schema = fn.read()

    return json.loads(schema.replace('{{FIELD}}', field_schema).replace('{{PARENT}}', '/field'))
1198097
function _generate(schemaName) {
  var schema = generateSchema(schemaName, this._instructions, this._macros, this._opts.strict);
  this.ajv.removeSchema(schema.id);
  return schema;
}
176761
function generateValidationFn(schema) {
        return function (req) {

            // if already an error, return without doing any additional validation
            if (req.error) { return req; }

            var keys = Object.keys(schema);
            var len = (req.value && req.value.trim().length) || 0;
            var i, key, originalKey;

            for (i = 0; i < keys.length; i++) {
                key = originalKey = keys[i];
                if (key.indexOf('ui-') === 0) {
                    key = key.substring(3);
                }

                // if validation function exists but it returns false then we have error
                if (check[key] && !check[key](schema, req.value)) {
                    var errMsg = schema[key + 'Desc'] || errorMessage[key] || 'Invalid input';
                    req.error = errMsg
                        .replace('{' + key + '}', schema[originalKey])
                        .replace('{value}', req.value)
                        .replace('{length}', len);
                    break;
                }
            }

            return req;
        };
    }
587609
def generate(env):
    """"""
    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    for suffix in ASSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)

    for suffix in ASPPSuffixes:
        static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
        static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)

    env['AS']        = 'nasm'
    env['ASFLAGS']   = SCons.Util.CLVar('')
    env['ASPPFLAGS'] = '$ASFLAGS'
    env['ASCOM']     = '$AS $ASFLAGS -o $TARGET $SOURCES'
    env['ASPPCOM']   = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES'
383458
def compile_schema(fields):
        
        path = os.path.dirname(os.path.realpath(__file__))
        # path = os.path.dirname(
        #     os.path.abspath(inspect.getfile(inspect.currentframe())))
        with codecs.open("%s/solr_schema_template.xml" % path, 'r', 'utf-8') as fh:
            schema_template = fh.read()

        schema = schema_template.format('\n'.join(fields))
        if six.PY2:
            return schema.encode('utf-8')

        return schema
569873
def validate_schema(sconf):
    

    # verify session_name
    if 'session_name' not in sconf:
        raise exc.ConfigError('config requires "session_name"')

    if 'windows' not in sconf:
        raise exc.ConfigError('config requires list of "windows"')

    for window in sconf['windows']:
        if 'window_name' not in window:
            raise exc.ConfigError('config window is missing "window_name"')

        if 'panes' not in window:
            raise exc.ConfigError(
                'config window %s requires list of panes' % window['window_name']
            )

    return True
453244
def sync_schema(self):
        """"""
        from ambry.orm.file import File
        from ambry.bundle.files import BuildSourceFile

        self.dstate = self.STATES.BUILDING

        synced = 0
        for fc in [File.BSFILE.SCHEMA, File.BSFILE.SOURCESCHEMA]:
            bsf = self.build_source_files.file(fc)
            if bsf.fs_is_newer:
                self.log('Syncing {}'.format(bsf.file_name))
                bsf.sync(BuildSourceFile.SYNC_DIR.FILE_TO_RECORD)
                synced += 1

        return synced
203134
def validate_doc(schema_names,  # type: Names
                 doc,           # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None]
                 loader,        # type: Loader
                 strict,        # type: bool
                 strict_foreign_properties=False  # type: bool
                 ):
    # type: (...) -> None
    """"""
    has_root = False
    for root in schema_names.names.values():
        if ((hasattr(root, 'get_prop') and root.get_prop(u"documentRoot")) or (
                u"documentRoot" in root.props)):
            has_root = True
            break

    if not has_root:
        raise validate.ValidationException(
            "No document roots defined in the schema")

    if isinstance(doc, MutableSequence):
        vdoc = doc
    elif isinstance(doc, CommentedMap):
        vdoc = CommentedSeq([doc])
        vdoc.lc.add_kv_line_col(0, [doc.lc.line, doc.lc.col])
        vdoc.lc.filename = doc.lc.filename
    else:
        raise validate.ValidationException("Document must be dict or list")

    roots = []
    for root in schema_names.names.values():
        if ((hasattr(root, "get_prop") and root.get_prop(u"documentRoot")) or (
                root.props.get(u"documentRoot"))):
            roots.append(root)

    anyerrors = []
    for pos, item in enumerate(vdoc):
        sourceline = SourceLine(vdoc, pos, Text)
        success = False
        for root in roots:
            success = validate.validate_ex(
                root, item, loader.identifiers, strict,
                foreign_properties=loader.foreign_properties,
                raise_ex=False, skip_foreign_properties=loader.skip_schemas,
                strict_foreign_properties=strict_foreign_properties)
            if success:
                break

        if not success:
            errors = []  # type: List[Text]
            for root in roots:
                if hasattr(root, "get_prop"):
                    name = root.get_prop(u"name")
                elif hasattr(root, "name"):
                    name = root.name

                try:
                    validate.validate_ex(
                        root, item, loader.identifiers, strict,
                        foreign_properties=loader.foreign_properties,
                        raise_ex=True, skip_foreign_properties=loader.skip_schemas,
                        strict_foreign_properties=strict_foreign_properties)
                except validate.ClassValidationException as exc:
                    errors = [sourceline.makeError(u"tried `%s` but\n%s" % (
                        name, validate.indent(str(exc), nolead=False)))]
                    break
                except validate.ValidationException as exc:
                    errors.append(sourceline.makeError(u"tried `%s` but\n%s" % (
                        name, validate.indent(str(exc), nolead=False))))

            objerr = sourceline.makeError(u"Invalid")
            for ident in loader.identifiers:
                if ident in item:
                    objerr = sourceline.makeError(
                        u"Object `%s` is not valid because"
                        % (relname(item[ident])))
                    break
            anyerrors.append(u"%s\n%s" %
                             (objerr, validate.indent(bullets(errors, "- "))))
    if anyerrors:
        raise validate.ValidationException(
            strip_dup_lineno(bullets(anyerrors, "* ")))
1156908
def build_schema(
    source: Union[str, Source],
    assume_valid=False,
    assume_valid_sdl=False,
    no_location=False,
    experimental_fragment_variables=False,
) -> GraphQLSchema:
    """"""
    return build_ast_schema(
        parse(
            source,
            no_location=no_location,
            experimental_fragment_variables=experimental_fragment_variables,
        ),
        assume_valid=assume_valid,
        assume_valid_sdl=assume_valid_sdl,
    )