Beispiel #1
0
	Camera loadCamera(const char * filename)
	{
		std::cout << "loadCamera in file: " << filename << std::endl;
		Camera camera;
		std::ifstream fileOut(filename, std::ios::in | std::ios::binary);
		if (!fileOut.good())
		{
			std::cout << "loadCamera not found: " << filename << std::endl;
			camera.idFrame = 0;
			camera.eyePosition = LVector3(0.0, 0.0, 0.0);
			camera.lookAt = LVector3(0.0, 0.0, 0.0);
			camera.keyframe = false;
		}
		else
		{
			boost::archive::binary_iarchive ia(fileOut);
			ia & camera;
			fileOut.close();
		}

		return camera;
	}
Beispiel #2
0
static int inflateAndDump(const std::string& path, const std::string& targetDir)
{
	Common::NativeAllocator allocator;
	OSEnvironment::NativeThreadManager threads;
	OSEnvironment::Managers managers(allocator, threads);
	CFM::FragmentManager fragmentManager;
	CFM::PEFLibraryResolver pefResolver(allocator, fragmentManager);
	ClassixCore::DlfcnLibraryResolver dlfcnResolver(allocator, managers);
	
	dlfcnResolver.RegisterLibrary("StdCLib");
	
	fragmentManager.LibraryResolvers.push_back(&pefResolver);
	fragmentManager.LibraryResolvers.push_back(&dlfcnResolver);
	
	if (fragmentManager.LoadContainer(path))
	{
		for (auto& pair : fragmentManager)
		{
			if (CFM::PEFSymbolResolver* resolver = dynamic_cast<CFM::PEFSymbolResolver*>(pair.second))
			{
				PEF::Container& container = resolver->GetContainer();
				for (PEF::InstantiableSection& section : container)
				{
					std::stringstream pathSS;
					pathSS << targetDir << '/' << section.Name;
					std::fstream fileOut(pathSS.str(), std::ios_base::out | std::ios_base::binary);
					fileOut.write(reinterpret_cast<char*>(section.Data), section.Size());
				}
			}
		}
	}
	else
	{
		std::cerr << "Couln't load " << path << std::endl;
		return -2;
	}
	return 0;
}
Beispiel #3
0
bool M4SCpWindow::saveToFile(const QString &fileName)
{
    QFile fileOut(fileName);
    if (!fileOut.open(QFile::WriteOnly | QFile::Text))
    {
         QMessageBox::warning(0, tr("error"),
                              tr("Can't save file %1:\n%2.")
                              .arg(fileName)
                              .arg(fileOut.errorString()));
         return false;
    }
    QTextStream out(&fileOut);
    out << mEditor->document()->toPlainText();
    fileOut.close();

    mFileName = fileName;
    setWindowTitle(mFileName + "[*]");
    mIsSaved = true;

    emitEvent(EditorObserverInterface::ContentSaved);

    return true;
}
void QgsBinaryWidgetWrapper::saveContent()
{
  QgsSettings s;
  QString file = QFileDialog::getSaveFileName( nullptr,
                 tr( "Save Contents to File" ),
                 defaultPath(),
                 tr( "All files" ) + " (*.*)" );
  if ( file.isEmpty() )
  {
    return;
  }

  QFileInfo fi( file );
  s.setValue( QStringLiteral( "/UI/lastBinaryDir" ), fi.absolutePath() );

  QFile fileOut( file );
  fileOut.open( QIODevice::WriteOnly );
  fileOut.write( mValue );
  fileOut.close();

  if ( mMessageBar )
    mMessageBar->pushSuccess( QString(), tr( "Saved content to <a href=\"%1\">%2</a>" ).arg(
                                QUrl::fromLocalFile( file ).toString(), QDir::toNativeSeparators( file ) ) );
}
void Generator::generate()
{
    if (m_classes.size() == 0) {
        ReportHandler::warning(QString("%1: no java classes, skipping")
                               .arg(metaObject()->className()));
        return;
    }


    foreach (AbstractMetaClass *cls, m_classes) {
        if (!shouldGenerate(cls))
            continue;

        QString fileName = fileNameForClass(cls);
        ReportHandler::debugSparse(QString("generating: %1").arg(fileName));

        FileOut fileOut(outputDirectory() + "/" + subDirectoryForClass(cls) + "/" + fileName);
        write(fileOut.stream, cls);

        if( fileOut.done() )
            ++m_num_generated_written;
        ++m_num_generated;
    }
}
bool CsvOutput(EdgeFinder *edges, std::string networkType, std::string filename, std::string sep) {
    std::ofstream fileOut(filename.c_str());
    if(!fileOut.is_open()) {
	return false;
    }
    std::vector<std::vector <int> > myEdges = edges->GetEdges();
    std::vector<std::string> edgeNames = edges->GetNames();
    std::vector<std::string> edgeIntervals = edges->GetIntervals();
    std::vector<std::string> attributeIntervals = edges->GetAttributeInterval();
    std::vector<std::string> colNames = edges->GetHeader();
    
    // Below part write the header
    if(networkType == "Whole Network - Dynamic" || networkType == "Ego Network - Dynamic") {
	fileOut << "Source" << sep << "Target" << sep << "Type" << sep << "Weight" << sep << "Time Interval";
	fileOut << '\n';
    } else if(networkType == "Partial Network - Static" || networkType == "Ego Network - Static") {
	fileOut << "Source" << sep << "Target" << sep << "Type" << sep << "Weight" << sep << "Appearance";
	fileOut << '\n';
    }
    
    std::vector<std::vector <int> >::iterator it;
    for(it  = myEdges.begin(); it != myEdges.end(); it++) {
	// Writing the edges below
	std::vector<int> currentEntry = *it;
	if(!currentEntry.empty()) {      

	    if(networkType == "Whole Network - Dynamic" || networkType == "Ego Network - Dynamic") {
		fileOut << edgeNames[currentEntry[0]] << sep << edgeNames[currentEntry[1]] << sep << "Undirected" << sep;
		fileOut << "<";
		for(unsigned int i = 2; i != currentEntry.size() - 2; i++) {
		    if(i % 2 == 0) { 
			fileOut << attributeIntervals[currentEntry[i]];
		    } else {
			fileOut << currentEntry[i] << "],";
		    }
		}
		fileOut << attributeIntervals[currentEntry[currentEntry.size() - 2]];
		fileOut << currentEntry[currentEntry.size() - 1] << "]>" << sep;
	    }
	    else if(networkType == "Partial Network - Static" || networkType == "Ego Network - Static") {
		fileOut << edgeNames[currentEntry[0]] << sep << edgeNames[currentEntry[1]] << sep << "Undirected" << sep << currentEntry[2] << sep;
	    }
	    
	    if(networkType == "Whole Network - Dynamic" || networkType == "Ego Network - Dynamic") {
		fileOut << "<";
		for(unsigned int i = 2; i != currentEntry.size() - 2; i++) {
		    if(i % 2 == 0) {
			fileOut << edgeIntervals[currentEntry[i]] << ",";
		    }
		}
		fileOut << edgeIntervals[currentEntry[currentEntry.size() - 2]] << ">";
		fileOut << '\n';
				    
	    } else if(networkType == "Partial Network - Static" || networkType == "Ego Network - Static") {
		for(unsigned int i = 3; i != currentEntry.size() - 1; i++) {
		    fileOut << colNames[currentEntry[i]] << " - ";
		}
		fileOut << colNames[currentEntry[currentEntry.size()- 1]];
		fileOut << '\n';
	    }
	}
    }
    fileOut.close();
    return true;
}
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	if (argc < 3) {
		std::cerr << QString::fromUtf8("Usage: %1 <in-file> <out-file>\n").arg(argv[0]).toStdString();
		return -1;
	}

	QFile fileIn(argv[1]);
	QFile fileOut(argv[2]);

	if (!fileIn.open(QIODevice::ReadOnly)) {
		std::cerr << QString::fromUtf8("Unable to open \"%1\" for reading\n").arg(fileIn.fileName()).toUtf8().data();
		return -2;
	}

	if (!fileOut.open(QIODevice::WriteOnly)) {
		std::cerr << QString::fromUtf8("Unable to open \"%1\" for writing\n").arg(fileOut.fileName()).toUtf8().data();
		return -3;
	}

	fileOut.write(QByteArray("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n"));
	fileOut.write(QByteArray("<osis xmlns=\"http://www.bibletechnologies.net/2003/OSIS/namespace\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.bibletechnologies.net/2003/OSIS/namespace http://www.bibletechnologies.net/osisCore.2.1.1.xsd\">\n\n"));
	fileOut.write(QByteArray("<osisText osisIDWork=\"RVG2010\" osisRefWork=\"defaultReferenceScheme\" lang=\"es\">\n\n"));
	fileOut.write(QByteArray("<header>\n"));
	fileOut.write(QByteArray("<work osisWork=\"RVG2010\">\n"));
	fileOut.write(QByteArray("<title>Reina Valera Gómez 2010 (edition 2015-01-20)</title>\n"));
	fileOut.write(QByteArray("<identifier type=\"OSIS\">Bible.RVG2010</identifier>\n"));
	fileOut.write(QByteArray("<refSystem>Bible.KJV</refSystem>\n"));
	fileOut.write(QByteArray("</work>\n"));
	fileOut.write(QByteArray("<work osisWork=\"defaultReferenceScheme\">\n"));
	fileOut.write(QByteArray("<refSystem>Bible.KJV</refSystem>\n"));
	fileOut.write(QByteArray("</work>\n"));
	fileOut.write(QByteArray("</header>\n"));

	unsigned int nVerseCount = 0;
	unsigned int nTst = 0;

	for (unsigned int nBk = 0; nBk < NUM_BK; ++nBk) {
		if ((nBk == 0) || (nBk == NUM_BK_OT))
			fileOut.write(QByteArray("<div type=\"x-testament\">\n"));


		QStringList lstVerseCounts = g_arrChapterVerseCounts[nBk].split(",");		// Number of chapters = size of lstVerseCounts, each entry is number of verses in chapter

		std::cout << QString::fromUtf8("Book: %1\n").arg(g_arrBooks[nBk].m_strName).toUtf8().data();
		fileOut.write(QString::fromUtf8("<div type=\"book\" osisID=\"%1\">\n").arg(g_arrBooks[nBk].m_strOsisAbbr).toUtf8());

		for (unsigned int nChp = 0; nChp < static_cast<unsigned int>(lstVerseCounts.size()); ++nChp) {
			unsigned int nVerses = lstVerseCounts.at(nChp).toUInt();

			std::cout << QString::fromUtf8("    Chapter: %1").arg(nChp+1).toUtf8().data();
			fileOut.write(QString::fromUtf8("<chapter osisID=\"%1.%2\">\n").arg(g_arrBooks[nBk].m_strOsisAbbr).arg(nChp+1).toUtf8().data());

			for (unsigned int nVrs = 0; nVrs < nVerses; ++nVrs) {
				if (fileIn.atEnd()) {
					std::cerr << "Unexpected end of input file!";
					break;
				}

				++nVerseCount;

				std::cout << ".";
				fileOut.write(QString::fromUtf8("<verse osisID=\"%1.%2.%3\">%4").arg(g_arrBooks[nBk].m_strOsisAbbr).arg(nChp+1).arg(nVrs+1).arg(convertVerseText(QString::fromUtf8(fileIn.readLine()), nBk, nChp, nVrs).trimmed()).toUtf8().data());
				fileOut.write(QByteArray("</verse>\n"));
			}

			std::cout << "\n";
			fileOut.write(QByteArray("</chapter>\n"));
		}

		fileOut.write(QByteArray("</div>\n"));				// End of Book

		if ((nBk == (NUM_BK_OT - 1)) || (nBk == (NUM_BK - 1))) {
			fileOut.write(QByteArray("</div>\n"));			// End of testament
			nTst++;
		}
	}

	if (nVerseCount != 31102) {
		std::cerr << QString::fromUtf8("Error: Expected 31102 verses, but found %1").arg(nVerseCount).toUtf8().data();
	}

	fileOut.write(QByteArray("\n</osisText>\n"));
	fileOut.write(QByteArray("\n</osis>\n"));

	fileOut.close();
	fileIn.close();

