Convert a GenericRecord to a byte array.
968939
public static byte[] recordToByteArray(GenericRecord record) throws IOException {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
      Encoder encoder = EncoderFactory.get().directBinaryEncoder(out, null);
      DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(record.getSchema());
      writer.write(record, encoder);
      byte[] byteArray = out.toByteArray();
      return byteArray;
    }
  }
1162602
def to_bytes(s, encoding=None, errors='strict'):
    """"""
    encoding = encoding or 'utf-8'
    if isinstance(s, bytes):
        if encoding != 'utf-8':
            return s.decode('utf-8', errors).encode(encoding, errors)
        else:
            return s
    if not is_string(s):
        s = string_type(s)
    return s.encode(encoding, errors)
673976
def recarray(self):
        """"""

        if self.records is None:
            self.parse()
        try:
            # simple (should this also be subjected to convert.to_int64() ?)
            return numpy.rec.fromrecords(self.records, names=self.names)
        except ValueError:
            # complicated because fromrecords cannot deal with records of lists
            # Quick hack: use objects for lists etc (instead of building the proper
            # data types (see docs for numpy.dtype , eg dtype('coord', (float, 3)) )

            D = numpy.empty(len(self.records[0]), dtype=object)    # number of fields from first record
            types = numpy.array([map(type, r) for r in self.records])  # types of all fields
            for icol, isSame in enumerate([numpy.all(col) for col in types.T]):
                if isSame:
                    D[icol] = types[0][icol]
                else:
                    D[icol] = object
            dtype = numpy.dtype(zip(self.names, D))
            # from numpy.rec.records
            # TODO: this is not working properly yet; for instance, text fields
            # are reduced to length 0 (<U0) and the final convert.to_int64 dies
            # with '<U0'*** TypeError: TypeError('data type not understood',)
            retval = numpy.array(self.records, dtype=dtype)
            res = retval.view(numpy.recarray)
            ## res.dtype = numpy.dtype((numpy.rec.record, res.dtype))  # fails -- ARGH, this makes it a recarray
            return convert.to_int64(res)
1235438
@Override
  public List<InputRow> parseBatch(GenericRecord record)
  {
    Map<String, Object> row = recordFlattener.flatten(record);

    final List<String> dimensions;
    if (!this.dimensions.isEmpty()) {
      dimensions = this.dimensions;
    } else {
      dimensions = Lists.newArrayList(
          Sets.difference(row.keySet(), parseSpec.getDimensionsSpec().getDimensionExclusions())
      );
    }
    // check for parquet Date
    // https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#date
    LogicalType logicalType = determineTimestampSpecLogicalType(record.getSchema(), timestampSpec.getTimestampColumn());
    DateTime dateTime;
    if (logicalType instanceof LogicalTypes.Date) {
      int daysSinceEpoch = (Integer) record.get(timestampSpec.getTimestampColumn());
      dateTime = DateTimes.utc(TimeUnit.DAYS.toMillis(daysSinceEpoch));
    } else {
      // Fall back to a binary format that will be parsed using joda-time
      dateTime = timestampSpec.extractTimestamp(row);
    }
    return ImmutableList.of(new MapBasedInputRow(dateTime, dimensions, row));
  }
923873
private static Byte[] castToByte( byte[] d )
    {
        Byte[] dest = new Byte[d.length];
        for ( int i = 0; i < d.length; i++ )
        {
            dest[i] = (byte)d[i];
        }
        return dest;
    }
1011506
public void fieldsToData(Rec record) throws DBException
    {
        this.setupNewDataSource();
        int fieldCount = record.getFieldCount(); // Number of fields to write out
        for (int iFieldSeq = Constants.MAIN_FIELD; iFieldSeq < fieldCount + Constants.MAIN_FIELD; iFieldSeq++)
        {
            Field field = record.getField(iFieldSeq);
            if (field.isVirtual()) //x || (!field.isSelected()))
                continue;               // This field is never moved to a buffer
            this.fieldToData(field);
        }
    }
