Example usage for java.lang Float toString

List of usage examples for java.lang Float toString

Introduction

In this page you can find the example usage for java.lang Float toString.

Prototype

public static String toString(float f) 

Source Link

Document

Returns a string representation of the float argument.

Usage

From source file:com.aapbd.utils.image.CacheImageDownloader.java

private void scaleImage1(ImageView view) {
    // Get the ImageView and its bitmap

    final Drawable drawing = view.getDrawable();
    if (drawing == null) {
        return; // Checking for null & return, as suggested in comments
    }/*from  w w  w . ja  v  a  2  s.  co m*/
    final Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

    // Get current dimensions AND the desired bounding box
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    final int bounding = dpToPx(view.getContext(), 300);
    Log.i("Test", "original width = " + Integer.toString(width));
    Log.i("Test", "original height = " + Integer.toString(height));
    Log.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    final float xScale = ((float) bounding) / width;
    final float yScale = ((float) bounding) / height;
    final float scale = (xScale <= yScale) ? xScale : yScale;
    Log.i("Test", "xScale = " + Float.toString(xScale));
    Log.i("Test", "yScale = " + Float.toString(yScale));
    Log.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    final Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the
    // ImageView
    final Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    final BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Log.i("Test", "scaled width = " + Integer.toString(width));
    Log.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Log.i("Test", "done");
}

From source file:org.archive.access.nutch.jobs.ImportArcs.java

