make an options schema for the module visitor, optionally
adding extra fields.
355066
function makeOptionsSchema(additionalProperties) {
  const base =  {
    'type': 'object',
    'properties': {
      'commonjs': { 'type': 'boolean' },
      'amd': { 'type': 'boolean' },
      'esmodule': { 'type': 'boolean' },
      'ignore': {
        'type': 'array',
        'minItems': 1,
        'items': { 'type': 'string' },
        'uniqueItems': true,
      },
    },
    'additionalProperties': false,
  }

  if (additionalProperties){
    for (let key in additionalProperties) {
      base.properties[key] = additionalProperties[key]
    }
  }

  return base
}
1162807
function partial(schema, defaults, options) {
  if (kindOf(schema) !== 'object') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Partial structs must be defined as an object, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const obj = scalar('object', undefined, options)
  const ks = []
  const properties = {}

  for (const key in schema) {
    ks.push(key)
    const s = schema[key]
    const kind = any(s, undefined, options)
    properties[key] = kind
  }

  const name = 'partial'
  const type = `{${ks.join()},...}`
  const validate = (value = resolveDefaults(defaults)) => {
    const [error] = obj.validate(value)

    if (error) {
      error.type = type
      return [error]
    }

    const errors = []
    const ret = {}

    for (const key in properties) {
      let v = value[key]
      const kind = properties[key]

      if (v === undefined) {
        const d = defaults && defaults[key]
        v = resolveDefaults(d, value)
      }

      const [e, r] = kind.validate(v, value)

      if (e) {
        const allE = e.errors || [e]
        allE.forEach(singleE => {
          singleE.path = [key].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      if (key in value || r !== undefined) {
        ret[key] = r
      }
    }

    if (errors.length) {
      const first = errors[0]
      first.errors = errors
      return [first]
    }

    return [undefined, ret]
  }

  return new Kind(name, type, validate)
}
966067
function generateConfigsFromSchema(schema) {
    const configSet = new RuleConfigSet();

    if (Array.isArray(schema)) {
        for (const opt of schema) {
            if (opt.enum) {
                configSet.addEnums(opt.enum);
            } else if (opt.type && opt.type === "object") {
                if (!configSet.addObject(opt)) {
                    break;
                }

            // TODO (IanVS): support oneOf
            } else {

                // If we don't know how to fill in this option, don't fill in any of the following options.
                break;
            }
        }
    }
    configSet.addErrorSeverity();
    return configSet.ruleConfigs;
}
1015888
private void addMissingSchemas(Set<String> missingSchemas) {
		if (missingSchemas.isEmpty()) {
			return;
		}
		for (String className: missingSchemas) {
			Class<?> cls;
			try {
				cls = Class.forName(className);
			} catch (ClassNotFoundException e) {
				throw DBLogger.newFatal("Invalid field type in schema", e);
			}
			//TODO primary node is not always right here...
			createSchema(cache.getSession().getPrimaryNode(), cls);
		}
	}
224064
def modify_schema(self, field_schema):
        """"""
        field_schema['maximum'] = self.maximum_value
        if self.exclusive:
            field_schema['exclusiveMaximum'] = True
1213550
def _add_variants(self, key, value, schema):
        ''' 
        '''
        variants = schema.get('variants')
        obj = {}
        if variants:
            for _key, func in variants.iteritems():
                _value = func(value, self.store)
                obj.update({_key: _value})
        return obj
1153451
def modifie_options(self, field_option, value):
        """"""
        options = dict(self["options"] or {}, **{field_option: value})
        self.modifications["options"] = options
65475
def add(self, schema):
        
        key = schema.tns[1]
        existing = self.namespaces.get(key)
        if existing is None:
            self.children.append(schema)
            self.namespaces[key] = schema
        else:
            existing.root.children += schema.root.children
            existing.root.nsprefixes.update(schema.root.nsprefixes)
1083166
private static Optional<Schema> isOfOptionType(Schema schema) {
    Preconditions.checkNotNull(schema);

    // If not of type UNION, cant be an OPTION
    if (!Schema.Type.UNION.equals(schema.getType())) {
      return Optional.<Schema>absent();
    }

    // If has more than two members, can't be an OPTION
    List<Schema> types = schema.getTypes();
    if (null != types && types.size() == 2) {
      Schema first = types.get(0);
      Schema second = types.get(1);

      // One member should be of type NULL and other of non NULL type
      if (Schema.Type.NULL.equals(first.getType()) && !Schema.Type.NULL.equals(second.getType())) {
        return Optional.of(second);
      } else if (!Schema.Type.NULL.equals(first.getType()) && Schema.Type.NULL.equals(second.getType())) {
        return Optional.of(first);
      }
    }

    return Optional.<Schema>absent();
  }
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
        })
486085
function setOptions(schema, options) {
  function setDefaults(array) {
    if (!array.length) {
      if (options.find) { array.push('find'); }
      if (options.findOne || !options.find) { array.push('findOne'); }
    }
  }

  options = options || {};

  options.only = options.only || [];
  options.validateBeforeSave = options.validateBeforeSave === undefined
                                ? schema.options.validateBeforeSave
                                : Boolean(options.validateBeforeSave);

  ['virtual', 'attach', 'modify'].filter(prop => options[prop])
    .forEach(
      prop => {
        if (typeof options[prop] !== 'object') {
          options[prop] = {};
        }
        options[prop].properties = options[prop].properties || {};
        options[prop].only = options[prop].only || Object.keys(options[prop].properties);
      }
    );

  if (options.modify) {
    delete options.modify.properties;
    options.modify.on = options.modify.on || [];
    setDefaults(options.modify.on);
  }
  if (options.attach) {
    Object.keys(options.attach.properties).forEach(property => {
      options.attach.properties[property].on = options.attach.properties[property].on || [];
      setDefaults(options.attach.properties[property].on);
    });
  }

  return options;
}
405995
function (values, schema, options) {
    var virtualList = find(schema, 'virtual');

    //Set default value for virtual if not exists in values
    if (options && options.query === true) {
    }
    else {
        for (var virtual in virtualList) {

            if (_.isArray(virtualList[virtual])) {

                for (var thisVirtual in virtualList[virtual]) {

                    if (_.isArray(values[virtual])) {
                        for (var thisValue in values[virtual]) {
                            setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options);
                        }
                    }
                }
            }
            else {
                if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) {
                    values[virtual] = (virtualList[virtual]).default;
                }
            }
        }
    }

    for (var value in values) {

        if (virtualList[value] && virtualList[value].virtual) {

            var setFunction = virtualList[value].virtual;

            //Check for setter and getter
            if (virtualList[value].virtual.set) {
                setFunction = virtualList[value].virtual.set;
            }

            //Check conditions and apply virtual
            rulesMatch(value, values[value], setFunction, null, function (err, data) {
                if (!err) {
                    if (_.isFunction(setFunction)) {
                        var virtualResult = setFunction(values[value]);
                        if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) {
                            //Check if virtual values does not exists in given values list. Do not overwrite given
                            for (var vValue in virtualResult) {
                                {
                                    if (vValue == 'this') {
                                        virtualResult[value] = virtualResult[vValue];
                                        delete(virtualResult[vValue]);
                                    }
                                    else {
                                        // Prevent overwrite of given values
                                        if (values[vValue] !== undefined) {
                                            delete(virtualResult[vValue]);
                                        }
                                    }
                                }
                            }
                            values = _.assign(values, virtualResult);
                        }
                    }
                }
            });
        }
    }
    return values;
}
336255
def __setIncludes(self, schema):
        
        for schemaLocation, val in schema.includes.items(): 
            if self._includes.has_key(schemaLocation):
                schema.addIncludeSchema(schemaLocation, self._imports[schemaLocation])