1262726
public static <T, E extends Exception> ByteList mapToByte(final Collection<? extends T> c, final int fromIndex, final int toIndex,
            final Try.ToByteFunction<? super T, E> func) throws E {
        checkFromToIndex(fromIndex, toIndex, size(c));
        N.checkArgNotNull(func);

        if (N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) {
            return new ByteList();
        }

        final ByteList result = new ByteList(toIndex - fromIndex);

        if (c instanceof List && c instanceof RandomAccess) {
            final List<T> list = (List<T>) c;

            for (int i = fromIndex; i < toIndex; i++) {
                result.add(func.applyAsByte(list.get(i)));
            }
        } else {
            int idx = 0;

            for (T e : c) {
                if (idx++ < fromIndex) {
                    continue;
                }

                result.add(func.applyAsByte(e));

                if (idx >= toIndex) {
                    break;
                }
            }
        }

        return result;
    }
18544
@Override
  public Iterable<GenericRecord> convertRecord(Schema outputSchema, JsonObject inputRecord, WorkUnitState workUnit)
      throws DataConversionException {
    GenericRecord avroRecord = convertNestedRecord(outputSchema, inputRecord, workUnit, this.ignoreFields);
    return new SingleRecordIterable<>(avroRecord);
  }
406388
public static byte[] toByteArray(Writable... writables) {
        final DataOutputBuffer out = new DataOutputBuffer();
        try {
            for (Writable w : writables) {
                w.write(out);
            }
            out.close();
        } catch (IOException e) {
            throw new RuntimeException("Fail to convert writables to a byte array", e);
        }
        return out.getData();
    }
1019440
@Override
    public AbstractHttpEntity harvest(long generation) {
        DecoderHelper decoder = null;
        DataFileWriter<GenericRecord> fileWriter = null;
        ByteBufferEntity entity = null;
        //Now iterate over records and write
        Iterator<GenericRecord> itr = m_records.iterator();
        try {
            while (itr.hasNext()) {
                GenericRecord record = itr.next();
                if (decoder == null) {
                    decoder = decoder(generation, record.getSchema());
                }
                fileWriter = decoder.m_fileWriter;
                fileWriter.append(record);
                itr.remove();
            }

            if (fileWriter != null) {
                fileWriter.flush();
            }
            if (decoder != null) {
                entity = new ByteBufferEntity(decoder.m_bbos.toByteBuffer(), AvroContentType);
            }
        }
        catch (IOException e) {
            throw new BulkException("failed to append to the avro data container", e);
        }
        finally {
            if (decoder != null) {
                decoder.m_bbos.reset();
            }
            m_records.clear();
        }

        return entity;
    }
