Example usage for java.io DataOutputStream writeDouble

List of usage examples for java.io DataOutputStream writeDouble

Introduction

In this page you can find the example usage for java.io DataOutputStream writeDouble.

Prototype

public final void writeDouble(double v) throws IOException 

Source Link

Document

Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

Usage

From source file:org.apache.hadoop.hive.serde2.lazy.LazyUtils.java

/**
 * Write out a binary representation of a PrimitiveObject to a byte stream.
 *
 * @param out ByteStream.Output, an unsynchronized version of ByteArrayOutputStream, used as a
 *            backing buffer for the the DataOutputStream
 * @param o the PrimitiveObject//  ww  w. ja v a 2  s . c  o  m
 * @param oi the PrimitiveObjectInspector
 * @throws IOException on error during the write operation
 */
public static void writePrimitive(OutputStream out, Object o, PrimitiveObjectInspector oi) throws IOException {

    DataOutputStream dos = new DataOutputStream(out);

    try {
        switch (oi.getPrimitiveCategory()) {
        case BOOLEAN:
            boolean b = ((BooleanObjectInspector) oi).get(o);
            dos.writeBoolean(b);
            break;

        case BYTE:
            byte bt = ((ByteObjectInspector) oi).get(o);
            dos.writeByte(bt);
            break;

        case SHORT:
            short s = ((ShortObjectInspector) oi).get(o);
            dos.writeShort(s);
            break;

        case INT:
            int i = ((IntObjectInspector) oi).get(o);
            dos.writeInt(i);
            break;

        case LONG:
            long l = ((LongObjectInspector) oi).get(o);
            dos.writeLong(l);
            break;

        case FLOAT:
            float f = ((FloatObjectInspector) oi).get(o);
            dos.writeFloat(f);
            break;

        case DOUBLE:
            double d = ((DoubleObjectInspector) oi).get(o);
            dos.writeDouble(d);
            break;

        case BINARY: {
            BytesWritable bw = ((BinaryObjectInspector) oi).getPrimitiveWritableObject(o);
            out.write(bw.getBytes(), 0, bw.getLength());
            break;
        }

        default:
            throw new RuntimeException("Hive internal error.");
        }
    } finally {
        // closing the underlying ByteStream should have no effect, the data should still be
        // accessible
        dos.close();
    }
}

From source file:ubic.basecode.io.ByteArrayConverter.java

/**
 * @param darray//from w  ww . j a v  a2  s .c  o  m
 * @return byte[]
 */
public byte[] doubleArrayToBytes(double[] darray) {
    if (darray == null)
        return null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    try {
        for (double element : darray) {
            dos.writeDouble(element);
        }
    } catch (IOException e) {
        // do nothing
    }
    return bos.toByteArray();
}

From source file:org.esa.nest.gpf.BackGeocodingOp.java

