Making an array for a static casted indexed array - c++

I don't know if my title is right but I am trying to eliminate duplicate so I think I should put this definitions in an array. Can someone suggest me how I could put the pButtons in array? I am thinking something like pButton[EButtonHost], pButton[EButtonUsername] etc.
#define pButtonHost static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonHost])
#define pButtonUsername static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonUsername])
#define pButtonPassword static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonPassword])
I have a method below like this.
XIniFile readIniFile;
readIniFile.open(k_systemIniFile, EIniReadOnly);
string data;
readIniFile.readString("Server", "host", data);
pButtonHost->setString(data);
m_host = pButtonHost->getString();
readIniFile.readString("Server", "username", data);
pButtonUsername->setString(data);
m_username = pButtonUsername->getString();
readIniFile.readString("Server", "password", data);
pButtonPassword->setString(data);
m_password = pButtonPassword->getString();
They look like duplicates so I am trying to optimize it. Thanks!
Update:
I have something like this now. Would this be right? or do you have any better suggestions?
for (int i = 0; i < 3; ++i) {
readIniFile.readString("Server", k_dataList[i], data);
static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->setString(data);
m_pData[i] = static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->getString();
}

A below code looks clear by using auto and `lambda',
auto GetConfigInfo = [&](string section_name, ButtonType btn_type)-> string
{
readIniFile.readString("Server", section_name, data);
m_pButtonList[btn_type_]->setString(data);
return m_pButtonList->getString();
};
m_host = GetConfigInfo("host", EButtonHost);
m_username = GetConfigInfo("username", EButtonUserName);
m_password = GetConfigInfo("password", EButtonPassword);
and a define data type by using struct can be other method.
struct ConfigDefine
{
string section_;
ButtonType btn_type_; //your enum button type, such as EButtonHost, EButtonUserName
string& result_;
}configs[] =
{
{"host", EButtonHost, m_host},
{"username", EButtonUserName, m_username},
{"password", EButtonPassword, m_password}
};
for_each(std::begin(configs), std::end(configs), [&](ConfigDefine& config)
{
readIniFile.readString("Server", config.section_, data);
m_pButtonList[config.btn_type_]->setString(data);
config.result_ = pButtonHost->getString();
});

Do you intend to have something like this one?
#define ASIZE 3
int indx[ASIZE] = {EButtonHost, EButtonUsername, EButtonPassword};
string s[ASIZE] = {"host", "username", "password"};
string *m[ASIZE] = {&m_host, &m_username, &m_password};
for (int i = 0; i < ASIZE; i++) {
readIniFile.readString("Server", s[i].c_str(), data);
pButtonHost->setString(data);
*m[i] = pButtonHost->getString();
}

Related

Appending a pointer to a Qlist

this is my first post here!
I'm working on a code that parses Json to fill a struct that I append to a Qlist of tests to run.
My problem is with the payload inside my struct: when I send the first object in my list the payload it is not empty when it should be.
struct FrameTest {
QString protocol;
QString Length;
QByteArray *payload;
};
QList<FrameTest> _validTestLists;
FrameTest TxFrame;
Code of the JSON parser
void Cesa::JsonParser(QJsonObject _ScriptTestObject)
{
TxFrame.protocol = "00";
TxFrame.Length = "00";
TxFrame.payload = new QByteArray();
for(QJsonObject::iterator it = _ScriptTestObject.begin(); it!=_ScriptTestObject.end(); ++it)
{
TxFrame.protocol= "00";
TxFrame.Length = "00";
TxFrame.payload->clear();
_CmdObject = _ScriptTestObject.value(key).toObject(); // Get Json object
if (_CmdObject.contains("Board") && _CmdObject.value("Board") == "Exia")
{
QString payload;
TxFrame.protocol= "03";
TxFrame.Length = "06";
payload = QString("%1").arg(obj.value("hopPeriod").toInt(), 2, 16, QChar('0'));
}
else if (_CmdObject.contains("Board") && _CmdObject.value("Board") == "Cevee")
{
TxFrame.protocol= "03";
TxFrame.Length = "06";
}
_testLists.append(TxFrame);
}
Test(_testLists); // Test with only one object
Function for sending via port COM
bool Cesa::Test(FrameTest frame)
{
QByteArray txFrame;
/* Transmit command */
txFrame.insert(0, frame.protocol);
txFrame.insert(2, frame.Length);
txFrame.insert(4, *frame.payload);
_comPort->write(QByteArray::fromHex(txFrame));
}
I'm a student still learning coding, any help and advice will be appreciated :)

How to get JSON objects value using casablanca in C++

I am new to Json. And i m using codeplex (casablanca) for reading the json values.
Below is the sample json string:
[{ "rollno": 2000,
"name": "suhani","marks":{"grade":"C"} }, {"rollno": 3000,"name": "ishu", "marks":{ "grade":"A"} }]
The code to access name & rollno, i am writing below code:
json::value jobj = json::value::parse(utility::conversions::to_string_t(resultbody));
for (unsigned int i = 0; i < jobj.size(); i++) {
auto getval = jobj[i];
if (getval.at(U("name")).is_string()) {
auto xstr = getval.at(U("name")).as_string();
std::string wide = utility::conversions::to_utf8string(xstr);
std::string str(wide.begin(), wide.end());
string name = str;
}
if (getval.at(U("rollno")).is_integer()) {
auto xstr = getval.at(U("rollno")).as_integer();
int rollno = xstr;
} }
HOW TO GET VALUE AT GRADE ?? When i access marks it is of type object, i am not getting how to access grade from there. Please respond.
Marks is still a json object. You'll need to access the grade property. From your code snippet add the following:
for (unsigned int i = 0; i < jobj.size(); i++) {
auto getval = jobj[i];
auto marks_object = getval.at(U("marks"));
auto grade_value = marks_object.at(U("grade")).as_string();

tinyxml parsing xml file

I have a xml file like this:
<?xml version="1.0"?>
<ApplicationSettings>
<BeamGeometry
Dimension="2"
Type="fan"
Shape="arc"
LengthFocalPointToISOCenter="558"
LengthISOCenterToDetector="394"
LengthDetectorSeperation="0.98"
LengthModuleSeperation="0.04"
NumberModules="57"
NumberDetectorsPerModule="16"
NumberISOCenterShift="3.25" />
</ApplicationSettings>
And I'd like to use tinyxml retrieving all the values (such as 558) based on the entry name such as (LengthFocalPointToISOCenter). Here is my code, not successful yet.
int SetFanbeamGeometry(const char* filename)
{
int ret = TRUE;
TiXmlDocument doc("E:\\Projects\\iterativeRecon\\ProjectPackage\\ApplicationSettings\\ApplicationSettings.xml");
int LengthFocalPointToISOCenter;
if( doc.LoadFile())
{
TiXmlHandle hDoc(&doc);
TiXmlElement *pRoot, *pParm;
pRoot = doc.FirstChildElement("ApplicationSettings");
if(pRoot)
{
pParm = pRoot->FirstChildElement("BeamGeometry");
int i = 0; // for sorting the entries
while(pParm)
{
pParm = pParm->NextSiblingElement("BeamGeometry");
i++;
}
}
}
else
{
printf("Warning: ApplicationSettings is not loaded!");
ret = FALSE;
}
return ret;
}
I am wondering how can I use tinyxml to do that? Sorry I am a first time user. and it looks confusing to me. Thanks.
There's only one BeamGeometry child element in the snippet you've shown; the information you're trying to access are its attributes - they're not individual elements.
So you need something like this:
// ...
pParm = pRoot->FirstChildElement("BeamGeometry");
if (pParm)
{
const char* pAttr = pParm->Attribute("LengthFocalPointToISOCenter");
if (pAttr)
{
int iLengthFocalPointToISOCenter = strtoul(pAttr, NULL, 10);
// do something with the value
}
}
If you want to loop through all attributes, it's quite simple:
const TiXmlAttribute* pAttr = pParm->FirstAttribute();
while (pAttr)
{
const char* name = pAttr->Name(); // attribute name
const char* value = pAttr->Value(); // attribute value
// do something
pAttr = pAttr->Next();
}

v8: Array of objects

I'm transforming a parser for v8 in NodeJS. Currently I have the following structure
struct Node {
short tag;
std::string data;
Node(std::string input, short tagId) {
tag = tagId;
data = input;
}
};
std::vector<Node> elems;
And I'm populating the vector from loop like this:
elems.push_back(Node(STRING, 3));
My goal is return a javascript object like this:
[
{ tag: 2, data: "asdsad" },
{ tag: 2, data: "asdsad" },
{ tag: 2, data: "asdsad" }
]
But since the V8 documentation is crappy, I couldn't figure out how to do it. My best shot was to make
Local<Value> data[2] = {
Local<Value>::New(Integer::New(2)),
String::New("test")
};
but I can't figure out how to make it an array and return it.
I'm using this example as template.
Here's what you might try (node v0.10.x):
// in globals
static Persistent<String> data_symbol;
static Persistent<String> tag_symbol;
// in addon initialization function
data_symbol = NODE_PSYMBOL("data");
tag_symbol = NODE_PSYMBOL("tag");
// in some function somewhere
HandleScope scope;
Local<Array> nodes = Array::New();
for (unsigned int i = 0; i < elems.length; ++i) {
HandleScope scope;
Local<Object> node_obj = Object::New();
node_obj->Set(data_symbol, String::New(elems[i].data.c_str()));
node_obj->Set(tag_symbol, Integer::New(elems[i].tag));
nodes->Set(i, node_obj);
}
return scope.Close(nodes);
I was looking for a solution for Node 5, and it seems mscdex's answer is outdated now. Hope this helps someone.
HandleScope scope(isolate);
Local<Array> nodes = Array::New(isolate);
for (unsigned int i = 0; i < elems.length; ++i) {
HandleScope scope(isolate);
Local<Object> node = Object::New(isolate);
node->Set(String::NewFromUtf8(isolate, "data"), String::New(isolate, elems[i].data.c_str()));
node->Set(String::NewFromUtf8(isolate, "tag"), Integer::New(isolate, elems[i].tag));
nodes->Set(i, node);
}
args.GetReturnValue().Set(nodes);

Function has corrupt return value

I have a situation in Visual C++ 2008 that I have not seen before. I have a class with 4 STL objects (list and vector to be precise) and integers.
It has a method:
inline int id() { return m_id; }
The return value from this method is corrupt, and I have no idea why.
debugger screenshot http://img687.imageshack.us/img687/6728/returnvalue.png
I'd like to believe its a stack smash, but as far as I know, I have no buffer over-runs or allocation issues.
Some more observations
Here's something that puts me off. The debugger prints right values in the place mentioned // wrong ID.
m_header = new DnsHeader();
assert(_CrtCheckMemory());
if (m_header->init(bytes, size))
{
eprintf("0The header ID is %d\n", m_header->id()); // wrong ID!!!
inside m_header->init()
m_qdcount = ntohs(h->qdcount);
m_ancount = ntohs(h->ancount);
m_nscount = ntohs(h->nscount);
m_arcount = ntohs(h->arcount);
eprintf("The details are %d,%d,%d,%d\n", m_qdcount, m_ancount, m_nscount, m_arcount);
// copy the flags
// this doesn't work with a bitfield struct :(
// memcpy(&m_flags, bytes + 2, sizeof(m_flags));
//unpack_flags(bytes + 2); //TODO
m_init = true;
}
eprintf("Assigning an id of %d\n", m_id); // Correct ID.
return
m_header->id() is an inline function in the header file
inline int id() { return m_id; }
I don't really know how best to post the code snippets I have , but here's my best shot at it. Please do let me know if they are insufficient:
Class DnsHeader has an object m_header inside DnsPacket.
Main body:
DnsPacket *p ;
p = new DnsPacket(r);
assert (_CrtCheckMemory());
p->add_bytes(buf, r); // add bytes to a vector m_bytes inside DnsPacket
if (p->parse())
{
read_packet(sin, *p);
}
p->parse:
size_t size = m_bytes.size(); // m_bytes is a vector
unsigned char *bytes = new u_char[m_bytes.size()];
copy(m_bytes.begin(), m_bytes.end(), bytes);
m_header = new DnsHeader();
eprintf("m_header allocated at %x\n", m_header);
assert(_CrtCheckMemory());
if (m_header->init(bytes, size)) // just set the ID and a bunch of other ints here.
{
size_t pos = DnsHeader::SIZE; // const int
if (pos != size)
; // XXX perhaps generate a warning about extraneous data?
if (ok)
m_parsed = true;
}
else
{
m_parsed = false;
}
if (!ok) {
m_parsed = false;
}
return m_parsed;
}
read_packet:
DnsHeader& h = p.header();
eprintf("The header ID is %d\n", h.id()); // ID is wrong here
...
DnsHeader constructor:
m_id = -1;
m_qdcount = m_ancount = m_nscount = m_arcount = 0;
memset(&m_flags, 0, sizeof(m_flags)); // m_flags is a struct
m_flags.rd = 1;
p.header():
return *m_header;
m_header->init: (u_char* bytes, int size)
header_fmt *h = (header_fmt *)bytes;
m_id = ntohs(h->id);
eprintf("Assigning an id of %d/%d\n", ntohs(h->id), m_id); // ID is correct here
m_qdcount = ntohs(h->qdcount);
m_ancount = ntohs(h->ancount);
m_nscount = ntohs(h->nscount);
m_arcount = ntohs(h->arcount);
You seem to be using a pointer to an invalid class somehow. The return value shown is the value that VS usually uses to initialize memory with:
2^32 - 842150451 = 0xCDCDCDCD
You probably have not initialized the class that this function is a member of.
Without seeing more of the code in context.. it might be that the m_id is out of the scope you expect it to be in.
Reinstalled VC++. That fixed everything.
Thank you for your time and support everybody! :) Appreciate it!