I am actually trying to edit the etherhost2 function to send to several destinations and I reached a point where it is possible only for the first time.
In the original code the function is working properly by just moving the two functions sendBurstPackets() and scheduleNextPacket(simTime()) in if condition with destMACAddress = resolveDestMACAddress() those two functions are only called once.
Does that mean that destMacAddress is set once through the whole simulation?
Original Code
void EtherTrafGen::handleMessage(cMessage *msg)
{
if (!isNodeUp())
throw cRuntimeError("Application is not running");
if (msg->isSelfMessage()) {
if (msg->getKind() == START) {
destMACAddress = resolveDestMACAddress();
// if no dest address given, nothing to do
if (destMACAddress.isUnspecified())
return;
}
sendBurstPackets();
scheduleNextPacket(simTime());
}
else
receivePacket(check_and_cast<cPacket *>(msg));
}
My Changes
void EtherTrafGen::handleMessage(cMessage *msg)
{
if (!isNodeUp())
throw cRuntimeError("Application is not running");
if (msg->isSelfMessage()) {
if (msg->getKind() == START) {
if (!multipacket)
{
destMACAddress = resolveDestMACAddress();
sendBurstPackets();
scheduleNextPacket(simTime());
}
// if no dest address given, nothing to do
if (destMACAddress.isUnspecified())
return;
}
}
else
receivePacket(check_and_cast<cPacket *>(msg));
}
The first message is only true for that condition (msg->getKind() == START), which means the the mac is set once for each host through the whole simulation. Removing that condition made it work.
I am worried if there are other self messages that might be mistaken with that function. Would be better to have separate EtherHost app that only works for my simulation.
If there is an idea how to look at all self messages, I would appreciate if some one informed me.
Related
I've been trying to use and understand the DirectoryWatcher class from Microsoft's Cloud Mirror sample. It uses ReadDirectoryChangesW to monitor changes to a directory. I don't think it's reporting all changes, to be honest. In any event, I had a question about the key part of the code, which is as follows:
concurrency::task<void> DirectoryWatcher::ReadChangesAsync()
{
auto token = _cancellationTokenSource.get_token();
return concurrency::create_task([this, token]
{
while (true)
{
DWORD returned;
winrt::check_bool(ReadDirectoryChangesW(
_dir.get(),
_notify.get(),
c_bufferSize,
TRUE,
FILE_NOTIFY_CHANGE_ATTRIBUTES,
&returned,
&_overlapped,
nullptr));
DWORD transferred;
if (GetOverlappedResultEx(_dir.get(), &_overlapped, &transferred, 1000, FALSE))
{
std::list<std::wstring> result;
FILE_NOTIFY_INFORMATION* next = _notify.get();
while (next != nullptr)
{
std::wstring fullPath(_path);
fullPath.append(L"\\");
fullPath.append(std::wstring_view(next->FileName, next->FileNameLength / sizeof(wchar_t)));
result.push_back(fullPath);
if (next->NextEntryOffset)
{
next = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(reinterpret_cast<char*>(next) + next->NextEntryOffset);
}
else
{
next = nullptr;
}
}
_callback(result);
}
else if (GetLastError() != WAIT_TIMEOUT)
{
throw winrt::hresult_error(HRESULT_FROM_WIN32(GetLastError()));
}
else if (token.is_canceled())
{
wprintf(L"watcher cancel received\n");
concurrency::cancel_current_task();
return;
}
}
}, token);
}
After reviewing an answer to another question, here's what I don't understand about the code above: isn't the code potentially re-calling ReadDirectoryChangesW before the prior call has returned a result? Or is this code indeed correct? Thanks for any input.
Yes, I seem to have confirmed in my testing that there should be another while loop there around the call to GetOverlappedResultEx, similar to the sample code provided in that other answer. I think the notifications are firing properly with it.
Shouldn't there also be a call to CancelIo in there, too? Or is that not necessary for some reason?
Following this answer, I'm doing consecutive ray casts:
m_rayCaster = new Qt3DRender::QRayCaster(m_scene->rootEntity());
m_rayCaster->setRunMode(Qt3DRender::QAbstractRayCaster::SingleShot);
m_scene->rootEntity()->addComponent(m_rayCaster);
I have these slots to handle whether and when next consecutive ray cast test should be done:
QObject::connect(m_rayCaster, &Qt3DRender::QRayCaster::hitsChanged, this, &RayCastHandler::handleRayCasterHits);
QObject::connect(m_rayCaster, &Qt3DCore::QNode::enabledChanged, this, &RayCastHandler::handleRayCasterEnabledChange);
QObject::connect(this, &RayCastHandler::isPreviousTestDoneChanged, this, &RayCastHandler::handleIsPreviousTestDoneChange);
QObject::connect(this, &RayCastHandler::isNextTestRequiredChanged, this, &RayCastHandler::handleIsNextTestRequiredChange);
The slots set the conditions and check them:
void RayCastHandler::handleRayCasterHits(const Qt3DRender::QAbstractRayCaster::Hits hits)
{
analyzeHits(hits);
bool required = isNextTestRequired(/* according to m_testCounter, m_testsTotal, ... */);
emit isNextTestRequiredChanged(required);
emit isPreviousTestDoneChanged(true);
return;
}
void RayCastHandler::handleRayCasterEnabledChange(const bool enabled)
{
m_isRayCasterEnabled = enabled;
triggerNextTestIfAllConditionsAreTrue();
return;
}
void RayCastHandler::handleIsPreviousTestDoneChange(const bool done)
{
m_isPreviousTestDone = done;
triggerNextTestIfAllConditionsAreTrue();
return;
}
void RayCastHandler::handleIsNextTestRequiredChange(const bool required)
{
m_isNextTestRequired = required;
if (!m_isNextTestRequired)
emit rayCastResultsChanged(m_collisions);
triggerNextTestIfAllConditionsAreTrue();
return;
}
The code which checks if next ray cast test is required:
bool RayCastHandler::isNextTestRequired(int &testCounter, const int &testsTotal)
{
testCounter++;
if (testCounter >= testsTotal) {
return false;
}
return true;
}
And finally, the function which checks all the conditions to trigger next ray cast test is:
bool RayCastHandler::triggerNextTestIfAllConditionsAreTrue()
{
if (m_isPreviousTestDone && m_isNextTestRequired && m_isRayCasterEnabled) {
triggerTest(/* Will trigger next ray cast test */);
m_isPreviousTestDone = false;
m_isNextTestRequired = false;
m_isRayCasterEnabled = false;
}
}
The code works fine, but after casting a few consecutive rays, it stops.
By logging to console, I observe that the m_rayCaster looks to be enabled/disabled randomly. I mean sometimes after finishing a ray cast test, it disables itself, and sometimes it enables itself! I wonder if anybody can introduce a reference on Qt3DRender::QRayCaster enabling/disabling logic. I looked at its source code a bit, I wonder which section of source code might help me to figure out.
Just wanted to share my observations:
I simplified the code by keeping only two signal-slot connections:
QObject::connect(m_rayCaster, &Qt3DRender::QRayCaster::hitsChanged, this, &RayCastHandler::handleRayCasterHits);
QObject::connect(m_rayCaster, &Qt3DCore::QNode::enabledChanged, this, &RayCastHandler::handleRayCasterEnabledChange);
One slot analyzes the hits of ray-caster:
void RayCastHandler::handleRayCasterHits(const Qt3DRender::QAbstractRayCaster::Hits hits)
{
analyzeHits( ... , hits);
return;
}
The other slot runs the next consecutive ray-cast test, if ray-caster has disabled itself:
void RayCastHandler::handleRayCasterEnabledChange(const bool enabled)
{
// When the component disables itself, it is ready for the next ray-cast test
if (!enabled) {
bool required = isNextTestRequired( ... );
if (required)
triggerTest( ... );
else
// Send final ray-cast results by a signal, if next test is NOT needed
emit rayCastResultsChanged( ... );
}
return;
}
The above code works as long as I trigger ray-cast tests with a time-delay. Sometimes I have to increase the above delay time to make it work. But at least it works. Although it is painful since it is NOT reliable:
void RayCastHandler::triggerTest( ... )
{
...
// 1 millisecond delay time
QTimer::singleShot(1, [rayCaster, origin, direction, length](){rayCaster->trigger(origin, direction, length);});
...
}
However, if I use no delay time, at some point, the ray caster stops unexpectedly, without sending any signal containing hit results, and ray caster stays enabled forever. Looks like ray-caster gets stuck:
void RayCastHandler::triggerTest( ... )
{
...
// No delay
rayCaster->trigger(origin, direction, length);
...
}
I am new to AVR programming, and I am trying to implement a sharp right turn using atmega8. I was able to implement the straight line path but cannot implement a sharp right turn. Here is my code:
`#include <avr/io.h>
#include<util/delay.h>
int main(void)
{
DDRC=0b00000000;
DDRB=0b11111111;
int count=1,right=1;
while(1)
{
if((PINC&=0b00011111)==0b00000000)
{
PORTB=0b00000110;
}
else if((PINC&=0b00011111)==0b00001110)
{
PORTB=0&00100111;
}
else if((PINC&=0b00011111)==0b00001100)
{
PORTB=0b00000111;
}
else if((PINC&=0b00011111)==0b00000110)
{
PORTB=0b00100110;
}
else if((PINC&=0b00011111)==0b00001111)
{
if(count)
{
PORTB=0b0010011;
_delay_ms(200);
count--;
}
else if(((PINC&=0b00011111)==0b00000110)&&~(count))
{
PORTB=0B00000111;
}
}
else if((PINC&=0b00011111)==0b00011110)
{
if(right)
{
PORTB=0b0010011;
_delay_ms(200);
right--;
}
else if(((PINC&=0b00011111)==0b00000110)&&~(right))
{
PORTB=0B00100110;
}
}
}
}
This doesn't seem to work at all for right and left turns.
Any idea where I am going wrong?
Without understanding your Program (see my Comment above) iam guessing it is because you permanently write to your PIN-regsiters in the if-clauses.
PINC&=0b00011111 means:
read PINC-value
binary AND it with 0b00011111
write the result back to PINC
Depending on which AVR your code is running you toggle the output by writing a 1 to a PINX-register bit. If DDR is configured to input you toggle the pullups. This is true for the newer AVR-cores. For the old one its undefined behavior to write to the PIN-registers as they are defined as read-only.
I have a series of QTextEdits and QLineEdits connected to a slot through a QSignalMapper(which emits a textChanged(QWidget*) signal). When the connected slot is called (pasted below), I need to be able to differentiate between the two so I know whether to call the text() or toPlainText() function. What's the easiest way to determine the subclass type of a QWidget?
void MainWindow::changed(QWidget *sender)
{
QTextEdit *temp = qobject_cast<QTextEdit *>(sender);
QString currentText = temp->toPlainText(); // or temp->text() if its
// a QLineEdit...
if(currentText.compare(""))
{
...
}
else
{
...
}
}
I was considering using try-catch but Qt doesn't seem to have very extensive support for Exceptions... Any ideas?
Actually, your solution is already almost there. In fact, qobject_cast will return NULL if it can't perform the cast. So try it on one of the classes, if it's NULL, try it on the other:
QString text;
QTextEdit *textEdit = qobject_cast<QTextEdit*>(sender);
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender);
if (textEdit) {
text = textEdit->toPlainText();
} else if (lineEdit) {
text = lineEdit->text();
} else {
// Return an error
}
You can also use sender->metaObject()->className() so you won't make unnecesary casts. Specially if you have a lot of classes to test. The code will be like this:
QString text;
QString senderClass = sender->metaObject()->className();
if (senderClass == "QTextEdit") {
QTextEdit *textEdit = qobject_cast<QTextEdit*>(sender);
text = textEdit->toPlainText();
} else if (senderClass == "QLineEdit") {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender);
text = lineEdit->text();
} else {
// Return an error
}
I know is an old question but I leave this answer just in case it would be useful for somebody...
This is related to a chapter from beautiful code.
And in that chapter I read about the nested ifs.
The author was talking about deeply nested ifs as originator of bugs and less readable.
And he was talking about replacing nested ifs with case statements and decision tables.
Can anybody illustrate how to remove nested ifs with case (select case) and decision tables ?
Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.
Invert “if” statement to reduce nesting
This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.
One example I always try to do is replace heavily nested if's like this (actually this one's not too bad but I've seen them up to 8 or 9 levels deep in the wild):
if (i == 1) {
// action 1
} else {
if (i == 2) {
// action 2
} else {
if (i == 3) {
// action 3
} else {
// action 4
}
}
}
with this:
switch (i) {
case 1:
// action 1
break;
case 2:
// action 2
break;
case 3:
// action 3
break;
default:
// action 4
break;
}
I also try to keep the actions as small as possible (function calls are best for this) to keep the switch statement compressed (so you don't have to go four pages ahead to see the end of it).
Decision tables, I believe, are simply setting flags indicating what actions have to be taken later on. The "later on" section is simple sequencing of actions based on those flags. I could be wrong (it won't be the first or last time :-).
An example would be (the flag-setting phase can be complicated if's since its actions are very simple):
switch (i) {
case 1:
outmsg = "no paper";
genmsg = true;
mailmsg = true;
phonemsg = false;
break;
case 2:
outmsg = "no ink";
genmsg = true;
mailmsg = true;
phonemsg = false;
break;
default:
outmsg = "unknown problem";
genmsg = true;
mailmsg = true;
phonemsg = true;
break;
}
if (genmsg)
// Send message to screen.
if (mailmsg)
// Send message to operators email address.
if (phonemsg)
// Hassle operators mobile phone.
How about chained ifs?
Replace
if (condition1)
{
do1
}
else
{
if (condition2)
{
do2
}
else (condition3)
{
do3;
}
}
with
if (condition1) {
do1;
} else if (condition2) {
do2;
} else if (condition3) {
do3;
}
This is much like switch statement for complex conditions.
Make the condition into booleans and then write boolean expression for each case.
If the code was:
if (condition1)
{
do1
}
else
{
if (condition2)
{
do2
}
else (condition3)
{
do3;
}
}
One can write it as:
bool cond1=condition1;
bool cond2=condition2;
bool cond3=condition3;
if (cond1) {do1;}
if (!cond1 and cond2) {do2;}
if (!cond1 and cond3) {do2;}
For decision tables, please see my answer to this question, or better still read chapter 18 in Code Complete 2.
You can just break once a part of the validation failed for example.
function validate(){
if(b=="" || b==null){
alert("Please enter your city");
return false;
}
if(a=="" || a==null){
alert("Please enter your address");
return false;
}
return true;
}
Decision tables are where you store the conditional logic in a data structure rather than within the code itself.
So instead of this (using #Pax's example):
if (i == 1) {
// action 1
} else {
if (i == 2) {
// action 2
} else {
if (i == 3) {
// action 3
} else {
// action 4
}
}
}
you do something like this:
void action1()
{
// action 1
}
void action2()
{
// action 2
}
void action3()
{
// action 3
}
void action4()
{
// action 4
}
#define NUM_ACTIONS 4
// Create array of function pointers for each allowed value of i
void (*actions[NUM_ACTIONS])() = { NULL, action1, action2, action3 }
// And now in the body of a function somewhere...
if ((i < NUM_ACTIONS) && actions[i])
actions[i]();
else
action4();
If the possibilities for i are not low-numbered integers then you could create a lookup table instead of directly accessing the ith element of the actions array.
This technique becomes much more useful than nested ifs or switch statements when you have a decision over dozens of possible values.
If and switch statements are not purely OO. They are conditional procedural logic, but do a very good job! If you want to remove these statements for a more OO approach, combine the 'State' and 'Descriptor' patterns.
You might also consider using the Visitor pattern.
Nested if are equivalent to the logical operator AND
if (condition1)
{
if (function(2))
{
if (condition3)
{
// do something
}
}
}
Equivalent code:
if (condition1 && function(2) && condition3)
{
// do something
}
In both cases, when an expression evaluates false, the subsequent expression will not be evaluated. For example, if condition1 is false, the function() will not be called, and condition3 won't be evaluated.
Another example some languages allow is this
switch true{
case i==0
//action
break
case j==2
//action
break
case i>j
//action
break
}