示例#1
0
/*!
	\brief Load .dat file
	\param	in	QTextStream which holds the .dat file
	SEGNAME, TYPE, FROM, TO and LENGTH are loaded from the file

	// TODO(panqing): Error processing should be added
*/
int DataIO::loadDatData(QTextStream &in)
{
	QString line;	//	One line of the file
	QStringList lineList;	// Items in one line, seperated by some delimiters
	const int lengthThreshold = 10;	// Recognize one line as a recording by its length

	while (!(line = in.readLine()).contains("SEGMENT"))
		;

  // 数据列之间可用tab或space分隔
	if(line.contains("\t"))
		lineList = line.split("\t", QString::SkipEmptyParts);
	else
		lineList = line.split(" ", QString::SkipEmptyParts);

	// FROM and TO are inserted into the attributes name list
	// NOTICE(panqing): because the SEGMENT NAME takes 2 positions in the lineList, 
	// the indices of FROM and TO (3, 4) are different from those below (2, 3)
	attributesMap.insert(false, lineList.at(3));
	attributesMap.insert(false, lineList.at(4));
	// LENGTH are inserted into the show name list
	attributesMap.insert(true, lineList.at(6));

	while ((line = in.readLine()).length() >= lengthThreshold)
	{
		EdgeAttr *edgeAttr = new EdgeAttr();

		// There are two format of the separator: tab and space
		if(line.contains("\t"))
			lineList = line.split("\t", QString::SkipEmptyParts);
		else
			lineList = line.split(" ", QString::SkipEmptyParts);

		edgeAttr->setIntAttr(EdgeAttr::SEGNAME, lineList.at(0).toInt());
		edgeAttr->setIntAttr(EdgeAttr::TYPE, lineList.at(1).toInt());		// NOTICE(panqing): Type in *.dat and *.prn are DIFFERENT!!!!!! Use the type from .dat file
		edgeAttr->setIntAttr(EdgeAttr::STARTNODE, lineList.at(2).toInt());
		edgeAttr->setIntAttr(EdgeAttr::ENDNODE, lineList.at(3).toInt());
		edgeAttr->setDoubleAttr(EdgeAttr::OLDDIAM, lineList.at(4).toDouble());
		edgeAttr->setDoubleAttr(EdgeAttr::LENGTH, lineList.at(5).toDouble());

		edgeAttrList.append(edgeAttr);	// ResManager::getEdgeAttrList() returns a reference to DataList
	}
	return 0;
}
示例#2
0
void
CloseHeader(QTextStream &file, const QString &pre_name_withoutpath)
{
    // close the file
    file.device()->close();
    delete file.device();

    QString pre_name;
    if (outputtoinputdir)
        pre_name = currentInputDir + pre_name_withoutpath;
    else
        pre_name = pre_name_withoutpath;

    // create the real target file name
    QString post_name = pre_name.right(pre_name.length() - preHeaderLeader.length());

    unsigned int pre_cksum;
    FileContentsChecksum(pre_name, &pre_cksum);
    unsigned int post_cksum;
    bool havePostFile = FileContentsChecksum(post_name, &post_cksum);

    if (havePostFile)
    {
        if (post_cksum == pre_cksum)
        {
            // Since the new header file is the same as the old, don't
            // touch the old and remove the new (pre) one.
            QFile(pre_name).remove();
            cOut << "Note: Header file \"" << post_name << "\" did NOT change." << Endl;
        }
        else
        {
            // Since the new headeer file is different from the old,
            // remove the old one and rename the new one.
            QFile(post_name).remove();
            QFile(pre_name).rename(post_name);
            cOut << "Note: Header file \"" << post_name << "\" changed." << Endl;
        }
    }
    else
    {
        QFile(pre_name).rename(post_name);
    }
}
示例#3
0
DataList ExternalCharges::parse(QTextStream& textStream) 
{
   bool parseOkay(true), isDouble;
   QString line;
   QStringList tokens;
   double x, y, z, q;

   Layer::Data* charges = new Layer::Data("Charges");

   while (!textStream.atEnd() && parseOkay) {
      line = textStream.readLine();

      if (line.contains("$external_charges", Qt::CaseInsensitive)) {
      }else if (line.contains("$end", Qt::CaseInsensitive)) {
         break;
      }else {
         tokens = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
         if (tokens.count() == 1) {
            tokens[0].toUInt(&parseOkay);
         }else if (tokens.count() == 4) {
            x = tokens[0].toDouble(&isDouble);  parseOkay = parseOkay && isDouble;
            y = tokens[1].toDouble(&isDouble);  parseOkay = parseOkay && isDouble;
            z = tokens[2].toDouble(&isDouble);  parseOkay = parseOkay && isDouble;
            q = tokens[3].toDouble(&isDouble);  parseOkay = parseOkay && isDouble;
            if (parseOkay) charges->appendRow(new Layer::Charge(q, qglviewer::Vec(x,y,z)));
         }else {
            parseOkay = false;
         }
      }
   } 

   if (parseOkay && charges->hasChildren()) {
      m_dataList.append(charges);
   }else {
      ChargeList list(charges->findLayers<Layer::Charge>(Layer::Children));
      ChargeList::iterator charge;
      for (charge = list.begin(); charge != list.end(); ++charge) {
          delete (*charge);
      }
      delete charges;
   }

   return m_dataList;
}
示例#4
0
文件: log.cpp 项目: dosnut/nut
namespace nuts {
	QTextStream err;
	QTextStream log;

