kotlin fun with string concatenation - function

I need help concatenating a string in a kotlin viewmodel. I am trying to return what the code should print to the status text view. The formula determines from a Int what the status should be then outputs a message to the User. I am unsure as to what method should be used to create a string that I wanted to return.
fun formula(f: Int, b: Int, l: Int, d: Int) : String {
if (f > 70 && f < 99) {
val ftxt = "Normal"
} else if (f < 71) {
val ftxt = "Hypoglycemic"
}
if (b > 140) {
val btxt = "Abnormal"
} else if (b < 71) {
val btxt = "Hypoglycemic"
}
if (l > 140) {
val ltxt = "Abnormal"
} else if (l < 71) {
val ltxt = "Hypoglycemic"
}
if (d > 140) {
val dtxt = "Abnormal"
}else if (d < 71) {
val dtxt = "Hypoglycemic"
}
else {
val ftxt = "Abnormal"
val btxt = "Normal"
val ltxt = "Normal"
val dtxt = "Normal"
}
var status = calendar.toString()
status += "\n Fasting: "
status += ftxt + "\n Breakfast: "
status += btxt + "\n Lunch: "
status += ltxt + "\n Dinner: " + dtxt
return status
}

Without entering into detail on how you could improve your function you're having the "red squiggles" because those val are declared within the scope of the if-else blocks.
You can declare them out of the block and assign values:
fun formula(f: Int, b: Int, l: Int, d: Int) : String {
var ftxt = ""
var btxt = ""
var ltxt = ""
var dtxt = ""
if (f > 70 && f < 99) {
ftxt = "Normal"
} else if (f < 71) {
ftxt = "Hypoglycemic"
}
if (b > 140) {
btxt = "Abnormal"
} else if (b < 71) {
btxt = "Hypoglycemic"
}
if (l > 140) {
ltxt = "Abnormal"
} else if (l < 71) {
ltxt = "Hypoglycemic"
}
if (d > 140) {
dtxt = "Abnormal"
}else if (d < 71) {
dtxt = "Hypoglycemic"
}
else {
ftxt = "Abnormal"
btxt = "Normal"
ltxt = "Normal"
dtxt = "Normal"
}
var status = calendar.toString()
status += "\n Fasting: "
status += ftxt + "\n Breakfast: "
status += btxt + "\n Lunch: "
status += ltxt + "\n Dinner: " + dtxt
return status
}

Related

Lua - Exception has occurred: attempt to call a nil value

I run the following code, but Lua keeps giving me "attempt to call a nil value". When I change the _G[fi] to _G.fi it gives me "attempt to call a string value".
i = "0"
j = "0"
k = "0"
fi = "f"..i
fj = "f"..j
fk= "f"..k
functions = {
f1 = function(next, v)
for t = 1, 1, 4 do
v[t] = v[t] + 1
v[t] = v[t] % 3
end
if (next == "0") then return v
else return functions[next](0, v) end
end,
f2 = function(next, v)
for t = 1, 1, 4 do
v[t] = v[t] + 2
v[t] = v[t] % 3
end
if (next == "0") then return v
else return functions[next](0, v) end
end,
f3 = function(next, v)
if (next == "0") then return v
else return functions[next](0, v) end
end,
f4 = function(next, v)
swap(v[2], v[3])
if (next == "0") then return v
else return functions[next](0, v) end
end,
f5 = function(next, v)
swap(v[1], v[3])
if (next == "0") then return v
else return functions[next](0, v) end
end,
f6 = function(next, v)
swap(v[1], v[2])
if (next == "0") then return v
else return functions[next](0, v) end
end,
}
for i = 0, 1, 6 do
for j = 0, 1, 6 do
for k = 0, 1, 6 do
if _G[fi](fj, {1,2,0}) == _G[fj](fk, {1,2,0}) and not _G[fi](-1, {1,2,0}) == _G[fk](-1, {1,2,0}) then
print(i + " " + j + " " + k)
end
end
end
end
The problem is you set fi = "f"..i at the start, which sets fi == "f0", and that never changes for the rest of the program until you later invoke _G[fi]. The value of fi does not automatically change just because you changed the value of i.
You probably want to expand i (and j and k) at the call point, with something more like:
_G["f"..i]("f"..j, {1,2,0})... etc

CountTime in AS3

