Parse a val schema definition.
342752
def parse_schema(schema):
    """"""

    if isinstance(schema, BaseSchema):
        return schema.validate

    if type(schema) is type:
        return _build_type_validator(schema)

    if isinstance(schema, dict):
        return _build_dict_validator(schema)

    if type(schema) in (list, tuple, set):
        return _build_iterable_validator(schema)

    if callable(schema):
        return _build_callable_validator(schema)

    return _build_static_validator(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)
106940
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema)
            throws IOException
    {
        return parseListFrom(in, schema, DEFAULT_INPUT_FACTORY);
    }
514642
def parse_row(schema, data):
    
    def parse_value(data_type, value):
      """Parses a value returned from a BigQuery response.

      Args:
        data_type: the type of the value as specified by the schema.
        value: the raw value to return (before casting to data_type).

      Returns:
        The value cast to the data_type.
      """
      if value is not None:
        if value == 'null':
          value = None
        elif data_type == 'INTEGER':
          value = int(value)
        elif data_type == 'FLOAT':
          value = float(value)
        elif data_type == 'TIMESTAMP':
          value = datetime.datetime.utcfromtimestamp(float(value))
        elif data_type == 'BOOLEAN':
          value = value == 'true'
        elif (type(value) != str):
          # TODO(gram): Handle nested JSON records
          value = str(value)
      return value

    row = {}
    if data is None:
      return row

    for i, (field, schema_field) in enumerate(zip(data['f'], schema)):
      val = field['v']
      name = schema_field['name']
      data_type = schema_field['type']
      repeated = True if 'mode' in schema_field and schema_field['mode'] == 'REPEATED' else False

      if repeated and val is None:
        row[name] = []
      elif data_type == 'RECORD':
        sub_schema = schema_field['fields']
        if repeated:
          row[name] = [Parser.parse_row(sub_schema, v['v']) for v in val]
        else:
          row[name] = Parser.parse_row(sub_schema, val)
      elif repeated:
        row[name] = [parse_value(data_type, v['v']) for v in val]
      else:
        row[name] = parse_value(data_type, val)

    return row
963731
def parse_value(self, sn: "DataNode") -> ScalarValue:
        """"""
        res = sn.type.parse_value(self.value)
        if res is None:
            raise InvalidKeyValue(self.value)
        return res
1262216
def _infer_schema(row, names=None):
    """"""
    if isinstance(row, dict):
        items = sorted(row.items())

    elif isinstance(row, (tuple, list)):
        if hasattr(row, "__fields__"):  # Row
            items = zip(row.__fields__, tuple(row))
        elif hasattr(row, "_fields"):  # namedtuple
            items = zip(row._fields, tuple(row))
        else:
            if names is None:
                names = ['_%d' % i for i in range(1, len(row) + 1)]
            elif len(names) < len(row):
                names.extend('_%d' % i for i in range(len(names) + 1, len(row) + 1))
            items = zip(names, row)

    elif hasattr(row, "__dict__"):  # object
        items = sorted(row.__dict__.items())

    else:
        raise TypeError("Can not infer schema for type: %s" % type(row))

    fields = [StructField(k, _infer_type(v), True) for k, v in items]
    return StructType(fields)
1114958
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema,
            boolean numeric, LinkedBuffer buffer) throws IOException
    {
        final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(),
                in, false);
        final JsonParser parser = newJsonParser(in, buffer.buffer, 0, 0, false, context);
        try
        {
            return parseListFrom(parser, schema, numeric);
        }
        finally
        {
            parser.close();
        }
    }
839702
def _parse_phone(self, val):
        

        ret = {
            'type': None,
            'value': None
        }

        try:

            ret['type'] = val[1]['type']

        except (IndexError, KeyError, ValueError, TypeError):

                pass

        ret['value'] = val[3].strip()

        try:

            self.vars['phone'].append(ret)

        except AttributeError:

            self.vars['phone'] = []
            self.vars['phone'].append(ret)