	class CLogInit {
	public:
		CLogInit() {
			int fd1 = dup(1), fd2 = dup(2);
			close(fd1); close(fd2);
			if (fd1 == -1 || fd2 == -1) {
				QFile *f = new QFile("/var/log/nuts.log");
				f->open(QIODevice::Append);
				dup2(f->handle(), 2);
				dup2(f->handle(), 1);
				err.setDevice(f);
				log.setDevice(f);
			} else {
				ferr = new QFile(); ferr->open(2, QIODevice::WriteOnly);
				err.setDevice(ferr);
				fout = new QFile(); fout->open(1, QIODevice::WriteOnly);
				log.setDevice(fout);
			}
		}

		~CLogInit() {
			delete ferr;
			delete fout;
		}

	private:
		QFile *ferr = nullptr;
		QFile *fout = nullptr;
	};

	static CLogInit *loginit;
	void LogInit() {
		loginit = new CLogInit();
	}

	void LogDestroy() {
		delete loginit;
		loginit = nullptr;
	}
}
示例#5
0
/**
 * @brief Constructs binary command line.
 * @param parfile       Parameter file.
 * @param num_iter      Number of iterations.
 * @param step_size     Step size.
 * @return      0 if success, else -1.
 */
int BinaryHandler::_set_bin_settings(const QString& parfile, const int num_iter,
                                     const int step_size)
{
    QString fname = "progress_" + QString::number(_id) + ".txt";
    if (_output_style == "Humppa") {
        fname = QString::number(_id) + "______progressbar.txt";
    }
    _progress_file.setFileName(fname);

    QString path_style = "..\bin\\";
    #if defined(__linux__) || defined(__APPLE__)
    path_style = "../bin/";
    #endif

    _cmd = "";
    QTextStream str;
    str.setString(&_cmd);

    // Check if we're dealing with a Python script.
    // It is users responsibility to make sure Python is available!
    QStringList blist = _binary.split(".");
    if (blist.size() > 1 && blist.at(1) == "py") {
        str << "python ";
    }

    str << path_style << _binary << " ";
    if (_input_style == "MorphoMaker" || _input_style == "") {
        str << "--param " << parfile << " --id " << _id << " --step "
            << step_size << " --niter " << num_iter;
    }
    else if (_input_style == "Humppa") {
        str << parfile << " " << _id << " " << step_size << " "
            << num_iter/step_size;
    }
    else {
        fprintf(stderr, "Invalid argument style: %s\n",
                _input_style.toStdString().c_str());
        return -1;
    }    

    if (DEBUG_MODE) fprintf(stderr, "cmd: %s\n", _cmd.toStdString().c_str());

    return 0;
}
示例#6
0
void font::menu_Ascii ( void )
{
	int rez  = 0;
	QString  str;
	ushort  rez_ushort;
	QString   fileName;

	do
	{
		switch ( rez )
		{

			case 1: //ASCII
				std_out << "ASCII:";
				std_out.flush();
				std_in >> str;

				if ( str.length() >=  1 )
				{
					rez_ushort = str[0].unicode () ;
//     number = rez_ushort;
				}

				break;

			case 2: //Attribute
				std_out << "Enter Attribute:";
				std_out.flush();
				std_in >> str;
				m_comment = str;
				break;

			case 3: //Restore
				m_comment = QString ( "Nothing" );
//    number = -1;
				break;

			default:
				break;
		}
	}

	while ( rez >= 0 );
}
示例#7
0
void openLogsFile(const QString & appDirPath)
{
    QString logsDirPath = appDirPath + "/Logs";

    QDir logsDir(logsDirPath);
    if (logsDir.exists() == false)
    {
        cout << "mkdir " << logsDirPath.toStdString() << endl;
        if (logsDir.mkdir(logsDirPath) == false)
        {
            cerr << "Failed mkdir '" << logsDirPath.toStdString() << "' for logs. Exit." << endl;
            exit(LightpackApplication::LogsDirecroryCreationFail_ErrorCode);
        }
    }

    QString logFilePath = logsDirPath + "/Prismatik.0.log";

    QStringList logFiles = logsDir.entryList(QStringList("Prismatik.?.log"), QDir::Files, QDir::Name);

    for (int i = logFiles.count() - 1; i >= 0; i--)
    {
        QString num = logFiles[i].split('.').at(1);
        QString from = logsDirPath + "/" + QString("Prismatik.") + num + ".log";
        QString to = logsDirPath + "/" + QString("Prismatik.") + QString::number(num.toInt() + 1) + ".log";

        if (i >= StoreLogsLaunches - 1)
        {
            QFile::remove(from);
            continue;
        }

        if (QFile::exists(to))
            QFile::remove(to);

        qDebug() << "Rename log:" << from << "to" << to;

        bool ok = QFile::rename(from, to);
        if (!ok)
            qCritical() << "Fail rename log:" << from << "to" << to;
    }

    QFile *logFile = new QFile(logFilePath);

    if (logFile->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
    {
        m_logStream.setDevice(logFile);
        m_logStream << endl;
        m_logStream << QDateTime::currentDateTime().date().toString("yyyy_MM_dd") << " ";
        m_logStream << QDateTime::currentDateTime().time().toString("hh:mm:ss:zzz") << " Prismatik " << VERSION_STR << endl;
    } else {
        cerr << "Failed to open logs file: '" << logFilePath.toStdString() << "'. Exit." << endl;
        exit(LightpackApplication::OpenLogsFail_ErrorCode);
    }

    qDebug() << "Logs file:" << logFilePath;
}
示例#8
0
QList<QStringList> CsvReader::parseTextStream(QTextStream& in)
{
    QList<QStringList> parsedFile;

    bool firstLine = true;

    while (!in.atEnd()) {
        QString line = in.readLine();
        if (firstLine && hasHeader_) {
            firstLine = false;
            continue;
        }

        QStringList parsedList = line.split(delimiter_);
        parsedFile.append(parsedList);
    }

    return parsedFile;
}
示例#9
0
void GameEngine::readHexagons(QTextStream &input)
{
    QString buf;
    buf = input.readLine();
    while ((buf != "[/HEXAGONS]") && (buf.size() != 0))
    {
        QStringList list = buf.split(" ", QString::SkipEmptyParts);
        int curHexagon = list[0].toInt() - 1;
        for (int i = 1; i < list.size(); ++i)
        {
            hexagons[curHexagon].setVertex(vertexes[list[i].toInt()-1]);
        }
        list.clear();
        buf = input.readLine();
        list = buf.split(" ");
        hexagons[curHexagon].setNominalCoord(list[0].toInt(), list[1].toInt());
        buf = input.readLine();
    }
}
示例#10
0
void Dialog::on_comboBox_activated(const QString &arg1)
{
  str =  ui->comboBox->currentText();
  QFile   mFile(str);
  if(!mFile.open(QFile::ReadOnly | QFile::Text))
  {
          QMessageBox msgBox;

          msgBox.setText("Error.");

          msgBox.exec();
          return;
}
  QTextStream stream (&mFile);


  str=stream.readAll();
  ui->label_2->setText(str);
}
示例#11
0
/**
  Take a stream onto a control file and return the decoded
  package information.

  Set isError == true if the information format is wrong.
*/
PackageInformationReader::PackageInformationReader( QTextStream &ts,
                                                    InstallControl::PackageInfo::Source src )
    : isError( false )
    , hasContent( false )
    , wasSizeUpdated( false )
    , accumulatingFullDesc( false )
    , source( src )
{
    reset();
    while (!ts.atEnd())
    {
        QString line = ts.readLine();
        readLine( line );
    }
    updateInstalledSize();

    if ( !pkg.isComplete(source, &error) )
        isError = true;
}
示例#12
0
ConversionStatus GettextImportPlugin::readHeader(QTextStream& stream)
{
   CatalogItem temp;
   int filePos=stream.device()->at();
   ConversionStatus status=readEntry(stream);

   if(status==OK || status==RECOVERED_PARSE_ERROR)
   {
      // test if this is the header
      if(!_msgid.first().isEmpty())
      {
         stream.device()->at(filePos);
      }

      return status;
   }

   return PARSE_ERROR;
}
示例#13
0
QString vars::get_tool(QString toolname)
{
    QString tool = "";
    QFile file ( QDir::homePath() +"/.first4/"+username+".first4.conf" );
    if ( file.open ( QIODevice::ReadOnly ) )
    {
        QTextStream stream ( &file );
        QString streamline;
        while(!stream.atEnd())
        {
            streamline = stream.readLine();
            if(streamline.contains(toolname+"=", Qt::CaseSensitive))
                tool = streamline.section("=", 1, 1);
        }
        file.close();
    }
    if(tool == "")
    {
        QString os = "";
#ifdef Q_OS_LINUX
        os="lnx";
#endif
#ifdef Q_OS_WIN32
        os="win";
#endif
#ifdef Q_OS_MAC
        os="mac";
#endif
        QString qstr1 = QString("SELECT var, value FROM maincfg WHERE `var`='tool_%1_"+toolname.toLower()+"';").arg(os);
        QSqlQuery querytools(qstr1);
        if ( querytools.isActive())
        {
            querytools.next();
            tool = querytools.value(1).toString();
        }
        else
        {
            QSqlError sqlerror = querytools.lastError();
            QMessageBox::critical(0,"Error...", "Unable to read settings from database!\n\n"+sqlerror.text());
        }
    }
    return tool;
}
示例#14
0
void readStars(QTextStream &stream, Galaxy &galaxy)
{

	QString line = stream.readLine().trimmed();
	while (!line.isNull())
	{
		if(line.contains("StarId"))
		{
			QStringRef idRef(&line,6,line.indexOf(' ')-6);
			unsigned id=idRef.toInt();
			galaxy.addStar(Star(stream, galaxy, id));
		}
		else if(line.contains('}'))
		{
			break;
		}
		line = stream.readLine().trimmed();
	}
}
RatpPrivate::RatpPrivate(Ratp *q):
    q_ptr(q)
{
    QFile file (":/data/backward/stations.txt");
    if (!file.open(QIODevice::ReadOnly)) {
        debug("ratp-plugin") << "Failed to read" << file.fileName().constData();
        return;
    }
    QTextStream fileStream (&file);
    while (!fileStream.atEnd()) {
        QString line = fileStream.readLine().trimmed();
        if (!line.isEmpty()) {
            stations.append(line);
        }
    }

    file.close();

}
示例#16
0
void QWSHexDump::sideviewDump(int at)
{
    if (dirty) {
        dirty = false;
        ++at;
        sideview[at] = '\0';
        int currentWidth = (2 * at) + (at / clustering) - (at%clustering?0:1);
        int missing = qMax(dataWidth - currentWidth, 0);
        while (missing--)
            *outstrm << ' ';

        *outstrm << " [";
        outstrm->setPadChar(' ');
        outstrm->setFieldWidth(wrap);
        outstrm->setFieldAlignment( QTextStream::AlignLeft );
        *outstrm << sideview;
        *outstrm << ']';
    }
}
ReportGenerationDialog::ReportGenerationDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ReportGenerationDialog),patientTracker(NULL)
{
    ui->setupUi(this);
    ui->presetDiagnosisComboBox->setEnabled(true);
    ui->diagnosisEditor->setEnabled(false);

    ui->screenshotListView->setModel(&screenshotModel);
    ui->screenshotListView->setIconSize(QSize(225, 225));

    ui->selectedScreenshotListView->setModel(&selectedScreenshotModel);
    ui->selectedScreenshotListView->setIconSize(QSize(175, 175));

    QScrollArea *area = new QScrollArea(this);
    area->move(10, 90);
    area->resize(781, 600);
    area->setWidget(ui->centreWidget);

    ui->tcdInfoTableView->setModel(&selectedValuesModel);
    QStringList headerList;
    headerList << "截图" << "血管名" << "Mean" << "Peak" << "EDV" << "PI" << "RI" << "S/D" << "HR";
    selectedValuesModel.setHorizontalHeaderLabels(headerList);


    QFile file("./PresetDiagnoses.txt");
    QTextStream in;
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(NULL, "预设诊断读取", "预设诊断读取失败!");
    }
    else
    {
        in.setDevice(&file);
        QString line;
        line = in.readLine();
        while (!line.isNull()) {
            ui->presetDiagnosisComboBox->addItem(line);
            diagnosesModel.appendRow(new QStandardItem(line));
            line = in.readLine();
        }
    }
}
void MXPImporter::loadInstructions( QTextStream &stream, Recipe &recipe )
{
	//==========================instructions ( along with other optional fields... mxp format doesn't define end of ingredients and start of other fields )==============//
	stream.skipWhiteSpace();
	QString current = stream.readLine().trimmed();
	while ( !current.contains( "- - - -" ) && !stream.atEnd() ) {
		if ( current.trimmed() == "Source:" ) {
			Element new_author( getNextQuotedString( stream ) );
			recipe.authorList.append( new_author );
			//kDebug()<<"Found source: "<<new_author.name<<" (adding as author)";
		}
		else if ( current.trimmed() == "Description:" ) {
			QString description = getNextQuotedString( stream );
			//kDebug()<<"Found description: "<<m_description<<" (adding to end of instructions)";
			recipe.instructions += "\n\nDescription: " + description;
		}
		else if ( current.trimmed() == "S(Internet Address):" ) {
			QString internet = getNextQuotedString( stream );
			//kDebug()<<"Found internet address: "<<m_internet<<" (adding to end of instructions)";
			recipe.instructions += "\n\nInternet address: " + internet;
		}
		else if ( current.trimmed() == "Yield:" ) {
			recipe.yield.setAmount(getNextQuotedString( stream ).trimmed().toInt());
			recipe.yield.setType(i18n("servings"));
			//kDebug()<<"Found yield: "<<recipe.yield.amount<<" (adding as servings)";
		}
		else if ( current.trimmed() == "T(Cook Time):" ) {
			( void ) getNextQuotedString( stream ); //this would be prep time, but we don't use prep time at the moment
			//kDebug()<<"Found cook time: "<<m_prep_time<<" (adding as prep time)";
		}
		else if ( current.trimmed() == "Cuisine:" ) {
			Element new_cat( getNextQuotedString( stream ) );
			recipe.categoryList.append( new_cat );
			//kDebug()<<"Found cuisine (adding as category): "<<new_cat.name;
		}
		else
			recipe.instructions += current + '\n';

		current = stream.readLine().trimmed();
	}
	recipe.instructions = recipe.instructions.trimmed();
	//kDebug()<<"Found instructions: "<<m_instructions;
}
示例#19
0
文件: Data.cpp 项目: mtab3/xafsm2
void Data::showS2DData( QTextStream &in,
			QVector<AMotor*> &AMotors, QVector<ASensor*> & /* ASensors */ )
{
  QStringList HeadLine1, HeadLine2, vals;
  QString line;


  
  theS2DB = (S2DB*)(theViewC->getView());
  theS2DB = (S2DB*)(theViewC->getView());
  theS2DB->setLoadBHidden( false );
  theS2DView = (S2DView*)(theS2DB->getView());
#if 0
  if ( theViewC->getNowDType() == NONDATA ) {
    theViewC->setNowDType( S2DSHOW );
    theViewC->setNowVType( S2DVIEW );
    // theS2DView->SetWindow0( 1e300, 0, -1e300, 0 );
  }
#endif
  theS2DView->setRatioType( AS_SCREEN );

  S2DInfo s2di;
  s2di.load( in, AMotors );
  theS2DB->setS2DI( s2di );
  theS2DView->setRange( s2di.sx[0], s2di.sx[1] - s2di.dx[1] / 2,
			s2di.dx[0], s2di.dx[1],
			s2di.ps[0], s2di.ps[1] + 1 );
  int ix = 0, iy = 0;
  while ( ! in.atEnd() ) {
    vals = in.readLine().simplified().split( QRegExp( "\\s+" ) );
    if ( vals.count() > 0 ) {
      if ( vals[0][0] != '#' ) {
	if ( vals.count() >= 3 ) {
	  theS2DView->setData( ix, iy, vals[2].toDouble() );
	  ix++;
	} else {
	  ix = 0;
	  iy++;
	}
      }
    }
  }
}
示例#20
0
//! Prepares some elements before a writing into the krarc debug log file
void KrDebugLogger::prepareWriting(QFile &file, QTextStream &stream)
{
    file.setFileName(logFile);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    stream.setDevice(&file);
    stream << "Pid:" << (int)getpid();
    // Applies the indentation level to make logs clearer
    for (int x = 0; x < indentation; ++x)
        stream << " ";
}
示例#21
0
//! [0]
void RainfallGraph::addDataSet()
{
    // Create a new variant data set and data item list
    m_dataSet =  new VariantDataSet;
    VariantDataItemList *itemList = new VariantDataItemList;

    // Read data from a data file into the data item list
    QTextStream stream;
    QFile dataFile(":/data/raindata.txt");
    if (dataFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        stream.setDevice(&dataFile);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            if (line.startsWith("#")) // Ignore comments
                continue;
            QStringList strList = line.split(",", QString::SkipEmptyParts);
            // Each line has three data items: Year, month, and rainfall value
            if (strList.size() < 3) {
                qWarning() << "Invalid row read from data:" << line;
                continue;
            }
            // Store year and month as strings, and rainfall value as double
            // into a variant data item and add the item to the item list.
            VariantDataItem *newItem = new VariantDataItem;
            for (int i = 0; i < 2; i++)
                newItem->append(strList.at(i).trimmed());
            newItem->append(strList.at(2).trimmed().toDouble());
            itemList->append(newItem);
        }
    } else {
        qWarning() << "Unable to open data file:" << dataFile.fileName();
    }

    //! [1]
    // Add items to the data set and set it to the proxy
    m_dataSet->addItems(itemList);
    m_proxy->setDataSet(m_dataSet);

    // Create new mapping for the data and set it to the proxy
    m_mapping =  new VariantBarDataMapping(0, 1, 2, m_years, m_numericMonths);
    m_proxy->setMapping(m_mapping);
    //! [1]
}
示例#22
0
文件: main.cpp 项目: Chris7/hifi
void processInput(QTextStream& in, QList<Streamable>* streamables) {
    Class clazz;
    Streamable currentStreamable;

    QRegExp exp(
        "(/\\*.*\\*/)|" // multi-line comments
        "(//.*\n)|" // single-line comments
        "(\\s*#.*\n)|" // preprocessor definitions
        "(\\s*STREAMABLE\\s+)|" // STREAMABLE tag for classes
        "(\\s*STREAM\\s+.*;)|" // STREAM tag for fields
        "(\\s*class\\s+[^;]+\\{)" // class definition
    );
    exp.setMinimal(true);

    QRegExp classExp("class (\\w+) ?:?([^:]*)\\{");

    // read in the entire input and look for matches with our expression
    QString all = in.readAll();
    for (int off = 0; (off = exp.indexIn(all, off)) != -1; off += exp.matchedLength()) {
        QString match = exp.cap().simplified();
        if (match.startsWith("/*") || match.startsWith("//") || match.startsWith('#')) {
            continue; // comment, preprocessor definition
        }
        if (match.startsWith("STREAMABLE")) {
            if (clazz.name.isEmpty()) {
                cerr << "Found STREAMABLE marker before class definition." << endl;
                continue;
            }
            if (!currentStreamable.clazz.name.isEmpty()) {
                streamables->append(currentStreamable);
            }
            currentStreamable.clazz = clazz;
            currentStreamable.fields.clear();

        } else if (match.startsWith("STREAM")) {
            match.chop(1); // get rid of the semicolon
            match = match.trimmed(); // and any space before it
            currentStreamable.fields.append(match.mid(match.lastIndexOf(' ') + 1));

        } else { // match.startsWith("class")
            classExp.exactMatch(match);
            clazz.name = classExp.cap(1);
            clazz.bases.clear();
            foreach (const QString& bstr, classExp.cap(2).split(',')) {
                QString base = bstr.trimmed();
                if (!base.isEmpty() && base.startsWith("STREAM")) {
                    clazz.bases.append(base.mid(base.lastIndexOf(' ') + 1));
                }
            }
        }
    }
    if (!currentStreamable.clazz.name.isEmpty()) {
        streamables->append(currentStreamable);
    }
}
示例#23
0
void PackageList::readFileEntries( QString filename, QString dest )
{
	pvDebug(5,"PackageList::readFileEntries "+filename+" dest "+dest);
  QStringList packEntry;
  QFile f( filename );
  if ( !f.open(IO_ReadOnly) ) return;
  QTextStream *statusStream = new QTextStream( &f );
  while ( !statusStream ->eof() )
  {
     QString line = statusStream->readLine();
     if ( line.find(QRegExp("[\n\t ]*")) || line == "" )
			{
			  //end of package
	  		if ( ! packEntry.isEmpty() )
		    {
		      OipkgPackage *p = new OipkgPackage( packEntry, settings );
	    	  if ( p )
					{
			      p->setDest( dest );
		  			insertPackage( p );
					  packEntry.clear();
					}
	   		 }
			}else{
	  		packEntry << line;
			};
    }
  //there might be no nl at the end of the package file
	if ( ! packEntry.isEmpty() )
	{
		OipkgPackage *p = new OipkgPackage( packEntry, settings );
	  if ( p )
		{
	      p->setDest( dest );
	 			insertPackage( p );
			  packEntry.clear();
		}
	}
 	delete statusStream;
	f.close();
  return;
}
    bool B9LayoutProjectData::Open(QString filepath, bool withoutVisuals) //returns success
    {
        int i;
        int FileVersion;
		bool jumpout = false;

		double resx;
		double resy;
        double xp, yp, zp;//instance positions/rotations/scales
        double xr, yr, zr;
        double xs, ys, zs;
        bool flipped = false;
        int numSupports;
        int hasFoundation;

        QFile file(filepath);
        QTextStream in;
        QString buff;//for io operations
        QString modelpath;//current model this function is trying to load.


        //input file operations here
		if(!file.open(QIODevice::ReadOnly))
		{
			return false;
        }
        //check file extension
        if(QFileInfo(filepath).completeSuffix().toLower() != "b9l")
            return false;


        SetDirtied(false);//presumably good from here so undirty the project

        in.setDevice(&file);//begin text streaming.
        in >> buff;
        if(buff == "ver")//we are looking at a post 1.4 b9 layout file
        {
            in >> buff;
            FileVersion = buff.toInt();//should be 14 or greater.
            in.skipWhiteSpace();
            mfilename = in.readLine();//get project name
        }
示例#25
0
void Sketch_Files::readXml(QString FileName)//Opens the sketch file
{
    if(FileName.contains(".xml")||FileName.contains(".skh"))
    {
         QFile fd(FileName);
         fd.open(QFile::ReadWrite);
         QXmlStreamReader rw(&fd);

         while(!rw.atEnd())
         {
            object = new Scene_Objects;
            if(rw.name()=="Type")//what type of object ex:line,rect...
            {
                QTextStream readline;
                QString str,subText;
                str=rw.readElementText();
                readline.setString(&str,QIODevice::ReadWrite);

                while(!readline.atEnd())
                {
                    readline>>subText;
                    if(subText.contains("Line"))
                        object->ObjectId=1;
                    if(subText.contains("Rectangle"))
                        object->ObjectId=2;
                    if(subText.contains("Ellipse"))
                        object->ObjectId=3;
                    if(subText.contains("RoundRect"))
                        object->ObjectId=5;
                }


            }

            if(rw.name()=="Dim")
            {
              parseText(rw.readElementText());
              object->print();
            }

            rw.readNext();
         }
示例#26
0
文件: logger.cpp 项目: phob/antimicro
/**
 * @brief Go through a list of pending messages and check if message should be
 *     logged according to the set log level. Log the message to the output
 *     stream.
 * @param Log level
 * @param String to write to output stream if appropriate to the current
 *     log level.
 */
void Logger::Log()
{
    QMutexLocker locker(&logMutex);
    Q_UNUSED(locker);

    QListIterator<LogMessage> iter(pendingMessages);
    while (iter.hasNext())
    {
        LogMessage pendingMessage = iter.next();

        LogLevel level = pendingMessage.level;
        QString message = pendingMessage.message;
        bool newline = pendingMessage.newline;

        if (outputLevel != LOG_NONE && level <= outputLevel)
        {
            QString displayTime = "";
            QString initialPrefix = "";
            if (outputLevel > LOG_INFO)
            {
                displayTime = QString("[%1] - ").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
                initialPrefix = displayTime;
            }

            QTextStream *writeStream = outputStream;
            if (level < LOG_INFO && errorStream)
            {
                writeStream = errorStream;
            }

            *writeStream << initialPrefix << message;
            if (newline)
            {
                *writeStream << endl;
            }

            writeStream->flush();
        }
    }

    pendingMessages.clear();
}
示例#27
0
bool IntraParser::parseFile(QTextStream* pcInputStream, ComSequence* pcSequence)
{
    Q_ASSERT( pcSequence != NULL );

    QString strOneLine;
    QRegExp cMatchTarget;


    /// <0,8> 8 36 31 36 30 36 31 36 0 36 2 36 1 36 0 36 1 36
    /// read one LCU
    ComFrame* pcFrame = NULL;
    ComCU* pcLCU = NULL;
    cMatchTarget.setPattern("^<(-?[0-9]+),([0-9]+)> (.*)");
    QTextStream cIntraDirInfoStream;
    int iDecOrder = -1;
    int iLastPOC  = -1;
    while( !pcInputStream->atEnd() )
    {

        strOneLine = pcInputStream->readLine();
        if( cMatchTarget.indexIn(strOneLine) != -1 )
        {
            /// poc and lcu addr
            int iPoc = cMatchTarget.cap(1).toInt();
            iDecOrder += (iLastPOC != iPoc);
            iLastPOC = iPoc;

            pcFrame = pcSequence->getFramesInDecOrder().at(iDecOrder);
            int iAddr = cMatchTarget.cap(2).toInt();
            pcLCU = pcFrame->getLCUs().at(iAddr);


            ///
            QString strIntraDir = cMatchTarget.cap(3);
            cIntraDirInfoStream.setString( &strIntraDir, QIODevice::ReadOnly );
            xReadIntraMode(&cIntraDirInfoStream, pcLCU);

        }

    }
    return true;
}
示例#28
0
void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    bool toFile = data.isOpen();

    QByteArray localMsg = msg.toLocal8Bit();
    QTextStream out;
    if (toFile)
        out.setDevice(&data);
    QString newLine = "\n";
    #ifdef Q_OS_WIN32
        newLine = "\r\n";
    #endif

    QString f = QString("%1").arg(context.function, -70, QChar(' '));

    switch (type) {
    case QtDebugMsg:
        if (toFile)
            out << "[" << f << "] " << localMsg << newLine;
        else
            fprintf(stderr, "%s %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtWarningMsg:
        if (toFile)
            out << "[" << f << "] " << "WARNING: " << localMsg << newLine;
        else
            fprintf(stderr, "%s WARNING: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtCriticalMsg:
        if (toFile)
            out << "[" << f << "] " << "CRITICAL: " << localMsg << newLine;
        else
            fprintf(stderr, "%s CRITICAL: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtFatalMsg:
        if (toFile)
            out << "[" << f << "] " << "FATAL: " << localMsg << newLine;
        else
            fprintf(stderr, "%s FATAL: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        abort();
    }
}
示例#29
0
void HttpServer :: replyGet(QTcpSocket *socket, QString const &req)
{
  QTextStream os (socket);
  os.setAutoDetectUnicode (true);
  QDir const dir (d->path.path() + req);
  auto contentFile = dir.canonicalPath();
  QFileInfo const info(contentFile);
  
  if (!info.exists() || !info.isFile() || !info.isReadable()) {
    os << "HTTP/1.0 404 Not Found\r\n"
      "\r\n";
  } else {
    
    auto size = QString::number(info.size());
    auto lastModified = info.lastModified().toString();
    auto suffix  = info.suffix();

    QFile file(contentFile);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      os << "HTTP/1.0 404 Not Found\r\n"
	"\r\n";
    }
    
    os << "HTTP/1.1 200 Ok\r\n"
      "Date: " << QDate::currentDate().toString() << "\r\n"
      "Last-Modified: " << lastModified << "\r\n"
      "Content-Type: text/html; charset=\"UTF-8\"\r\n"
      "Content-Length: " << size << "\r\n"
      "\r\n";
      
    QTextStream in(&file);
    while (!in.atEnd()) {
      os << in.readLine() << "\n";
    }
  }
  
  socket->close();

  if (socket->state() == QTcpSocket::UnconnectedState) {
    delete socket;
  }
}
bool CSVOldFormatConverter::convertFaculties(QString csvDirPath) {
  QFile facultiesCsv(csvDirPath + "/Факультет.csv");
  QTextStream facultiesStream;
  facultiesStream.setDevice(&facultiesCsv);
  facultiesStream.setCodec("UTF-8");
  if (!facultiesCsv.open(QIODevice::ReadOnly)) {
    return false;
  }
  QSqlQuery query;
  query.prepare("INSERT INTO university_faculty (name) VALUES (?)");
  while (!facultiesStream.atEnd()) {
    query.addBindValue(facultiesStream.readLine().split(';').at(1));
    if (!query.exec()) {
      return false;
    }
  }
  return true;
}