private static void outputToFile(final String filePath, double[][] fbuf) throws IOException {

    try {/*w  w w  . j a  va 2s  .  c o  m*/
        FileOutputStream fos = new FileOutputStream(filePath);
        DataOutputStream dos = new DataOutputStream(fos);

        for (double[] aFbuf : fbuf) {
            for (int j = 0; j < fbuf[0].length; j++) {
                dos.writeDouble(aFbuf[j]);
            }
        }
        //dos.flush();
        dos.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:es.yrbcn.graph.weighted.WeightedPageRankPowerMethod.java

/** Computes the next step of the Power Method.
 *///from  www  .jav a 2s .  c om
public void step() throws IOException {
    double[] oldRank = rank, newRank = previousRank;
    DoubleArrays.fill(newRank, 0.0);
    // for each node, calculate its outdegree and redistribute its rank among pointed nodes
    double accum = 0.0;

    progressLogger.expectedUpdates = numNodes;
    progressLogger.start("Iteration " + (++iterationNumber) + "...");

    final ArcLabelledNodeIterator nodeIterator = g.nodeIterator();
    int i, outdegree, j, n = numNodes;
    int[] succ;
    Label[] lab;

    while (n-- != 0) {
        i = nodeIterator.nextInt();
        outdegree = nodeIterator.outdegree();

        if (outdegree == 0 || buckets != null && buckets.get(i))
            accum += oldRank[i];
        else {
            j = outdegree;
            succ = nodeIterator.successorArray();
            lab = nodeIterator.labelArray();
            while (j-- != 0) {
                newRank[succ[j]] += (oldRank[i] * lab[j].getFloat()) / sumoutweight[i];
            }
        }
        progressLogger.update();
    }
    progressLogger.done();

    final double accumOverNumNodes = accum / numNodes;

    final double oneOverNumNodes = 1.0 / numNodes;
    if (preference != null)
        if (preferentialAdjustment == null)
            for (i = numNodes; i-- != 0;)
                newRank[i] = alpha * newRank[i] + (1 - alpha) * preference.getDouble(i)
                        + alpha * accumOverNumNodes;
        else
            for (i = numNodes; i-- != 0;)
                newRank[i] = alpha * newRank[i] + (1 - alpha) * preference.getDouble(i)
                        + alpha * accum * preferentialAdjustment.getDouble(i);
    else if (preferentialAdjustment == null)
        for (i = numNodes; i-- != 0;)
            newRank[i] = alpha * newRank[i] + (1 - alpha) * oneOverNumNodes + alpha * accumOverNumNodes;
    else
        for (i = numNodes; i-- != 0;)
            newRank[i] = alpha * newRank[i] + (1 - alpha) * oneOverNumNodes
                    + alpha * accum * preferentialAdjustment.getDouble(i);

    //make the rank just computed the new rank
    rank = newRank;
    previousRank = oldRank;

    // Compute derivatives.
    n = iterationNumber;

    if (subset == null) {
        for (i = 0; i < order.length; i++) {
            final int k = order[i];
            final double alphak = Math.pow(alpha, k);
            final double nFallingK = Util.falling(n, k);
            for (j = 0; j < numNodes; j++)
                derivative[i][j] += nFallingK * (rank[j] - previousRank[j]) / alphak;
        }
    } else {
        for (i = 0; i < order.length; i++) {
            final int k = order[i];
            final double alphak = Math.pow(alpha, k);
            final double nFallingK = Util.falling(n, k);

            for (int t : subset)
                derivative[i][t] += nFallingK * (rank[t] - previousRank[t]) / alphak;
        }
    }

    // Compute coefficients, if required.

    if (coeffBasename != null) {
        final DataOutputStream coefficients = new DataOutputStream(
                new FastBufferedOutputStream(new FileOutputStream(coeffBasename + "-" + (iterationNumber))));
        final double alphaN = Math.pow(alpha, n);
        for (i = 0; i < numNodes; i++)
            coefficients.writeDouble((rank[i] - previousRank[i]) / alphaN);
        coefficients.close();
    }
}

From source file:org.apache.hadoop.hive.accumulo.mr.TestHiveAccumuloTableInputFormat.java

private byte[] parseDoubleBytes(String s) throws IOException {
    double val = Double.parseDouble(s);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8);
    DataOutputStream out = new DataOutputStream(baos);
    out.writeDouble(val);
    out.close();//from  www .j a va  2 s. c  o  m
    return baos.toByteArray();
}

From source file:org.structr.core.graph.SyncCommand.java

private static void writeObject(final DataOutputStream outputStream, final byte type, final Object value)
        throws IOException {

    switch (type) {

    case 0://from w  w  w.  j a  v a 2  s. co m
    case 1:
        outputStream.writeByte((byte) value);
        break;

    case 2:
    case 3:
        outputStream.writeShort((short) value);
        break;

    case 4:
    case 5:
        outputStream.writeInt((int) value);
        break;

    case 6:
    case 7:
        outputStream.writeLong((long) value);
        break;

    case 8:
    case 9:
        outputStream.writeFloat((float) value);
        break;

    case 10:
    case 11:
        outputStream.writeDouble((double) value);
        break;

    case 12:
    case 13:
        outputStream.writeChar((char) value);
        break;

    case 14:
    case 15:
        serializeData(outputStream, ((String) value).getBytes("UTF-8"));

        // this doesn't work with very long strings
        //outputStream.writeUTF((String)value);
        break;

    case 16:
    case 17:
        outputStream.writeBoolean((boolean) value);
        break;
    }
}

From source file:org.slc.sli.dal.encrypt.AesCipher.java

@Override
public String encrypt(Object data) {
    if (data instanceof String) {
        return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data));
    } else {/* w  w  w  .  ja  va  2  s  .  c o m*/
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(byteOutputStream);
        String type;
        try {
            if (data instanceof Boolean) {
                dos.writeBoolean((Boolean) data);
                type = "EBOOL:";
            } else if (data instanceof Integer) {
                dos.writeInt((Integer) data);
                type = "EINT:";
            } else if (data instanceof Long) {
                dos.writeLong((Long) data);
                type = "ELONG:";
            } else if (data instanceof Double) {
                dos.writeDouble((Double) data);
                type = "EDOUBLE:";
            } else {
                throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName());
            }
            dos.flush();
            dos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = byteOutputStream.toByteArray();
        return type + encryptFromBytes(bytes);
    }
}