public void map(final WritableComparable key, final Writable value, final OutputCollector output,
        final Reporter r) throws IOException {
    // Assumption is that this map is being run by ARCMapRunner.
    // Otherwise, the below casts fail.
    String url = key.toString();//  w  w w  .  ja v  a 2 s  .  co  m

    ARCRecord rec = (ARCRecord) ((ObjectWritable) value).get();
    ARCReporter reporter = (ARCReporter) r;

    // Its null first time map is called on an ARC.
    checkArcName(rec);
    if (!isIndex(rec)) {
        return;
    }
    checkCollectionName();

    final ARCRecordMetaData arcData = rec.getMetaData();
    String oldUrl = url;

    try {
        url = urlNormalizers.normalize(url, URLNormalizers.SCOPE_FETCHER);
        url = filters.filter(url); // filter the url
    } catch (Exception e) {
        LOG.warn("Skipping record. Didn't pass normalization/filter " + oldUrl + ": " + e.toString());

        return;
    }

    final long b = arcData.getContentBegin();
    final long l = arcData.getLength();
    final long recordLength = (l > b) ? (l - b) : l;

    // Look at ARCRecord meta data line mimetype. It can be empty.  If so,
    // two more chances at figuring it either by looking at HTTP headers or
    // by looking at first couple of bytes of the file.  See below.
    String mimetype = getMimetype(arcData.getMimetype(), this.mimeTypes, url);

    if (skip(mimetype)) {
        return;
    }

    // Copy http headers to nutch metadata.
    final Metadata metaData = new Metadata();
    final Header[] headers = rec.getHttpHeaders();
    for (int j = 0; j < headers.length; j++) {
        final Header header = headers[j];

        if (mimetype == null) {
            // Special handling. If mimetype is still null, try getting it
            // from the http header. I've seen arc record lines with empty
            // content-type and a MIME unparseable file ending; i.e. .MID.
            if ((header.getName() != null)
                    && header.getName().toLowerCase().equals(ImportArcs.CONTENT_TYPE_KEY)) {
                mimetype = getMimetype(header.getValue(), null, null);

                if (skip(mimetype)) {
                    return;
                }
            }
        }

        metaData.set(header.getName(), header.getValue());
    }

    // This call to reporter setStatus pings the tasktracker telling it our
    // status and telling the task tracker we're still alive (so it doesn't
    // time us out).
    final String noSpacesMimetype = TextUtils.replaceAll(ImportArcs.WHITESPACE,
            ((mimetype == null || mimetype.length() <= 0) ? "TODO" : mimetype), "-");
    final String recordLengthAsStr = Long.toString(recordLength);

    reporter.setStatus(getStatus(url, oldUrl, recordLengthAsStr, noSpacesMimetype));

    // This is a nutch 'more' field.
    metaData.set("contentLength", recordLengthAsStr);

    rec.skipHttpHeader();
    reporter.setStatusIfElapse("read headers on " + url);

    // TODO: Skip if unindexable type.
    int total = 0;

    // Read in first block. If mimetype still null, look for MAGIC.
    int len = rec.read(this.buffer, 0, this.buffer.length);

    if (mimetype == null) {
        MimeType mt = this.mimeTypes.getMimeType(this.buffer);

        if (mt == null || mt.getName() == null) {
            LOG.warn("Failed to get mimetype for: " + url);

            return;
        }

        mimetype = mt.getName();
    }

    metaData.set(ImportArcs.CONTENT_TYPE_KEY, mimetype);

    // How much do we read total? If pdf, we will read more. If equal to -1,
    // read all.
    int readLimit = (ImportArcs.PDF_TYPE.equals(mimetype)) ? this.pdfContentLimit : this.contentLimit;

    // Reset our contentBuffer so can reuse.  Over the life of an ARC
    // processing will grow to maximum record size.
    this.contentBuffer.reset();

    while ((len != -1) && ((readLimit == -1) || (total < readLimit))) {
        total += len;
        this.contentBuffer.write(this.buffer, 0, len);
        len = rec.read(this.buffer, 0, this.buffer.length);
        reporter.setStatusIfElapse("reading " + url);
    }

    // Close the Record.  We're done with it.  Side-effect is calculation
    // of digest -- if we're digesting.
    rec.close();
    reporter.setStatusIfElapse("closed " + url);

    final byte[] contentBytes = this.contentBuffer.toByteArray();
    final CrawlDatum datum = new CrawlDatum();
    datum.setStatus(CrawlDatum.STATUS_FETCH_SUCCESS);

    // Calculate digest or use precalculated sha1.
    String digest = (this.sha1) ? rec.getDigestStr() : MD5Hash.digest(contentBytes).toString();
    metaData.set(Nutch.SIGNATURE_KEY, digest);

    // Set digest back into the arcData so available later when we write
    // CDX line.
    arcData.setDigest(digest);

    metaData.set(Nutch.SEGMENT_NAME_KEY, this.segmentName);

    // Score at this stage is 1.0f.
    metaData.set(Nutch.SCORE_KEY, Float.toString(datum.getScore()));

    final long startTime = System.currentTimeMillis();
    final Content content = new Content(url, url, contentBytes, mimetype, metaData, getConf());
    datum.setFetchTime(Nutchwax.getDate(arcData.getDate()));

    MapWritable mw = datum.getMetaData();

    if (mw == null) {
        mw = new MapWritable();
    }

    if (collectionType.equals(Global.COLLECTION_TYPE_MULTIPLE)) {
        mw.put(new Text(ImportArcs.ARCCOLLECTION_KEY),
                new Text(SqlSearcher.getCollectionNameWithTimestamp(collectionName, arcData.getDate())));
    } else {
        mw.put(new Text(ImportArcs.ARCCOLLECTION_KEY), new Text(collectionName));
    }
    mw.put(new Text(ImportArcs.ARCFILENAME_KEY), new Text(arcName));
    mw.put(new Text(ImportArcs.ARCFILEOFFSET_KEY), new Text(Long.toString(arcData.getOffset())));
    datum.setMetaData(mw);

    TimeoutParsingThread tout = threadPool.getThread(Thread.currentThread().getId(), timeoutIndexingDocument);
    tout.setUrl(url);
    tout.setContent(content);
    tout.setParseUtil(parseUtil);
    tout.wakeupAndWait();

    ParseStatus parseStatus = tout.getParseStatus();
    Parse parse = tout.getParse();
    reporter.setStatusIfElapse("parsed " + url);

    if (!parseStatus.isSuccess()) {
        final String status = formatToOneLine(parseStatus.toString());
        LOG.warn("Error parsing: " + mimetype + " " + url + ": " + status);
        parse = null;
    } else {
        // Was it a slow parse?
        final double kbPerSecond = getParseRate(startTime, (contentBytes != null) ? contentBytes.length : 0);

        if (LOG.isDebugEnabled()) {
            LOG.debug(getParseRateLogMessage(url, noSpacesMimetype, kbPerSecond));
        } else if (kbPerSecond < this.parseThreshold) {
            LOG.warn(getParseRateLogMessage(url, noSpacesMimetype, kbPerSecond));
        }
    }

    Writable v = new FetcherOutput(datum, null, parse != null ? new ParseImpl(parse) : null);
    if (collectionType.equals(Global.COLLECTION_TYPE_MULTIPLE)) {
        LOG.info("multiple: "
                + SqlSearcher.getCollectionNameWithTimestamp(this.collectionName, arcData.getDate()) + " "
                + url);
        output.collect(Nutchwax.generateWaxKey(url,
                SqlSearcher.getCollectionNameWithTimestamp(this.collectionName, arcData.getDate())), v);
    } else {
        output.collect(Nutchwax.generateWaxKey(url, this.collectionName), v);
    }
}

From source file:org.apache.hadoop.mapreduce.TestMapCollection.java

@Test
public void testLargeRecConcurrent() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(Job.COMPLETION_POLL_INTERVAL_KEY, 100);
    Job job = Job.getInstance(conf);//from   w w w  . j  av a  2  s . c  o  m
    conf = job.getConfiguration();
    conf.setInt(MRJobConfig.IO_SORT_MB, 1);
    conf.set(MRJobConfig.MAP_SORT_SPILL_PERCENT, Float.toString(.986328125f));
    conf.setClass("test.mapcollection.class", StepFactory.class, RecordFactory.class);
    StepFactory.setLengths(conf, 4000, 261120, 96, 1024, 251);
    conf.setInt("test.spillmap.records", 255);
    conf.setBoolean("test.disable.key.read", false);
    conf.setBoolean("test.disable.val.read", false);
    runTest("largeconcurrent", job);
}

From source file:com.bazaarvoice.jackson.rison.RisonGenerator.java

