Example usage for java.lang Float valueOf

List of usage examples for java.lang Float valueOf

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static Float valueOf(float f) 

Source Link

Document

Returns a Float instance representing the specified float value.

Usage

From source file:com.esri.arcgis.android.samples.GeoJSONEarthquakeMap.GeoJSONEarthquakeMapActivity.java

private void getEarthquakeEvents() {
    int size;/*from ww  w .ja va  2 s. co  m*/
    String url = this.getResources().getString(R.string.earthquake_url);
    try {
        // Making the request and getting the response
        HttpClient client = new DefaultHttpClient();
        HttpGet req = new HttpGet(url);
        HttpResponse res = client.execute(req);

        // Converting the response stream to string
        HttpEntity jsonentity = res.getEntity();
        InputStream in = jsonentity.getContent();
        String json_str = convertStreamToString(in);

        JSONObject jsonobj = new JSONObject(json_str);
        JSONArray feature_arr = jsonobj.getJSONArray("features");

        SimpleMarkerSymbol symbol = new SimpleMarkerSymbol(Color.rgb(255, 128, 64), 15,
                SimpleMarkerSymbol.STYLE.CIRCLE);

        for (int i = 0; i < feature_arr.length(); i++) {

            // Getting the coordinates and projecting them to map's spatial
            // reference

            JSONObject obj_geometry = feature_arr.getJSONObject(i).getJSONObject("geometry");
            double lon = Double.parseDouble(obj_geometry.getJSONArray("coordinates").get(0).toString());
            double lat = Double.parseDouble(obj_geometry.getJSONArray("coordinates").get(1).toString());
            Point point = (Point) GeometryEngine.project(new Point(lon, lat), SpatialReference.create(4326),
                    mMapView.getSpatialReference());

            JSONObject obj_properties = feature_arr.getJSONObject(i).getJSONObject("properties");
            Map<String, Object> attr = new HashMap<String, Object>();

            String place = obj_properties.getString("place").toString();
            attr.put("Location", place);

            // Setting the size of the symbol based upon the magnitude
            float mag = Float.valueOf(obj_properties.getString("mag").toString());
            size = getSizefromMag(mag);
            symbol.setSize(size);
            attr.put("Magnitude", mag);

            // Converting time from unix time to date format
            long timeStamp = Long.valueOf(obj_properties.getString("time").toString());
            java.util.Date time = new java.util.Date((long) timeStamp);
            attr.put("Time ", time.toString());

            attr.put("Rms ", obj_properties.getString("rms").toString());
            attr.put("Gap ", obj_properties.getString("gap").toString());

            // Add graphics to the graphic layer
            graphicsLayer.addGraphic(new Graphic(point, symbol, attr));

        }

    } catch (ClientProtocolException e) {
        // Catch exceptions here
        e.printStackTrace();
    } catch (IOException e) {
        // Catch exceptions here
        e.printStackTrace();
    } catch (JSONException e) {
        // Catch exceptions here
        e.printStackTrace();
    }

}

From source file:com.zenoss.zenpacks.zenjmx.call.OperationCall.java

private static Object[] createParamValues(ConfigAdapter config) throws ConfigurationException {
    String[] params = config.getOperationParamValues();
    String[] paramTypes = config.getOperationParamTypes();

    if (params.length != paramTypes.length) {
        throw new ConfigurationException("Datasource " + config.getDatasourceId()
                + " number of parameter types and " + "parameter values does not match");
    }/*from w ww.ja va 2  s. c  o  m*/
    Object[] values = new Object[params.length];
    for (int i = 0; i < params.length; i++) {

        String type = paramTypes[i].trim();
        String valueStr = params[i].trim();
        Object resultValue = null;
        try {
            if (INT_TYPES.contains(type)) {
                resultValue = Integer.valueOf(valueStr);
            } else if (DOUBLE_TYPES.contains(type)) {
                resultValue = Double.valueOf(valueStr);
            } else if (LONG_TYPES.contains(type)) {
                resultValue = Long.valueOf(valueStr);
            } else if (FLOAT_TYPES.contains(type)) {
                resultValue = Float.valueOf(valueStr);
            } else if (STRING_TYPES.contains(type)) {
                resultValue = valueStr;
            } else if (BOOLEAN_TYPES.contains(type)) {
                resultValue = new Boolean(valueStr);
            } else {
                throw new ConfigurationException("Datasource " + config.getDatasourceId() + " Type " + type
                        + " is not handled for operation calls");
            }
        } catch (NumberFormatException e) {
            throw new ConfigurationException(
                    String.format("Datasource %1$s; value %2$s could not be converted to %3$s",
                            config.getDatasourceId(), valueStr, type));
        }
        values[i] = resultValue;
    }

    return values;
}