From source file:RealFunctionValidation.java

public static SummaryStatistics assessAccuracy(final Method method, final DataInputStream in,
        final DataOutputStream out)
        throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    if (method.getReturnType() != Double.TYPE) {
        throw new IllegalArgumentException("method must return a double");
    }/*from   w ww.  j av a  2 s . c o m*/

    final Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        if (!types[i].isPrimitive()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("argument #").append(i + 1).append(" of method ").append(method.getName())
                    .append("must be of primitive of type");
            throw new IllegalArgumentException(builder.toString());
        }
    }

    final SummaryStatistics stat = new SummaryStatistics();
    final Object[] parameters = new Object[types.length];
    while (true) {
        try {
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = readAndWritePrimitiveValue(in, out, types[i]);
            }
            final double expected = in.readDouble();
            if (FastMath.abs(expected) > 1E-16) {
                final Object value = method.invoke(null, parameters);
                final double actual = ((Double) value).doubleValue();
                final double err = FastMath.abs(actual - expected);
                final double ulps = err / FastMath.ulp(expected);
                out.writeDouble(expected);
                out.writeDouble(actual);
                out.writeDouble(ulps);
                stat.addValue(ulps);
            }
        } catch (EOFException e) {
            break;
        }
    }
    return stat;
}

From source file:com.rapidminer.cryptography.hashing.DigesterProvider.java

/**
 * Writes the provided value to the provided {@link DataOutputStream}.
 *//*from   w  w  w .j  a  v  a  2 s  . c o  m*/
private void writeBytes(Object value, DataOutputStream dos) throws IOException, JEPFunctionException {
    if (value instanceof String) {
        dos.writeUTF((String) value);
    } else if (value instanceof Integer) {
        dos.writeInt((int) value);
    } else if (value instanceof Long) {
        dos.writeLong((long) value);
    } else if (value instanceof Float) {
        dos.writeFloat((float) value);
    } else if (value instanceof GregorianCalendar) {
        dos.writeLong(((GregorianCalendar) value).getTimeInMillis());
    } else if (value instanceof Date) {
        dos.writeLong(((Date) value).getTime());
    } else if (value instanceof Double) {
        dos.writeDouble((double) value);
    } else if (value instanceof UnknownValue) {
        dos.writeDouble(Double.NaN);
    } else {
        // should not happen
        throw new JEPFunctionException("Unknown input type: " + value.getClass());
    }
}

From source file:org.openmrs.module.odkconnector.serialization.serializer.openmrs.ObsSerializer.java

/**
 * Write the data to the output stream./*  w w w.  j a v a2  s  .co  m*/
 *
 * @param stream the output stream
 * @param data   the data that need to be written to the output stream
 * @throws java.io.IOException thrown when the writing process encounter is failing
 */
@Override
public void write(final OutputStream stream, final Object data) throws IOException {
    try {
        Obs obs = (Obs) data;

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        DataOutputStream outputStream = new DataOutputStream(stream);
        // write the person id of the observation
        outputStream.writeInt(obs.getPersonId());
        // write the concept name of the observation
        outputStream.writeUTF(obs.getConcept().getDisplayString());
        // write the data type and the value of the observation
        if (obs.getValueDatetime() != null) {
            outputStream.writeByte(TYPE_DATE);
            outputStream.writeUTF(dateFormat.format(obs.getValueDatetime()));
        } else if (obs.getValueCoded() != null) {
            outputStream.writeByte(TYPE_STRING);
            outputStream.writeUTF(obs.getValueCoded().getDisplayString());
        } else if (obs.getValueNumeric() != null) {
            outputStream.writeByte(TYPE_DOUBLE);
            outputStream.writeDouble(obs.getValueNumeric());
        } else {
            outputStream.writeByte(TYPE_STRING);
            outputStream.writeUTF(obs.getValueAsString(Context.getLocale()));
        }
        // write the datetime of the observation
        outputStream.writeUTF(dateFormat.format(obs.getObsDatetime()));
    } catch (IOException e) {
        log.info("Writing obs information failed!", e);
    }
}