How to fix scanner while error - if-statement

Back again with CacheScript, this time an easier question.
Here is the problem code:
while (open.hasNext() == true) {
String code = open.nextLine();
if (code.equals("CacheScript")) {
JOptionPane.showMessageDialog(this, "Package Successfully Loaded.");
txtBar.setText("Cache Script 2014");
}
if (code.equals("cache.color.orange")) {
map.setBackground(Color.orange);
}
}
For some reason, when I run this, the scanner (open) does not follow through... How can I fix the while code so each line can be tested to see if it equals one of the commands?

Try this;
while (open.hasNext() == true) {
if (code.equals("CacheScript")) {
JOptionPane.showMessageDialog(this, "Package Successfully Loaded.");
txtBar.setText("Cache Script 2014");
}
if (code.equals("cache.color.orange")) {
map.setBackground(Color.orange);
}
String code = open.nextLine();
continue;
}

Related

clang-format: empty line before and after control statements

Is there any possibility to achieve inserting an empty line before and after control statemets (for, if etc.)?
E.g. I have the following source code:
if(bCondition)
{
// some code
}
for(int i : vecOfInts)
{
// some code
}
if(bAnotherCondition)
{
// some code
}
and this is what I want:
if(bCondition)
{
// some code
}
for(int i : vecOfInts)
{
// some code
}
if(bAnotherCondition)
{
// some code
}
Reading the official documentation, https://clang.llvm.org/docs/ClangFormatStyleOptions.html , there seems to be no such option.

Return error message if the command is wrong in C++