From source file:com.closertag.smartmove.server.service.pearson.DeafultPearsonService.java

/**
 * Get and save the single entry into the database
 * /*from  w  w w  . java 2  s.co  m*/
 * @param manager
 * @param it
 * @throws Exception
 */
private boolean getSingleEntry(HttpConnectionManager manager, JsonNode entry) throws Exception {
    String id = entry.get("@id").getTextValue();
    /*If a coordinate is missing exit */
    if (entry.get("@latitude") == null) {
        return false;

    }
    String category = StringUtils.substringBefore(entry.get("@categories").getTextValue(), ",");

    try {

        // Chiamo la singola string per eseguire la query
        // https://api.pearson.com/eyewitness/london/block/EWTG_LONDON097APSHOU_001.json?apikey=d14b9d3c132ba476437046de8b1395a8
        ObjectMapper mapper_item = new ObjectMapper();
        JsonNode itemNode = mapper_item.readValue(
                new String(manager.getByteArrayResourcePost(
                        "/eyewitness/london/block/" + id + ".json?apikey=" + getApikey(), null, null)),
                JsonNode.class);
        JsonNode block = itemNode.get("block");
        String text = block.get("title").get("#text").getTextValue();

        Item item = new Item();

        item.setGid(new Gid("PEARSON"));
        item.setItemId(id);

        JsonNode tagInfo = block.get("tg_info");
        Category c = new Category(category);
        item.setCategory(c);

        if (tagInfo == null) {
            return false;
        }
        Cost cost = new Cost();
        if (tagInfo.get("admission_charge") != null) {
            cost.setItem(item);
            cost.setLocale(Locale.ENGLISH);
            cost.setValue(tagInfo.get("admission_charge").getTextValue());
            item.setWebsite(tagInfo.get("url").get("#text").getTextValue());
            item.getCosts().add(cost);
        }

        String description = text;
        if (tagInfo.get("opening_info") != null) {
            description += " Opening: " + tagInfo.get("opening_info").get("#text").getTextValue();
        }
        if (tagInfo.get("closing_info") != null) {
            description += " Closing: " + tagInfo.get("closing_info").get("#text").getTextValue();
        }
        if (tagInfo.get("additional_info") != null) {

            if (!tagInfo.get("additional_info").isArray()) {
                description += "Additional info: " + tagInfo.get("additional_info").get("#text").getTextValue();
            } else {
                for (int i = 0; i < tagInfo.get("additional_info").size(); i++) {
                    JsonNode node = tagInfo.get("additional_info").get(i);
                    if (node.get("#text") != null) {
                        description += " " + node.get("#text").getTextValue();
                    }
                }
            }
        }

        if (tagInfo.get("phone") != null) {
            if (tagInfo.get("phone").isArray()) {

                item.setTelephone(tagInfo.get("phone").get(0).get("#text").getTextValue());

            } else {

                item.setTelephone(tagInfo.get("phone").get("#text").getTextValue());

            }
        }

        if (tagInfo.get("tg_data") != null) {
            if (tagInfo.get("tg_data").isArray()) {
                for (int i = 0; i < tagInfo.get("tg_data").size(); i++) {
                    JsonNode data = tagInfo.get("tg_data").get(i);

                    Extra e = new Extra();
                    e.setItem(item);
                    e.setLabel(data.get("@role").getTextValue());
                    e.setValue("present");
                    item.getExtras().add(e);

                }
            } else {
                Extra e = new Extra();
                e.setItem(item);
                e.setLabel(tagInfo.get("tg_data").get("@role").getTextValue());
                e.setValue("present");
                item.getExtras().add(e);

            }
        }

        item.getLocalizedItems().add(new LocalizedItem(item, Label.Description, Locale.ENGLISH, description));
        item.getLocalizedItems().add(new LocalizedItem(item, Label.Title, Locale.ENGLISH, text));
        if (tagInfo.get("url") != null) {
            item.setWebsite(tagInfo.get("url").get("#text").getTextValue());
        }

        String address = tagInfo.get("address") != null ? tagInfo.get("address").get("#text").getTextValue()
                : null;
        item.getGpsPositions().add(new GpsPosition(item, Float.valueOf(tagInfo.get("@lat").getTextValue()),
                Float.valueOf(tagInfo.get("@long").getTextValue()), address, "London"));

        if (LOG.isDebugEnabled()) {

            LOG.debug("Importing content id:" + id + " " + text);

        }
        itemService.saveOrUpdate(item);
        return true;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {

            LOG.debug("Error importing content " + e.toString());

        }
        e.printStackTrace();
        throw new Exception(e.toString() + " import dell'id  " + id);

    }
}