//	return a.exec();
	return 0;
}
Beispiel #8
0
int main(int argc, char **argv)
{
	if (argc < 3){
		fprintf(stderr, "Usage: wavCopy <input file> <output file>\n");
		return -1;
	}

	SF_INFO soundInfoIn; /* Input sound file Info */

	uint i;
	short sample[2];
	short tmp[2];

	std::string file = "testfile";

	std::string fileIn(argv[argc-2]);
	std::string fileOut(argv[2]);

	// long valAvg = 0;
	// long diffAvg = 0;

	{
		Predictor p(100);

		SFReader sfReader(fileIn);

		sfReader.open();
		sfReader.printInfo();

		BitStream bs1 = BitStream(file, BitStream::WRITE);


		if (bs1.open() != 0){
    		printf("Error closing!\n");
    	}


		for (i = 0; i < sfReader.getNFrames() ; i++)
		{

			sfReader.nextFrame(sample);

			p.predict(tmp);

			Golomb::encode(VAL_M, tmp[0] - sample[0], bs1);
			Golomb::encode(VAL_M, tmp[1] - sample[1], bs1);

			// valAvg += 2*abs(sample[0]);
			// valAvg += 2*abs(sample[1]);

			// diffAvg += abs(2*(prevSample[0] - sample[0]));
			// diffAvg += abs(2*(prevSample[1] - sample[1]));

			p.update(sample);
		}

		// printf("%ld, %ld\n", valAvg/(long)frames*2, diffAvg/(long)frames*2);

		if (bs1.close() != 0){
        	printf("Error closing!\n");
    	}
    	sfReader.close();
    	soundInfoIn = sfReader.getInfo();
	}

	{

		Predictor p(100);

		SFWriter sfWriter(fileOut,
			soundInfoIn.frames, soundInfoIn.samplerate, soundInfoIn.channels);

		BitStream bs2 = BitStream(file, BitStream::READ);

		if (bs2.open() != 0){
    		printf("Error opening!\n");
    		return -1;
    	}

    	sfWriter.printInfo();
    	sfWriter.open();


		int smp = 0;


		while (true){
			p.predict(tmp);

			if (Golomb::decode(VAL_M, &smp, bs2)!=0)
				break;

			sample[0] = tmp[0] - (short)smp;

			if (Golomb::decode(VAL_M, &smp, bs2)!=0)
				break;

			sample[1] = tmp[1] - (short)smp;


			sfWriter.writeFrame(sample);

			p.update(sample);

		}
		bs2.close();
		sfWriter.close();

	}

	char dumbness[50];
	strcpy(dumbness, "cmp ");
	strcat(dumbness, argv[1]);
	strcat(dumbness, " ");
	strcat(dumbness, argv[2]);

	if (system(dumbness) != 0)
		printf("uh oh\n");
	else {
		printf("files match\n");
		strcpy(dumbness, "ls -sh -1 ");
		strcat(dumbness, argv[1]);
		strcat(dumbness, " ");
		strcat(dumbness, file.c_str());
		system(dumbness);
	}

	return 0;
}
Beispiel #9
0
    QString myPixRead(const QString &list)
    {
	QString imageInfo;
	l_int32    d = 0;
	l_uint32 pxres = 0,pyres = 0;
	l_float32  scalex = 0.0,scaley = 0.0;
	PIX *pixs = NULL, *pix1 = NULL, *pixd = NULL;
    
	QStringList list2 = list.split(",");
	if (list2.count() != 2) {
		 return QObject::tr("Failed to read QStringList");
	     }
	const QByteArray aux1 = list2.at(0).toUtf8(); //aux1 and aux2 must be not delete or change
	const char *fileName = aux1.constData();
	const QByteArray aux2 = list2.at(1).toUtf8();
	int page = aux2.toInt(0,10);
	if (page == 0) {
	    if ((pixs = pixRead(fileName)) == NULL) {
		 QString msg = QObject::tr("Failed to open image %1").arg(fileName);
		 return msg;
	     }
	}
	else {
	    if ((pixs = pixReadTiff(fileName, page)) == NULL) {
		 QString msg = QObject::tr("Failed to open subimage %1 %2")
				 .arg(fileName)
				 .arg(page);
		 return msg;
	    }
	}
    
    
	d = pixGetDepth(pixs);
	if (d != 1 && d != 2 && d != 4 && d != 8 && d != 16 && d != 32) {
	     QString msg = QObject::tr("depth image must be 1,2,4,8,16 or 32");
	     return msg;
	}
    
	pixGetResolution(pixs,&pxres,&pyres);
	imageInfo = QString("%1,%2,%3,%4,%5").arg(page).arg(pixs->w).arg(pixs->h).arg(pxres)
										    .arg(pyres);
	if (pxres && pyres) {
	    scalex = 300.0 / pxres;
	    scaley = 300.0 / pyres;
	    pix1 = pixScale(pixs,scalex,scaley);
	    if (pix1->d > 1) {
		pixd = pixConvertTo8(pix1,FALSE);
		pixDestroy(&pix1);
	    }
	    else
		pixd = pix1;
	}
	else
	    if (pixs->d > 1)
		pixd = pixConvertTo8(pixs,FALSE);
	    else
		pixd = pixClone(pixs);
	pixDestroy(&pixs);
	
	/* ------------------ Image file format types -------------- */
	/*  
	 *  The IFF_UNKNOWN flag is used to write the file out in
	 *  a compressed and lossless format; namely, IFF_TIFF_G4
	 *  for d = 1 and IFF_PNG for everything else.
	 */
	QByteArray fileOut(getTempFileName(aux1,page));
	if (pixWrite(fileOut.constData(),pixd,IFF_DEFAULT)) {
	     QString msg = QObject::tr("pix not written to file");
	     return msg;
	}
	pixDestroy(&pixd);
	return imageInfo;
    }
void Solution::writeToFile(string file_name)
{
	fstream fileOut(file_name.c_str(), ios_base::out);
	for(vector<Process*>::iterator it = processes_.begin(); it != processes_.end(); it++)
	  fileOut << (*it)->getMachine()->getId() << "  ";
}
Beispiel #11
0
void DoMuscle(CompositeVect*CVLocation)
	{
	SetOutputFileName(g_pstrOutFileName);
	SetInputFileName(g_pstrInFileName);

	SetMaxIters(g_uMaxIters);
	SetSeqWeightMethod(g_SeqWeight1);

	TextFile fileIn(g_pstrInFileName);
	SeqVect v;
	v.FromFASTAFile(fileIn);
	const unsigned uSeqCount = v.Length();

	if (0 == uSeqCount)
		Quit("No sequences in input file");

	ALPHA Alpha = ALPHA_Undefined;
	switch (g_SeqType)
		{
	case SEQTYPE_Auto:
		Alpha = v.GuessAlpha();
		break;

	case SEQTYPE_Protein:
		Alpha = ALPHA_Amino;
		break;

	case SEQTYPE_DNA:
		Alpha = ALPHA_DNA;
		break;

	case SEQTYPE_RNA:
		Alpha = ALPHA_RNA;
		break;

	default:
		Quit("Invalid seq type");
		}
	SetAlpha(Alpha);
	v.FixAlpha();

	PTR_SCOREMATRIX UserMatrix = 0;
	if (0 != g_pstrMatrixFileName)
		{
		const char *FileName = g_pstrMatrixFileName;
		const char *Path = getenv("MUSCLE_MXPATH");
		if (Path != 0)
			{
			size_t n = strlen(Path) + 1 + strlen(FileName) + 1;
			char *NewFileName = new char[n];
			sprintf(NewFileName, "%s/%s", Path, FileName);
			FileName = NewFileName;
			}
		TextFile File(FileName);
		UserMatrix = ReadMx(File);
		g_Alpha = ALPHA_Amino;
		g_PPScore = PPSCORE_SP;
		}

	SetPPScore();

	if (0 != UserMatrix)
		g_ptrScoreMatrix = UserMatrix;

	unsigned uMaxL = 0;
	unsigned uTotL = 0;
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		unsigned L = v.GetSeq(uSeqIndex).Length();
		uTotL += L;
		if (L > uMaxL)
			uMaxL = L;
		}

	SetIter(1);
	g_bDiags = g_bDiags1;
	SetSeqStats(uSeqCount, uMaxL, uTotL/uSeqCount);

	SetMuscleSeqVect(v);

	MSA::SetIdCount(uSeqCount);

// Initialize sequence ids.
// From this point on, ids must somehow propogate from here.
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		v.SetSeqId(uSeqIndex, uSeqIndex);

	if (0 == uSeqCount)
		Quit("Input file '%s' has no sequences", g_pstrInFileName);
	if (1 == uSeqCount)
		{
		TextFile fileOut(g_pstrOutFileName, true);
		v.ToFile(fileOut);
		return;
		}

	if (uSeqCount > 1)
		MHackStart(v);