93833
def schema_from_context(context):
    """"""
    item_class = context.get('class')
    return (
        serializer_mapping[item_class] if item_class else BaseSchema,
        context.get('many', False)
    )
800825
def _ParseEntry(self, key, val):
    
    if key in self._repeated:
      setting = self.section.setdefault(key, [])
      setting.extend(val)
    else:
      self.section.setdefault(key, val)
1250012
private void parseval() throws IOException {

    final String lang = this.parsedArguments.getString("language");
    final String model = this.parsedArguments.getString("model");
    final String testset = this.parsedArguments.getString("testset");
    final Properties props = setParsevalProperties(lang, model, testset);

    final ParserEvaluate parserEvaluator = new ParserEvaluate(props);
    parserEvaluator.evaluate();
  }
1085645
def parse(self, data):
        """"""
        val = data.get(self.name, missing)
        if not isinstance(val, dict):
            return (self.operators['$eq'], self.field.deserialize(val)),

        return tuple(
            (
                self.operators[op],
                (self.field.deserialize(val)) if op not in self.list_ops else [
                    self.field.deserialize(v) for v in val])
            for (op, val) in val.items() if op in self.operators
        )
378011
private static List<String>  parseFontFamily(String val)
   {
      List<String> fonts = null;
      TextScanner  scan = new TextScanner(val);
      while (true)
      {
         String item = scan.nextQuotedString();
         if (item == null)
            item = scan.nextTokenWithWhitespace(',');
         if (item == null)
            break;
         if (fonts == null)
            fonts = new ArrayList<>();
         fonts.add(item);
         scan.skipCommaWhitespace();
         if (scan.empty())
            break;
      }
      return fonts;
   }
776747
def _parse_schema(schema, method):
    
    if method and schema.get('readOnly', False):
        return _READONLY_PROPERTY

    # allOf: Must be valid against all of the subschemas
    if 'allOf' in schema:
        schema_ = copy.deepcopy(schema['allOf'][0])
        for x in schema['allOf'][1:]:
            _dict_merge(schema_, x)

        return _parse_schema(schema_, method)

    # anyOf: Must be valid against any of the subschemas
    # TODO(stephenfin): Handle anyOf

    # oneOf: Must be valid against exactly one of the subschemas
    if 'oneOf' in schema:
        # we only show the first one since we can't show everything
        return _parse_schema(schema['oneOf'][0], method)

    if 'enum' in schema:
        # we only show the first one since we can't show everything
        return schema['enum'][0]

    schema_type = schema.get('type', 'object')

    if schema_type == 'array':
        # special case oneOf so that we can show examples for all possible
        # combinations
        if 'oneOf' in schema['items']:
            return [
                _parse_schema(x, method) for x in schema['items']['oneOf']]

        return [_parse_schema(schema['items'], method)]

    if schema_type == 'object':
        if method and all(v.get('readOnly', False)
                          for v in schema['properties'].values()):
            return _READONLY_PROPERTY

        results = []
        for name, prop in schema.get('properties', {}).items():
            result = _parse_schema(prop, method)
            if result != _READONLY_PROPERTY:
                results.append((name, result))

        return collections.OrderedDict(results)

    if (schema_type, schema.get('format')) in _TYPE_MAPPING:
        return _TYPE_MAPPING[(schema_type, schema.get('format'))]

    return _TYPE_MAPPING[(schema_type, None)]