From source file:com.savedollars.ProductTotalPriceDisplay.java

private void parseJsonData(String data) {
    // Convert to JSON object for parsing
    JSONData = data;/*from w ww . j  ava2s  . c om*/
    try {
        JSONObject jsonResponse = new JSONObject(data);
        if (jsonResponse.has("items")) {
            JSONArray parsedItems = jsonResponse.getJSONArray("items");

            JSONObject inventory = null;
            for (int j = 0; j < parsedItems.length(); j++) {

                inventory = parsedItems.getJSONObject(j);

                JSONObject objPrice = inventory.getJSONObject("product");

                JSONObject merchant = objPrice.getJSONObject("author");
                String merchantName = merchant.getString("name");
                JSONArray invObj = objPrice.getJSONArray("inventories");

                for (int z = 0; z < invObj.length(); z++) {
                    JSONObject price = invObj.getJSONObject(z);
                    String productPrice = price.getString("price");

                    String shipping = "0.0";
                    if (price.has("shipping")) {
                        shipping = price.getString("shipping");
                    }

                    float finalPrice = Float.parseFloat(productPrice) + Float.parseFloat(shipping);

                    merchantMap.put(merchantName, finalPrice);
                    sortedList.add(Float.valueOf(finalPrice));
                }

                JSONArray imgObj = objPrice.getJSONArray("images");

                for (int i = 0; i < imgObj.length(); i++) {
                    JSONObject imgLink = imgObj.getJSONObject(i);
                    String img = imgLink.getString("link");

                }
                // retrieve product title
                pdtName = objPrice.getString("title");
                // retrieve merchant page
                merchantPage = objPrice.getString("link");

                merchantLinkMap.put(merchantName, merchantPage);

            }

            Collections.sort(sortedList);
            sortMerchantPrices();
            merchantNameKeys = sortedMap.keySet();
            merchantNames = Arrays.copyOf(merchantNameKeys.toArray(), merchantNameKeys.toArray().length,
                    String[].class);

        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

}

From source file:com.zion.htf.ui.DonateActivity.java

@Override
public void afterTextChanged(Editable s) {
    int previousAmount = this.amount;
    int value;/* www. j  a  v  a2s .c  o m*/
    try {
        value = (int) (Float.valueOf(s.toString().replace(',', '.')) * 100);
    } catch (NumberFormatException e) {
        value = 0;
    }

    if (DonateActivity.MIN_DONATION > value) {
        this.amount = DonateActivity.MIN_DONATION;
        previousAmount = -1;// Forces controls update
    } else if (DonateActivity.MAX_DONATION < value) {
        this.amount = DonateActivity.MAX_DONATION;
        previousAmount = -1;// Forces controls update
    } else {
        this.amount = value;
    }

    int cursorPosition = this.amountEditText.getSelectionStart();
    if (previousAmount != this.amount)
        this.updateControls();
    if (cursorPosition < this.amountEditText.length())
        this.amountEditText.setSelection(cursorPosition);
}

From source file:hivemall.dataset.LogisticRegressionDataGeneratorUDTF.java

private void generateDenseData() {
    float label = rnd1.nextFloat();
    float sign = (label >= prob_one) ? 1.f : 0.f;
    labels[position] = classification ? sign : label;
    Float[] features = featuresFloatArray[position];
    assert (features != null);
    for (int i = 0; i < n_features; i++) {
        float w = (float) rnd2.nextGaussian() + (sign * eps);
        features[i] = Float.valueOf(w);
    }//from  www  .  j a  v  a2s .  c  o  m
}

From source file:io.github.malapert.jwcs.JWcs.java

/**
 * Returns the reference system.//from  w  w w  . j a  va  2 s  .com
 * <p>
 * To find the reference system, the algorithm proceed as it:
 * <ul>
 * <li>Gets the RADESYS value when the keyword is found
 * <li>Otherwise gets the EQUINOX value when the keyword is found and select
 * either FK4 or FK5 according to the equinox value
 * <li>Otherwise ICRS is set
 * </ul>
 *
 * @return the reference system
 */
private ReferenceSystemInterface getReferenceSystem() {
    String mjdObs = getMJDObs();
    ReferenceSystemInterface refSystem;
    if (hasKeyword(RADESYS)) {
        String radesys = getValueAsString(RADESYS);
        switch (radesys) {
        case "ICRS":
            refSystem = new ICRS();
            break;

        case "FK5":
            refSystem = new FK5();
            if (hasKeyword(EQUINOX)) {
                ((FK5) refSystem).setEquinox(getValueAsFloat(EQUINOX));
            }
            break;

        case "FK4":
            refSystem = new FK4();
            if (hasKeyword(EQUINOX)) {
                ((FK4) refSystem).setEquinox(getValueAsFloat(EQUINOX));
            }
            if (mjdObs != null) {
                ((FK4) refSystem).setEpochObs(Float.valueOf(mjdObs));
            }
            break;

        case "FK4-NO-E":
            refSystem = new FK4_NO_E();
            if (hasKeyword(EQUINOX)) {
                ((FK4_NO_E) refSystem).setEquinox(getValueAsFloat(EQUINOX));
            }
            if (mjdObs != null) {
                ((FK4_NO_E) refSystem).setEpochObs(Float.valueOf(mjdObs));
            }
            break;

        default:
            throw new JWcsError("The reference frame, " + radesys + " is not supported");
        }
    } else if (hasKeyword(EQUINOX)) {
        float equinox = getValueAsFloat(EQUINOX);
        if (equinox < 1984.0) {
            refSystem = new FK4(equinox);
            if (mjdObs != null) {
                ((FK4) refSystem).setEpochObs(Float.valueOf(mjdObs));
            }
        } else {
            refSystem = new FK5(equinox);
        }
    } else {
        // RADESYSa defaults to ICRS if both it and EQUINOX a are absent.
        refSystem = new ICRS();
    }
    return refSystem;
}

From source file:cz.muni.fi.mir.db.dao.impl.FormulaDAOImpl.java

@Override
public SearchResponse<Formula> findSimilar(Formula formula, Map<String, String> properties, boolean override,
        boolean directWrite, Pagination pagination) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    org.hibernate.search.jpa.FullTextQuery ftq = null;

    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Formula.class)
            .overridesForField("co.element", "keywordAnalyzer").get();

    BooleanJunction<BooleanJunction> junction = qb.bool();

    SimilarityForms sf = similarityFormConverter
            .process(formula.getOutputs().get(formula.getOutputs().size() - 1));

    if (Boolean.valueOf(properties.get(FormulaService.USE_DISTANCE))) {
        junction.must(qb.keyword().fuzzy()
                .withThreshold(Float.valueOf(properties.get(FormulaService.VALUE_DISTANCEMETHOD)))
                .withPrefixLength(1).onField("co.distanceForm").ignoreFieldBridge()
                .matching(sf.getDistanceForm()).createQuery());
    }/*ww w  . j  a  va2 s.c  om*/

    if (Boolean.valueOf(properties.get(FormulaService.USE_COUNT))) {
        if ("must".equalsIgnoreCase(properties.get(FormulaService.CONDITION_COUNT))) {
            BooleanJunction<BooleanJunction> junctionElements = qb.bool();
            if ("must".equalsIgnoreCase(properties.get(FormulaService.VALUE_COUNTELEMENTMETHOD))) {
                for (String stringElement : sf.getCountForm().keySet()) {
                    junctionElements.must(qb.keyword().onField("co.element").ignoreFieldBridge()
                            .matching(stringElement + "=" + sf.getCountForm().get(stringElement))
                            .createQuery());
                }
            } else {
                for (String stringElement : sf.getCountForm().keySet()) {
                    junctionElements.should(qb.keyword().onField("co.element").ignoreFieldBridge()
                            .matching(stringElement + "=" + sf.getCountForm().get(stringElement))
                            .createQuery());
                }
            }

            junction.must(junctionElements.createQuery());
        } else if ("should".equalsIgnoreCase(properties.get(FormulaService.CONDITION_COUNT))) {
            BooleanJunction<BooleanJunction> junctionElements = qb.bool();
            if ("must".equalsIgnoreCase(properties.get(FormulaService.VALUE_COUNTELEMENTMETHOD))) {
                for (String stringElement : sf.getCountForm().keySet()) {
                    junctionElements.must(qb.keyword().onField("co.element").ignoreFieldBridge()
                            .matching(stringElement + "=" + sf.getCountForm().get(stringElement))
                            .createQuery());
                }
            } else {
                for (String stringElement : sf.getCountForm().keySet()) {
                    junctionElements.should(qb.keyword().onField("co.element").ignoreFieldBridge()
                            .matching(stringElement + "=" + sf.getCountForm().get(stringElement))
                            .createQuery());
                }
            }

            junction.should(junctionElements.createQuery());
        } else {
            throw new IllegalArgumentException("condi");
        }
    }

    Query query = junction.createQuery();
    logger.info(query);

    ftq = fullTextEntityManager.createFullTextQuery(query, Formula.class);

    SearchResponse<Formula> fsr = new SearchResponse<>();
    fsr.setTotalResultSize(ftq.getResultSize());
    List<Formula> resultList = ftq.setFirstResult(pagination.getPageSize() * (pagination.getPageNumber() - 1))
            .setMaxResults(pagination.getPageSize()).getResultList();

    // we would like to write results immediately
    if (directWrite) { // override old results ?
        if (override) {
            formula.setSimilarFormulas(new ArrayList<>(resultList));
        } else { // check if null and append to earlier
            List<Formula> similars = new ArrayList<>();
            if (formula.getSimilarFormulas() != null) {
                similars.addAll(formula.getSimilarFormulas());
                similars.addAll(resultList);

                formula.setSimilarFormulas(similars);
            } else {
                similars.addAll(resultList);

                formula.setSimilarFormulas(similars);
            }
        }
        // update
        super.update(formula);
    }

    fsr.setResults(resultList);

    return fsr;
}