I have received the same error after I tested the timed game:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BlowfishPong_fla::MainTimeline/countTime()
function countTime(e: Event): void {
if (stopwatch.currentFrame == 61) {
seconds++;
speedSeconds++;
if (seconds > 59 && speedSeconds > 59) {
seconds = 0;
speedSeconds = 0;
speedtimerSec_txt.text = "0" + speedSeconds;
timerSec_txt.text = "0" + seconds;
minutes++;
speedMinutes++;
if (minutes > 10 && speedMinutes > 10) {
speedtimerMin_txt.text = "" + speedMinutes;
timerMin_txt.text = "" + minutes;
}
else {
speedtimerMin_txt.text = "0" + speedMinutes;
timerMin_txt.text = "0" + minutes;
}
if (minutes > 59 && speedMinutes > 59) {
stopwatch.stop();
gotoAndPlay("gameover_Timed");
}
}
else {
if (seconds >= 10 && speedSeconds >= 10) {
speedtimerSec_txt.text = "" + speedSeconds;
timerSec_txt.text = "" + seconds;
}
else {
speedtimerSec_txt.text = "0" + speedSeconds;
timerSec_txt.text = "0" + seconds;
}
}
}
}
Can you check this code to this problem?

Fuzzy matching of an OCR output in text file

I have a question regarding partial match of two strings.
I have a string and I need to validate it. To be more specific, I have an output from OCR reading and it contains some mistakes, of course. I need to check if the string is really there but as it can be written incorrectly I need only 70% match.
Is it possible to do that in UiPath? The string is in notepad (.txt) so any idead would be helpful.
Try passing OCR output/words_detected against a base word.(double fuzzyness is 0-1)
list<string> Search(string word, list<string> wordList, double fuzzyness) {
list<string> foundWords;
for (string s : wordList) {
int levenshteinDistance = LevenshteinDistance(word, s);
int length = max(word.length(), s.length());
double score = 1.0 - (double)levenshteinDistance / length;
if (score > fuzzyness) foundWords.push_back(s);
}
if (foundWords.size() > 1) {
for (double d = fuzzyness; ; d++) {
foundWords = Search(word, wordList, d);
if (foundWords.size() == 1) break;
}
}
return foundWords;}
int LevenshteinDistance(string src, string dest) {
std::vector<vector<int>> d;
d.resize((int)src.size() + 1, std::vector<int>((int)dest.size() + 1, 0));
int i, j, cost;
std::vector<char> str1(src.begin(), src.end());
std::vector<char> str2(dest.begin(), dest.end());
for (i = 0; i <= str1.size(); i++) d[i][0] = i;
for (j = 0; j <= str2.size(); j++) d[0][j] = j;
for (i = 1; i <= str1.size(); i++) {
for (j = 1; j <= str2.size(); j++) {
if (str1[i - 1] == str2[j - 1]) cost = 0;
else cost = 1;
d[i][j] = min(d[i - 1][j] + 1, min(d[i][j - 1] + 1, d[i - 1][j - 1] + cost));
if ((i > 1) && (j > 1) && (str1[i - 1] == str2[j - 2]) && (str1[i - 2] == str2[j - 1])) d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost);
}
}
return d[str1.size()][str2.size()];}

Divide function

I need to write the divide function in the Jack language.
my code is:
function int divide(int x, int y) {
var int result;
var boolean neg;
let neg = false;
if(((x>0) & (y<0)) | ((x<0) & (y>0))){
let neg = true;
let x = Math.abs(x);
let y = Math.abs(y);
}
if (y>x){
return 0;
}
let result = Math.divide(x, y+y);
if ((x-(2*result*y)) < y) {
if (neg){
return -(result + result);
} else {
return (result + result);
}
} else {
if (neg){
return -(result + result + 1);
} else {
return (result + result + 1);
}
}
}
this algorithm is sub-optimal since each multiplication operation also requires O(n) addition and subtraction operations.
Can I compute the product 2*result*y without any multiplication?
Thanks
Here's an implementation of (unsigned) restoring division (x/y), I don't actually know Jack though so I'm not 100% sure about this
var int r;
let r = 0;
var int i;
let i = 0;
while (i < 16)
{
let r = r + r;
if ((x & 0x8000) = 0x8000) {
let r = r + 1;
}
if ((y ^ 0x8000) > (r ^ 0x8000)) { // this is an unsigned comparison
let x = x + x;
}
else {
let r = r - y;
let x = x + x + 1;
}
let i = i + 1;
}
return x;
You should be able to turn that into signed division.