// First iteration
	Tree GuideTree;
	if (0 != g_pstrUseTreeFileName)
	{
	// Discourage users...
		if (!g_bUseTreeNoWarn)
			fprintf(stderr, "%s", g_strUseTreeWarning);

	// Read tree from file
		TextFile TreeFile(g_pstrUseTreeFileName);
		GuideTree.FromFile(TreeFile);

	// Make sure tree is rooted
		if (!GuideTree.IsRooted())
			Quit("User tree must be rooted");

		if (GuideTree.GetLeafCount() != uSeqCount)
			Quit("User tree does not match input sequences");

		const unsigned uNodeCount = GuideTree.GetNodeCount();
		for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
			{
			if (!GuideTree.IsLeaf(uNodeIndex))
				continue;
			const char *LeafName = GuideTree.GetLeafName(uNodeIndex);
			unsigned uSeqIndex;
			bool SeqFound = v.FindName(LeafName, &uSeqIndex);
			if (!SeqFound)
				Quit("Label %s in tree does not match sequences", LeafName);
			unsigned uId = v.GetSeqIdFromName(LeafName);
			GuideTree.SetLeafId(uNodeIndex, uId);
			}
		}
	else
		TreeFromSeqVect(v, GuideTree, g_Cluster1, g_Distance1, g_Root1,
		  g_pstrDistMxFileName1);

	const char *Tree1 = ValueOpt("Tree1");
	if (0 != Tree1)
		{
		TextFile f(Tree1, true);
		GuideTree.ToFile(f);
		if (g_bClusterOnly)
			return;
		}

	SetMuscleTree(GuideTree);
	ValidateMuscleIds(GuideTree);

	MSA msa;
	msa.SetCompositeVector(CVLocation);
	ProgNode *ProgNodes = 0;
	if (g_bLow)
		ProgNodes = ProgressiveAlignE(v, GuideTree, msa);
	else
		ProgressiveAlign(v, GuideTree, msa);
	SetCurrentAlignment(msa);

	if (0 != g_pstrComputeWeightsFileName)
		{
		extern void OutWeights(const char *FileName, const MSA &msa);
		SetMSAWeightsMuscle(msa);
		OutWeights(g_pstrComputeWeightsFileName, msa);
		return;
		}

	ValidateMuscleIds(msa);

	if (1 == g_uMaxIters || 2 == uSeqCount)
		{
		//TextFile fileOut(g_pstrOutFileName, true);
		//MHackEnd(msa);
		//msa.ToFile(fileOut);
		MuscleOutput(msa);
		return;
		}

	if (0 == g_pstrUseTreeFileName)
		{
		g_bDiags = g_bDiags2;
		SetIter(2);

		if (g_bLow)
			{
			if (0 != g_uMaxTreeRefineIters)
				RefineTreeE(msa, v, GuideTree, ProgNodes);
			}
		else
			RefineTree(msa, GuideTree);

		const char *Tree2 = ValueOpt("Tree2");
		if (0 != Tree2)
			{
			TextFile f(Tree2, true);
			GuideTree.ToFile(f);
			}
		}

	SetSeqWeightMethod(g_SeqWeight2);
	SetMuscleTree(GuideTree);

	if (g_bAnchors)
		RefineVert(msa, GuideTree, g_uMaxIters - 2);
	else
		RefineHoriz(msa, GuideTree, g_uMaxIters - 2, false, false);

#if	0
// Refining by subfamilies is disabled as it didn't give better
// results. I tried doing this before and after RefineHoriz.
// Should get back to this as it seems like this should work.
	RefineSubfams(msa, GuideTree, g_uMaxIters - 2);
#endif

	ValidateMuscleIds(msa);
	ValidateMuscleIds(GuideTree);

	//TextFile fileOut(g_pstrOutFileName, true);
	//MHackEnd(msa);
	//msa.ToFile(fileOut);
	MuscleOutput(msa);
	}
Beispiel #12
0
static void DoOutput(MSA &msa)
	{
	bool AnyOutput = false;

// Value options
	if (g_pstrFASTAOutFileName)
		{
		TextFile File(g_pstrFASTAOutFileName, true);
		msa.ToFASTAFile(File);
		AnyOutput = true;
		}

	if (g_pstrMSFOutFileName)
		{
		TextFile File(g_pstrMSFOutFileName, true);
		msa.ToMSFFile(File);
		AnyOutput = true;
		}

	if (g_pstrClwOutFileName)
		{
		TextFile File(g_pstrClwOutFileName, true);
		msa.ToAlnFile(File);
		AnyOutput = true;
		}

	if (g_pstrClwStrictOutFileName)
		{
		g_bClwStrict = true;
		TextFile File(g_pstrClwStrictOutFileName, true);
		msa.ToAlnFile(File);
		AnyOutput = true;
		}

	if (g_pstrHTMLOutFileName)
		{
		TextFile File(g_pstrHTMLOutFileName, true);
		msa.ToHTMLFile(File);
		AnyOutput = true;
		}

	if (g_pstrPHYIOutFileName)
		{
		TextFile File(g_pstrPHYIOutFileName, true);
		msa.ToPhyInterleavedFile(File);
		AnyOutput = true;
		}

	if (g_pstrPHYSOutFileName)
		{
		TextFile File(g_pstrPHYSOutFileName, true);
		msa.ToPhySequentialFile(File);
		AnyOutput = true;
		}

// Flag options, at most one used (because only one -out filename)
	TextFile fileOut(g_pstrOutFileName, true);
	if (g_bFASTA)
		{
		msa.ToFASTAFile(fileOut);
		AnyOutput = true;
		}
	else if (g_bMSF)
		{
		msa.ToMSFFile(fileOut);
		AnyOutput = true;
		}
	else if (g_bAln)
		{
		msa.ToAlnFile(fileOut);
		AnyOutput = true;
		}
	else if (g_bHTML)
		{
		msa.ToHTMLFile(fileOut);
		AnyOutput = true;
		}
	else if (g_bPHYI)
		{
		msa.ToPhyInterleavedFile(fileOut);
		AnyOutput = true;
		}
	else if (g_bPHYS)
		{
		msa.ToPhySequentialFile(fileOut);
		AnyOutput = true;
		}

// If -out option was given but no flags, output as FASTA
	if (!AnyOutput)
		msa.ToFASTAFile(fileOut);
	
	fileOut.Close();

	if (0 != g_pstrScoreFileName)
		WriteScoreFile(msa);
	}