422633
def make_schema(fields, datefields=()):
    '''
    
    '''
    text_field = whoosh.fields.TEXT(analyzer=whoosh.analysis.SimpleAnalyzer())
    fields = dict.fromkeys(fields, text_field)
    if datefields:
        datefields = dict.fromkeys(datefields, whoosh.fields.DATETIME)
        fields.update(datefields)
    schema = whoosh.fields.Schema()
    for fieldname in fields:
        schema.add(fieldname, fields[fieldname])
    return schema
918851
def schema_handler(self, schema):
        '''
        
        '''
        dict_for_render = schema.get('properties', dict()).items()
        if schema.get('$ref', None):
            def_name = schema.get('$ref').split('/')[-1]
            dict_for_render = self.definitions[def_name].get('properties', dict()).items()
        elif schema.get('properties', None) is None:
            return ''

        answer_dict = dict()
        json_dict = dict()
        for opt_name, opt_value in dict_for_render:
            var_type = opt_value.get('format', None) or opt_value.get('type', None) or 'object'
            json_name = self.indent + ':jsonparameter {} {}:'.format(var_type, opt_name)
            json_dict[json_name] = self.get_json_props_for_response(var_type, opt_value)

            answer_dict[opt_name] = self.get_response_example(opt_name, var_type, opt_value)
            if var_type == 'string':
                answer_dict[opt_name] = answer_dict[opt_name].format(opt_name)

        self.write('')
        for line in json.dumps(answer_dict, indent=4).split('\n'):
            self.write(line, self.indent_depth)

        self.write('')
        for json_param_name, json_param_value in json_dict.items():
            desc = '{}{}'.format(
                json_param_value['title'], json_param_value['props_str']
            ) or 'None'
            self.write(json_param_name + ' ' + desc)