@Override
public void writeNumber(float f) throws IOException, JsonGenerationException {
    if (_cfgNumbersAsStrings ||
    // [JACKSON-139]
            (((Float.isNaN(f) || Float.isInfinite(f))
                    && isEnabled(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
        writeString(Float.toString(f));
        return;/*from  w w  w  . ja  v  a  2  s. c o  m*/
    }
    // What is the max length for floats?
    _verifyValueWrite("write number");
    _writeRaw(formatFloat(f));
}

From source file:co.foldingmap.mapImportExport.SvgExporter.java

private void writeImage(BufferedWriter outputStream, IconStyle style, Coordinate c, String id) {

    BufferedImage bi;/* w w  w.  j a  va 2  s . c  o  m*/
    byte[] imageBytes;
    ByteArrayOutputStream baos;
    float x, y, height, width;
    ImageIcon image;
    OutputStream os64;
    Point2D.Float point;
    String imageEnc;

    try {
        point = c.getCenterPoint();

        if (style.getImageFile() == null) {
            //No image
            outputStream.write(getIndent());
            outputStream.write("<circle cx=\"");
            outputStream.write(Float.toString(point.x - 2));
            outputStream.write("\" cy=\"");
            outputStream.write(Float.toString(point.y - 2));
            outputStream.write("\" r=\"2\" stroke=\"#");
            outputStream.write(getHexColor(style.getOutlineColor()));
            outputStream.write("\" stroke-width=\"1\"  fill=\"");
            outputStream.write(getHexColor(style.getFillColor()));
            outputStream.write("\"/>\n");
        } else {
            //Has image
            //first encode image into a string
            baos = new ByteArrayOutputStream();
            bi = ImageIO.read(style.getImageFile());

            ImageIO.write(bi, "PNG", baos);
            imageBytes = baos.toByteArray();
            imageEnc = Base64.encodeBase64String(imageBytes);

            baos.close();

            image = style.getObjectImage();
            height = image.getIconHeight();
            width = image.getIconWidth();
            x = point.x - (width / 2.0f);
            y = point.y - (height / 2.0f);

            outputStream.write(getIndent());
            outputStream.write("<image\n");
            addIndent();

            //y coordiante
            outputStream.write(getIndent());
            outputStream.write("y=\"");
            outputStream.write(Float.toString(y));
            outputStream.write("\"\n");

            //x coordiante
            outputStream.write(getIndent());
            outputStream.write("x=\"");
            outputStream.write(Float.toString(x));
            outputStream.write("\"\n");

            //id
            outputStream.write(getIndent());
            outputStream.write("id=\"");
            outputStream.write(id);
            outputStream.write("\"\n");

            //xlink
            outputStream.write(getIndent());
            outputStream.write("xlink:href=\"data:image/png;base64,");
            outputStream.write(imageEnc);
            outputStream.write("\"\n");

            //x coordiante
            outputStream.write(getIndent());
            outputStream.write("height=\"");
            outputStream.write(Float.toString(height));
            outputStream.write("\"\n");

            //y coordiante
            outputStream.write(getIndent());
            outputStream.write("width=\"");
            outputStream.write(Float.toString(width));
            outputStream.write("\" />\n");
        }
    } catch (Exception e) {
        Logger.log(Logger.ERR, "Error in SvgExporter.writeImage() - " + e);
    }
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;//from  ww w  .j av a 2 s .  c  o m

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

private static String toXmlString(float value) {
    if (Float.isNaN(value)) {
        return "NaN";
    } else if (value == Float.POSITIVE_INFINITY) {
        return "INF";
    } else if (value == Float.NEGATIVE_INFINITY) {
        return "-INF";
    } else {//from w  ww .ja  v  a  2  s. co  m
        return Float.toString(value);
    }
}

From source file:org.apache.pdfbox.pdfwriter.COSWriter.java

/**
 * This will write the header to the PDF document.
 *
 * @param doc The document to get the data from.
 *
 * @throws IOException If there is an error writing to the stream.
 *//*from   w ww.j  ava  2s . c o  m*/
protected void doWriteHeader(COSDocument doc) throws IOException {
    String headerString;
    if (fdfDocument != null) {
        headerString = "%FDF-" + Float.toString(fdfDocument.getDocument().getVersion());
    } else {
        headerString = "%PDF-" + Float.toString(pdDocument.getDocument().getVersion());
    }
    getStandardOutput().write(headerString.getBytes(Charsets.ISO_8859_1));

    getStandardOutput().writeEOL();
    getStandardOutput().write(COMMENT);
    getStandardOutput().write(GARBAGE);
    getStandardOutput().writeEOL();
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

private static float getEditFloat(SharedPreferences prefs, String name, float d) throws NumberFormatException {
    String v = prefs.getString(name, Float.toString(d));
    if (v.length() < 1 || v.length() > 9)
        return d;
    return Float.parseFloat(v);
}

From source file:com.alibaba.citrus.service.requestcontext.support.ValueListSupport.java

/**
 * ???/?
 *
 * @param value ?
 */
public void addValue(float value) {
    addValue(Float.toString(value));
}