void Program::createLogFile()
{
	std::wstring filePath = boost::str(boost::wformat(L"%1%\\audio.txt") % savePath);
	std::fstream fileOut(filePath.c_str(), std::ios_base::out);
	fileOut.close();
}
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	g_setBooks();

	if (argc != 3) {
		std::cerr << QString("Usage: %1 <in-file> <out-file>\n").arg(argv[0]).toStdString();
		return -1;
	}

	QFile fileIn(argv[1]);
	QFile fileOut(argv[2]);


	if (!fileIn.open(QIODevice::ReadOnly)) {
		std::cerr << QString("Unable to open \"%1\" for reading\n").arg(fileIn.fileName()).toUtf8().data();
		return -2;
	}

	if (!fileOut.open(QIODevice::WriteOnly)) {
		std::cerr << QString("Unable to open \"%1\" for writing\n").arg(fileOut.fileName()).toUtf8().data();
		return -3;
	}

	fileOut.write(QString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n").toUtf8());
	fileOut.write(QString("<osis xmlns=\"http://www.bibletechnologies.net/2003/OSIS/namespace\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.bibletechnologies.net/2003/OSIS/namespace http://www.bibletechnologies.net/osisCore.2.1.1.xsd\">\n\n").toUtf8());
	fileOut.write(QString("<osisText osisIDWork=\"RV1865\" osisRefWork=\"defaultReferenceScheme\" lang=\"es\">\n\n").toUtf8());
	fileOut.write(QString("<header>\n").toUtf8());
	fileOut.write(QString("<work osisWork=\"RV1865\">\n").toUtf8());
	fileOut.write(QString("<title>Reina-Valera 1865 para Jeff McArdle, La Sociedad Biblica Valera: 22 de Junio de 2014.</title>\n").toUtf8());
	fileOut.write(QString("<identifier type=\"OSIS\">Bible.RV1865</identifier>\n").toUtf8());
	fileOut.write(QString("<refSystem>Bible.KJV</refSystem>\n").toUtf8());
	fileOut.write(QString("</work>\n").toUtf8());
	fileOut.write(QString("<work osisWork=\"defaultReferenceScheme\">\n").toUtf8());
	fileOut.write(QString("<refSystem>Bible.KJV</refSystem>\n").toUtf8());
	fileOut.write(QString("</work>\n").toUtf8());
	fileOut.write(QString("</header>\n").toUtf8());

	fileOut.write("<div type=\"x-testament\">\n");

	QString strLine;

	strLine = QString::fromUtf8(fileIn.readLine()).trimmed();			// Book Subtitle

	for (unsigned int nBk=0; nBk<NUM_BK; ++nBk) {
		QString strOsisAbbr = g_arrBooks[nBk].m_strOsisAbbr;
		QStringList lstCounts = g_arrChapterVerseCounts[nBk].split(",");

		if (fileIn.atEnd()) {
			std::cerr << "Unexpected end of file!!\n";
			break;
		}

		// Note: Have already read Subtitle either before loop or at bottom of loop (needed for colophon processing)

		fileOut.write(QString("<div type=\"book\" osisID=\"%1\" canonical=\"true\">\n").arg(strOsisAbbr).toUtf8().data());

		if (!strLine.isEmpty()) {
			fileOut.write(QString("<title type=\"main\">%1</title>\n").arg(convertVerseText(strLine)).toUtf8().data());
		}
		strLine = QString::fromUtf8(fileIn.readLine()).trimmed();			// Book Title

		for (int nChp = 0; nChp < lstCounts.size(); ++nChp) {
			if (fileIn.atEnd()) {
				std::cerr << "Unexpected end of file!!\n";
				break;
			}
			strLine = QString::fromUtf8(fileIn.readLine()).trimmed();		// Blank line separates each chapter


			fileOut.write(QString("<chapter osisID=\"%1.%2\">\n").arg(strOsisAbbr).arg(nChp+1).toUtf8().data());

			int nVrsCount = lstCounts.at(nChp).toInt();
			for (int nVrs = 0; nVrs < nVrsCount; ++nVrs) {
				if (fileIn.atEnd()) {
					std::cerr << "Unexpected end of file!!\n";
					break;
				}
				strLine = QString::fromUtf8(fileIn.readLine()).trimmed();

				int nSpaceIndex = strLine.indexOf(' ');
				int nDocVerse = ((nSpaceIndex != -1) ? strLine.left(nSpaceIndex).toInt() : 0);
				if (nDocVerse != 0) {
					strLine = strLine.mid(nSpaceIndex+1);		// note: with the +1, will be whole line if there was no space
				}

				if ((nDocVerse == 0) &&
					(nBk+1 == PSALMS_BOOK_NUM) &&
					(strLine.left(1).compare(QString::fromUtf8("«")) == 0) &&
					(strLine.right(1).compare(QString::fromUtf8("»")) == 0)) {
					fileOut.write("<title type=\"psalm\" canonical=\"true\">");
					fileOut.write(convertVerseText(strLine.mid(1, strLine.length()-2)).toUtf8().data());
					fileOut.write("</title>\n");
					--nVrs;
				} else {
					fileOut.write(QString("<verse osisID=\"%1.%2.%3\" sID=\"%1.%2.%3\"/>").arg(strOsisAbbr).arg(nChp+1).arg(nVrs+1).toUtf8().data());
//					fileOut.write(QString("<verse osisID=\"%1.%2.%3\">").arg(strOsisAbbr).arg(nChp+1).arg(nVrs+1).toUtf8().data());
					if ((nBk+1 == PSALMS_BOOK_NUM) && (nChp+1 == 119) &&
						((nVrs % 8) == 0)) {
						// Add Psalm 119 acrostics:
						QString strLetterName;
						QChar qcHebrewLetter;
						switch (nVrs/8) {
							// Spellings here as per RV1865 document:
							case 0:		strLetterName = "ALEF";		qcHebrewLetter = QChar(0x005D0);	break;
							case 1:		strLetterName = "BET";		qcHebrewLetter = QChar(0x005D1);	break;
							case 2:		strLetterName = "GIMEL";	qcHebrewLetter = QChar(0x005D2);	break;
							case 3:		strLetterName = "DALET";	qcHebrewLetter = QChar(0x005D3);	break;
							case 4:		strLetterName = "HE";		qcHebrewLetter = QChar(0x005D4);	break;
							case 5:		strLetterName = "VAU";		qcHebrewLetter = QChar(0x005D5);	break;
							case 6:		strLetterName = "ZAIN";		qcHebrewLetter = QChar(0x005D6);	break;
							case 7:		strLetterName = "HET";		qcHebrewLetter = QChar(0x005D7);	break;
							case 8:		strLetterName = "TET";		qcHebrewLetter = QChar(0x005D8);	break;
							case 9:		strLetterName = "JOD";		qcHebrewLetter = QChar(0x005D9);	break;
							case 10:	strLetterName = "CAF";		qcHebrewLetter = QChar(0x005DB);	break;	// Using nonfinal-Caph
							case 11:	strLetterName = "LAMED";	qcHebrewLetter = QChar(0x005DC);	break;
							case 12:	strLetterName = "MEM";		qcHebrewLetter = QChar(0x005DE);	break;	// Using nonfinal-Mem
							case 13:	strLetterName = "NUN";		qcHebrewLetter = QChar(0x005E0);	break;	// Using nonfinal-Nun
							case 14:	strLetterName = "SAMEC";	qcHebrewLetter = QChar(0x005E1);	break;
							case 15:	strLetterName = "AIN";		qcHebrewLetter = QChar(0x005E2);	break;
							case 16:	strLetterName = "PE";		qcHebrewLetter = QChar(0x005E4);	break;	// Using nonfinal-Pe
							case 17:	strLetterName = "ZADE";		qcHebrewLetter = QChar(0x005E6);	break;	// Using nonfinal-Tzaddi
							case 18:	strLetterName = "COF";		qcHebrewLetter = QChar(0x005E7);	break;
							case 19:	strLetterName = "RES";		qcHebrewLetter = QChar(0x005E8);	break;
							case 20:	strLetterName = "SIN";		qcHebrewLetter = QChar(0x005E9);	break;
							case 21:	strLetterName = "TAU";		qcHebrewLetter = QChar(0x005EA);	break;
							default:	break;
						}
						if (!strLetterName.isEmpty()) {
							fileOut.write(QString("<title type=\"acrostic\" canonical=\"true\"><foreign n=\"%1\">%2.</foreign></title>").arg(qcHebrewLetter).arg(strLetterName).toUtf8().data());
						} else {
							std::cerr << QString("Error : Invalid Hebrew Acrostic index for Verse %1\n").arg(nVrs+1).toUtf8().data();
						}
					}
					fileOut.write(convertVerseText(strLine).toUtf8().data());
					fileOut.write(QString("<verse eID=\"%1.%2.%3\"/>\n").arg(strOsisAbbr).arg(nChp+1).arg(nVrs+1).toUtf8().data());
//					fileOut.write(QString("</verse>\n").toUtf8().data());
					if (nDocVerse != nVrs+1) {
						std::cerr << QString("Error : Expected %1 %2:%3, found %4 %5").arg(strOsisAbbr).arg(nChp+1).arg(nVrs+1).arg(nDocVerse).arg(strLine).toUtf8().data() << std::endl;
					}
				}
			}

			fileOut.write("</chapter>\n");
		}

		strLine = QString::fromUtf8(fileIn.readLine()).trimmed();				// Book Subtitle
		if ((strLine.left(1).compare(QString::fromUtf8("«")) == 0) &&
			(strLine.right(1).compare(QString::fromUtf8("»")) == 0)) {
			fileOut.write(QString("<div type=\"colophon\" osisID=\"%1.c\">").arg(strOsisAbbr).toUtf8().data());
			fileOut.write(convertVerseText(strLine.mid(1, strLine.length()-2)).toUtf8().data());
			fileOut.write("</div>\n");
			strLine = QString::fromUtf8(fileIn.readLine()).trimmed();			// Book Subtitle
		}

		fileOut.write("</div>\n");

		if (nBk+1 == NUM_BK_OT) {
			fileOut.write("</div>\n");
			fileOut.write("<div type=\"x-testament\">\n");
		}
	}

	fileOut.write("</div>\n");

	fileOut.write("</osisText>\n");
	fileOut.write("</osis>\n");

	fileOut.close();
	fileIn.close();

//	return a.exec();
	return 0;
}
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	if (argc < 3) {
		std::cerr << QString("Usage: %1 <in-file> <out-file>\n").arg(argv[0]).toStdString();
		return -1;
	}

	QFile fileIn(argv[1]);
	QFile fileOut(argv[2]);

	if (!fileIn.open(QIODevice::ReadOnly)) {
		std::cerr << QString("Unable to open \"%1\" for reading\n").arg(fileIn.fileName()).toStdString();
		return -2;
	}

	if (!fileOut.open(QIODevice::WriteOnly)) {
		std::cerr << QString("Unable to open \"%1\" for writing\n").arg(fileOut.fileName()).toStdString();
		return -3;
	}

	fileOut.write(QString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n").toUtf8());
	fileOut.write(QString("<osis xmlns=\"http://www.bibletechnologies.net/2003/OSIS/namespace\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.bibletechnologies.net/2003/OSIS/namespace http://www.bibletechnologies.net/osisCore.2.1.1.xsd\">\n\n").toUtf8());
	fileOut.write(QString("<osisText osisIDWork=\"KJF\" osisRefWork=\"defaultReferenceScheme\" lang=\"fr\">\n\n").toUtf8());
	fileOut.write(QString("<header>\n").toUtf8());
	fileOut.write(QString("<work osisWork=\"KJF\">\n").toUtf8());
	fileOut.write(QString::fromUtf8("<title>la Bible King James Française, édition 2015</title>\n").toUtf8());
	fileOut.write(QString("<identifier type=\"OSIS\">Bible.KJF</identifier>\n").toUtf8());
	fileOut.write(QString("<refSystem>Bible.KJV</refSystem>\n").toUtf8());
	fileOut.write(QString("</work>\n").toUtf8());
	fileOut.write(QString("<work osisWork=\"defaultReferenceScheme\">\n").toUtf8());
	fileOut.write(QString("<refSystem>Bible.KJV</refSystem>\n").toUtf8());
	fileOut.write(QString("</work>\n").toUtf8());
	fileOut.write(QString("</header>\n").toUtf8());

	unsigned int nBk = 0;
	unsigned int nChp = 0;
	unsigned int nVrs = 0;

	while (!fileIn.atEnd()) {
		QByteArray arrLine;
		QString strLine;

		arrLine = fileIn.readLine();
		strLine = QString::fromUtf8(arrLine.data(), arrLine.size());
		if ((strLine.isEmpty()) || (strLine.at(0) == '\n') || (strLine.at(0) != '#')) continue;

		int nOsisSplit = strLine.indexOf(' ');
		QString strOsisRef = strLine.left(nOsisSplit);
		if (nOsisSplit != -1) {
			strLine = strLine.mid(nOsisSplit+1);
		} else {
			strLine.clear();
		}
		QStringList strOsisParts = strOsisRef.split('.');
		QString strBookName = strOsisParts.at(0).mid(1);
		unsigned int nBkNew;
		for (nBkNew = 1; nBkNew <= NUM_BK; ++nBkNew) {
			if (strBookName.compare(g_arrBooks[nBkNew-1].m_strOsisAbbr, Qt::CaseInsensitive) == 0) break;
		}
		if (nBkNew > NUM_BK) continue;
		unsigned int nChpNew = ((strOsisParts.size() > 1) ? (strOsisParts.at(1).toUInt()) : 0);
		if (nChpNew == 0) continue;
		unsigned int nVrsNew = ((strOsisParts.size() > 2) ? (strOsisParts.at(2).toUInt()) : 0);

		while (nBk < nBkNew) {
			QStringList lstCounts;
			if (nBk) lstCounts = g_arrChapterVerseCounts[nBk-1].split(",");

			if (nVrs) {
				fileOut.write(QString("</verse>\n").toUtf8());
				nVrs = 0;
			}

			if (nChp) {
				fileOut.write(QString("</chapter>\n").toUtf8());
			}

			while (nChp < static_cast<unsigned int>(lstCounts.size())) {
				++nChp;
				std::cout << QString(".").toUtf8().data();
				fileOut.write(QString("<chapter osisID=\"%1.%2\">\n").arg(g_arrBooks[nBk-1].m_strOsisAbbr).arg(nChp).toUtf8());
				fileOut.write(QString("</chapter>\n").toUtf8());
			}
			nChp = 0;
			if (nBk) {
				std::cout << QString("\n").toUtf8().data();
				fileOut.write(QString("</div>\n").toUtf8());
			}
			++nBk;
			std::cout << QString("Book: %1").arg(g_arrBooks[nBk-1].m_strOsisAbbr).toUtf8().data();

			fileOut.write(QString("<div type=\"book\" osisID=\"%1\">\n").arg(g_arrBooks[nBk-1].m_strOsisAbbr).toUtf8());
		}


		while (nChp < nChpNew) {
			if (nVrs) {
				fileOut.write(QString("</verse>\n").toUtf8());
				nVrs = 0;
			}
			if (nChp) {
				fileOut.write(QString("</chapter>\n").toUtf8());
			}
			++nChp;
			std::cout << QString(".").toUtf8().data();

			fileOut.write(QString("<chapter osisID=\"%1.%2\">\n").arg(g_arrBooks[nBk-1].m_strOsisAbbr).arg(nChp).toUtf8());
		}

		if (nVrsNew != nVrs) {
			if (nVrs) {
				fileOut.write(QString("</verse>\n").toUtf8());
			}
			nVrs = nVrsNew;

			if (nVrs != 0) {
				fileOut.write(QString("<verse osisID=\"%1.%2.%3\">").arg(g_arrBooks[nBk-1].m_strOsisAbbr).arg(nChp).arg(nVrs).toUtf8());
			}
		}
		if (nVrs == 0) continue;

		fileOut.write(convertVerseText(strLine.trimmed()).toUtf8());

// TODO : Handle Superscriptions and Colophons
//
//		if (strLine.at(0) == QChar('^')) {
//			fileOut.write(QString("<title canonical=\"true\" subType=\"x-preverse\" type=\"section\">%1 </title>").arg(convertVerseText(strLine.mid(1).trimmed())).toUtf8());
//		} else if (strLine.at(0) == QChar('@')) {
//			//<div osisID="Heb.c" type="colophon">Written to the Hebrews from Italy by Timothy.</div>
//			if (!strVerseText.isEmpty()) {
//				fileOut.write(QString("<verse osisID=\"%1.%2.%3\">%4").arg(g_arrBooks[nBk-1].m_strOsisAbbr).arg(nChp).arg(nVrs).arg(convertVerseText(strVerseText)).toUtf8());
//				strVerseText.clear();
//				fileOut.write(QString("<div osisID=\"%1.c\" type=\"colophon\">%2</div>").arg(g_arrBooks[nBk-1].m_strOsisAbbr).arg(convertVerseText(strLine.mid(1).trimmed())).toUtf8());
//				fileOut.write(QString("</verse>\n").toUtf8());
//			} else {
//				assert(false);			// Colophon tags are always following a verse!
//			}

	}
	if (nVrs != 0) fileOut.write(QString("</verse>\n").toUtf8());
	if (nChp != 0) fileOut.write(QString("</chapter>\n").toUtf8());
	if (nBk != 0) {
		std::cout << QString("\n").toUtf8().data();
		fileOut.write(QString("</div>\n").toUtf8());
	}
	fileOut.write(QString("\n</osisText>\n").toUtf8());
	fileOut.write(QString("\n</osis>\n").toUtf8());

	fileOut.close();
	fileIn.close();

//	return a.exec();
	return 0;
}
Beispiel #16
0
void
Downloader::getFilesFromIndex(const QString& rootUrl, const QString& relPath, const QStringList& wantedExtensions)
{
	// ASSUMPTION: relPath ends with '/'

	++expectedIndexCount;
	QNetworkRequest indexReq(QUrl(rootUrl + relPath));
	QNetworkReply* indexReply = nam->get(indexReq);
	connect(indexReply, &QNetworkReply::finished, [=]
	{
		++loadedIndexCount;

		QString page = indexReply->readAll();
		indexReply->deleteLater();

		// ASSUMPTION: There's no whitespace around the '='
		QStringList links = page.split("a href=\"");
		links.removeFirst();

		QStringList wantedFiles;
		for (int i = 0; i < links.size(); ++i)
		{
			QString link = links[i].split('"').at(0);
			if (isWanted(link, wantedExtensions))
				wantedFiles << link;
		}

		expectedFileCount += wantedFiles.size();
		for (const QString& filename : wantedFiles)
		{
			QNetworkRequest fileReq(QUrl(rootUrl + relPath + filename));
			auto fileReply = nam->get(fileReq);
			connect(fileReply, &QNetworkReply::finished, [=]
			{
				qDebug() << "\tLoaded" << fileReply->url().toString();

				QByteArray data = fileReply->readAll();
				fileReply->deleteLater();

				QFile fileOut(relPath + filename);
				if (!fileOut.open(QFile::WriteOnly))
				{
					qDebug() << "\tERROR: Unable to open file for writing:" << fileOut.fileName();
					return;
				}

				fileOut.write(data);
				fileOut.close();

				this->recordDownload();
			});

			connect(fileReply, ( void (QNetworkReply::*)(QNetworkReply::NetworkError) )&QNetworkReply::error, [=]
			{
				qDebug() << "\tERROR:" << fileReply->errorString();
			});
		}
	});

	connect(indexReply, ( void (QNetworkReply::*)(QNetworkReply::NetworkError) )&QNetworkReply::error, [=]
	{
		qDebug() << "\tERROR:" << indexReply->errorString();
	});
}
Beispiel #17
0
//********************************************************************
//
// Method: find
// Parameter: none, read input
//          create instance of Intermediary
//
// Purpose: use Intermediary to find, output found text or picture
//
//********************************************************************
void MainWindow::find()
{
    QString path = ui->picPathTextField_2->item(0)->text();
    im = new Intermediary(path);
    for(int index = 1; index < (ui->picPathTextField_2->count()); index++)
    {
        im->addImage(ui->picPathTextField_2->item(index)->text());
    }

    if(im->imageOrTextHidden() == 1) //1 => text, 0 => picture
    {
        qDebug("Hidden text found.");
        QString* plain = im->getHiddenText();
        //decrypt
        if(ui->decryptCheckBox->isChecked())
        {
            plain = decrypt(plain);
        }
        if(ui->textToFieldRadio->isChecked())
        {
            ui->picField->clear();
            ui->textEdit_2->setText(*plain);
        } else if(ui->textToDocRadio->isChecked())
        {
            QString newPath = QFileDialog::getSaveFileName(
                                  this,
                                  "Save Textfile",
                                  actDir.absolutePath(),
                                  "Text Files(*.txt)");
            actDir.setPath(newPath);
            QFile fileOut(newPath);
            if (fileOut.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                QTextStream streamFileOut(&fileOut);
                streamFileOut.setCodec("UTF-8");
                streamFileOut.setGenerateByteOrderMark(true);
                streamFileOut << *plain;
                streamFileOut.flush();
                fileOut.close();
            }
        }
    }
    else if(im->imageOrTextHidden() == 0)
    {
        qDebug("Hidden image found.");
        QImage* image;
        image = im->getHiddenImage();
        if(ui->textToFieldRadio->isChecked())
        {
            ui->textEdit_2->clear();
            QPixmap img = QPixmap::fromImage(*image);
            if (img.height() > ui->picField->height() && img.width() > ui->picField->width())
            {
                img = img.scaled(ui->picField->width(), ui->picField->height());
            }
            else if(img.height() > ui->picField->height())
            {
                img = img.scaledToHeight(ui->picField->height());
            }
            else if(img.width() > ui->picField->width())
            {
                img = img.scaledToWidth(ui->picField->width());
            }
            ui->picField->setPixmap(img);
        }
        else {
            QString newPath = QFileDialog::getSaveFileName(
                                  this,
                                  "Save Image",
                                  actDir.absolutePath(),
                                  "Image Files(*.png)");
            actDir.setPath(newPath);
            image->save(newPath,"PNG",100);
        }
    }
    ui->saveLabel->clear();
}
Beispiel #18
0
int main(int Narg, char* pszArg[])
{

  if (Narg > 5) return 0;
  string title(pszArg[1]);
  string reactionTitle(pszArg[2]);
  string fileName = title+".inp";
  int jdata = atoi(pszArg[3]);
  string toFit(pszArg[4]);  


  string fileO = reactionTitle+".vvv";
  ofstream fileOut(fileO.c_str());
  fileOut.precision(3);
  fileOut << fixed;

  fileO = reactionTitle+"A.grid";
  ofstream fileGrid(fileO.c_str());
  fileGrid.precision(3);

  fileO = reactionTitle+"A.x";
  ofstream fileXsec(fileO.c_str());
  fileXsec.precision(3);
  fileXsec << fixed;

  fileO = reactionTitle+"A.min";
  ofstream fileMin(fileO.c_str());
  fileMin.precision(3);

  //read in input file to cound how many fitted parameters
  ifstream file(fileName.c_str());
  if (file.fail())
    {
      cout << "could not open file " << fileName << endl;
      abort();
    }
  //char line[80];
  //skip two lines
  //file.getline(line,80);
  string variable;
  double parameter,varied,squared,scaling,pMin,pMax;
  int Ndim = 0;
  for (int i=0;i<fitOM::TotPara;i++)
    {
      file >> parameter >> varied >> squared>>scaling >> pMin>> 
              pMax >>variable;
      if (varied) Ndim++;
    }  
  

  file.close();
  file.clear();
  fitOM *Fit;

  for (int id =0;id<=jdata;id++)
    {
      cout << "fitting data set " << id << endl;
      Fit = new fitOM (&title,reactionTitle,id,Ndim,1,1);

     //end of reaction data
     if (Fit->React[0]->data[0].nX < 0) 
       {
	 delete Fit;
        break;
       }

     // if there are no xsec data , then skip
     if (Fit->React[0]->data[0].nX == 0) 
       {
         cout << "no xsec data" << endl;
         delete Fit;
         continue;
       }

     //check if number of fit parametersed changed
     if (Ndim != Fit->mm)
       {
	 Ndim = Fit->mm;
       }
     delete Fit;
     Fit = new fitOM(&title,reactionTitle,id,Ndim,1,1);
   



     //grid search
     double chiMin=0.;
     if (toFit == "G" || toFit ==  "g")
       {
         chiMin = Fit->gridFit();
         cout << " min chisq from grid = " << chiMin << endl;
         fileGrid << id << " " << Fit->React[0]->data[0].energyLab << " " 
                  <<chiMin << " " ;
         for (int i=0;i<Fit->TotPara;i++) fileGrid << Fit->paraBest[i] << " ";
	 fileGrid <<  Fit->React[0]->data[0].name.substr(0,9) << endl;

       }

  
     double * para;
     para = new double [Ndim];

     for (int i=0;i<Ndim;i++)
       {
         int j= Fit->map2[i];
         para[i] = Fit->allPara[j]*Fit->scaling[j];
       }

      double* xi[Ndim];
     for (int i=0;i<Fit->ND;i++) 
       {
         xi[i] = new double [Ndim];
         for (int j=0;j<Fit->ND;j++)
	   {
	     if (i == j) xi[i][j] = 1.;
	     else xi[i][j] = 0.;
	   }
       }
     double const ftol = 1.e-2;



     //string toFit("X");
     cout << toFit << endl;
       if (toFit == "X" || toFit ==  "x" || toFit == "G" || toFit == "g")
       {
         chiMin=Fit->powell(para,xi,ftol);
       }

     cout << "minimum chisq= " << chiMin << endl;

     Fit->SavePara(para);

     Fit->WriteFit(chiMin);

     for (int i=0;i<Fit->Nreact;i++)
       {
	 Fit->React[i]->OpenRootFile();
	 cout << "PlotFit" << endl;
         try
	   {
	    Fit->React[i]->PlotFit();
	   }
         catch (compoundException)
	   {
	     cout << "compound exception" << endl;
	   }
	 Fit->React[i]->CloseRootFile();

       }

     cout << " for Ecm = "<< Fit->React[0]->data[0].energyCM << " MeV" << endl;
     cout << " for Elab = "<< Fit->React[0]->data[0].energyLab << " MeV" << endl;
     //     if (Fit->React[0]->Zp == 0) 
     //  cout << " predicted= " << Fit->React[0]->scatter->TotXsection() << 
     //  "exp = " << Fit->React[0]->TotXdata[0].xsec << " mb "<< endl;

     Fit->React[0]->scatter->VIntegrals();
     cout << " JReal= " << Fit->React[0]->scatter->JReal 
          << " JImag= " << Fit->React[0]->scatter->JImag 
          << " RrmsReal= " << Fit->React[0]->scatter->RrmsReal 
          << " RrmsImag= " << Fit->React[0]->scatter->RrmsImag << endl;


     fileOut<< setw(5) << Fit->React[0]->data[0].energyLab << " " 
            << setw(6) << -Fit->React[0]->scatter->JReal  << " " 
	    << setw(6) <<-Fit->React[0]->scatter->JImag << " " 
            << setw(5) << Fit->React[0]->scatter->RrmsReal  << " " 
	    << setw(5) << Fit->React[0]->scatter->RrmsImag  << " " ;
     if (Fit->React[0]->data[0].nA == 0)fileOut << setw(6) << 0. << " " 
                                                << setw(5) << 0. << " ";
     else fileOut << setw(6) << -Fit->React[0]->scatter->JSO << " " 
		  << setw(5) << Fit->React[0]->scatter->RrmsSO << " " ;
     fileOut << setw(5) << chiMin << " " << 
       Fit->React[0]->data[0].name.substr(0,9) <<endl;

     /*
     Fit->React[0].loadOM();
     Fit->React[0]->scatter->statistical(scatter->konst,
         Fit->React[0]->data[0].energyEcm);
     */
     fileXsec << setw(3) << id << " " 
             << setw(6) << Fit->React[0]->data[0].energyLab << " "
	     << setw(6) << Fit->React[0]->scatter->AbsorptionXsection()<<  " "
	     << setw(6) << Fit->React[0]->scatter->sigmaAbsorption<< " " 
	     << setw(6) << Fit->React[0]->scatter->sigmaCompoundElastic<< " " ;
           
     if (Fit->React[0]->Zp == 0) fileXsec << setw(6) << 
       Fit->React[0]->scatter->TotXsection() << " " ;

     fileXsec   <<  Fit->React[0]->data[0].name.substr(0,9) << endl;




     fileMin << id << " " << Fit->React[0]->data[0].energyLab << " "
	     << chiMin << " "; 
     for (int i=0;i<Fit->TotPara;i++) fileMin << Fit->allPara[i] << " " ;
     fileMin<<  Fit->React[0]->data[0].name.substr(0,9) << endl;
     delete Fit;
    }
     fileOut.close();
     fileOut.clear();

     fileGrid.close();
     fileGrid.clear();

     fileXsec.close();
     fileXsec.clear();

     fileMin.close();
     fileMin.clear();


  return 0;
}
Beispiel #19
0
void SelectFile::callSWWYL()
{

    QString inFile;
    QString inFile_2d;
    QString outPath;
    QDir dir(root_path+"/yubao/wenyanliu/3d_pic/");
    QFileInfoList list;
    QFile file_init("initial.txt");
    QTextStream fileOut(&file_init);


    inFile = ui->lineEdit->text();
    outPath = ui->lineEdit_3->text();

    QFileInfo fi(inFile);

    if(inFile.isEmpty() || outPath.isEmpty()){
        QMessageBox::warning(0,"Warning",QStringLiteral("请选择输入文件和输出路径"),QMessageBox::Yes);//查看路径
    }else {

        file_date = fi.fileName().mid(12,8);
        qDebug() << file_date << "1111111";
//        return;
        //载入loading…动画
        loadMovie->start();
        ui->label_5->show();

        // 清空原文件,复制用户选择的文件到程序运行目录,并重命名
//        QFile::remove(root_path+"/yubao/wenyanliu/ocean_his_4750.nc");

        list = dir.entryInfoList();
        for(int i=0; i<list.size(); i++)
        {
//            QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes);
            QFile::remove(list.at(i).filePath());
        }

//        dir = QDir("C:/pic/SWWYL_3d");
//        list = dir.entryInfoList();
//        for(int i=0; i<list.size(); i++)
//        {
////            QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes);
//            QFile::remove(list.at(i).filePath());
//        }

//        dir = QDir("C:/pic/SWWYL_2d");
//        list = dir.entryInfoList();
//        for(int i=0; i<list.size(); i++)
//        {
////            QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes);
//            QFile::remove(list.at(i).filePath());
//        }

        copyFileToPath(inFile, root_path+"/yubao/wenyanliu/",true);
        inFile_2d = fi.absolutePath()+"/2d/ecs_new_"+file_date+".nc";
        qDebug() << inFile_2d;
        copyFileToPath(inFile_2d, root_path+"/yubao/wenyanliu/",true);


        //m_fsw->removePaths(m_fsw->directories());
        m_outPath = outPath;
        m_fsw->addPath( root_path+"/yubao/wenyanliu/3d_pic/");

        // 写配置文件 initial1.txt 调用程序
        qDebug() << root_path;
        QDir::setCurrent(root_path+"/yubao/wenyanliu/");

        file_init.open(QIODevice::WriteOnly);
        fileOut << file_date << "\n";
        file_init.close();

        QProcess::startDetached("swwyl.exe");
//            QProcess::execute("swwyl.exe");

        // 还原系统路径
        QDir::setCurrent(root_path);

    }
}
void Program::loadSettings()
{
	std::wstring filePath = boost::str(boost::wformat(L"%1%\\audio.ini") % savePath);
	if (!boost::filesystem::exists(filePath))
	{
		std::fstream fileOut(filePath.c_str(), std::ios_base::out);
		fileOut.close();
	}
	CSimpleIniW ini(true, false, true);
	SI_Error error = ini.LoadFile(filePath.c_str());
	if (!error)
	{
		bool modified = false;
		const wchar_t *value[8];
		value[0] = ini.GetValue(L"settings", L"allow_radio_station_adjustment");
		value[1] = ini.GetValue(L"settings", L"connect_attempts");
		value[2] = ini.GetValue(L"settings", L"connect_delay");
		value[3] = ini.GetValue(L"settings", L"connect_timeout");
		value[4] = ini.GetValue(L"settings", L"enable_logging");
		value[5] = ini.GetValue(L"settings", L"network_timeout");
		value[6] = ini.GetValue(L"settings", L"stream_files_from_internet");
		value[7] = ini.GetValue(L"settings", L"transfer_files_from_server");
		if (value[0])
		{
			try
			{
				settings->allowRadioStationAdjustment = boost::lexical_cast<bool>(value[0]);
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"allow_radio_station_adjustment", boost::lexical_cast<std::wstring>(settings->allowRadioStationAdjustment).c_str());
			modified = true;
		}
		if (value[1])
		{
			try
			{
				settings->connectAttempts = boost::lexical_cast<unsigned int>(value[1]);
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"connect_attempts", boost::lexical_cast<std::wstring>(settings->connectAttempts).c_str());
			modified = true;
		}
		if (value[2])
		{
			try
			{
				settings->connectDelay = boost::lexical_cast<unsigned int>(value[2]) * 1000;
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"connect_delay", boost::lexical_cast<std::wstring>(settings->connectDelay / 1000).c_str());
			modified = true;
		}
		if (value[3])
		{
			try
			{
				settings->connectTimeout = boost::lexical_cast<unsigned int>(value[3]) * 1000;
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"connect_timeout", boost::lexical_cast<std::wstring>(settings->connectTimeout / 1000).c_str());
			modified = true;
		}
		if (value[4])
		{
			try
			{
				settings->enableLogging = boost::lexical_cast<bool>(value[4]);
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"enable_logging", boost::lexical_cast<std::wstring>(settings->enableLogging).c_str());
			modified = true;
		}
		if (value[5])
		{
			try
			{
				settings->networkTimeout = boost::lexical_cast<unsigned int>(value[5]) * 1000;
			}
			catch (boost::bad_lexical_cast &) {}
			if (settings->networkTimeout < 20000)
			{
				settings->networkTimeout = 20000;
			}
		}
		else
		{
			ini.SetValue(L"settings", L"network_timeout", boost::lexical_cast<std::wstring>(settings->networkTimeout / 1000).c_str());
			modified = true;
		}
		if (value[6])
		{
			try
			{
				settings->streamFiles = boost::lexical_cast<bool>(value[6]);
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"stream_files_from_internet", boost::lexical_cast<std::wstring>(settings->streamFiles).c_str());
			modified = true;
		}
		if (value[7])
		{
			try
			{
				settings->transferFiles = boost::lexical_cast<bool>(value[7]);
			}
			catch (boost::bad_lexical_cast &) {}
		}
		else
		{
			ini.SetValue(L"settings", L"transfer_files_from_server", boost::lexical_cast<std::wstring>(settings->transferFiles).c_str());
			modified = true;
		}
		if (modified)
		{
			ini.SaveFile(filePath.c_str());
		}
	}
	if (settings->enableLogging)
	{
		createLogFile();
	}
}
void DataInterface::writeEdgeList(
		   const QString sourceSelection, const QString targetSelection, const bool directedRelationships,
		   const QString relationsType, const std::string filename, const std::string sepOne, const std::string sepTwo
		   ) {
  // We point to the InputTable and we get all the stuff out that we need from the input table and the function arguments.
  std::string sourceString = sourceSelection.toStdString();
  std::string targetString = targetSelection.toStdString();
  std::string relationshipType = "Undirected";
  if (directedRelationships) {
    relationshipType = "Directed";
  }
  std::string relationshipLabel = relationsType.toStdString();
  std::istringstream convertSepOne(sepOne.c_str());
  char sepOneChar;
  convertSepOne >> sepOneChar;
  std::istringstream convertSepTwo(sepTwo.c_str());
  char sepTwoChar;
  convertSepTwo >> sepTwoChar;
    
  // We need to know in which part of the data vector the source and target node reside.
  // We create and set an index to achieve that.
  int sourceIndex = 0;
  int targetIndex = 0;
  for (std::vector<std::string>::size_type i = 0; i != header.size(); i++) {
    std::string currentString = header[i];
    if (currentString == sourceString) {
      sourceIndex = i;
    }
    if (currentString == targetString) {
      targetIndex = i;
    }
  }

  // Then we prepare the file for writing.
  std::ofstream fileOut(filename.c_str());
  if (!fileOut.is_open()) {
    QPointer<QMessageBox> errorBox = new QMessageBox;
    errorBox->setText(tr("<b>ERROR: Could not write file</b>"));
    errorBox->setInformativeText("The program had problems trying to open the file in which to write data");
    errorBox->exec();
    return;
  }
  
  // First we write the header of the file.
  if (relationshipLabel.length() > 0) {
    fileOut << "Source" << sepOne << "Target" << sepOne << "Weight" << sepOne << "Type" << sepOne << "Type_User_Defined";
  } else {
    fileOut << "Source" << sepOne << "Target" << sepOne << "Weight" << sepOne << "Type";
  }
  fileOut << '\n';

  // We make a vector to store our lines for the output file.
  std::vector <std::string> fileVector;
  
  // Then we iterate through the data vector, find the appropriate entries, and write them to our file vector.
  std::vector <std::vector <std::string> >::iterator itData;
  for (itData = rowData.begin(); itData != rowData.end(); itData++) {
    std::vector <std::string> currentData = *itData;
    std::string currentSource = currentData[sourceIndex];
    std::string currentTarget = currentData[targetIndex];
    std::vector <std::string> sepSources;
    std::vector <std::string> sepTargets;

    // Some of the entries may have multiple values in one string. We need to separate these now.
    std::istringstream sourceStream(currentSource);
    while (sourceStream) {
      std::string s;
      if (!getline(sourceStream, s, sepTwoChar)) break;
      while (s[0] == ' ') {
	s = s.substr(1, s.length());
      }
      sepSources.push_back(s);
    }
    std::istringstream targetStream(currentTarget);
    while (targetStream) {
      std::string s;
      if (!getline(targetStream, s, sepTwoChar)) break;
      while (s[0] == ' ') {
	s = s.substr(1, s.length());
      }
      sepTargets.push_back(s);
    }
    std::vector <std::string>::iterator itSepSources;
    std::vector <std::string>::iterator itSepTargets;

    // After making sures that the values have been separated where necessary, we can write the bulk of our file.
    for (itSepSources = sepSources.begin(); itSepSources != sepSources.end(); itSepSources++) {
      std::string currentSepSource = *itSepSources;
      for (itSepTargets = sepTargets.begin(); itSepTargets != sepTargets.end(); itSepTargets++) {
	std::string currentSepTarget = *itSepTargets;
	if (currentSepSource != currentSepTarget) {
	  std::vector <std::string> tempVector;
	  tempVector.push_back(currentSepSource);
	  tempVector.push_back(currentSepTarget);
	  if (sourceSelection == targetSelection) {
	    std::sort(tempVector.begin(), tempVector.end());
	  }
	  std::string sourceTarget = tempVector[0] + sepOne + tempVector[1];
	  if (relationshipLabel.size() > 0) {
	    fileVector.push_back(sourceTarget + sepOne + "1" + sepOne + relationshipType + sepOne +  relationshipLabel + '\n');
	  } else {
	    fileVector.push_back(sourceTarget + sepOne + "1" + sepOne + relationshipType + '\n');
	  }
	}
      }
    }
  }
  if (fileVector.empty()) {
    QPointer<QMessageBox> errorBox =  new QMessageBox;
    errorBox->setText("<b>WARNING</b>");
    errorBox->setInformativeText("The Edge list is empty. Check your settings.");
    errorBox->exec();
  }
  // We remove all doubles from the edge list here.
  std::sort(fileVector.begin(), fileVector.end());
  fileVector.erase(std::unique(fileVector.begin(), fileVector.end()), fileVector.end());

  // Then we iterate through our file vector and write everything to our file.
  std::vector <std::string>::iterator lineReader;
  for (lineReader = fileVector.begin(); lineReader != fileVector.end(); lineReader++) {
    fileOut << *lineReader;
  }
  
  // And after that we can close the file and end the function.
  fileOut.close();
  return;
}
Beispiel #22
0
void DoMuscle()
	{
	SetOutputFileName(g_pstrOutFileName.get());
	SetInputFileName(g_pstrInFileName.get());

	SetMaxIters(g_uMaxIters.get());
	SetSeqWeightMethod(g_SeqWeight1.get());

	TextFile fileIn(g_pstrInFileName.get());
	SeqVect v;
	v.FromFASTAFile(fileIn);
	const unsigned uSeqCount = v.Length();

	if (0 == uSeqCount)
		Quit("No sequences in input file");

	ALPHA Alpha = ALPHA_Undefined;
	switch (g_SeqType.get())
		{
	case SEQTYPE_Auto:
		Alpha = v.GuessAlpha();
		break;

	case SEQTYPE_Protein:
		Alpha = ALPHA_Amino;
		break;

	case SEQTYPE_DNA:
		Alpha = ALPHA_DNA;
		break;

	case SEQTYPE_RNA:
		Alpha = ALPHA_RNA;
		break;

	default:
		Quit("Invalid seq type");
		}
	SetAlpha(Alpha);
	v.FixAlpha();

//
// AED 21/12/06: Moved matrix loading code inside the PP param function so it gets called for all alignment types
//
	SetPPScore();


	unsigned uMaxL = 0;
	unsigned uTotL = 0;
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		unsigned L = v.GetSeq(uSeqIndex).Length();
		uTotL += L;
		if (L > uMaxL)
			uMaxL = L;
		}

	SetIter(1);
	g_bDiags.get() = g_bDiags1.get();
	SetSeqStats(uSeqCount, uMaxL, uTotL/uSeqCount);

	SetMuscleSeqVect(v);

	MSA::SetIdCount(uSeqCount);