627220
def make_migrations(schema=None):
    """"""

    entrypoints = {}
    old = {}

    def apply_migrations(migrations, new_model):
        """Apply migration data to compile an up to date model"""

        def get_path(raw_path):
            """Get local path of schema definition"""

            print("RAW PATH:", raw_path, type(raw_path))
            path = []
            for item in raw_path.split("["):
                print(item)
                item = item.rstrip("]")
                item = item.replace('"', '')
                item = item.replace("'", '')
                try:
                    item = int(item)
                except ValueError:
                    pass
                path.append(item)
            path.remove('root')
            print("PATH:", path)
            return path

        def apply_entry(changetype, change, result):
            """Upgrade with a single migration"""

            def apply_removes(removes, result):
                """Delete removed fields"""

                for remove in removes:
                    path = get_path(remove)
                    amount = dpath.util.delete(result, path)
                    assert amount == 1
                return result

            def apply_additions(additions, result):
                """Add newly added fields"""

                for addition in additions:
                    path = get_path(addition)
                    entry = additions[addition]
                    hfoslog('Adding:', entry, 'at', path)
                    dpath.util.new(result, path, entry)
                return result

            if changetype == 'type_changes':
                hfoslog('Creating new object')
                result = change['root']['new_value']
                return result

            if changetype == 'dictionary_item_added':
                hfoslog('Adding items')
                result = apply_additions(change, result)
            elif changetype == 'dictionary_item_removed':
                hfoslog('Removing items')
                result = apply_removes(change, result)
            elif changetype == 'values_changed':
                hfoslog("Changing items' types")
                for item in change:
                    path = get_path(item)
                    hfoslog('Changing', path, 'from',
                            change[item]['old_value'], ' to',
                            change[item]['new_value'])
                    assert dpath.util.get(result, path) == change[item][
                        'old_value']
                    amount = dpath.util.set(result, path, change[item][
                        'new_value'])
                    assert amount == 1

            return result

        def get_renames(migrations):
            """Check migrations for renamed fields"""

            hfoslog('Checking for rename operations:')
            pprint(migrations)
            for entry in migrations:

                added = entry.get('dictionary_item_added', None)
                removed = entry.get('dictionary_item_removed', None)

            renames = []

            if added and removed:
                for addition in added:
                    path = get_path(addition)
                    for removal in removed:
                        removed_path = get_path(removal)
                        if path[:-1] == removed_path[:-1]:
                            hfoslog('Possible rename detected:', removal, '->',
                                    addition)
                            renames.append((removed_path, path))
            return renames

        result = {}
        for no, migration in enumerate(migrations):
            hfoslog('Migrating', no)
            hfoslog('Migration:', migration, lvl=debug)
            renamed = get_renames(migrations)

            for entry in migration:
                result = apply_entry(entry, migration[entry], result)

        pprint(result)
        return result

    def write_migration(schema, counter, path, previous, current):
        """Write out complete migration data"""

        filename = "%s_%04i.json" % (schema, counter)
        migration = DeepDiff(previous, current, verbose_level=2).json
        if migration == "{}":
            hfoslog('Nothing changed - no new migration data.', lvl=warn)
            return

        print('Writing migration: ', os.path.join(path, filename))
        pprint(migration)

        with open(os.path.join(path, filename), 'w') as f:
            f.write(migration)

    for schema_entrypoint in iter_entry_points(group='hfos.schemata',
                                               name=None):
        try:
            hfoslog("Schemata found: ", schema_entrypoint.name, lvl=debug,
                    emitter='DB')
            if schema is not None and schema_entrypoint.name != schema:
                continue

            entrypoints[schema_entrypoint.name] = schema_entrypoint
            pprint(schema_entrypoint.dist.location)
            schema_top = schema_entrypoint.dist.location
            schema_migrations = schema_entrypoint.module_name.replace(
                'schemata', 'migrations').replace('.', '/')
            path = os.path.join(schema_top, schema_migrations)
            new_model = schema_entrypoint.load()['schema']

            migrations = []

            try:
                for file in sorted(os.listdir(path)):
                    if not file.endswith('.json'):
                        continue
                    fullpath = os.path.join(path, file)
                    hfoslog('Importing migration', fullpath)
                    with open(fullpath, 'r') as f:
                        migration = DeepDiff.from_json(f.read())
                    migrations.append(migration)
                    hfoslog('Successfully imported')

                if len(migrations) == 0:
                    raise ImportError
                pprint(migrations)
                model = apply_migrations(migrations, new_model)
                write_migration(schema, len(migrations) + 1, path, model,
                                new_model)
            except ImportError as e:
                hfoslog('No previous migrations for', schema, e,
                        type(e), exc=True)

            if len(migrations) == 0:
                write_migration(schema, 1, path, None, new_model)

        except (ImportError, DistributionNotFound) as e:
            hfoslog("Problematic schema: ", e, type(e),
                    schema_entrypoint.name, exc=True, lvl=warn,
                    emitter='SCHEMATA')

    hfoslog("Found schemata: ", sorted(entrypoints.keys()), lvl=debug,
            emitter='SCHEMATA')

    pprint(entrypoints)

    def make_single_migration(old, new):
        pass
844378
function schemaType(schema) {
    let type;
    if (schema.hasOwnProperty('type')) {
        type = schema.type;
    } else if (schema.hasOwnProperty('properties') || schema.hasOwnProperty('allOf') || schema.hasOwnProperty('additionalProperties')) {
        type = 'object';
    } else if (schema.hasOwnProperty('items')) {
        type = 'array';
    }

    switch (type) {
        case 'array':
        case 'boolean':
        case 'file':
        case 'integer':
        case 'number':
        case 'object':
        case 'string':
            return type;
    }
}