I'm working on this project where I set up some commands that my TelegramBot can execute. And I would like to add an error message if the command written is wrong. Here is the code:
void handleNewMessages(int numNewMessages){
Serial.print("Handle New Messages: ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++){
// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != chatId){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
// Print the received message
String text = bot.messages[i].text;
Serial.println(text);
String fromName = bot.messages[i].from_name;
if (text == "/FlashOn") {
flashState = HIGH;
digitalWrite(LED, flashState);
}
if (text == "/FlashOff") {
flashState = LOW;
digitalWrite(LED, flashState);
}
if (text == "/photo") {
sendPhoto = true;
Serial.println("New photo request");
}
if (text == "/PIRON"){
PirControler = 1;
bot.sendMessage(chatId, "PIR Sensor is ON, you will get a notification if a motion is detected.", "");
}
if (text == "/PIROFF"){
PirControler = 0;
bot.sendMessage(chatId, "PIR sensor is OFF, you will no longer receive any notification.", "");
if (text == "/start"){
String welcome = "Hi sir, here are the commands I can execute for you :\n";
welcome += "/Photo : Take a new photo.\n";
welcome += "/FlashOn : Turns LED On.\n";
welcome += "/FlashOff : Turns LED off\n";
welcome += "/PIRON : Activate your PIR sensor.\n";
welcome += "/PIROFF : Shut your PIR sensor down.\n";
// welcome += "/readings : request sensor readings\n\n";
welcome += "You'll receive a photo whenever motion is detected.\n";
bot.sendMessage(chatId, welcome, "Markdown");
}
/*else {
bot.sendMessage(chatId, "I don't understand, sorry. Refer to the commands I showed you above.", "");
} **(Here is the message that I'd like to add)**
}
}
However, by trying to add the last line,
/*else {
bot.sendMessage(chatId, "I don't understand, sorry. Refer to the commands I showed you above.", "");
}*/
It returns an error to all the right commands except for the "/start" one.
Any ideas on how I could do that would be much appreciated :)
Let's make the example smaller
if (text == "/FlashOn") {
do stuff
}
if (text == "/start"){
do stuff
}
else {
report error
}
This code will always test if (text == "/start") regardless of the outcome of if (text == "/FlashOn") and if text is "/FlashOn", it cannot be "/start" and will execute the else and print the error message.
Solution
if (text == "/FlashOn") {
do stuff
}
else if (text == "/start"){
do stuff
}
else {
report error
}
Now if (text == "/start") will not be tested and the else case will not be run if text == "/FlashOn".
What this looks like if fully indented and bracketed:
if (text == "/FlashOn") {
do stuff
}
else {
if (text == "/start"){
do stuff
}
else {
report error
}
}

How to use parameters using MySQL and a TADOQuery instance?

I have a TADOConnection pointing to a MySQL 8.0 instance. The connection is tested and it works. Following this example on how to use prepared statement, I'm having an error and I have no idea why.
The following code works fine, it will return true from the very last statement. No errors, no warnings.
AnsiString sqlQuery = "SELECT e.name FROM employee e WHERE e.id = 1;";
if (!_query->Connection->Connected) {
try {
_query->Connection->Connected = true;
} catch (EADOError& e) {
return false;
}
}
_query->SQL->Clear();
_query->SQL->Add(sqlQuery);
_query->Prepared = true;
try {
_query->Active = true;
if (_query->RecordCount == 0) {
return false;
}
} catch (EADOError& e) {
return false;
}
return true;
However, the following code fails executing _query->SQL->Add(sqlQuery); with this error:
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
AnsiString sqlQuery = "SELECT e.name FROM employee e WHERE e.id = :id;";
if (!_query->Connection->Connected) {
try {
_query->Connection->Connected = true;
} catch (EADOError& e) {
return false;
}
}
_query->SQL->Clear();
_query->SQL->Add(sqlQuery); // <---- EOleException here
_query->Parameters->ParamByName("id")->Value = id;
_query->Prepared = true;
try {
_query->Active = true;
if (_query->RecordCount == 0) {
return false;
}
} catch (EADOError& e) {
return false;
}
return true;
Everywhere I find examples, all of them use :paramName to specify parameters. What am I missing?
Update 1
I have tried changing the code like this :
_query->SQL->Clear();
TParameter * param = _query->Parameters->AddParameter();
param->Name = "id";
param->Value = 1;
_query->SQL->Add(sqlQuery); // <---- EOleException still here
Some forum post suggests to switch the Advanced Compiler option "Register Variables" to "None", but this is already the setting of my project, and the exception is still thrown.
Update 2
I can ignore the error, and everything gets executed just fine, however it fails whenever I perform a step-by-step execution. Of course, I can still put a breakpoint after, and jump right over the faulty line, but it's still annoying and does not explain why there is this error there in the first place.
The exception is on setting the SQL string - which tells you that it's wrong. As per #RogerCigol's comment, you should NOT have the ; at the end of your SQL string.
Kudos to Roger for that.
If you want to access parameters, you MUST set the SQL string first, it will be parsed to identify the parameters. The parameters will not exist until the string is parsed, or you manually create them (which is pointless as they would be recreated on parsing the string).
You can also access the parameters as an ordered index, and I have always been able to use ? as an anonymous parameter with MySQL.

How to refactor code that is using PPL heavily. C++

So I have function that looks like this
task<shared_ptr<myObjectsResult>> task1 = create_task([this,token, stream]
{
// Here I have code that is working, but I would like to refactor it
// maybe even make it go after or before this surrounding task.
create_task(BitmapDecoder::CreateAsync(stream)).then([this, token]
(BitmapDecoder^ bitmapDecoder)
{
create_task(bitmapDecoder->GetSoftwareBitmapAsync()).then([this, token]
(SoftwareBitmap^ softwareBitmap)
{
OcrEngine^ ocrEngine = OcrEngine::TryCreateFromUserProfileLanguages();
if (ocrEngine != nullptr)
{
create_task(ocrEngine->RecognizeAsync(softwareBitmap)).then([fileInfo, this, transactionPriority, token]
(OcrResult^ ocrResult)
{
doSomethingWithText(OcrResult->Text->Data());
});
}
});
});
...
return runAsyncFunctionThatReturnsMyObjectResultTask(token);
});
It works and all is great, but I want to move OCR logic to some other part of code not in here, but I would love to call it from here.
What I have tried is creating
task<OcrResult^> GetOCRTextFromStream(_In_ IRandomAccessStream^ stream)
{
create_task(BitmapDecoder::CreateAsync(stream)).then([]
(BitmapDecoder^ bitmapDecoder)
{
create_task(bitmapDecoder->GetSoftwareBitmapAsync()).then([]
(SoftwareBitmap^ softwareBitmap)
{
OcrEngine^ ocrEngine = OcrEngine::TryCreateFromUserProfileLanguages();
if (ocrEngine != nullptr)
{
return create_task(ocrEngine->RecognizeAsync(softwareBitmap));
}
else
{
OcrResult^ ocrResult = nullptr;
return concurrency::task_from_result(ocrResult);
}
}
}
and then call this.
GetOCRTextFromStream(stream).then([this, token]
(OcrResult^ ocrResult)
{
doSomethingWithText(OcrResult->Text->Data());
}
Ofcourse this does not work, but you get what I want, I just want to refactor this, and I just cannot understand how to do what I want, and if it is doable (I guess it is?)
Thanks all and sorry if my question is nooby :)
This is C++/CX, and solution is to put return.
This should work if you just add return in front of two create_task that you have
return create_task([]
{
return create_task([]
{
...
}
}

If statement with 1 condition has 4 branches in code coverage tool

While looking at the following results from codecov I noticed that the if statement at line 40 has 4 branches instead of 2 as I was expecting.
if (!m_helper->getCwd(cwd)) {
throw std::runtime_error("Couldn't get current working dir");
}
Has this anything to do with the exception?
How do I get full coverage of that statement with the unit tests?
You can find the project here: https://github.com/pamarcos/gencc/
Edit:
The code of getCwd is available here:
bool HelperImpl::getCwd(std::string& str)
{
if (getcwd(reinterpret_cast<char*>(m_buffer.data()), sizeof(m_buffer)) == nullptr) {
str.clear();
return false;
}
str = reinterpret_cast<char*>(m_buffer.data());
return true;
}