XMLNode::XMLNode(io::IXMLReader *xml) { m_file_name = "[unknown]"; while(xml->getNodeType()!=io::EXN_ELEMENT && xml->read()); readXML(xml); } // XMLNode
World* ImageMapWorldCreator::createWorld(Engine& engine, MapDirectory& mapDirectory) { World* world = NULL; SDL_Surface* surface = IMG_Load(mapDirectory.getImagePath().c_str()); if (surface) { world = new World(surface->w, surface->h); if (mapDirectory.hasXML()) { readXML(&mapDirectory, &engine, surface, world); } for (int x = 0; x < surface->w; x++) { for (int y = 0; y < surface->h; y++) { Uint32 color = getPixel(surface, x, y); map<Uint32, string>::iterator it; it = m_textures.find(color); if (it != m_textures.end()) { ostringstream texturePath; texturePath << mapDirectory.getPath() << "/Blocks/" << it->second; Image* image = engine.loadImage(texturePath.str().c_str()); if (image) { DefaultBlock* block = new DefaultBlock(*world, x, y, BLOCK_TYPE_DIRT, *image); world->setBlock(x, y, block); } } } } SDL_FreeSurface(surface); } return world; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->tableWidget->setColumnCount(4); ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "Id" << "Date" << "Hour" << "Temperature"); ui->tableWidget->verticalHeader()->setVisible(false); ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems); ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(ui->tableWidget, SIGNAL(cellClicked(int,int)), this, SLOT(setId(int, int))); connect(ui->customPlot, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(showCoordinates(QMouseEvent *))); if (!readXML()) { qFatal("read XML err"); } dbInit(); drawData(""); plotPaint(); ui->tabWidget->setCurrentIndex(0); setWindowTitle("Body Temperature Monitor"); }
Document XmlParser::getDocument(string xml) { Document doc; ifstream infile(xml.c_str()); string temp; if(infile.is_open()) { xml = ""; while(getline(infile, temp)) { if(temp.find("<?")==string::npos && temp.find("?>")==string::npos) xml.append(temp+"\n"); } } Element root; StringUtil::trim(xml); if(xml.find("<")==0 && xml.find(">")!=string::npos) { if(xml.find("<?")!=string::npos && xml.find("?>")!=string::npos) { xml = xml.substr(xml.find("?>")+2); } readXML(xml,"",&root); } /*else if(xml!="") { logger << "Invalid XML Document" << endl; string errmsg = ("Invalid XML Document"); XmlParseException exception(errmsg); throw exception; }*/ doc.setRootElement(root); return doc; }
trackManager::trackManager(){ //generateMeditation(); readXML("track1.xml"); speed=1; bTimerReached=true; }
void FarHrcSettings::readProfile() { StringBuffer* path = new StringBuffer(PluginPath); path->append(DString(FarProfileXml)); readXML(path, false); delete path; }
void PanelConfig::initialize(QMap<QString, QString> config) { configuration = config; emit getConnectionState(); readXML("panel_config.xml"); setupConfigList(); setupTableHeader(); selectConfig(0); }
// This function creates the second network and load into it the weights // in the QFile fi. void TestXmlParsing::createNetwork2(NeuralNetwork *network2, QFile *fi) { // Reading XML files fi->open(QIODevice::ReadWrite) ; QXmlStreamReader *streamR = new QXmlStreamReader(fi) ; readXML(network2, streamR) ; delete streamR ; fi->close(); }
void PanelPlot::initialize(QMap<QString, QString> config) { configuration = config; emit getConnectionState(); readXML("panel_plot.xml"); setupPlotList(); initializePlot(0); setupPlotNames(0); }
bool PRUplus::readXML(string xmlFileName) { try { xmlpp::TextReader reader(xmlFileName.c_str()); readXML(reader); return true; } catch(const std::exception& e) { std::cerr << "Exception caught: " << e.what() << std::endl; return false; } }
PRUplus::PRUplus(string xmlFileName) { DEBUG("XML constructor of PRU+\n"); try { xmlpp::TextReader reader(xmlFileName.c_str()); readXML(reader); } catch(const std::exception& e) { std::cerr << "Exception caught: " << e.what() << std::endl; } DEBUG(*this<<std::endl); }
bool IexFmncFab::readXMLFile( const string& fullpath ) { xmlDoc* doc = NULL; xmlXPathContext* docctx = NULL; parseFile(fullpath, &doc, &docctx); readXML(docctx, "/"); closeParsed(doc, docctx); return true; };
int getCores(string hostsFile) { XMLElement hosts; if (!readXML(hostsFile, hosts)) { cerr << "Error reading " << hostsFile << endl; return false; } vector<const XMLElement*> emuls = hosts.findChildrenByName("emul"); for (unsigned int i=0; i<emuls.size(); i++) { coreToHost[i]=emuls[i]->getAttribute("hostname"); if (verbose) cerr << coreToHost[i] << endl; } return true; }
void VSPTree::LoadFunctionSummary(QString functionSummary) { Log("Reading : " + functionSummary); QDomDocument doc = readXML( functionSummary ); QTreeWidgetItem* root = new QTreeWidgetItem(m_functionSummaryTreeWidget); root->setText(0,"FunctionSummary"); m_functionSummaryTreeWidget->insertTopLevelItem(0, root); QDomNodeList functionList = doc.elementsByTagName("Function"); QStringList fields; fields << "FunctionName" << "InclSamples" << "ExclSamples" << "InclSamplesPercent" << "ExclSamplesPercent" << "SourceFile" << "LineNumber" << "ModuleName" << "ModulePath" << "FunctionAddress" << "ProcessName" << "PID"; m_functionSummaryTreeWidget->setColumnCount(fields.count()); m_functionSummaryTreeWidget->setHeaderLabels(fields); for ( int i = 0; i < functionList.count(); i++ ) { QTreeWidgetItem* tempWidgetItem = new QTreeWidgetItem(); for ( int j = 0; j < fields.count(); j++ ) { QString cellText = functionList.at(i).toElement().attribute( fields.at(j) ); if ( fields.at(j) == "ExclSamplesPercent" && cellText.count() < 5) { cellText.prepend('0'); } if ( fields.at(j) == "InclSamplesPercent" && cellText.count() < 5) { cellText.prepend('0'); } if ( fields.at(j) == "Level" && cellText.count() < 2) { cellText.prepend('0'); } tempWidgetItem->setText( j, cellText ); } root->addChild(tempWidgetItem); } m_functionSummaryTreeWidget->expandAll(); m_functionSummaryTreeWidget->setAlternatingRowColors(true); m_functionSummaryTreeWidget->setSortingEnabled(true); }
bool vtUtilityMap::ReadOSM(const char *pathname, bool progress_callback(int)) { // Avoid trouble with '.' and ',' in Europe // OSM always has English punctuation ScopedLocale normal_numbers(LC_NUMERIC, "C"); UtilOSMVisitor visitor(this); try { readXML(pathname, visitor, progress_callback); } catch (xh_exception &ex) { VTLOG1(ex.getFormattedMessage().c_str()); return false; } return true; }
cwLinePlotTask::cwLinePlotTask(QObject *parent) : cwTask(parent) { Region = new cwCavingRegion(); SurvexFile = new QTemporaryFile(this); SurvexFile->open(); SurvexFile->close(); SurvexExporter = new cwSurvexExporterRegionTask(); SurvexExporter->setParentTask(this); SurvexExporter->setOutputFile(SurvexFile->fileName()); connect(SurvexExporter, SIGNAL(finished()), SLOT(runCavern())); connect(SurvexExporter, SIGNAL(stopped()), SLOT(done())); CavernTask = new cwCavernTask(); CavernTask->setParentTask(this); CavernTask->setSurvexFile(SurvexFile->fileName()); connect(CavernTask, SIGNAL(finished()), SLOT(convertToXML())); connect(CavernTask, SIGNAL(stopped()), SLOT(done())); PlotSauceTask = new cwPlotSauceTask(); PlotSauceTask->setParentTask(this); connect(PlotSauceTask, SIGNAL(finished()), SLOT(readXML())); connect(PlotSauceTask, SIGNAL(stopped()), SLOT(done())); PlotSauceParseTask = new cwPlotSauceXMLTask(); PlotSauceParseTask->setParentTask(this); connect(PlotSauceParseTask, SIGNAL(finished()), SLOT(generateCenterlineGeometry())); connect(PlotSauceParseTask, SIGNAL(stopped()), SLOT(done())); //connect(PlotSauceParseTask, SIGNAL(stationPosition(QString,QVector3D)), SLOT(updateStationPositionForCaves(QString,QVector3D))); CenterlineGeometryTask = new cwLinePlotGeometryTask(); CenterlineGeometryTask->setParentTask(this); connect(CenterlineGeometryTask, SIGNAL(finished()), SLOT(linePlotTaskComplete())); connect(CenterlineGeometryTask, SIGNAL(stopped()), SLOT(done())); }
//--------------------------------------------------------------------- // Method: // Database::readFiles() // // Used to read in the DB file and XML taxomony. //--------------------------------------------------------------------- void Database::readFiles() { readXML(); for (map<int, TaxVertex *>::iterator mapIt = headerTable.begin(); mapIt != headerTable.end(); mapIt++) { //cout << "Itemset: " << (*mapIt).first << endl; if (!(*mapIt).second->getChildren()->empty()) { findAllLeafNodes((*mapIt).second, (*mapIt).first); } } /*for (map<int, list<TaxVertex *> >::iterator mapIt = leafNodes.begin(); mapIt != leafNodes.end(); mapIt++) { if ((*mapIt).second.size() == 1) { numGeneralizedItems--; } }*/ //cout << leafNodes.size() << endl; numGeneralizedItems = (unsigned int)leafNodes.size() - 1; readDBFromFile(); //cout << "Num Gen. Itemsets: " << numGeneralizedItems << endl; /*map<int, list<TaxVertex *> >::iterator mapIt2; for (mapIt2 = leafNodes.begin(); mapIt2 != leafNodes.end(); mapIt2++) { cout << "Generalized Item: " << (*mapIt2).first << endl; map<int, TaxVertex *>::iterator tmpMap = headerTable.find((*mapIt2).first); list<TaxVertex *>::iterator nodeIt; for(nodeIt = (*mapIt2).second.begin(); nodeIt != (*mapIt2).second.end(); nodeIt++) { cout << "Item: " << (*nodeIt)->getItem() << endl; } }*/ }
/** Reads a XML file and convert it into a XMLNode tree. * \param filename Name of the XML file to read. */ XMLNode::XMLNode(const std::string &filename) { m_file_name = filename; io::IXMLReader *xml = file_manager->createXMLReader(filename); if (xml == NULL) { throw std::runtime_error("Cannot find file "+filename); } bool is_first_element = true; while(xml->read()) { switch (xml->getNodeType()) { case io::EXN_ELEMENT: { if(!is_first_element) { fprintf(stderr, "More than one root element in '%s' - ignored.\n", filename.c_str()); } readXML(xml); is_first_element = false; break; } case io::EXN_ELEMENT_END: break; // Ignore all other types case io::EXN_UNKNOWN: break; case io::EXN_COMMENT: break; case io::EXN_TEXT: break; default: break; } // switch } // while xml->drop(); } // XMLNode
void WaitTimeBar::update() { // Pole the xml side of things every minute if(ofGetUnixTime() > lastCheck-checktime) loadXML(); readXML(); // Flip them tags every 10 seconds flipTag = ofGetSeconds() % 10; if(flipTag == 0) flag = true; if(flipTag == 1 && flag == true) { tagNum = (tagNum+1) % 4; flag = false; scale = 0.0f; } fbo->begin(); ofClear(0,0,0,0); ofPushMatrix(); // if(XMLS.getValue("width", 1920) < XMLS.getValue("height", 1080) ) { // float scale = XMLS.getValue("width", 1920) / XMLS.getValue("height", 1080); // ofScale(scale, scale); // } ofTranslate(74,50); background->draw(0,0); ofPushMatrix(); ofTranslate(0,30); ofTranslate(15,0); TTF.drawString(carTime > 0 ? "It's your turn!" : ofToString(carTime) + " minutes left!", 158, 35); TTF.drawString(houseTime > 0 ? "It's your turn!" : ofToString(houseTime) + " minutes left!", 529,35); TTF.drawString(travelTime > 0 ? "It's your turn!" : ofToString(travelTime) + " minutes left!", 1048, 35); TTF.drawString(memberTime > 0 ? "It's your turn!" : ofToString(memberTime) + " minutes left!", 1469, 35); ofPopMatrix(); ofTranslate(0,17); drawFlipTag(); ofPopMatrix(); fbo->end(); }
ThemeComponent::ThemeComponent(Window* window, bool detailed, std::string path) : GuiComponent(window) { mDetailed = detailed; mSoundMap["menuScroll"] = std::shared_ptr<Sound>(new Sound); mSoundMap["menuSelect"] = std::shared_ptr<Sound>(new Sound); mSoundMap["menuBack"] = std::shared_ptr<Sound>(new Sound); mSoundMap["menuOpen"] = std::shared_ptr<Sound>(new Sound); //register all sound with the audiomanager AudioManager::getInstance()->registerSound(mSoundMap["menuScroll"]); AudioManager::getInstance()->registerSound(mSoundMap["menuSelect"]); AudioManager::getInstance()->registerSound(mSoundMap["menuBack"]); AudioManager::getInstance()->registerSound(mSoundMap["menuOpen"]); mListFont = NULL; mDescFont = NULL; mFastSelectFont = NULL; setDefaults(); if(!path.empty()) readXML(path); }
bool vtUtilityMap::ReadXML(const char *pathname, bool progress_callback(int)) { // The locale might be set to something European that interprets '.' as ',' // and vice versa, which would break our usage of sscanf/atof terribly. // So, push the 'standard' locale, it is restored when it goes out of scope. LocaleWrap normal_numbers(LC_NUMERIC, "C"); bool success = false; UtilityVisitor visitor(this); try { readXML(pathname, visitor, progress_callback); success = true; } catch (xh_exception &ex) { // TODO: would be good to pass back the error message. VTLOG("XML Error: "); VTLOG(ex.getFormattedMessage().c_str()); return false; } return success; }
model loader::load(model& model) { std::map<std::pair<QString, QString>, QString> xmlTokens; typedef std::map<std::pair<QString, QString>, QString> Dict; typedef Dict::const_iterator It; QFile* data = new QFile("data.xml"); if (!data->open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Not read only"; } QXmlStreamReader readXML(data); while(!readXML.atEnd() && !readXML.hasError()) { QXmlStreamReader::TokenType token = readXML.readNext(); if(token == QXmlStreamReader::StartDocument) { continue; } else if (readXML.isEndElement() != true) { if(readXML.attributes().length()>2) xmlTokens[std::make_pair(readXML.attributes()[0].value().toString(), readXML.attributes()[1].value().toString())] = readXML.attributes()[2].value().toString(); } } tmpClassType = "bool"; tmpClassName = "checkBoxsdf"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setcheckBoxsdf(static_cast<bool>(boolValue)); } } tmpClassType = "bool"; tmpClassName = "swagbox"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setswagbox(static_cast<bool>(boolValue)); } } tmpClassType = "bool"; tmpClassName = "swagboxII"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setswagboxII(static_cast<bool>(boolValue)); } } tmpClassType = "QString"; tmpClassName = "comboBox"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { model.setcomboBox((QString)(it -> second)); } } tmpClassType = "double"; tmpClassName = "doubleSpinBox"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { double doubleValue = ((QString)(it -> second)).toDouble(); model.setdoubleSpinBox(doubleValue); } } tmpClassType = "QString"; tmpClassName = "lineEdit"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { model.setlineEdit((QString)(it -> second)); } } tmpClassType = "bool"; tmpClassName = "radioButton"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setradioButton(static_cast<bool>(boolValue)); } } tmpClassType = "bool"; tmpClassName = "radioButton_2"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setradioButton_2(static_cast<bool>(boolValue)); } } tmpClassType = "bool"; tmpClassName = "radioButton_3"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int boolValue = ((QString)(it -> second)).toInt(); model.setradioButton_3(static_cast<bool>(boolValue)); } } tmpClassType = "int"; tmpClassName = "horizontalScrollBar"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int intValue = ((QString)(it -> second)).toInt(); model.sethorizontalScrollBar(intValue); } } tmpClassType = "int"; tmpClassName = "verticalScrollBar"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int intValue = ((QString)(it -> second)).toInt(); model.setverticalScrollBar(intValue); } } tmpClassType = "int"; tmpClassName = "spinBox"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { int intValue = ((QString)(it -> second)).toInt(); model.setspinBox(intValue); } } tmpClassType = "QString"; tmpClassName = "textEdit"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { model.settextEdit((QString)(it -> second)); } } tmpClassType = "QString"; tmpClassName = "textEdit_2"; for (It it= xmlTokens.begin(); it != xmlTokens.end(); ++it) { if((it -> first.second).compare(tmpClassName) == 0) { model.settextEdit_2((QString)(it -> second)); } } return model; }
bool vtStructureArray::ReadXML(const char *pathname, bool progress_callback(int)) { // The locale might be set to something European that interprets '.' as ',' // and vice versa, which would break our usage of sscanf/atof terribly. // So, push the 'standard' locale, it is restored when it goes out of scope. LocaleWrap normal_numbers(LC_NUMERIC, "C"); // check to see if it's old or new format bool bOldFormat = false; gzFile fp = vtGZOpen(pathname, "r"); if (!fp) return false; m_strFilename = pathname; gzseek(fp, 24, SEEK_SET); char buf[10]; gzread(fp, buf, 10); if (!strncmp(buf, "structures", 10)) bOldFormat = true; else { // RFJ quick hack for extra carriage returns gzseek(fp, 26, SEEK_SET); gzread(fp, buf, 10); if (!strncmp(buf, "structures", 10)) bOldFormat = true; } gzclose(fp); bool success = false; if (bOldFormat) { StructureVisitor visitor(this); try { readXML(pathname, visitor, progress_callback); success = true; } catch (xh_exception &ex) { // TODO: would be good to pass back the error message. VTLOG("XML Error: "); VTLOG(ex.getFormattedMessage().c_str()); return false; } } else { StructVisitorGML visitor(this); try { readXML(pathname, visitor, progress_callback); success = true; } catch (xh_exception &ex) { // TODO: would be good to pass back the error message. VTLOG("XML Error: "); VTLOG(ex.getFormattedMessage().c_str()); return false; } } return success; }
Porting::Porting() { readXML(&m_renamedHeaders, &m_renamedClasses, &m_renamedEnums); }
bool QgsComposition::loadFromTemplate( const QDomDocument& doc, QMap<QString, QString>* substitutionMap, bool addUndoCommands ) { deleteAndRemoveMultiFrames(); //delete all items and emit itemRemoved signal QList<QGraphicsItem *> itemList = items(); QList<QGraphicsItem *>::iterator itemIter = itemList.begin(); for ( ; itemIter != itemList.end(); ++itemIter ) { QgsComposerItem* cItem = dynamic_cast<QgsComposerItem*>( *itemIter ); if ( cItem ) { removeItem( cItem ); emit itemRemoved( cItem ); delete cItem; } } mItemZList.clear(); mPages.clear(); mUndoStack.clear(); QDomDocument importDoc; if ( substitutionMap ) { QString xmlString = doc.toString(); QMap<QString, QString>::const_iterator sIt = substitutionMap->constBegin(); for ( ; sIt != substitutionMap->constEnd(); ++sIt ) { xmlString = xmlString.replace( "[" + sIt.key() + "]", encodeStringForXML( sIt.value() ) ); } QString errorMsg; int errorLine, errorColumn; if ( !importDoc.setContent( xmlString, &errorMsg, &errorLine, &errorColumn ) ) { return false; } } else { importDoc = doc; } //read general settings QDomElement compositionElem = importDoc.documentElement().firstChildElement( "Composition" ); if ( compositionElem.isNull() ) { return false; } bool ok = readXML( compositionElem, importDoc ); if ( !ok ) { return false; } //addItemsFromXML addItemsFromXML( importDoc.documentElement(), importDoc, 0, addUndoCommands, 0 ); // read atlas parameters QDomElement atlasElem = importDoc.documentElement().firstChildElement( "Atlas" ); atlasComposition().readXML( atlasElem, importDoc ); return true; }
simXMLReader::simXMLReader() { simCount = -1; readXML(); }
void VSPTree::LoadCallTree(QString callTreeSummary) { Log("Reading : " + callTreeSummary); QDomDocument doc = readXML( callTreeSummary ); QTreeWidgetItem* root = new QTreeWidgetItem(m_callTreeWidget); root->setText(0,"CallTree"); m_callTreeWidget->insertTopLevelItem(0, root); QTreeWidgetItem* flatroot = new QTreeWidgetItem(m_flatCallTreeWidget); flatroot->setText(0,"FlatCallTree"); m_callTreeWidget->insertTopLevelItem(0, flatroot); QDomNodeList functionList = doc.elementsByTagName("CallTree"); QHash<int, QTreeWidgetItem*> levelHash; levelHash.insert(0,root); QStringList fields; fields << "FunctionName" << "InclSamples" << "ExclSamples" << "InclSamplesPercent" << "ExclSamplesPercent" << "SourceFile" << "LineNumber" << "ModuleName" << "ModulePath" << "FunctionAddress" << "Level" << "ProcessName" << "PID"; m_callTreeWidget->setColumnCount(fields.count()); m_callTreeWidget->setHeaderLabels(fields); m_flatCallTreeWidget->setColumnCount(fields.count()); m_flatCallTreeWidget->setHeaderLabels(fields); for ( int i = 0; i < functionList.count(); i++ ) { QTreeWidgetItem* tempWidgetItem = new QTreeWidgetItem(); for ( int j = 0; j < fields.count(); j++ ) { QString cellText = functionList.at(i).toElement().attribute( fields.at(j) ); if ( fields.at(j) == "ExclSamplesPercent" && cellText.count() < 5) { cellText.prepend('0'); } if ( fields.at(j) == "InclSamplesPercent" && cellText.count() < 5) { cellText.prepend('0'); } if ( fields.at(j) == "Level" && cellText.count() < 2) { cellText.prepend('0'); } tempWidgetItem->setText( j, cellText ); } int level = functionList.at(i).toElement().attribute("Level").toInt(); levelHash.value(level)->addChild(tempWidgetItem); QTreeWidgetItem* flatTreeWidgetItem = tempWidgetItem->clone(); flatroot->addChild(flatTreeWidgetItem); m_flatHash.insert(flatTreeWidgetItem,tempWidgetItem); levelHash.insert(level+1,tempWidgetItem); } m_callTreeWidget->expandAll(); m_callTreeWidget->setAlternatingRowColors(true); m_flatCallTreeWidget->expandAll(); m_flatCallTreeWidget->setAlternatingRowColors(true); m_flatCallTreeWidget->setSortingEnabled(true); }
int main(int argc, char **argv) { int option = 0; // For getopt temp option usbDevice_t *dev; ucp_cmd_t buffer; //room for dummy report ID int err; //Initialize globalArgs before we get to work globalArgs.rFlag = 0; //False globalArgs.iFlag = 0; //False globalArgs.wFlag = 0; //False globalArgs.fFlag = 0; //False globalArgs.pFlag = 0; //False globalArgs.hashFlag = 0; //False globalArgs.kFlag = 0; //False strncpy(globalArgs.pin,"0000",sizeof(globalArgs.pin)); //Default pin globalArgs.offset = 0; //Default globalArgs.size = 512; //Default globalArgs.fileName = NULL; globalArgs.file = NULL; //Check if no arguments at all if(argc==1) printUsage(argv[0]); //If there's some argument, parse them while((option = getopt(argc, argv, "rwif:o:p:Pk:s:h?")) !=-1){ //Check option flags switch(option){ case 'r': globalArgs.rFlag = 1; //True break; case 'w': globalArgs.wFlag = 1; //True break; case 'i': globalArgs.iFlag = 1; //True break; case 'f': globalArgs.fFlag = 1; //True globalArgs.fileName = optarg; printf("File: %s\n",globalArgs.fileName); break; case 'o': globalArgs.offset = atoi(optarg); break; case 'p': globalArgs.pFlag = 1; //True strncpy(globalArgs.pin,optarg, sizeof(globalArgs.pin)); break; case 'P': globalArgs.hashFlag=1; //True break; case 'k': globalArgs.kFlag = 1; //True globalArgs.keyboard = optarg; printf("Keyboard: %s\n", globalArgs.keyboard); case 's': globalArgs.size = atoi(optarg); break; case 'h': case '?': printUsage(argv[0]); break; //Unknown flag, don't know what to do default: //After getopt prints the error printUsage(argv[0]); break; } } //Check that only one action is done at a time if(globalArgs.rFlag + globalArgs.wFlag + globalArgs.iFlag > 1) printUsage(argv[0]); //Check that not set PIN and read HASH are given at a time if(globalArgs.pFlag + globalArgs.hashFlag > 1) printUsage(argv[0]); //Check that if write from file to device, we are given a file and a pin to encrypt! if(globalArgs.wFlag && !globalArgs.fFlag) printUsage(argv[0]); if(globalArgs.wFlag && !globalArgs.pFlag) printUsage(argv[0]); //Also check pin for read flag if(globalArgs.rFlag && !globalArgs.pFlag) printUsage(argv[0]); //Try to open the device, exit if no device present. if((dev = openDevice()) == NULL) exit(1); //Clean the buffer before working with it memset((void*)&buffer, 0, sizeof(buffer)); //Check and perform the desired commands if(globalArgs.rFlag){ //READ COMMAND buffer.cmd = UCP_CMD_READ; deviceRead.offset = globalArgs.offset; deviceRead.size = globalArgs.size; memcpy((void*)&buffer.buff, (void*)&deviceRead, sizeof(deviceRead)); //give some feedback fprintf(stderr,"Reading from the MemType: offset=%d bytes, size=%d bytes.\n",deviceRead.offset, deviceRead.size); }else if(globalArgs.wFlag){ //WRITE COMMAND buffer.cmd = UCP_CMD_WRITE; deviceRead.offset = globalArgs.offset; deviceRead.size = readXML(globalArgs.fileName); memcpy((void*)&buffer.buff, (void*)&deviceRead, sizeof(deviceRead)); //give some feedback fprintf(stderr,"Writing to the MemType: offset=%d bytes, size=%d bytes.\n",deviceRead.offset, deviceRead.size); }else if(globalArgs.iFlag){ //INFO COMMAND buffer.cmd = UCP_CMD_INFO; }else if(globalArgs.hashFlag){ //READ PIN HASH COMMAND buffer.cmd = UCP_CMD_READ_PIN; }else if(globalArgs.pFlag){ //SET PIN COMMAND buffer.cmd = UCP_CMD_SET_PIN; buffer.buff[0] = 16; //sizeof hash in bytes }else if(globalArgs.kFlag){ buffer.cmd = UCP_CMD_KEYBOARD; } //Add a dummy report ID and send data to device buffer.reportid = 2; if((err = usbhidSetReport(dev, (char*)&buffer, sizeof(buffer))) != 0) fprintf(stderr, "Error sending data to device: %s\n", usbErrorMessage(err)); //Read back report int len = sizeof(buffer); if((err = usbhidGetReport(dev, 2, (char*)&buffer, &len)) != 0) { //... if not OK, print error fprintf(stderr, "Error reading data from device: %s\n", usbErrorMessage(err)); } else //... if OK, do things :) { fprintf( stderr, "\nMemType CMD Response: "); hexdump( (void*)&buffer.cmd, sizeof(buffer.cmd)+sizeof(buffer.buff)); fprintf( stderr, "Received data from the device: \n"); switch(buffer.cmd) { case UCP_CMD_RESET: fprintf( stderr, "RESET\n"); break; case UCP_CMD_READ: fprintf( stderr, "READ\n"); cmdRead(dev, deviceRead.size); break; case UCP_CMD_WRITE: fprintf( stderr, "WRITE\n"); cmdWrite(dev, flashMemory, deviceRead.size); fprintf(stderr, "[ENCRYPTION TEST] only hexdump"); break; case UCP_CMD_SET_PIN: fprintf(stderr, "SET PIN\n"); cmdSetPin(dev); break; case UCP_CMD_READ_PIN: fprintf(stderr, "READ PIN HASH\n"); cmdReadPinHash(dev); break; case UCP_CMD_KEYBOARD: fprintf(stderr, "KEYBOARD\n"); cmdKeyboard(dev); break; case UCP_CMD_DATA: fprintf( stderr, "DATA\n"); break; case UCP_CMD_INFO: fprintf( stderr, "sizeof(info) -> %lu\n", sizeof(deviceInfo)); memcpy((void*)&deviceInfo, (void*)buffer.buff, sizeof(deviceInfo)); /* Call info */ cmdInfo(&deviceInfo); break; case UCP_CMD_ERROR: //Wait! the device returned one error! switch( (unsigned char) buffer.buff[0] ) { case UCP_ERR: fprintf( stderr, "GENERIC ERROR\n"); break; case UCP_ERR_PACKET: fprintf( stderr, "PACKET ERROR\n"); break; case UCP_ERR_CMD: fprintf( stderr, "CMD ERROR\n"); break; case UCP_ERR_ADDR: fprintf( stderr, "ADDR ERROR\n"); break; case UCP_ERR_SIZE: fprintf( stderr, "SIZE ERRROR\n"); break; case UCP_ERR_PROTOCOL: fprintf( stderr, "PROTOCOL ERROR\n"); break; case UCP_ERR_LOCKED: fprintf( stderr, "DEVICE LOCKED ERROR\n"); break; default: fprintf( stderr, "UNKNOWN ERROR\n"); } break; default: fprintf( stderr, "UNKNOWN CMD ERROR\n"); } } usbhidCloseDevice(dev); return 0; }
void XmlParser::readXML(string xml,string parent,Element *par) { if(xml=="") return; StringUtil::trim(xml); int cdt = xml.find("<![CDATA["); if(cdt==0) { int ecdt = xml.find("]]>"); if(ecdt==string::npos) { string errmsg = ("Incomplete CDATA tag\n"); XmlParseException exception(errmsg); throw exception; } else { par->setCdata(true); par->setText(xml.substr(cdt+9,ecdt-cdt-9)); return; } } int cmt = xml.find("<!--"); if(cmt!=string::npos) { int ecmt = xml.find("-->"); if(ecmt==string::npos) { string errmsg = ("Incomplete Comment tag\n"); XmlParseException exception(errmsg); throw exception; } else { string stx = xml.substr(0,cmt); string enx = xml.substr(ecmt+3); xml = stx + enx; } } int st = xml.find("<")+1; int ed = 0; int ed1 = xml.find("/>"); int ed2 = xml.find(">"); if((ed2<ed1 || ed1==-1) && ed2!=-1) ed = ed2; else if(ed1!=-1) { /*if(xml[ed1+1]=='>')*/ ed = ed1; /*else ed = ed2;*/ } string tag = xml.substr(st,ed-st); int ss = tag.find_first_not_of(" "); int se = tag.find_last_not_of(" ")+1; tag = tag.substr(ss,se-ss); Element element; //split the tag with a space to get all the attribute sets of the element string ta; if(tag.find_first_of(" ")!=string::npos) { ta = tag.substr(0,tag.find_first_of(" ")); tag = tag.substr(tag.find_first_of(" ")+1); while(tag.find_first_of("=")!=string::npos && tag.find_first_of("\"")!=string::npos) { string atname = tag.substr(0,tag.find_first_of("=")); int as = atname.find_first_not_of(" "); int ae = atname.find_last_not_of(" ")+1; atname = atname.substr(as,ae-as); int ds = tag.find_first_of("\"")+1; tag = tag.substr(ds); string atvalue = tag.substr(0,tag.find_first_of("\"")); tag = tag.substr(tag.find_first_of("\"")+1); if(parent!="") { element.addAttribute(atname,atvalue); } else { par->addAttribute(atname,atvalue); } //logger << "attname = " << atname << " attvalue = " << atvalue << "\n" << flush; } } else ta = tag; int initcheck = xml.find_first_of("<"); unsigned int someTag = (xml.substr(initcheck+1)).find("<"); int pndTag=0,endTag=0; if(xml.find("</"+ta)!=string::npos) pndTag = xml.find("</"+ta); else if(xml.find("/>")!=string::npos && xml.find("/>")<someTag) endTag = xml.find("/>"); if(xml.find("< ")!=string::npos) { string errmsg = ("Invalid Start Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("< ")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("<\t")!=string::npos) { string errmsg = ("Invalid Start Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("<\t")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("</ ")!=string::npos) { string errmsg = ("Invalid End Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("</ ")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("</\t")!=string::npos) { string errmsg = ("Invalid End Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("</\t")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("< /")!=string::npos) { string errmsg = ("Invalid End Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("< /")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("/ >")!=string::npos) { string errmsg = ("Invalid End Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("/ >")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("<\t/")!=string::npos) { string errmsg = ("Invalid End Tag - at position: " + CastUtil::lexical_cast<string>((int)xml.find("<\t/")+1) + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("<"+ta)==string::npos && xml.find("</"+ta)!=string::npos) { string errmsg = ("No Start Tag - for : " + ta + "\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("<"+ta)!=string::npos && pndTag==0 && endTag==0) { string errmsg = ("No End Tag - for : " + ta + "\n"); XmlParseException exception(errmsg); throw exception; } if(xml.find("<"+ta)!=string::npos && (xml.find("</"+ta)!=string::npos || xml.find("/>")!=string::npos)) { //logger << "tag = " << ta << flush; //logger << " parent = " << parent << flush; //logger << "\n" << flush; if(ed==ed1) { if(parent!="") { element.setTagName(ta); par->addElement(element); } else { par->setTagName(ta); } xml = xml.substr(xml.find("/>")+2); } else if(xml.find("</"+ta)!=string::npos) { //split each set by = to get the pairs string tagx = "</"+ta+">"; int end = xml.find("</"+ta+">"); string txml = xml.substr(ed+1,end-ed-1); //logger << "temp = " << txml << flush; //logger << "\n" << flush; if(parent!="") { element.setTagName(ta); if(txml.find("<")!=string::npos) { readXML(txml,ta,&element); } else element.setText(txml); par->addElement(element); } else { par->setTagName(ta); if(txml.find("<")!=string::npos) { readXML(txml,ta,par); } else par->setText(txml); } xml = xml.substr(end+tagx.length()); } } if(xml.find("<")!=string::npos && (xml.find("</")!=string::npos || xml.find("/>")!=string::npos)) { //logger << "xml = " << xml << flush; //logger << "\n" << flush; readXML(xml,parent,par); } else if(xml.find("<")!=string::npos && (xml.find("</")==string::npos || xml.find("/>")==string::npos)) { string errmsg = ("Invalid Start Tag\n"); XmlParseException exception(errmsg); throw exception; } else if(xml.find("<")==string::npos && (xml.find("</")!=string::npos || xml.find("/>")!=string::npos)) { string errmsg = ("Invalid End Tag\n"); XmlParseException exception(errmsg); throw exception; } }
/* * This will handle connection for each client * */ void *connection_handler(void *args) { //Get the socket descriptor struct arg_struct *argStr = (struct arg_struct*) args; int sock = argStr->socket; int index = argStr->index; free(argStr); int read_size; char *message , client_message[MESSAGE_SIZE]; char name[CONTENT_SIZE],mgName[CONTENT_SIZE],content[CONTENT_SIZE],mytime[TIMESTAMP_SIZE]; time_t ltime; struct tm *tm; /// @sleep befor read from socket in order to wait until first msg be a complete message sleep(1); //Receive a message from client while( (read_size = recv(sock , client_message , MESSAGE_SIZE , 0)) > 0 ) { //Send the message back to client write(sock , client_message , strlen(client_message)); /// read from client msg and fill struct readXML(client_message,name, mgName , content , mytime); //debug // printf("$$$ name %s time is %s \n",name, mytime ); pthread_mutex_lock(&mutexArray[index]); strcpy(clients[index].name ,name); if( strcmp(mgName,"cpu") == 0 ) { // printf("@@@@@@@C \n %s \t %s \n",clients[index].cpu , content ); strcpy(clients[index].cpu ,content); } else if( strcmp(mgName,"mem") == 0 ) { // printf("@@@@@@@M \n %s \t %s \n",clients[index].mem , content ); strcpy(clients[index].mem ,content); } else if( strcmp(mgName,"fsw") == 0 ) { // printf("@@@@@@@W \n %s \t %s \n",clients[index].fsw , content ); strcpy(clients[index].fsw ,content); // printf("@@@@@@@ \n %s \t %s \n",clients[index].fsw , content ); } else if( strcmp(mgName,"fsr") == 0 ) { // printf("@@@@@@@R \n %s \t %s \n",clients[index].fsr , content ); strcpy(clients[index].fsr ,content); // printf("@@@@@@@ \n %s \t %s \n",clients[index].fsr , content ); } else{ printf("bad requset :(\n"); } ltime=time(NULL); tm=localtime(<ime); sprintf(clients[index].midServerTime,"%d:%d:%d",tm->tm_hour,tm->tm_min,tm->tm_sec); updateTimestamp(mytime , index); // printf("@@@@@@@@@@@@@\n%s\n",clients[index].timestamp ); pthread_mutex_unlock(&mutexArray[index]); //debug // printf("@@@@@@@@@@@@@\n%s\n",client_message ); // printf("@@@@@@@@@@@@@@@@@@@@\n%s\nat %s\nCPU usage: %s%%\nMemory usage: %s%%\nFS write: %s B/sec\nFS read: %s B/sec\n===================\n", // clients[index].name,clients[index].timestamp,clients[index].cpu, // clients[index].mem,clients[index].fsw,clients[index].fsr); //end debug /// memset agian memset(client_message,0,sizeof(char) * MESSAGE_SIZE); memset(name,0,sizeof(char) * CONTENT_SIZE); memset(mgName,0,sizeof(char) * CONTENT_SIZE); memset(content,0,sizeof(char) * CONTENT_SIZE); memset(mytime,0,sizeof(char) * TIMESTAMP_SIZE); } if(read_size == 0) { puts("Client disconnected"); fflush(stdout); } else if(read_size == -1) { perror("recv failed"); } return 0; }