The encoder for this schema.
        Tries each encoder in order of the types specified for this schema.
160512
def encode(self, value):
        
        if value is None and self._default is not None:
            value = self._default

        for encoder in self._encoders:
            try:
                return encoder(value)
            except ValueError as ex:
                pass

        raise ValueError('Value \'{}\' is invalid. {}'
                         .format(value, ex.message))
721745
function encoder(mtype) {
  const gen = util.codegen([ 'm', 'w' ], mtype.name + '$encode')('if(!w)')('w=Writer.create()');
  let ref;

  // "when a message is serialized its known fields should be written sequentially by field number"
  const fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);

  for (let i = 0; i < fields.length; ++i) {
    const field = fields[i].resolve();
    const index = mtype._fieldsArray.indexOf(field);
    const type = field.resolvedType instanceof Enum ? 'int32' : field.type;
    const wireType = types.basic[type];
    ref = 'm' + util.safeProp(field.name);

    // Map fields
    if (field.map) {
      gen('if(%s && %s[Symbol.iterator]){', ref, ref)('for(var k of %s.keys()) {', ref)('w.uint32(%d).fork().uint32(%d).%s(k)', (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
      if (wireType === undefined) {
        gen('types[%d].encode(%s.get(k),w.uint32(18).fork()).ldelim().ldelim()', index, ref); // can't be groups
      } else {
        gen('.uint32(%d).%s(%s.get(k)).ldelim()', 16 | wireType, type, ref);
      }
      gen('}');
      gen('} else if(%s!=null&&m.hasOwnProperty(%j)){', ref, field.name)('for(var ks=Object.keys(%s),i=0;i<ks.length;++i){', ref)('w.uint32(%i).fork().uint32(%i).%s(ks[i])', (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
      if (wireType === undefined) {
        gen('types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()', index, ref); // can't be groups
      } else {
        gen('.uint32(%i).%s(%s[ks[i]]).ldelim()', 16 | wireType, type, ref);
      }
      gen('}')('}');

      // Repeated fields
    } else if (field.repeated) {
      gen('if(%s!=null&&%s.length){', ref, ref); // !== undefined && !== null

      // Packed repeated
      if (field.packed && types.packed[type] !== undefined) {
        gen('w.uint32(%i).fork()', (field.id << 3 | 2) >>> 0)('for(var i=0;i<%s.length;++i)', ref)('w.%s(%s[i])', type, ref)('w.ldelim()');

        // Non-packed
      } else {
        gen('for(var i=0;i<%s.length;++i)', ref);
        if (wireType === undefined) { genTypePartial(gen, field, index, ref + '[i]'); } else gen('w.uint32(%i).%s(%s[i])', (field.id << 3 | wireType) >>> 0, type, ref);

      }
      gen('}');

      // Non-repeated
    } else {
      if (field.optional) gen('if(%s!=null&&m.hasOwnProperty(%j))', ref, field.name); // !== undefined && !== null

      if (wireType === undefined) { genTypePartial(gen, field, index, ref); } else gen('w.uint32(%i).%s(%s)', (field.id << 3 | wireType) >>> 0, type, ref);

    }
  }

  return gen('return w');
}
917790
public void generateSchema(SchemaGenerator generator) throws UnsupportedTypeException {
    if (inputs == null && outputs == null && inputTypes != null && outputTypes != null) {
      // Generate both inputs and outputs before making this visible
      Map<String, Set<Schema>> inputs = generateSchema(generator, inputTypes);
      Map<String, Set<Schema>> outputs = generateSchema(generator, outputTypes);

      this.inputs = inputs;
      this.outputs = outputs;
    }
  }
473919
def _sort_schema(schema):
    """"""

    if isinstance(schema, dict):
        for k, v in sorted(schema.items()):
            if isinstance(v, dict):
                yield k, OrderedDict(_sort_schema(v))
            elif isinstance(v, list):
                yield k, list(_sort_schema(v))
            else:
                yield k, v
    elif isinstance(schema, list):
        for v in schema:
            if isinstance(v, dict):
                yield OrderedDict(_sort_schema(v))
            elif isinstance(v, list):
                yield list(_sort_schema(v))
            else:
                yield v
    else:
        yield d
334365
private StereoEncoderFactory makeStereoEncoderFactory() {
        if (stereoEncoders.isEmpty()) {
            return StereoEncoderFactory.EMPTY;
        } else if (stereoEncoders.size() == 1) {
            return stereoEncoders.get(0);
        } else {
            StereoEncoderFactory factory = new ConjugatedEncoderFactory(stereoEncoders.get(0), stereoEncoders.get(1));
            for (int i = 2; i < stereoEncoders.size(); i++) {
                factory = new ConjugatedEncoderFactory(factory, stereoEncoders.get(i));
            }
            return factory;
        }
    }
521674
function RawEncoder(schema, opts) {
  opts = opts || {};

  stream.Transform.call(this, {
    writableObjectMode: true,
    allowHalfOpen: false
  });

  this._type = types.createType(files.load(schema));
  this._writeValue = function (tap, val) {
    try {
      this._type._write(tap, val);
    } catch (err) {
      this.emit('error', err);
    }
  };
  this._tap = new Tap(new Buffer(opts.batchSize || 65536));
}
1122028
function inferTypeByKeyword (schema) {
  for (const keyword of objectKeywords) {
    if (keyword in schema) return 'object'
  }
  for (const keyword of arrayKeywords) {
    if (keyword in schema) return 'array'
  }
  for (const keyword of stringKeywords) {
    if (keyword in schema) return 'string'
  }
  for (const keyword of numberKeywords) {
    if (keyword in schema) return 'number'
  }
  return schema.type
}
1095843
static String encodeRaw(TypeMirror type) {
    StringBuilder sb = new StringBuilder();
    return type.accept(RAW_ENCODING_TYPE_VISITOR, sb).toString();
  }
480920
def list_encoder(values, instance, field: Field):
    """"""
    return [field.to_db_value(element, instance) for element in values]
375345
private Decoder getColumnDecoder(Schema writtenFieldAvroSchema, InputStream in) {
    // Use a special Avro decoder that has special handling for int, long,
    // and String types. See ColumnDecoder for more information.
    if (writtenFieldAvroSchema.getType() == Type.INT
        || writtenFieldAvroSchema.getType() == Type.LONG
        || writtenFieldAvroSchema.getType() == Type.STRING) {
      return new ColumnDecoder(in);
    } else {
      return DecoderFactory.get().binaryDecoder(in, null);
    }
  }
158211
def init_encoders(self, config=DataConfig()):
        
        self.log('info', 'Initializing the encoders ...')

        # create the integer encoder and fit it to our corpus' vocab
        self.ie = LabelEncoder()
        self.ie_vocab = self.ie.fit_transform(self.vocab_list)
482544
def to_schema(self):
        
        types = set()
        generated_schemas = []
        for schema_generator in self._schema_generators:
            generated_schema = schema_generator.to_schema()
            if len(generated_schema) == 1 and 'type' in generated_schema:
                types.add(generated_schema['type'])
            else:
                generated_schemas.append(generated_schema)

        if types:
            if len(types) == 1:
                (types,) = types
            else:
                types = sorted(types)
            generated_schemas = [{'type': types}] + generated_schemas
        if len(generated_schemas) == 1:
            (result_schema,) = generated_schemas
        elif generated_schemas:
            result_schema = {'anyOf': generated_schemas}
        else:
            result_schema = {}

        return result_schema
1284109
private void generateEncodeBody(GeneratorAdapter mg, Schema schema, TypeToken<?> outputType,
                                  int value, int encoder, int schemaLocal, int seenRefs) {
    Schema.Type schemaType = schema.getType();

    switch (schemaType) {
      case NULL:
        break;
      case BOOLEAN:
        encodeSimple(mg, outputType, schema, "writeBool", value, encoder);
        break;
      case INT:
      case LONG:
      case FLOAT:
      case DOUBLE:
      case BYTES:
      case STRING:
        String encodeMethod = "write" + schemaType.name().charAt(0) + schemaType.name().substring(1).toLowerCase();
        encodeSimple(mg, outputType, schema, encodeMethod, value, encoder);
        break;
      case ENUM:
        encodeEnum(mg, outputType, value, encoder, schemaLocal);
        break;
      case ARRAY:
        if (Collection.class.isAssignableFrom(outputType.getRawType())) {
          Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType,
                                      "Only support parameterized collection type.");
          TypeToken<?> componentType = TypeToken.of(((ParameterizedType) outputType.getType())
                                                      .getActualTypeArguments()[0]);

          encodeCollection(mg, componentType, schema.getComponentSchema(),
                           value, encoder, schemaLocal, seenRefs);
        } else if (outputType.isArray()) {
          TypeToken<?> componentType = outputType.getComponentType();
          encodeArray(mg, componentType, schema.getComponentSchema(),
                      value, encoder, schemaLocal, seenRefs);
        }
        break;
      case MAP:
        Preconditions.checkArgument(Map.class.isAssignableFrom(outputType.getRawType()),
                                    "Only %s type is supported.", Map.class.getName());
        Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType,
                                    "Only support parameterized map type.");
        java.lang.reflect.Type[] mapArgs = ((ParameterizedType) outputType.getType()).getActualTypeArguments();
        Map.Entry<Schema, Schema> mapSchema = schema.getMapSchema();
        encodeMap(mg, TypeToken.of(mapArgs[0]), TypeToken.of(mapArgs[1]),
                  mapSchema.getKey(), mapSchema.getValue(), value, encoder, schemaLocal, seenRefs);
        break;
      case RECORD:
        encodeRecord(mg, schema, outputType, value, encoder, schemaLocal, seenRefs);
        break;
      case UNION:
        encodeUnion(mg, outputType, schema, value, encoder, schemaLocal, seenRefs);
        break;
    }
  }
1188267
def MapEncoder(field_descriptor):
  
  # Can't look at field_descriptor.message_type._concrete_class because it may
  # not have been initialized yet.
  message_type = field_descriptor.message_type
  encode_message = MessageEncoder(field_descriptor.number, False, False)

  def EncodeField(write, value):
    for key in value:
      entry_msg = message_type._concrete_class(key=key, value=value[key])
      encode_message(write, entry_msg)

  return EncodeField
950115
def get_schema_type(cls, schema):
        
        schema_type = type(schema)

        # Marker
        if issubclass(schema_type, markers.Marker):
            return const.COMPILED_TYPE.MARKER
        # Marker Type
        elif issubclass(schema_type, six.class_types) and issubclass(schema, markers.Marker):
            return const.COMPILED_TYPE.MARKER
        # CompiledSchema
        elif isinstance(schema, CompiledSchema):
            return const.COMPILED_TYPE.SCHEMA
        else:
            return primitive_type(schema)
392462
public void encodeType(byte[] frame, int[] limits) {
    JSType.setByte(frame, limits, (byte)JSType.TUPLE);
    JSType.setCount(frame, limits, getFieldCount());
    if (fields != null)
      for (int i = 0; i < fields.length; i++)
        fields[i].encodeType(frame, limits);
  }
161211
def realize_input_schema(input_types,  # type: MutableSequence[Dict[Text, Any]]
                         schema_defs   # type: Dict[Text, Any]
                        ):  # type: (...) -> MutableSequence[Dict[Text, Any]]
    """"""
    for index, entry in enumerate(input_types):
        if isinstance(entry, string_types):
            if '#' in entry:
                _, input_type_name = entry.split('#')
            else:
                input_type_name = entry
            if input_type_name in schema_defs:
                entry = input_types[index] = schema_defs[input_type_name]
        if isinstance(entry, collections.Mapping):
            if isinstance(entry['type'], string_types) and '#' in entry['type']:
                _, input_type_name = entry['type'].split('#')
                if input_type_name in schema_defs:
                    input_types[index]['type'] = realize_input_schema(
                        schema_defs[input_type_name], schema_defs)
            if isinstance(entry['type'], collections.MutableSequence):
                input_types[index]['type'] = realize_input_schema(
                    entry['type'], schema_defs)
            if isinstance(entry['type'], collections.Mapping):
                input_types[index]['type'] = realize_input_schema(
                    [input_types[index]['type']], schema_defs)
            if entry['type'] == 'array':
                items = entry['items'] if \
                    not isinstance(entry['items'], string_types) else [entry['items']]
                input_types[index]['items'] = realize_input_schema(items, schema_defs)
            if entry['type'] == 'record':
                input_types[index]['fields'] = realize_input_schema(
                    entry['fields'], schema_defs)
    return input_types