1242244
def schema_val(self, messages=None):
        ""
        self._ymlproc = YAMLProcessor(self._ymlfile)
        self._schemaproc = SchemaProcessor(self._schemafile)
        valid = True

        log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile)

        # Make sure the yml and schema have been loaded
        if self._ymlproc.loaded and self._schemaproc.loaded:
            # Load all of the yaml documents. Could be more than one in the same YAML file.
            for docnum, data in enumerate(yaml.load_all(self._ymlproc.data)):

                # Since YAML allows integer keys but JSON does not, we need to first
                # dump the data as a JSON string to encode all of the potential integers
                # as strings, and then read it back out into the YAML format. Kind of
                # a clunky workaround but it works as expected.
                data = yaml.load(json.dumps(data))

                # Now we want to get a validator ready
                v = jsonschema.Draft4Validator(self._schemaproc.data)

                # Loop through the errors (if any) and set valid = False if any are found
                # Display the error message
                for error in sorted(v.iter_errors(data)):
                    msg = "Schema-based validation failed for YAML file '" + self._ymlfile + "'"
                    self.ehandler.process(docnum, self._ymlproc.doclines, error, messages)
                    valid = False

                if not valid:
                    log.error(msg)

        elif not self._ymlproc.loaded:
            raise util.YAMLError("YAML must be loaded in order to validate.")
        elif not self._schemaproc.loaded:
            raise jsonschema.SchemaError("Schema must be loaded in order to validate.")

        log.debug("END: Schema-based validation complete for '%s'", self._ymlfile)
        return valid
725292
function tuple(schema, defaults, options) {
  if (kindOf(schema) !== 'array') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Tuple structs must be defined as an array, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const kinds = schema.map(s => any(s, undefined, options))
  const array = scalar('array', undefined, options)
  const name = 'tuple'
  const type = `[${kinds.map(k => k.type).join()}]`
  const validate = (value = resolveDefaults(defaults)) => {
    const [error] = array.validate(value)

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

    const ret = []
    const errors = []
    const length = Math.max(value.length, kinds.length)

    for (let i = 0; i < length; i++) {
      const kind = kinds[i]
      const v = value[i]

      if (!kind) {
        const e = { data: value, path: [i], value: v }
        errors.push(e)
        continue
      }

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

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

      ret[i] = r
    }

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

    return [undefined, ret]
  }

  return new Kind(name, type, validate)
}
82922
def _load_referenced_schema_from_properties(val, a_scheme, a_property):
    
    scheme = copy.copy(a_scheme)
    if _value_properties_are_referenced(val):
        ref_schema_uri = val['properties']['$ref']
        sub_schema = load_ref_schema(ref_schema_uri)
        ## dereference the sub schema
        sub_schema_copy_level_0 = copy.deepcopy(sub_schema)

        # nesting level 1
        # @TODO: NEEDS REFACTOR
        for prop_0 in sub_schema_copy_level_0['properties']:
            val_0 = sub_schema_copy_level_0['properties'][prop_0]
            # arrays may contain the nesting
            is_type_array_0 = (val_0['type'] == 'array')
            is_type_object_0 = (val_0['type'] == 'object')
            if ((is_type_array_0 or is_type_object_0)
                and (_value_properties_are_referenced(val_0))):
                # found a nested  thingy
                sub_schema_copy_level_1 = _load_referenced_schema_from_properties(val_0, sub_schema_copy_level_0,
                                                                                  prop_0)
                ###
                # one more loop level
                ###
                for prop_1 in sub_schema_copy_level_1['properties']:
                    val_1 = sub_schema_copy_level_1['properties'][prop_1]
                    is_type_array_1 = (val_1['type'] == 'array')
                    is_type_object_1 = (val_1['type'] == 'object')
                    if ((is_type_array_1 or is_type_object_1) and
                            (_value_properties_are_referenced(val_1))):
                        ### need to figure out a better way for loading
                        # the referenced stuff
                        # found a nested  thingy
                        # sub_schema_copy_level_2 = _load_referenced_schema_from_properties(val_1, sub_schema_copy_level_1, prop_1)
                        raise SalesKingException("too much nesting in the schemes")

            if _value_is_required(val_0):
                # remove required
                sub_schema_copy_level_0['properties'][prop_0]['required'] = False
            # hack to bypass text format valitation to string
            if _value_is_type_text(val_0):
                log.debug("patched text to string")
                sub_schema_copy_level_0['properties'][prop_0]['type'] = u"string"


        # outer scheme
        scheme['properties'][a_property]['properties'] = sub_schema_copy_level_0['properties']

    return scheme