From source file:com.thanu.schoolbustracker.RouteActivity.java

@Override
public void onMapLongClick(LatLng point) {
    if (name == null || name.equalsIgnoreCase("Admin")) {
        locationCount++;// w  ww .j a v  a  2  s . c  o  m

        // Drawing marker on the map
        drawMarker(point);

        /** Opening the editor object to write data to sharedPreferences */
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // Storing the latitude for the i-th location
        editor.putString("lat" + Integer.toString((locationCount - 1)), Double.toString(point.latitude));

        // Storing the longitude for the i-th location
        editor.putString("lng" + Integer.toString((locationCount - 1)), Double.toString(point.longitude));

        // Storing the count of locations or marker count
        editor.putInt("locationCount", locationCount);

        /** Storing the zoom level to the shared preferences */
        editor.putString("zoom", Float.toString(myMap.getCameraPosition().zoom));

        /** Saving the values stored in the shared preferences */
        editor.commit();

        // Setting latitude in ContentValues
        lat = point.latitude;
        latitude = (Double.valueOf(lat)).toString();

        // Setting longitude in ContentValues
        lon = point.longitude;
        longitude = (Double.valueOf(lon)).toString();

        // Setting zoom in ContentValues
        zoomLevel = myMap.getCameraPosition().zoom;
        zoom = (Float.valueOf(zoomLevel)).toString();

        // Creating an instance of LocationInsertTask
        new LocationInsertTask().execute();

        Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();

        markerClicked = false;
    }
}

From source file:com.highcharts.export.controller.ExportController.java

private static Float scaleToFloat(String scale) {
    scale = sanitize(scale);//from  w w  w .  j  a v  a2s. c  o  m
    if (scale != null) {
        Float parsedScale = Float.valueOf(scale);
        if (parsedScale.compareTo(MAX_SCALE) > 0) {
            return MAX_SCALE;
        } else if (parsedScale.compareTo(0.0F) > 0) {
            return parsedScale;
        }
    }
    return null;
}