How to export (dump) WebSQL data

I'm working on a Chrome Extension that uses WebSQL to store historical data.
Being WebSQL, the DB is stored on the client.
I'd like to add an option to export/import such data so that the user can share/use this data with other users, or with other PCs.
These are my first steps on a client-only database, so I wonder how to do this.
I was thinking to convert the DB to a huge json string that the user can copy/paste but doesn't look very user-friendly.
Is there any better solution?
I got a single table dump solution working on a HTML5 database client I wrote a few days ago.
Check out http://html5db.desalasworks.com/script.js and scroll down to SqlClient.exportTable, this has an example that needs to be expanded to cover the whole database.
The steps are:
Step 1: Create the schema:
SELECT sql FROM sqlite_master
Step 2: Get a list of tables:
SELECT tbl_name from sqlite_master WHERE type = 'table'
Step 3: Loop through each of them and create an INSERT script with the results
transaction.executeSql("SELECT * FROM " + _tbl_name + ";", [],
function(transaction, results) {
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var _fields = [];
var _values = [];
for (col in row) {
_fields.push(col);
_values.push('"' + row[col] + '"');
}
_exportSql += ";\nINSERT INTO " + _tbl_name + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ")";
}
}
}
);
Hope this is useful.
UPDATE JAN 2016 - WHOLE DB EXPORT
I've got a JS websqldump library that you can download from github as well.
This one will export the whole database. Check out the code on:
https://github.com/sdesalas/websqldump
Usage as follows
websqldump.export({
database: 'NorthwindLite',
success: function(sql) {alert(sql);}
});
Not the most elegant way, yet most convenient.
Just paste the script in chrome debugger tools then call c(), and you should get the file.
var looongSQL = "";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows) {
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _fields = [];
var _values = [];
for (col in dataRow) {
_fields.push(col);
_values.push('"' + dataRow[col] + '"');
}
looongSQL += "INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ");\n";
}
}
options.n++;
x(options);
}
);
});
}else
{
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE TABLE ") != -1 && row.sql.indexOf("__") == -1) {
var tableName = row.sql.replace("CREATE TABLE ", "").split(/ |\(/)[0];
sqlStatements.push('DROP TABLE IF EXISTS ' + tableName);
}if(row.sql != null && row.sql.indexOf("__") == -1){
sqlStatements.push(row.sql);}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ';\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0
});
});
}
);
});
};
Another version that exports it as JSON
var looongSQL = "[\n";
var stringidiedLocalStorage = JSON.stringify(JSON.stringify(localStorage));
looongSQL += "/* 1 */ " + stringidiedLocalStorage + ",\n";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows && rslt.rows.length > 0) {
var _fields = [];
for (var col in rslt.rows.item(0)) {
_fields.push(col);
}
var insertTableSQL = "\"INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") ";
looongSQL += "/* " + options.count + " */ " + insertTableSQL;
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _values = [];
for (var col in dataRow) {
_values.push('\'' + dataRow[col] + '\'');
}
looongSQL += "SELECT " + _values.join(",");
if (m < rslt.rows.length - 1 && (m % 499 != 0 || m == 0)) {
looongSQL += " UNION ALL ";
}
if (m % 499 == 0 && m != 0) {
options.count++;
looongSQL += "\",\r\n/* " + options.count + " */ " + insertTableSQL;
}
}
looongSQL += "\",\r\n";
options.count++;
}
options.n++;
x(options);
}
);
});
} else {
looongSQL += ']';
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
var count = 2;
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE ") != -1) {
var objectType = row.sql.replace("CREATE ", "").split(/ |\(/)[0];
if (row.sql.indexOf("CREATE " + objectType + " ") != -1 && row.sql.indexOf("__") == -1) {
var objectName = row.sql.replace("CREATE " + objectType + " ", "").split(/ |\(/)[0];
sqlStatements.push('/* ' + count + ' */ "DROP ' + objectType + ' IF EXISTS ' + objectName + '"');
count++;
}
if (row.sql != null && row.sql.indexOf("__") == -1) {
sqlStatements.push('/* ' + count + ' */ "' + row.sql.replace(/(\r\n|\n|\r)/gm, " ") + '"');
count++;
}
}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ',\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0,
count: count
});
});
}
);
});
};