764057
private void retrieveTypeAndFillRecord(int pos, int type, Record record) throws SQLException,
			NotTransformableSQLFieldException {
		switch (type) {
		case java.sql.Types.NULL:
			record.setField(pos, NullValue.getInstance());
			break;
		case java.sql.Types.BOOLEAN:
			record.setField(pos, new BooleanValue(resultSet.getBoolean(pos + 1)));
			break;
		case java.sql.Types.BIT:
			record.setField(pos, new BooleanValue(resultSet.getBoolean(pos + 1)));
			break;
		case java.sql.Types.CHAR:
			record.setField(pos, new StringValue(resultSet.getString(pos + 1)));
			break;
		case java.sql.Types.NCHAR:
			record.setField(pos, new StringValue(resultSet.getString(pos + 1)));
			break;
		case java.sql.Types.VARCHAR:
			record.setField(pos, new StringValue(resultSet.getString(pos + 1)));
			break;
		case java.sql.Types.LONGVARCHAR:
			record.setField(pos, new StringValue(resultSet.getString(pos + 1)));
			break;
		case java.sql.Types.LONGNVARCHAR:
			record.setField(pos, new StringValue(resultSet.getString(pos + 1)));
			break;
		case java.sql.Types.TINYINT:
			record.setField(pos, new ShortValue(resultSet.getShort(pos + 1)));
			break;
		case java.sql.Types.SMALLINT:
			record.setField(pos, new ShortValue(resultSet.getShort(pos + 1)));
			break;
		case java.sql.Types.BIGINT:
			record.setField(pos, new LongValue(resultSet.getLong(pos + 1)));
			break;
		case java.sql.Types.INTEGER:
			record.setField(pos, new IntValue(resultSet.getInt(pos + 1)));
			break;
		case java.sql.Types.FLOAT:
			record.setField(pos, new DoubleValue(resultSet.getDouble(pos + 1)));
			break;
		case java.sql.Types.REAL:
			record.setField(pos, new FloatValue(resultSet.getFloat(pos + 1)));
			break;
		case java.sql.Types.DOUBLE:
			record.setField(pos, new DoubleValue(resultSet.getDouble(pos + 1)));
			break;
		case java.sql.Types.DECIMAL:
			record.setField(pos, new DoubleValue(resultSet.getBigDecimal(pos + 1).doubleValue()));
			break;
		case java.sql.Types.NUMERIC:
			record.setField(pos, new DoubleValue(resultSet.getBigDecimal(pos + 1).doubleValue()));
			break;
		case java.sql.Types.DATE:
			record.setField(pos, new StringValue(resultSet.getDate(pos + 1).toString()));
			break;
		case java.sql.Types.TIME:
			record.setField(pos, new LongValue(resultSet.getTime(pos + 1).getTime()));
			break;
		case java.sql.Types.TIMESTAMP:
			record.setField(pos, new StringValue(resultSet.getTimestamp(pos + 1).toString()));
			break;
		case java.sql.Types.SQLXML:
			record.setField(pos, new StringValue(resultSet.getSQLXML(pos + 1).toString()));
			break;
		default:
			throw new NotTransformableSQLFieldException("Unknown sql-type [" + type + "]on column [" + pos + "]");

			// case java.sql.Types.BINARY:
			// case java.sql.Types.VARBINARY:
			// case java.sql.Types.LONGVARBINARY:
			// case java.sql.Types.ARRAY:
			// case java.sql.Types.JAVA_OBJECT:
			// case java.sql.Types.BLOB:
			// case java.sql.Types.CLOB:
			// case java.sql.Types.NCLOB:
			// case java.sql.Types.DATALINK:
			// case java.sql.Types.DISTINCT:
			// case java.sql.Types.OTHER:
			// case java.sql.Types.REF:
			// case java.sql.Types.ROWID:
			// case java.sql.Types.STRUCT:
		}
	}
133509
@SuppressWarnings({ "unchecked" })
    @Override
    public void serializeObject(HashGenericRecord rec, String fieldName, String typeName, Object obj) {
        if (obj == null) {
            return;
        }

        getSerializer(typeName).serialize(obj, rec);
    }
784968
public static byte[] intArrayToBytes(Collection<Integer> values)
    {
        ByteBuffer buffer = ByteBuffer.allocate(values.size() * Integer.BYTES);
        for (int value : values) {
            buffer.putInt(value);
        }
        return buffer.array();
    }
476900
def get_bytearray(self):
        
        if isinstance(self._bytearray, DB):
            return self._bytearray._bytearray
        return self._bytearray
893731
public static byte[] toByteArray(Object obj) {
    int len = (int) sizeOf(obj);
    byte[] bytes = new byte[len];
    unsafe.copyMemory(obj, 0, bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, bytes.length);
    return bytes;
  }
1195542
def to_bytes(self):
        '''
        
        '''
        # Verify that properties make sense
        self.sanitize()

        # Start with the type
        bitstream = BitArray('uint:4=%d' % self.message_type)

        # Add the flags
        bitstream += BitArray('bool=%d, bool=%d, bool=%d'
                              % (self.probe,
                                 self.enlra_enabled,
                                 self.security))

        # Add padding
        bitstream += self._reserved1

        # Add record count
        bitstream += BitArray('uint:8=%d' % len(self.records))

        # Add the nonce
        nonce = bytes(self.nonce)
        if len(nonce) < 8:
            padding_len = 8 - len(nonce)
            bitstream += BitArray(8 * padding_len)

        bitstream += BitArray(bytes=nonce)

        # Add the map-reply records
        for record in self.records:
            bitstream += record.to_bitstream()

        # If the security flag is set then there should be security data here
        # TODO: deal with security flag [LISP-Security]
        if self.security:
            raise NotImplementedError('Handling security data is not ' +
                                      'implemented yet')

        return bitstream.bytes
127791
private Object jsonToObject(String recordValue) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		Object json = mapper.readValue(recordValue, Object.class);	
		return json;
	}