Mule ESB, issue when adding up numbers within a JSON array - json

I use the following dynamic query (even though I could have used a prepared stmt) in my Database COnnection node:
SELECT BALANCE FROM xxx.TAB
I have the following expression in the SetPayload command that is run immediately after the Datbase Connection node:
#[message.payload]
and I get the following response from curl:
[{"BALANCE":111.11},{"BALANCE":222.12},{"BALANCE":444.30}]
So I modify the flow, putting an expression node between the Database connection node and the SetPayload node with the following expressions:
sum = 0;
foreach (row : message.payload) {
sum += row['BALANCE'];
}
message.payload = sum;
I run curl again, but this time I get the following:
777.5299999999999994315658113919199
Actually, the answer should be 777.53
What happened to this data?
Is there a way to fix this ?
Thanks

It's because the value is a Float or Double. Take a look at something like: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Bit messy, but something like:
sum = 0;
foreach (row : message.payload) {
sum += row['BALANCE'];
}
message.payload = new java.text.DecimalFormat("#.##").format(sum);

Related

how nodejs socket.on('data' works?

how nodejs socket.on('data' works without end of line at the end of data ?
I mean how nodejs separate every data without any separator like \n
this question is because I found a little bug in my script
the bug is :
when sending data very fast , all data will be attached to one and socket.on('data' will run only once
for example
in client side :
if sending two or mode data at same time (on same open connection) like this :
client.write('1');
client.write('2');
on the server socket.on('data' will be called once and data will be 12
and this will get error if sendig json data
finally I found the solution
since in nodejs tcp sockets , every chunk not contain previous chunk
this trick would 100 percent work !
server :
socket.on('data', function (data) {
var newdata = ""+data;
var newdatachunks = newdata.split("\n");
for (var i = 0 ; i<(newdatachunks.length-1);i++) {
console.log("real data is :"+newdatachunks[i]);
}
});
client :
in client side every message must finish with \n (or any separator you like)
client.write("1\n");
client.write("2\n");
client.write("3\n");
client.write("4\n");
notice : and if you work with json dont forget use try/catch

Node-red payload convertion for mysql node

How to convert a msg.payload like 12345,67890 into "12345","67890" ?
Basically I receive a payload with many values and need to pass them to a mysql node.
Thanks in advance.
Sep
Depending on the exact type of input there are a couple options
First the core CSV node will split a payload into either an array or an object (if the first line of multiple lines contains the column names).
Second if you just have a single input then you can break it up with a function node using the normal NodeJS/Javascript functions for working with Strings. e.g.
var chunks = msg.payload.split(',');
msg.payload = {};
msg.paylaod.first = chunks[0];
msg.payload.second = chunk[1];
return msg;

Attempt to perform arithmetic on field 'x' (a table value)

I'm working with lua-alchemy, and I'm setting a global variable in my AS3 code in this way:
_lua.setGlobal("map", _map);
With _map being a object with the following function in it:
public function get x():int
{
return 10;
}
if then I try to do something like this in Lua
local a = map.x + 1
I get the following error:
Lua script failed: luaDoString:21: attempt to perform arithmetic on field 'x' (a table value)
Does anyone knows why it does that, and how I could fix it?
EDIT :
When I print type(map.id), it prints table... Shouldn't it print number?
I found my error. According to this page, I have to use as3.tolua(map.x) to convert it to the right type.

in iOS sqlite getting insertion error for html strings

I am in the requirement of saving the html strings in SQLite Database. While running the insert query, I am getting a syntax error near the style tag of the HTML file.
Here is the code:
-(BOOL)insertAttendees{
sqlite3_stmt *statement;
NSString *insertSQL;
BOOL var=NO;
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
//work only for the 1st event
for (int i=0; i<[attendeeCount[0]integerValue];i++)
{
insertSQL = [NSString stringWithFormat:#"INSERT INTO ATTENDEE (A_NAME,A_IMAGE,A_EMAIL,A_PHONE,A_BIO) VALUES (\"%#\",\"%#\", \"%#\",\"%#\",\"%#\")",arrayOf_AName[0][i],arrayOf_AImage[0][i],arrayOf_AEmail[0][i],arrayOf_APhone[0][i],arrayOf_ABio[0][i]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(db, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
var=YES;
}
else
{
NSLog(#"sqlite insertion error %s", sqlite3_errmsg(db));
var=NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
return var;
}
return var;
}
There are a whole bunch of issues here:
The root of the problem is that you're building your SQL using stringWithFormat, which you should not do. If your values contained a quotation mark in them (such as might be near your style tag in your HTML), your SQLite code would fail. Instead, you should:
Your SQL should use ? placeholders (note, no quotation marks in the SQL, either):
const char *insert_stmt = "INSERT INTO ATTENDEE (A_NAME,A_IMAGE,A_EMAIL,A_PHONE,A_BIO) VALUES (?,?,?,?,?)";
Then you should then bind values with something like:
if (sqlite3_bind_text(statement, 1, [string UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
NSLog(#"%s: bind column 1 failed: %s", __FUNCTION__, sqlite3_errmsg(db));
}
where string is the NSString value you want to insert, and that second parameter (1, in the above example) is the index of the ? placeholder that you're binding to the text value (where the leftmost placeholder has an index of one).
Only after you've called sqlite3_bind_xxxx() for each of the five ? placeholders, then you can proceed by calling sqlite3_step(), etc.
A second problem is that you are not checking to see if sqlite3_prepare_v2 succeeded or not. This is significant because the meaningful error messages you would have seen if you called sqlite3_errmsg immediately after the prepare statement failed is now lost. You're ignoring any potential prepare error, proceeding with sqlite3_step regardless, and so the meaningful error message will be replaced with one that effectively (but cryptically) says that you called sqlite3_step without first successfully calling sqlite3_prepare_v2.
So, check to make sure if sqlite3_prepare_v2 succeeded, and if it failed, check sqlite3_errmsg immediately before doing any other SQLite calls.
Once you solve the above two issues, you might consider optimizing your code a little. Notably, if you perform a BEGIN TRANSACTION before all of your INSERT statements, and COMMIT TRANSACTION when you're done with all of your inserts, it will be much faster. If you're only inserting a couple of records it might not be observable, but if inserting a lot of records, the performance gain can be staggering.
As yet a further optimization, let's imagine that you addressed my above points (notably, eliminated stringWithFormat for the SQL and used ? placeholders instead) and you had something like the following pseudo code (but obviously checking all of the sqlite3 function return values and handling errors properly):
sqlite3_exec("begin transaction");
for (i = 0; i < whatever; i++) {
sqlite3_prepare(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_step();
sqlite3_finalize();
}
sqlite3_exec("commit transaction");
Rather than preparing the same SQL many times, you can prepare it once, bind the values, perform the step, and then reset the bindings so you can do it again:
sqlite3_exec("begin transaction");
sqlite3_prepare(...);
for (i = 0; i < whatever; i++) {
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_bind(...);
sqlite3_step();
sqlite3_reset();
}
sqlite3_finalize();
sqlite3_exec("commit transaction");
Personally, I'd suggest you focus on points 1 and 2 above, and only once you fix the fundamental problem should you contemplate the optimizations of points 3 and 4. Make sure you've got it working before you bother to optimize it.
Finally, I'd be remiss if I didn't point out that you really should contemplate the wonderful third-party FMDB Objective-C wrapper around the SQLite C interface. When you write proper SQLite code, that is binding each value, checking each return code, etc., it gets unwieldy quickly. FMDB greatly simplifies your code.
If you really want to insert HTML in sqlite database then replace all " with \" before executing the query.
(You have't mentioned that whether you are replacing special characters or not).
Suppose, you are doing this..
"SELECT * FROM table WHERE someColume = <div style="width:25px"></div>"
It will fail right after style=" because sqlite will try to execute "SELECT * FROM table WHERE someColume = <div style=",
But if you replace " with \", then your final query will look like this -
"SELECT * FROM table WHERE someColume = <div style=\"width:25px\"></div>"
Good luck.

Breaking sql statement in Linq in 2 or more parts, depends on program condition

I'm a principiant of Linq so i need some help..
I don’t know if in Linq syntax by breaking a query in 2 or more parts,
just like the following example,
the records will be downloaded immediatly from sql server in each step,or they will be sent to server at the moment when I’ll start to see all the data?
for exemple when I bind some objects (a Datagrid for exemple)
System.Linq.IQueryable<Panorami> Result = db.Panorami;
byte FoundOneContion = 0;
//step 1
if (!string.IsNullOrEmpty(Title))
{
Result = Result.Where(p => SqlMethods.Like(p.Title, "%" + Title + "%"));
FoundOneContion = 1;
}
//step 2
if (!string.IsNullOrEmpty(Subject))
{
Result = Result.Where(p => SqlMethods.Like(p.Subject, "%" + Subject + "%"));
FoundOneContion = 1;
}
if (FoundOneContion == 0)
{
return null;
}
else
{
return Result.OrderBy(p => p.Title).Skip(PS * CP).Take(PS);
}
If unfortunatly Linq download immediately all the records
(Therefore such a doubt I have had was right!)
exist any syntax to round the problem?
For example: ternary operator ( condition ? true part : false part )
For any suggestions i would appreciate them a lot. thanks everyone!
The above method does not enumerate the query - therefore no database calls are made. The query is constructed and not executed.
You can enumerate the query by calling foreach, or calling some method that calls foreach (such as ToList, ToArray), or by calling GetEnumerator(). This will cause the query to execute.