// Initialize sequence ids.
// From this point on, ids must somehow propogate from here.
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		v.SetSeqId(uSeqIndex, uSeqIndex);

	if (0 == uSeqCount)
		Quit("Input file '%s' has no sequences", g_pstrInFileName.get());
	if (1 == uSeqCount)
		{
		TextFile fileOut(g_pstrOutFileName.get(), true);
		v.ToFile(fileOut);
		return;
		}

	if (uSeqCount > 1)
		MHackStart(v);

// First iteration
	Tree GuideTree;
	if (0 != g_pstrUseTreeFileName.get())
		{
	// Discourage users...
		if (!g_bUseTreeNoWarn.get())
			fprintf(stderr, g_strUseTreeWarning);

	// Read tree from file
		TextFile TreeFile(g_pstrUseTreeFileName.get());
		GuideTree.FromFile(TreeFile);

	// Make sure tree is rooted
		if (!GuideTree.IsRooted())
			Quit("User tree must be rooted");

		if (GuideTree.GetLeafCount() != uSeqCount)
			Quit("User tree does not match input sequences");

		const unsigned uNodeCount = GuideTree.GetNodeCount();
		for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
			{
			if (!GuideTree.IsLeaf(uNodeIndex))
				continue;
			const char *LeafName = GuideTree.GetLeafName(uNodeIndex);
			unsigned uSeqIndex;
			bool SeqFound = v.FindName(LeafName, &uSeqIndex);
			if (!SeqFound)
				Quit("Label %s in tree does not match sequences", LeafName);
			unsigned uId = v.GetSeqIdFromName(LeafName);
			GuideTree.SetLeafId(uNodeIndex, uId);
			}
		}
	else
		TreeFromSeqVect(v, GuideTree, g_Cluster1.get(), g_Distance1.get(), g_Root1.get(),
		  g_pstrDistMxFileName1.get());

	const char *Tree1 = ValueOpt("Tree1");
	if (0 != Tree1)
		{
		TextFile f(Tree1, true);
		GuideTree.ToFile(f);
		if (g_bClusterOnly.get())
			return;
		}

	SetMuscleTree(GuideTree);
	ValidateMuscleIds(GuideTree);

	MSA msa;
	ProgNode *ProgNodes = 0;
	if (g_bLow.get())
		ProgNodes = ProgressiveAlignE(v, GuideTree, msa);
	else
		ProgressiveAlign(v, GuideTree, msa);
	SetCurrentAlignment(msa);

	if (0 != g_pstrComputeWeightsFileName.get())
		{
		extern void OutWeights(const char *FileName, const MSA &msa);
		SetMSAWeightsMuscle(msa);
		OutWeights(g_pstrComputeWeightsFileName.get(), msa);
		return;
		}

	ValidateMuscleIds(msa);

	if (1 == g_uMaxIters.get() || 2 == uSeqCount)
		{
		//TextFile fileOut(g_pstrOutFileName.get(), true);
		//MHackEnd(msa);
		//msa.ToFile(fileOut);
		MuscleOutput(msa);
		return;
		}

	if (0 == g_pstrUseTreeFileName.get())
		{
		g_bDiags.get() = g_bDiags2.get();
		SetIter(2);

		if (g_bLow.get())
			{
			if (0 != g_uMaxTreeRefineIters.get())
				RefineTreeE(msa, v, GuideTree, ProgNodes);
			}
		else
			RefineTree(msa, GuideTree);

		const char *Tree2 = ValueOpt("Tree2");
		if (0 != Tree2)
			{
			TextFile f(Tree2, true);
			GuideTree.ToFile(f);
			}
		}

	SetSeqWeightMethod(g_SeqWeight2.get());
	SetMuscleTree(GuideTree);

	if (g_bAnchors.get())
		RefineVert(msa, GuideTree, g_uMaxIters.get() - 2);
	else
		RefineHoriz(msa, GuideTree, g_uMaxIters.get() - 2, false, false);

