Why if I use BigDecimal
in this case, I don't get the expected result?
double value1 = 5.68;
double value2 = 2.45;
System.out.println(BigDecimal.valueOf(value1 + value2));
EXIT:
8.129999999999999
EXPECTED:
8.13
Why if I use BigDecimal
in this case, I don't get the expected result?
double value1 = 5.68;
double value2 = 2.45;
System.out.println(BigDecimal.valueOf(value1 + value2));
8.129999999999999
8.13
Is there a way to remove a character typed by console with System.out
or System.err
?
For example if I have a process that loads for a while, simulate an animation with the 3 ellipses ...
. Something similar to this demo on fiddle .
int puntos = 0;
final String PUNTO = ".";
System.out.print("Conectando, espera");
while (condicionQueSeCumplaAlAcabarElProceso) {
if (puntos < 3) { // comprobar cuantos puntos hay
System.out.print(PUNTO); // poner un punto
puntos ++; // indicarlo
try {
Thread.sleep(1000); // esperar 1 segundo
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
} else {
// aqui hay que borrar los 3 puntos ¿como se hace?
puntos = 0; // resetear
}
}
For a system, there is a process that synchronizes information from an external API (6 tables in total) using transactions with Web SQL, this process is done manually using the button SINCRONIZAR
and while the process is running it is necessary to prevent them from logging in or Resynchronize them so both buttons are locked:
I tried to comment out the irrelevant parts to make it a bit easier to understand.
By using setInterval() and clearInterval() I somehow managed to wait for the completion of multiple asynchronous events:
// URLs para consumir cada tabla del API externo
// baseAPI viene desde otro archivo
var cultivosAPI = baseAPI + "/api/cultivos/";
var usuariosAPI = baseAPI + "/api/usuarios/";
var terminalesAPI = baseAPI + "/api/terminales/";
var personalAPI = baseAPI + "/api/personal/";
var laboresAPI = baseAPI + "/api/labores/";
var plantasAPI = baseAPI + "/api/plantas/";
// Objeto para saber el estado de la sincronización de cada
// tabla
var updateStates = {};
// ID inicial del intervalo usado en la función setInterval()
var intervalId = 0;
$(document).ready(function(){
// ...
// Boton ACTUALIZAR, antes de sincronizar se asegura
// de que exista conexión con el servidor
$("#updateBtn").on("click", testConnection);
// ...
});
function testConnection() {
$.ajax(
baseAPI
).done(function (data) {
// Si todo está bien, sincronizar las tablas
updateTables();
}).fail(function() {
// ...
});
}
function updateTables() {
// ...
// Hash para conocer el resultado de actualización de cada tabla,
// es la variable definidida arriba
updateStates = {
"cultivo": null,
"labor": null,
"personal": null,
"planta": null,
"terminal": null,
"usuario": null
};
// Deshabilitar botones
$("#loginBtn").prop("disabled", true);
$("#updateBtn").prop("disabled", true);
// ...
// ***************************************************
// Esta es la parte asíncrona en donde se llama el API
// de cada tabla
// ***************************************************
// Insertar cultivos
$.getJSON(cultivosAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["cultivo"] = false;
// ...
});
// Insertar personal
$.getJSON(personalAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["personal"] = false;
// ...
});
// Insertar terminales
$.getJSON(terminalesAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["terminal"] = false;
// ...
});
// Insertar usuarios
$.getJSON(usuariosAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["usuario"] = false;
// ...
});
// Insertar labores
$.getJSON(laboresAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["labor"] = false;
// ...
});
// Insertar plantas
$.getJSON(plantasAPI, {
format: "json"
}).done(function (data) {
db.transaction(function(tx) {
// SQL y otras cosas
});
}).fail(function(data) {
// Marcamos la tabla como incompleta
updateStates["planta"] = false;
// ...
});
// Esperar que finalicen las actualizaciones para habilitar
// los botones, valida cada segundo
intervalId = setInterval(updateIsFinished, 1000);
}
function updateIsFinished() {
// El proceso puede haber terminado sin terminar de actualizar por algún
// error encontrado
var updated = true;
var finished = true;
// Iteramos cada estado de la tabla, si la tabla tiene un valor
// false es porque hubo un error en la llamada AJAX, si tiene un
// valor null es porque el AJAX aun no finaliza
for (table in updateStates) {
if (updateStates[table] == false) {
updated = false;
}
if (updateStates[table] == null) {
finished = false;
}
}
if (updated || finished) {
// Limpiar el intervalo
clearInterval(intervalId);
// Resetear valores globales
updateStates = {};
intervalId = 0;
// Habilitar botones
if (updated) {
$("#loginBtn").prop("disabled", false);
$("#updateBtn").prop("disabled", false);
} else if (finished) {
$("#updateBtn").prop("disabled", false);
}
}
}
Although it works, I feel that there might be a better way to achieve it without the need to check every second. I tried using jQuery.when() but it didn't work.
How can I wait for asynchronous events without having to check every certain time interval?
This is what I've used to call non-member functions in C++ from C code and it works fine.
file.cpp
extern "C" void f(int);
void f(int i){
printf("c++!\n");
}
main.c
#include <stdio.h>
#include <stdlib.h>
void f(int);
int main()
{
printf("Hello world!\n");
f(1);
return 0;
}
shell:
Hello world!
c++!
How can I call member functions from C?
I have this associative array in a little Perl program that does something very weird:
#!/usr/bin/perl
use utf8;
use strict;
use warnings;
use open qw(:utf8 :std);
my %distancia = (
esto => 1,
eso => 10,
aquello => 100,
aquí => 1,
ahí => 10,
allí => 100,
);
for my $clave (keys %distancia) {
my $valor = $distancia{$clave};
printf "%-8s es %3d.\n", $clave, $valor;
}
Every time I print it, it randomly changes the order:
mac(tchrist)% perl matriz-asociativa
esto es 1.
aquello es 100.
eso es 10.
allí es 100.
ahí es 10.
aquí es 1.
mac(tchrist)% perl matriz-asociativa
eso es 10.
ahí es 10.
aquí es 1.
esto es 1.
aquello es 100.
allí es 100.
mac(tchrist)% perl matriz-asociativa
allí es 100.
aquí es 1.
ahí es 10.
eso es 10.
esto es 1.
aquello es 100.
mac(tchrist)% perl matriz-asociativa
aquello es 100.
aquí es 1.
allí es 100.
esto es 1.
eso es 10.
ahí es 10.
mac(tchrist)% perl matriz-asociativa
ahí es 10.
aquí es 1.
eso es 10.
aquello es 100.
allí es 100.
esto es 1.
What is happening to me here, and what should I do to get a certain order every time?
If it matters, it says that the version of perl I have is v5.22.0 :
mac(tchrist)% perl -v
This is perl 5, version 22, subversion 0 (v5.22.0) built for darwin-2level
Copyright 1987-2015, Larry Wall
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl". If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.