List of usage examples for java.lang Float toString
public static String toString(float f)
From source file:es.elearningmedia.courseslastaccess.service.BbServiceImpl.java
@Override public List<CourseLastAccess> getCoursesLastAccess() { List<CourseLastAccess> result = new ArrayList<CourseLastAccess>(); try {/* w w w. j a va 2 s .co m*/ List<Course> cursos = CourseDbLoader.Default.getInstance().loadAllCourses(); for (Course curso : cursos) { List<CourseMembership> courseMemberships = CourseMembershipDbLoader.Default.getInstance() .loadByCourseId(curso.getId()); Calendar lastAccess = null; int studentsCount = 0; int instructorsCount = 0; for (CourseMembership courseMembership : courseMemberships) { if (lastAccess == null) { lastAccess = courseMembership.getLastAccessDate(); } else { Calendar access = courseMembership.getLastAccessDate(); if (access != null) { if (access.after(lastAccess)) { lastAccess = courseMembership.getLastAccessDate(); } } } Role role = courseMembership.getRole(); if (role.equals(CourseMembership.Role.STUDENT)) { studentsCount++; } else { instructorsCount++; } } CourseLastAccess courseLastAccess = new CourseLastAccess(); courseLastAccess.setCourse_id(curso.getCourseId()); SimpleDateFormat formatedDate = new SimpleDateFormat("yyyy-MM-dd"); if (lastAccess == null) { courseLastAccess.setLast_access("Never"); courseLastAccess.setDate_sort("0"); } else { courseLastAccess.setLast_access(formatedDate.format(lastAccess.getTime())); courseLastAccess.setDate_sort(Long.toString(lastAccess.getTimeInMillis())); } courseLastAccess.setCreated(formatedDate.format(curso.getCreatedDate().getTime())); String status = "Unavailable"; if (curso.getIsAvailable()) { status = "Available"; } courseLastAccess.setStatus(status); courseLastAccess.setInstructors(Integer.toString(instructorsCount)); courseLastAccess.setStudents(Integer.toString(studentsCount)); courseLastAccess.setSize(Float.toString((getCourseSizes(curso) / 1024f) / 1024f)); result.add(courseLastAccess); } } catch (KeyNotFoundException e) { e.printStackTrace(); } catch (PersistenceException e) { e.printStackTrace(); } //Collections.sort(result); return result; }
From source file:com.variable.demo.api.fragment.ThermaFragment.java
@Override public void onTemperatureReading(ThermaSensor sensor, SensorReading<Float> reading) { Message m = mHandler.obtainMessage(MessageConstants.MESSAGE_THERMA_TEMPERATURE); m.getData().putFloat(MessageConstants.FLOAT_VALUE_KEY, reading.getValue()); final Context thiscontext = this.getActivity(); final String serialnumOne = sensor.getSerialNumber(); final String serialnum = serialnumOne.replaceAll("[^\\u0000-\\uFFFF]", ""); final String scan = Float.toString(reading.getValue()); String json = "temperature;" + serialnum + ";" + scan; // POST to variable dashboard Ion.getDefault(thiscontext).getConscryptMiddleware().enable(false); Ion.with(thiscontext).load(/*from w w w .j a v a 2 s . co m*/ "https://datadipity.com/clickslide/fleetplusdata.json?PHPSESSID=gae519f8k5humje0jqb195nob6&update&postparam[payload]=" + json) .setLogging("MyLogs", Log.DEBUG).asString().withResponse() .setCallback(new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> result) { if (e == null) { Log.i(TAG, "ION SENT MESSAGE WITH RESULT CODE: " + result.toString()); } else { Log.i(TAG, "ION SENT MESSAGE WITH EXCEPTION"); e.printStackTrace(); } } }); m.sendToTarget(); }
From source file:com.linkedin.pinot.core.predicate.NoDictionaryEqualsPredicateEvaluatorsTest.java
@Test public void testFloatPredicateEvaluators() { // FLOAT data type float floatValue = _random.nextFloat(); EqPredicate eqPredicate = new EqPredicate(COLUMN_NAME, Collections.singletonList(Float.toString(floatValue))); PredicateEvaluator eqPredicateEvaluator = EqualsPredicateEvaluatorFactory .newNoDictionaryBasedEvaluator(eqPredicate, FieldSpec.DataType.FLOAT); NEqPredicate neqPredicate = new NEqPredicate(COLUMN_NAME, Collections.singletonList(Float.toString(floatValue))); PredicateEvaluator neqPredicateEvaluator = NotEqualsPredicateEvaluatorFactory .newNoDictionaryBasedEvaluator(neqPredicate, FieldSpec.DataType.FLOAT); Assert.assertTrue(eqPredicateEvaluator.apply(floatValue)); Assert.assertFalse(neqPredicateEvaluator.apply(floatValue)); float[] randomFloats = new float[NUM_MULTI_VALUES]; PredicateEvaluatorTestUtils.fillRandom(randomFloats); randomFloats[_random.nextInt(randomFloats.length)] = floatValue; Assert.assertTrue(eqPredicateEvaluator.apply(randomFloats)); Assert.assertFalse(neqPredicateEvaluator.apply(randomFloats)); for (int i = 0; i < 100; i++) { float random = _random.nextFloat(); Assert.assertEquals(eqPredicateEvaluator.apply(random), (random == floatValue)); Assert.assertEquals(neqPredicateEvaluator.apply(random), (random != floatValue)); PredicateEvaluatorTestUtils.fillRandom(randomFloats); Assert.assertEquals(eqPredicateEvaluator.apply(randomFloats), ArrayUtils.contains(randomFloats, floatValue)); Assert.assertEquals(neqPredicateEvaluator.apply(randomFloats), !ArrayUtils.contains(randomFloats, floatValue)); }//from w ww . j a va 2 s. c o m }
From source file:Logica.Usuario.java
/** * * @param item/*from w w w . j a v a 2 s . c o m*/ * @return boolean * @throws RemoteException * * Crea un tem */ @Override public boolean crearItem(ItemInventario item) throws RemoteException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU"); boolean hecho = false; ItemJpaController itm = new ItemJpaController(emf); Item i = new Item(item.getNumero(), item.getInventario(), item.getDescripcion(), item.getPresentacion(), new Double(Float.toString(item.getCantidad())), new Double(Float.toString(item.getPrecio())), item.getcCalidad(), item.getCEsp()); try { itm.create(i); hecho = true; emf.close(); } catch (Exception ex) { Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex); } return hecho; }
From source file:org.intermine.bio.dataconversion.PdbConverter.java
private void processPDBFile(File file, String taxonId) throws Exception { Item proteinStructure = createItem("ProteinStructure"); PDBFileParser pdbfileparser = new PDBFileParser(); Reader reader = new FileReader(file); PdbBufferedReader pdbBuffReader = new PdbBufferedReader(reader); Structure structure = pdbfileparser.parsePDBFile(pdbBuffReader); String idCode = (String) structure.getHeader().get("idCode"); if (StringUtils.isNotEmpty(idCode)) { proteinStructure.setAttribute("identifier", idCode); } else {//from ww w . j a v a2 s .c om throw new BuildException("No value for title in structure: " + idCode); } List<String> dbrefs = pdbBuffReader.getDbrefs(); for (String accnum : dbrefs) { String proteinRefId = getProtein(accnum, taxonId); proteinStructure.addToCollection("proteins", proteinRefId); } String title = (((String) structure.getHeader().get("title"))).trim(); if (StringUtils.isNotEmpty(title)) { proteinStructure.setAttribute("title", title); } else { LOG.warn("No value for title in structure: " + idCode); } String technique = ((String) structure.getHeader().get("technique")).trim(); if (StringUtils.isNotEmpty(technique)) { proteinStructure.setAttribute("technique", technique); } else { LOG.warn("No value for technique in structure: " + idCode); } String classification = ((String) structure.getHeader().get("classification")).trim(); proteinStructure.setAttribute("classification", classification); Object resolution = structure.getHeader().get("resolution"); if (resolution instanceof Float) { final Float resolutionFloat = (Float) structure.getHeader().get("resolution"); proteinStructure.setAttribute("resolution", Float.toString(resolutionFloat.floatValue())); } try { proteinStructure.setAttribute("atm", structure.toPDB()); } catch (ArrayIndexOutOfBoundsException e) { LOG.error("Failed to process structure " + idCode); } store(proteinStructure); }
From source file:com.laex.cg2d.model.joints.BERevoluteJoint.java
@Override public Object getPropertyValue(Object id) { if (isReferenceAngleProp(id)) { return Double.toString(Math.toDegrees(revoluteJointDef.referenceAngle)); }//from w w w.j a va2s. c o m if (isEnableLimitProp(id)) { return BooleanUtil.getIntegerFromBoolean(revoluteJointDef.enableLimit); } if (isLowerAngleProp(id)) { return Float.toString(revoluteJointDef.lowerAngle); } if (isUpperAngleProp(id)) { return Float.toString(revoluteJointDef.upperAngle); } if (isEnableMotorProp(id)) { return BooleanUtil.getIntegerFromBoolean(revoluteJointDef.enableMotor); } if (isMotorSpeedProp(id)) { return Float.toString(revoluteJointDef.motorSpeed); } if (isMaxMotorTorqueProp(id)) { return Float.toString(revoluteJointDef.maxMotorTorque); } return super.getPropertyValue(id); }
From source file:eu.itesla_project.modules.histo.tools.HistoDbPrintVoltageRangeTool.java
@Override public void run(CommandLine line) throws Exception { Interval interval = Interval.parse(line.getOptionValue("interval")); Path caseFile = Paths.get(line.getOptionValue("case-file")); Map<String, VoltageStats> ranges = new HashMap<>(); Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); }/*from ww w .j av a 2s .c om*/ network.getStateManager().allowStateMultiThreadAccess(true); OfflineConfig config = OfflineConfig.load(); try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) { Set<HistoDbAttributeId> attrIds = new LinkedHashSet<>(); for (VoltageLevel vl : network.getVoltageLevels()) { attrIds.add(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V)); } HistoDbStats stats = histoDbClient.queryStats(attrIds, interval, HistoDbHorizon.SN, false); for (VoltageLevel vl : network.getVoltageLevels()) { HistoDbNetworkAttributeId attrId = new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V); float min = stats.getValue(HistoDbStatsType.MIN, attrId, Float.NaN) / vl.getNominalV(); float max = stats.getValue(HistoDbStatsType.MAX, attrId, Float.NaN) / vl.getNominalV(); int count = (int) stats.getValue(HistoDbStatsType.COUNT, attrId, 0); VoltageStats vstats = new VoltageStats(Range.closed(min, max), count, vl.getNominalV()); for (Generator g : vl.getGenerators()) { vstats.pmax += g.getMaxP(); } ranges.put(vl.getId(), vstats); } } Table table = new Table(7, BorderStyle.CLASSIC_WIDE); table.addCell("ID"); table.addCell("vnom"); table.addCell("range"); table.addCell("min"); table.addCell("max"); table.addCell("count"); table.addCell("pmax"); ranges.entrySet().stream().sorted((e1, e2) -> { VoltageStats stats1 = e1.getValue(); VoltageStats stats2 = e2.getValue(); Range<Float> r1 = stats1.range; Range<Float> r2 = stats2.range; float s1 = r1.upperEndpoint() - r1.lowerEndpoint(); float s2 = r2.upperEndpoint() - r2.lowerEndpoint(); return Float.compare(s1, s2); }).forEach(e -> { String vlId = e.getKey(); VoltageStats stats = e.getValue(); Range<Float> r = stats.range; float s = r.upperEndpoint() - r.lowerEndpoint(); table.addCell(vlId); table.addCell(Float.toString(stats.vnom)); table.addCell(Float.toString(s)); table.addCell(Float.toString(r.lowerEndpoint())); table.addCell(Float.toString(r.upperEndpoint())); table.addCell(Integer.toString(stats.count)); table.addCell(Float.toString(stats.pmax)); }); System.out.println(table.render()); }
From source file:com.koda.integ.hbase.test.BlockCacheMultithreadedTest.java
@Override protected void setUp() throws IOException { if (regions != null) return;// w w w .j a v a 2 s.co m regions = new HRegion[numThreads]; // Init columns CQQ = new byte[5][]; for (int i = 0; i < CQQ.length; i++) { CQQ[i] = ("cq" + i).getBytes(); } Configuration conf = TEST_UTIL.getConfiguration(); conf.set(OffHeapBlockCache.BLOCK_CACHE_MEMORY_SIZE, Long.toString(cacheSize)); conf.set(OffHeapBlockCache.BLOCK_CACHE_IMPL, cacheImplClass); conf.set(OffHeapBlockCache.BLOCK_CACHE_YOUNG_GEN_FACTOR, Float.toString(youngGenFactor)); conf.set(OffHeapBlockCache.BLOCK_CACHE_COMPRESSION, cacheCompression); conf.set(OffHeapBlockCache.BLOCK_CACHE_OVERFLOW_TO_EXT_STORAGE_ENABLED, Boolean.toString(cacheOverflowEnabled)); conf.set(OffHeapBlockCache.BLOCK_CACHE_ONHEAP_ENABLED, Boolean.toString(onHeapCacheEnabled)); conf.set("io.storefile.bloom.block.size", Integer.toString(BLOOM_BLOCK_SIZE)); conf.set("hfile.index.block.max.size", Integer.toString(INDEX_BLOCK_SIZE)); conf.set("hfile.block.cache.size", Float.toString(onHeapCacheRatio)); // Enable File Storage conf.set(FileExtStorage.FILE_STORAGE_FILE_SIZE_LIMIT, Integer.toString((int) fileSizeLimit)); conf.set(FileExtStorage.FILE_STORAGE_MAX_SIZE, Long.toString(fileStoreSize)); conf.set(OffHeapBlockCache.BLOCK_CACHE_OVERFLOW_TO_EXT_STORAGE_ENABLED, Boolean.toString(cacheOverflowEnabled)); conf.set(OffHeapBlockCache.BLOCK_CACHE_EXT_STORAGE_IMPL, FileExtStorage.class.getName()); conf.set(FileExtStorage.FILE_STORAGE_BASE_DIR, dataDir); conf.set(OffHeapBlockCache.BLOCK_CACHE_TEST_MODE, Boolean.toString(true)); conf.set(OffHeapBlockCache.BLOCK_CACHE_EXT_STORAGE_MEMORY_SIZE, Long.toString(extRefCacheSize)); for (int i = 0; i < numThreads; i++) { HColumnDescriptor desc = new HColumnDescriptor(CF); desc.setCacheDataOnWrite(true); desc.setCacheIndexesOnWrite(true); desc.setCacheBloomsOnWrite(true); desc.setBlocksize(BLOCK_SIZE); desc.setBloomFilterType(BloomType.ROW); regions[i] = TEST_UTIL.createTestRegion(TABLE_NAME, desc); populateData(regions[i]); } cache = new CacheConfig(conf).getBlockCache(); LOG.info("Block cache: " + cache.getClass().getName() + " Size=" + cache.getCurrentSize()); for (int i = 0; i < numThreads; i++) { regions[i].compactStores(true); cacheRegion(regions[i]); } LOG.info("After compact & pre-caching. Block cache: " + cache.getClass().getName() + " Size=" + cache.getCurrentSize()); }
From source file:mitm.djigzo.web.pages.sms.Clickatell.java
private void updateBalance() throws HierarchicalPropertiesException { try {/*from w w w . jav a 2 s . co m*/ float value = clickatellWS.getBalance(getClickatellParameters().getAPIID(), getClickatellParameters().getUser(), getClickatellParameters().getPassword()); balance = Float.toString(value); } catch (WebServiceCheckedException e) { logger.error("Error getting balance.", e); clickatellError = true; clickatellErrorMessage = e.getMessage(); balance = ""; } }
From source file:edu.rosehulman.grocerydroid.ItemDialogFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_dialog_item, container, false); // EditText nameBox = (EditText) view.findViewById(R.id.item_name_box); AutoCompleteTextView nameBox = (AutoCompleteTextView) view.findViewById(R.id.item_name_box); nameBox.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // String[] names = new String[] { "Bob", "Joe", "Caleb", "Jonathan", // "Elise" }; String[] foodNames = getResources().getStringArray(R.array.food_names); // ArrayAdapter<String> autoAdapter = new ArrayAdapter<String>( // getActivity(), android.R.layout.simple_list_item_1, names); ArrayAdapter<String> autoAdapter = new ArrayAdapter<String>(getActivity(), R.layout.dropdown_item, foodNames);//from w ww . j a v a 2s . c om // android.R.layout.sherlock.* both white/invisible // android.R.layout. // simple_spinner_item too thin // simple list item 2: crash // activity_list_item crash //simple_spinner_dropdown_item nameBox.setAdapter(autoAdapter); // mEditIcon.setOnKeyListener(new OnKeyListener() { // @Override // public boolean onKey(View v, int keyCode, KeyEvent event) { // // If the event is a key-down event on the "enter" button // if ((event.getAction() == KeyEvent.ACTION_DOWN) // && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Toast.makeText(StockActivity.this, tv.getText(), // Toast.LENGTH_SHORT).show(); // return true; // } // return false; // } // }); EditText priceBox = (EditText) view.findViewById(R.id.item_price_box); priceBox.setInputType(InputType.TYPE_CLASS_PHONE); // priceBox.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL); // first true : is signed, second one : is decimal priceBox.setKeyListener(new DigitsKeyListener(false, true)); EditText sizeBox = (EditText) view.findViewById(R.id.item_unit_size_box); sizeBox.setText("" + mItem.getUnitSize()); Spinner unitSpinner = (Spinner) view.findViewById(R.id.item_unit_label_spinner); ArrayAdapter<Item.UnitLabel> adapter; adapter = new ArrayAdapter<Item.UnitLabel>(this.getActivity(), android.R.layout.simple_spinner_item, Item.UnitLabel.values()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); unitSpinner.setAdapter(adapter); EditText numStockBox = (EditText) view.findViewById(R.id.item_num_stock); numStockBox.setText("" + mItem.getNStock()); // If this activity was started with the purpose of editing an existing // item, then we use the item passed in the intent to populate the // spinners and edit text boxes. if (!mItem.getName().equals("")) { // TODO Make non-focusable, non-touchable so it doesn't kick off the drop down. // But it doesn't work! nameBox.setFocusable(false); nameBox.setFocusableInTouchMode(false); nameBox.setText(mItem.getName()); // Reset the focus & touch nameBox.setFocusable(true); nameBox.setFocusableInTouchMode(true); priceBox.setText(Float.toString(mItem.getPrice())); unitSpinner.setSelection(mItem.getUnitLabel().ordinal()); } Button incrementNumStockButton = (Button) view.findViewById(R.id.item_increment_num_stock); incrementNumStockButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText et = (EditText) view.findViewById(R.id.item_num_stock); int numStock = getIntegerFromEditText(et); numStock++; et.setText(numStock + ""); } }); Button decrementNumStockButton = (Button) view.findViewById(R.id.item_decrement_num_stock); decrementNumStockButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText et = (EditText) view.findViewById(R.id.item_num_stock); int numStock = getIntegerFromEditText(et); numStock--; et.setText(numStock + ""); } }); Button saveButton = (Button) view.findViewById(R.id.item_save_button); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText et = (EditText) view.findViewById(R.id.item_name_box); String name = et.getText().toString(); et = (EditText) view.findViewById(R.id.item_price_box); float price = getFloatFromEditText(et); et = (EditText) view.findViewById(R.id.item_unit_size_box); float size = getFloatFromEditText(et); Spinner spinner = (Spinner) view.findViewById(R.id.item_unit_label_spinner); int unitIndex = spinner.getSelectedItemPosition(); et = (EditText) view.findViewById(R.id.item_num_stock); int numStock = getIntegerFromEditText(et); mItem = new Item(mItem.getId(), mItem.getListId(), name, numStock, mItem.getNBuy(), price, size, Item.UnitLabel.values()[unitIndex], mItem.isBought(), mItem.getStockIdx(), mItem.getShopIdx()); if (mMode == Mode.ADD) { ((ShoppingListActivity) getActivity()).addItem(mItem); } else if (mMode == Mode.EDIT) { ((ShoppingListActivity) getActivity()).updateItem(mItem); } else { // shouldn't get here. } dismiss(); } }); Button cancelButton = (Button) view.findViewById(R.id.item_cancel_button); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); Button deleteButton = (Button) view.findViewById(R.id.item_delete_button); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mMode == Mode.EDIT) { ConfirmDeleteItemDialogFragment df = new ConfirmDeleteItemDialogFragment(); df.setItem(mItem); df.show(getActivity().getSupportFragmentManager(), "confirm"); } // Otherwise, we are adding this item, so we don't need to // delete it. // TODO: Remove modes altogether once autocomplete works, since // every item here will exist and be beging added. // CONSIDER: at that point, I will need to make sure that items // that have a name only (from autocomplete) have been saved in // the DB // and have a unique ID so they can be deleted. dismiss(); } }); return view; }