#if	0
// Refining by subfamilies is disabled as it didn't give better
// results. I tried doing this before and after RefineHoriz.
// Should get back to this as it seems like this should work.
	RefineSubfams(msa, GuideTree, g_uMaxIters.get() - 2);
#endif

	ValidateMuscleIds(msa);
	ValidateMuscleIds(GuideTree);

	//TextFile fileOut(g_pstrOutFileName.get(), true);
	//MHackEnd(msa);
	//msa.ToFile(fileOut);
	MuscleOutput(msa);
	}
void DataInterface::writeNodeList(
		    QString sourceSelection, QString targetSelection, std::vector <std::string> sourceProperties,
		    std::vector<std::string> targetProperties, bool excludeSources, bool excludeTargets,
		    std::string filename, std::string sepOne, std::string sepTwo
		    ) {
  // We point to the output table and get everything we need from the table and the function arguments.

  std::istringstream convertSepOne(sepOne.c_str());
  char sepOneChar;
  convertSepOne >> sepOneChar;
  std::istringstream convertSepTwo(sepTwo.c_str());
  char sepTwoChar;
  convertSepTwo >> sepTwoChar;
  std::string sourceString = sourceSelection.toStdString();
  std::string targetString = targetSelection.toStdString();
  /* 
     sharedProperties will be a new vector that holds the properties that the source and target node have in common (if any).
     These will be deleted from the original vectors for source and target properties. This is done to make sure that they
     are not include twice when writing the file. 
  */
  std::vector <std::string> sharedProperties;
  for (std::vector <std::string>::size_type i = 0; i != sourceProperties.size(); i++) {
    for (std::vector <std::string>::size_type j = 0; j != targetProperties.size(); j++) {
      if (sourceProperties[i] == targetProperties[j]) {
	sharedProperties.push_back(sourceProperties[i]);
	sourceProperties.erase(sourceProperties.begin() + i);
	targetProperties.erase(targetProperties.begin() + j);
      }
    }
  }

  /* 
     We need to know in which part of the data vector the source and target node reside.
     We create and set an index to achieve that.
     We need to do something similar for the properties of the nodes and the edges.
     Because there can be multiple properties per node, we make a vector of index numbers for each of these.
  */
  int sourceIndex = 0;
  int targetIndex = 0;
  std::vector <int> sourcePropertiesIndexes;
  std::vector <int> targetPropertiesIndexes;
  std::vector <int> sharedPropertiesIndexes;
  for (std::vector<std::string>::size_type i = 0; i != header.size(); i++) {
    // First we set the indexes for our source and target nodes.
    std::string currentString = header[i];
    if (currentString == sourceString) {
      sourceIndex = i;
    }
    if (currentString == targetString) {
      targetIndex = i;
    }
    // Here we make indexes for our source properties.
    std::vector <std::string>::iterator sourcePropertiesIt;
    for (sourcePropertiesIt = sourceProperties.begin(); sourcePropertiesIt != sourceProperties.end(); sourcePropertiesIt++) {
      std::string currentSourceProperty = *sourcePropertiesIt;
      if (currentString == currentSourceProperty) {
	sourcePropertiesIndexes.push_back(i);
      }
    }
    // Here we make indexes for our target properties.
    std::vector <std::string>::iterator targetPropertiesIt;
    for (targetPropertiesIt = targetProperties.begin(); targetPropertiesIt != targetProperties.end(); targetPropertiesIt++) {
      std::string currentTargetProperty = *targetPropertiesIt;
      if (currentString == currentTargetProperty) {
	targetPropertiesIndexes.push_back(i);
      }
    }
    // And here we set the indexes for the shared properties.
    std::vector <std::string>::iterator sharedPropertiesIt;
    for (sharedPropertiesIt = sharedProperties.begin(); sharedPropertiesIt != sharedProperties.end(); sharedPropertiesIt++) {
      std::string currentSharedProperty = *sharedPropertiesIt;
      if (currentString == currentSharedProperty) {
	sharedPropertiesIndexes.push_back(i);
      }
    }
  }

  // We need to make sure that our output file header also takes into account any properties that are to be included.
  // We create the different parts of the header here.
  std::string sourcePropertiesHeader = "";
  if (sourceProperties.size() > 0) {
    std::vector <std::string>::iterator sourcePropertiesIt;
    for (sourcePropertiesIt = sourceProperties.begin(); sourcePropertiesIt != sourceProperties.end(); sourcePropertiesIt++) {
      std::string currentSourceHeader = *sourcePropertiesIt;
      sourcePropertiesHeader = sourcePropertiesHeader + sepOne + currentSourceHeader;
    }
  }
  std::string targetPropertiesHeader = "";    
  if (targetProperties.size() > 0) {
    std::vector <std::string>::iterator targetPropertiesIt;
    for (targetPropertiesIt = targetProperties.begin(); targetPropertiesIt != targetProperties.end(); targetPropertiesIt++) {
      std::string currentTargetHeader = *targetPropertiesIt;
      targetPropertiesHeader = targetPropertiesHeader + sepOne + currentTargetHeader;
    }
  }
  std::string sharedPropertiesHeader = "";
  if (sharedProperties.size() >0) {
    std::vector <std::string>::iterator sharedPropertiesIt;
    for (sharedPropertiesIt = sharedProperties.begin(); sharedPropertiesIt != sharedProperties.end(); sharedPropertiesIt++) {
      std::string currentSharedHeader = *sharedPropertiesIt;
      sharedPropertiesHeader = sharedPropertiesHeader + sepOne + currentSharedHeader;
    }
  }

  // Then we prepare the file for writing.
  std::ofstream fileOut(filename.c_str());
  if (!fileOut.is_open()) {
    QPointer<QMessageBox> errorBox = new QMessageBox;
    errorBox->setText(tr("<b>ERROR: Could not write file</b>"));
    errorBox->setInformativeText("The program had problems trying to open the file in which to write data");
    errorBox->exec();
    return;
  }
  
  // First we write the header of the file. We add conditionals to handle the possibility that source or target nodes are excluded.
  if (excludeSources) {
    fileOut << "Id" << sepOne << "Type" << sepOne << "Label" << targetPropertiesHeader;
    fileOut << '\n';
  } else if (excludeTargets) {
    fileOut << "Id" << sepOne << "Type" << sepOne << "Label" << sourcePropertiesHeader;
    fileOut << '\n';
  } else {
    fileOut << "Id" << sepOne << "Type" << sepOne << "Label" << sharedPropertiesHeader << sourcePropertiesHeader << targetPropertiesHeader;
    fileOut << '\n';
  }

  // And then we iterate through our dat and process them before we write the bulk of the file.
  std::vector <std::vector <std::string> >::iterator itData;

  // We still need to separate entries with multiple values. We make two vectors that will store these
  // separated entries.
  std::vector <std::string> sepSources;
  std::vector <std::string> sepTargets;
  for (itData = rowData.begin(); itData != rowData.end(); itData++) {
    std::vector <std::string> currentData = *itData;
    std::string currentSource = currentData[sourceIndex];
    std::string currentTarget = currentData[targetIndex];
    // The so-called fake string will act as dummies that make sure that the file lines of the source and target nodes
    // are of the same length and have the same columns. Basically, they represent empty cells in the output file.
    std::string fakeSourceString = "";
    std::string sourcePropsString = "";
    std::vector <int>::iterator sourcePropsIt;
    for (sourcePropsIt = sourcePropertiesIndexes.begin(); sourcePropsIt != sourcePropertiesIndexes.end(); sourcePropsIt++) {
      int currentIndex = *sourcePropsIt;
      std::string tempData = currentData[currentIndex];
      sourcePropsString = sourcePropsString + sepOne + tempData;
      fakeSourceString = fakeSourceString + sepOne + "";
    }
    std::string targetPropsString = "";
    std::string fakeTargetString = "";
    std::vector <int>::iterator targetPropsIt;
    for (targetPropsIt = targetPropertiesIndexes.begin(); targetPropsIt != targetPropertiesIndexes.end(); targetPropsIt++) {
      int currentIndex = *targetPropsIt;
      std::string tempData = currentData[currentIndex];
      targetPropsString = targetPropsString + sepOne + tempData;
      fakeTargetString = fakeTargetString + sepOne + "";
    }
    std::string sharedPropsString = "";
    std::vector <int>::iterator sharedPropsIt;
    for (sharedPropsIt = sharedPropertiesIndexes.begin(); sharedPropsIt != sharedPropertiesIndexes.end(); sharedPropsIt++) {
      int currentIndex = *sharedPropsIt;
      std::string tempData = currentData[currentIndex];
      sharedPropsString = sharedPropsString + sepOne + tempData;
    }
    // And here the entries with multiple values are separated out. We don't do that for properties.
    std::istringstream sourceStringStream(currentSource);
    while (sourceStringStream) {
      std::string s;
      if (!getline(sourceStringStream, s, sepTwoChar)) break;
      while (s[0] == ' ') {
	s = s.substr(1, s.length());
      }
      s = s + sharedPropsString + sourcePropsString + fakeTargetString;
      sepSources.push_back(s);
    }
    std::istringstream targetStringStream(currentTarget);
    while (targetStringStream) {
      std::string s;
      if (!getline(targetStringStream, s, sepTwoChar)) break;
      while (s[0] == ' ') {
	s = s.substr(1, s.length());
      }
      s = s + sharedPropsString + fakeSourceString + targetPropsString;
      sepTargets.push_back(s);
    }
  }
    
  // There will be duplicates in the list of nodes. These are removed here.
  if (!excludeSources) {
    std::sort(sepSources.begin(), sepSources.end());
    sepSources.erase(std::unique(sepSources.begin(), sepSources.end()), sepSources.end());
  }
  if (!excludeTargets) {
    std::sort(sepTargets.begin(), sepTargets.end());
    sepTargets.erase(std::unique(sepTargets.begin(), sepTargets.end()), sepTargets.end());
  }

  /*
    In the above we have basically prepared our data for writing. The actual writing happens below.
    Instead of writing immediately to a file, the lines for the file are first put into a vector,
    which is then written to a file incrementaly. This is mostly an artefact of a function I decided
    no longer to include in the program, but I don't dislike this procedure, so I kept it.
  */
  std::vector <std::string> fileVector;
  if (!excludeSources) {
    std::vector <std::string>::iterator ssI;
    std::vector <std::string> firstSources;
    // Below we separate out the name of the current node. We need to have it separate because we will
    // include the name in the file twice.
    for (ssI = sepSources.begin(); ssI != sepSources.end(); ssI++) {
      std::string currentSource = *ssI;
      std::size_t firstStop = currentSource.find_first_of(sepOne);
      currentSource = currentSource.substr(0, firstStop);
      firstSources.push_back(currentSource);
    }
    // Here we create the actual line of data to be used as output.
    std::vector <std::string>::iterator itSepSource;
    std::vector <std::string>::iterator itSepSourceFirst = firstSources.begin();
    for (itSepSource = sepSources.begin(); itSepSource != sepSources.end(); itSepSource++, itSepSourceFirst++) {
      std::string sepSource = *itSepSource;
      std::string first = *itSepSourceFirst;
      std::string currentLine = first + sepOne + sourceString + sepOne + sepSource + '\n';
      fileVector.push_back(currentLine);
    }
  }

  if (sourceSelection != targetSelection) {
    // And here we basically do the same for the target nodes.
    if (!excludeTargets) {
      std::vector <std::string> firstTargets;
      std::vector <std::string>::iterator stI;
      for (stI = sepTargets.begin(); stI != sepTargets.end(); stI++) {
	std::string currentTarget = *stI;
	std::size_t firstStop = currentTarget.find_first_of(sepOne);
	currentTarget = currentTarget.substr(0, firstStop);
	firstTargets.push_back(currentTarget);
      }
      std::vector <std::string>::iterator itSepTarget;
      std::vector <std::string>::iterator itSepTargetFirst = firstTargets.begin();
      for (itSepTarget = sepTargets.begin(); itSepTarget != sepTargets.end(); itSepTarget++, itSepTargetFirst++) {
	std::string sepTarget = *itSepTarget;
	std::string first = *itSepTargetFirst;
	std::string currentLine = first + sepOne + targetString + sepOne + sepTarget + '\n';
	fileVector.push_back(currentLine);
      }
    }
  }
  
  // Now that we have put all the data we want to write in the file vector, we iterate through the vector
  // and actually write the file.
  std::vector <std::string>::iterator fileIterator;
  for (fileIterator = fileVector.begin(); fileIterator != fileVector.end(); fileIterator++) {
    std::string currentLine = *fileIterator;
    fileOut << currentLine;
  }
  
  // And when we are finished, we can close the file.
  fileOut.close();
  return;
}