Example #1
0
ZipArchive ZipManipulator::commit()
{
	// write to a tmp file
	std::string outFile(_zipFile + ".tmp");
	ZipArchive retVal(compress(outFile));
	//renaming
	{
		Poco::File aFile(_zipFile);
		if (_backupOriginalFile)
		{
			Poco::File tmp(_zipFile+".bak");
			if (tmp.exists())
				tmp.remove();
			aFile.renameTo(_zipFile+".bak");
		}
		else
			aFile.remove();
	}

	{
		Poco::File resFile(outFile);
		Poco::File zipFile(_zipFile);
		if (zipFile.exists())
			zipFile.remove();
		resFile.renameTo(_zipFile);
	}
	return retVal;
}
void cNewO_NameManager::LoadHomFloats(cNewO_OneIm * anI1,cNewO_OneIm * anI2,std::vector<Pt2df> * aVP1,std::vector<Pt2df> * aVP2)
{
   if (anI1->Name() > anI2->Name())
   {
       ElSwap(anI1,anI2);
       ElSwap(aVP1,aVP2);
   }
   std::string aNameH = NameHomFloat(anI1,anI2);

   ELISE_fp aFile(aNameH.c_str(),ELISE_fp::READ,false);
   // FILE *  aFP = aFile.FP() ;
   int aRev = aFile.read_INT4();
   if (aRev>NumHgRev())
   {
   }
   int aNb = aFile.read_INT4();


   aVP1->reserve(aNb);
   aVP2->reserve(aNb);
   aVP1->resize(aNb);
   aVP2->resize(aNb);
   aFile.read(VData(*aVP1),sizeof((*aVP1)[0]),aNb);
   aFile.read(VData(*aVP2),sizeof((*aVP2)[0]),aNb);

   aFile.close();
}
Example #3
0
// readTracks
void readTracks() {
  // Create a filename and open a file
  char buffer[50];
  sprintf(buffer,"Tracks%d.dat",mSequenceLength);
  std::ofstream aFile(buffer);
  // Read number of frames considered
  aFile >> mSequenceLength;
  // Read number of tracks
  int aCount;
  aFile >> aCount;
  // Read each track
  for (int i = 0; i < aCount; i++) {
    // Read label and length of track
    int aSize;
	mTracks.push_back(CSimpleTrack());
	CSimpleTrack& aTrack = mTracks.back();
	aFile >> aTrack.mLabel;
	aFile >> aSize;
	aTrack.mPoints.setSize(aSize);
	// Read x,y coordinates and frame number of the tracked point 
	for (int j = 0; j < aSize; j++) {
	  aFile >> aTrack.mPoints[j].x;
	  aFile >> aTrack.mPoints[j].y;
	  aFile >> aTrack.mPoints[j].frame;
	}
  }
}
bool cNewO_NameManager::LoadTriplet(cNewO_OneIm * anI1 ,cNewO_OneIm * anI2,cNewO_OneIm * anI3,std::vector<Pt2df> * aVP1,std::vector<Pt2df> * aVP2,std::vector<Pt2df> * aVP3)
{
   int aRnk[3] ;
   Rank3(aRnk,anI1->Name(),anI2->Name(),anI3->Name());

   tPtrNIm aVIm[3];
   aVIm[aRnk[0]] =  anI1;
   aVIm[aRnk[1]] =  anI2;
   aVIm[aRnk[2]] =  anI3;

   std::string aName3 = NameHomTriplet(aVIm[0],aVIm[1],aVIm[2]);
   if (! ELISE_fp::exist_file(aName3)) return false;

   tPtrVPt2df aVPt[3];
   aVPt[aRnk[0]] =  aVP1;
   aVPt[aRnk[1]] =  aVP2;
   aVPt[aRnk[2]] =  aVP3;



   ELISE_fp aFile(aName3.c_str(),ELISE_fp::READ,false);
   int aRev = aFile.read_INT4();
   if (aRev>NumHgRev())
   {
   }
   int aNb = aFile.read_INT4();
   for (int aK=0 ; aK<3 ; aK++)
   {
      aVPt[aK]->reserve(aNb);
      aVPt[aK]->resize(aNb);
      aFile.read(VData(*(aVPt[aK])),sizeof(Pt2df),aNb);
   }
   aFile.close();
   return true;
}
void CResourceLoader::ConstructL( const TDesC& aFilename )
    {
    User::LeaveIfError( iFs.Connect() );
    TFileName aFile(aFilename);
    BaflUtils::NearestLanguageFile( iFs, aFile );
    iResFile.OpenL( iFs, aFile );
    iResFile.ConfirmSignatureL();
    }
cDbleGrid * cDbleGrid::read(const  std::string & aName)
{
     ELISE_fp aFile(aName.c_str(),ELISE_fp::READ);
     cDbleGrid * aRes = read(aFile);
     aFile.close();

     return aRes;
}
void  cAppli_GenPTripleOneImage::GenerateTriplet(int aKC1,int aKC2)
{
   std::string aNameH12 = mNM->NameHomFloat(mVCams[aKC1],mVCams[aKC2]);
   if (!ELISE_fp::exist_file(aNameH12)) return;


   std::string aName3 = mNM->NameHomTriplet(mCam,mVCams[aKC1],mVCams[aKC2]);
   if (ELISE_fp::exist_file(aName3)) return;

   tMapM aMap;

    {
       std::vector<Pt2df> aVP1;
       std::vector<Pt2df> aVP2;
       mNM->LoadHomFloats(mVCams[aKC1],mVCams[aKC2],&aVP1,&aVP2);

       AddVPts2Map(aMap,aVP1,1,aVP2,2);
    }
    AddVPts2Map(aMap,mVP1[aKC1],0,mVP2[aKC1],1);
    AddVPts2Map(aMap,mVP1[aKC2],0,mVP2[aKC2],2);

    aMap.DoExport();
    const tListM aLM =  aMap.ListMerged();

    std::vector<Pt2df> aVP1,aVP2,aVP3;
    std::vector<U_INT1> aVNb;
    for (tListM::const_iterator itM=aLM.begin() ; itM!=aLM.end() ; itM++)
    {
          if ((*itM)->NbSom()==3 )
          {
              aVP1.push_back((*itM)->GetVal(0));
              aVP2.push_back((*itM)->GetVal(1));
              aVP3.push_back((*itM)->GetVal(2));
              aVNb.push_back((*itM)->NbArc());
          }
    }

    int aNb = aVP1.size();
    if (aNb<TNbMinTriplet)
    {
       aMap.Delete();
       return;
    }

    ELISE_fp aFile(aName3.c_str(),ELISE_fp::WRITE,false);
    aFile.write_INT4(NumHgRev());
    aFile.write_INT4(aNb);
    aFile.write(&(aVP1[0]),sizeof(aVP1[0]),aNb);
    aFile.write(&(aVP2[0]),sizeof(aVP2[0]),aNb);
    aFile.write(&(aVP3[0]),sizeof(aVP3[0]),aNb);
    aFile.write(&(aVNb[0]),sizeof(aVNb[0]),aNb);
    aFile.close();



    aMap.Delete();
}
TEST(FileSystem, ReadFileIntoString)
{
    filesystem::Path aPath("test/dummy.txt");
    filesystem::File aFile(aPath);
    EXPECT_TRUE(aFile.isValid());
    std::string aTarget;
    EXPECT_TRUE(aFile.read(aTarget));
    EXPECT_EQ("this is a nice first line,./aa\nthis is a proper second line....\n\nafter the previous empty line this is number 4\n\n6\n\n", aTarget);
}
Example #9
0
void MainWindow::synTwoFiles(QString fileA, QString fileB)
{
    if(isPathExcept(fileA))
        return;
    QFileInfo aFile(fileA);
    QFileInfo bFile(fileB);
//    qDebug() << "fileA:" + fileA;
//    qDebug() << "fileB:" + fileB;
    // 同步增加或修改
    if(aFile.exists())
    {
        // 同步修改
        if(bFile.exists() && synModify && aFile.lastModified() != bFile.lastModified())
        {
            if(!QFile::remove(fileB))
                qDebug() << "can't delete : " + fileB;
            if(!QFile::copy(fileA, fileB))
            {
                qDebug() << "can't copy : " + fileA;
            }
            else
            {
                lastSynFileNotify("正在修改: " + fileB);
                qDebug() << "copy : " + fileA;
            }
        }
        else if(!bFile.exists() && synAdd)
        {
            // 同步增加
            if(!QFile::copy(fileA, fileB))
            {
                qDebug() << "can't copy : " + fileA;
            }
            else
            {
                lastSynFileNotify("正在增加: " + fileB);
                qDebug() << "copy : " + fileA;
            }
        }

    }
    // 同步删除
    else
    {
        if(bFile.exists() && synDel)
        {
            if(!QFile::remove(fileB))
                qDebug() << "can't delete : " + fileB;
            else
            {
                lastSynFileNotify("正在删除: " + fileB);
                qDebug() << "del :" + fileB;
            }
        }
    }
}
Example #10
0
void WordXML::saveToFile(QString aFileName)
{
    QFile aFile(aFileName);
    aFile.open(QIODevice::WriteOnly);

    QTextStream aStream(&aFile);
    aStream.setCodec("UTF-8");

    writeToStream(aStream);
}
Example #11
0
/*
 *  Saves the selected messages into a file, all if none selected
 */
void Superconductor_Messages::saveOutput()
{
	QString s = QFileDialog::getSaveFileName(
                    "/home",
                    "Log files (*.log)",
                    this,
                    "save file dialog"
                    "Choose a filename to save under" );
	if ( s ) {
		QFile aFile( s );
		QTextStream stream;
		QString output;
		if ( strings ) {
			output = strings->join( "\n" );
			output += "\n";
		}
		else {
			output = " ";
		}
		if ( aFile.exists() ) {
			switch( QMessageBox::warning( this, "Log Save",
	        "This file already exists. Overwrite?\n",
			"Yes",
	        "No", 0, 0, 1 ) ) {
 			case 0:  // user clicked ok... overwrite file
				aFile.open( IO_WriteOnly | IO_Truncate | IO_Raw );
				aFile.at( 0 );
				stream.setDevice( &aFile );
				stream << output;
				stream.unsetDevice();
				aFile.close();
				this->close();
				break;
			case 1: // The user clicked the Quit or pressed Escape
				break;
			default:
				break;
			}
		}
		else {  // file doesn't exist, just write it
			if ( !s.endsWith( (QString)".log" )) {
				s.append( ".log" );
				aFile.setName( s );
			}
			aFile.open( IO_WriteOnly | IO_Truncate | IO_Raw );
			aFile.at( 0 );
			stream.setDevice( &aFile );
			stream << output;
			stream.unsetDevice();
			aFile.close();
			this->close();
		}
	}
}
Example #12
0
void cEtalonnage::TestVisuFTM()
{
   
    INT aSzPh = 4100;
    INT aSz = 800;
    REAL aZ =  aSz / REAL(aSzPh);
    Video_Win  aW = Video_Win::WStd(Pt2di(aSzPh,aSzPh),aZ);


    std::vector<std::string> mVNames = mParam.AllImagesCibles();
    for
    (
           std::vector<string>::const_iterator iTN = mVNames.begin();
           iTN != mVNames.end();
           iTN++
    )
    {
        std::string aName = NamePointeResult(*iTN,false,true);
        cout <<  aName << "\n";
        ELISE_fp aFile(aName.c_str(),ELISE_fp::READ);
        string buf;
        bool GotEOF = false;

        while (! GotEOF)
        {
            //aFile.fgets(buf,NbBuf,GotEOF,false);
		aFile.fgets(buf,GotEOF);
            if (GotEOF)
            {
            }
            if ((!GotEOF) && (buf[0] != '#'))
            {
               INT anId;
               REAL anX,anY,aL;
               sscanf(buf.c_str(),"%d %lf %lf %lf",&anId,&anX,&anY,&aL);
               if (anId>=0)
               {
                   INT aCoul = P8COL::red;
                   if (aL > 1.0)  aCoul = P8COL::blue;
                   if (aL > 1.5)  aCoul = P8COL::green;
                   aW.draw_circle_abs
                   (
                       Pt2dr(anX,anY),
                       aL*10.0,
                       aW.pdisc()(aCoul)
                   );
               }
            }
        }

    }
    getchar();
}
Example #13
0
void
FsWatcher::ScanDirectory_NotifyUpdates_Execute(QString dirPath)
{
  _LOG_TRACE(" >> ScanDirectory_NotifyUpdates_Execute");

  // exclude working only on last component, not the full path; iterating through all directories,
  // even excluded from monitoring
  QRegExp exclude("^(\\.|\\.\\.|\\.chronoshare|.*~|.*\\.swp)$");

  QDirIterator dirIterator(dirPath, QDir::Dirs | QDir::Files | /*QDir::Hidden |*/ QDir::NoSymLinks |
                                      QDir::NoDotAndDotDot,
                           QDirIterator::Subdirectories); // directory iterator(recursive)

  // iterate through directory recursively
  while (dirIterator.hasNext()) {
    dirIterator.next();

    // Get FileInfo
    QFileInfo fileInfo = dirIterator.fileInfo();

    QString name = fileInfo.fileName();
    _LOG_DEBUG("+++ Scanning: " << name.toStdString());

    if (!exclude.exactMatch(name)) {
      _LOG_DEBUG("Not excluded file/dir: " << fileInfo.absoluteFilePath().toStdString());
      QString absFilePath = fileInfo.absoluteFilePath();

      // _LOG_DEBUG("Attempt to add path to watcher: " << absFilePath.toStdString());
      m_watcher->removePath(absFilePath);
      m_watcher->addPath(absFilePath);

      if (fileInfo.isFile()) {
        QString relFile = absFilePath;
        relFile.remove(0, m_dirPath.size());
        fs::path aFile(relFile.toStdString());

        if (
          //!m_fileState->LookupFile(aFile.relative_path().generic_string())
          ///* file does not exist there, but exists locally: added */)
          !fileExists(aFile.relative_path()) /*file does not exist in db, but exists in fs: add */) {
          addFile(aFile.relative_path());
          DidFileChanged(absFilePath);
        }
      }
    }
    else {
      // _LOG_DEBUG("Excluded file/dir: " << fileInfo.filePath().toStdString());
    }
  }
}
bool JournalDM_Category::Load( const QString& thePath, const QList<JournalDM_IParser*>& theParsers )
{
  QFile aFile( thePath );
  if( !aFile.open( QFile::ReadOnly | QFile::Text ) )
    return false;

  QTextStream aStream( &aFile );
  while( !aStream.atEnd() )
  {
    QString aLine = aStream.readLine();
    myLines.append( aLine );
    GenerateExercises( aLine, theParsers );
  }
  aFile.close();
  return true;
}
Example #15
0
/*******************************************************************************
 * MAIN                                                                        *
 ******************************************************************************/
int main(int argc, char** argv) {

    if (argc <= REQUIRED_PARAMS_NUM) {
        usage(argv[0]);
    }

    const char* fileNameE = argv[1];
    const char* fileNameF = argv[2];
    const char* fileNameA = argv[3];
    maxPhraseLength = std::atoi(argv[4]);

    //
    read_optional_params(argc, argv, 5);

    // Init phrase pairs counters (add +1 for dummy zero-length counter).
    phrasePairsCounters.resize(maxPhraseLength + 1, 0);

    std::cerr << "Starting phrase pairs counter ..." << std::endl;

    // open input files
    std::ifstream eFile(fileNameE);
    std::ifstream fFile(fileNameF);
    std::ifstream aFile(fileNameA);

    //
    readInput(eFile, fFile, aFile);

    std::cerr << std::endl; // Leave the progress bar end on previous line.

    // close input files
    eFile.close();
    fFile.close();
    aFile.close();

    std::cout
        << "############################" << std::endl
        << "# len # phrase pairs count #" << std::endl
        << "############################" << std::endl;

    for ( size_t i = 1; i < phrasePairsCounters.size(); ++i ) {
        std::cout << "# " << std::setw(3) << i << " # " << std::setw(18) << phrasePairsCounters[i] << " #" << std::endl;
    }

    std::cout
        << "############################" << std::endl;

}
int AgentQLTraining::loadQTable(std::string file, int weightSize)
{
	//cout << "@loadQTable" << endl;
	float absQval = 0.0;
	int totalVisits= 0;
	int stateVisited = 0;
	std::vector<float> behaviorState = getOneVectorState();
	int stateSize = behaviorState.size();
	int inputSize = stateSize + weightSize;

	std::ifstream aFile (file.c_str());
	int numberOfNodes=std::count(std::istreambuf_iterator<char>(aFile), std::istreambuf_iterator<char>(), '\n');
	int nodeSize = sizeof(std::map<std::vector<float> , qTableOutput>::value_type);
	allocateNb = nodeSize * numberOfNodes;
	allocP = qTable.get_allocator().allocate( allocateNb );
	//para cada linea
	aFile.seekg(0);
	for (size_t line = 0; line < numberOfNodes; line++) {
		//extraigo el input
		std::vector<float> inV;
		for (size_t in = 0; in < inputSize; in++) {
			float aux;
			aFile >> aux;
			inV.push_back(ceil(aux*1000)/1000);
		}
		//extraigo el Output
		char dummy; //para el "="
		qTableOutput outAux;
		aFile >> dummy >> outAux.visits >> outAux.qValue ;
		//lo cargo al mapa
		qTable[inV] = outAux;

	}

	for (std::map<std::vector<float> , qTableOutput, std::less< std::vector<float> >, std::allocator< std::pair<std::vector<float> , qTableOutput> > >::iterator itqtable = qTable.begin(); itqtable != qTable.end(); ++itqtable)
	{
		absQval += fabs(itqtable->second.qValue);
		totalVisits += itqtable->second.visits;
		if (itqtable->second.visits != 0 ) {
			stateVisited++;
		}
	}

	cout << "Qtable load con " << totalVisits << " visitas y QvalAbs " << absQval << ". Total Inputs visited " << stateVisited << "/" << qTable.size() << endl;
	return qTable.size();
}
Example #17
0
TEST(FileSystem, ReadFileIntoVectorOfString)
{
    filesystem::Path aPath("test/dummy.txt");
    filesystem::File aFile(aPath);
    EXPECT_TRUE(aFile.isValid());
    std::vector<std::string> aTarget;
    EXPECT_TRUE(aFile.readLines(aTarget));
    EXPECT_EQ(aTarget.size(), (unsigned)8);
    
    EXPECT_EQ(aTarget[0], "this is a nice first line,./aa");
    EXPECT_EQ(aTarget[1], "this is a proper second line....");
    EXPECT_EQ(aTarget[2], "");
    EXPECT_EQ(aTarget[3], "after the previous empty line this is number 4");
    EXPECT_EQ(aTarget[4], "");
    EXPECT_EQ(aTarget[5], "6");
    EXPECT_EQ(aTarget[6], "");
    EXPECT_EQ(aTarget[7], "");
}
Example #18
0
void cButton::update(string fileName, string map)
{

	if (m_InputMgr->getLeftMouseBtn())
	{
		glm::vec2 areaClicked = m_InputMgr->getMouseXY();
		if (areaClicked.x >= spritePos2D.x && areaClicked.x <= (spritePos2D.x + textureWidth) && areaClicked.y >= spritePos2D.y && areaClicked.y <= (spritePos2D.y + textureHeight))
		{
			buttonClickedRC.x = (int)(areaClicked.x - spritePos2D.x) / textureWidth;
			buttonClickedRC.y = (int)(areaClicked.y - spritePos2D.y) / textureHeight;
			clicked = true;
			
			cFileHandler aFile(fileName);

			if (!aFile.openFile(ios::out)) //open file clearing the contents
			{
				MessageBox(NULL, "Could not open specified file.", "An error occurred", MB_ICONERROR | MB_OK);
			}
			else
			{
				// Read data from map and write to file
				string mapData = "";
				int strPos = 0;
				for (int row = 0; row < 8; row++)
				{
					for (int column = 0; column < 15; column++)
					{
						mapData += map[strPos];
						strPos++;
					}
					strPos++;
					mapData += map[strPos];
					aFile.writeDataToFile(mapData);
					mapData = "";
					strPos++;
				}
				aFile.closeFile();
			}
			m_InputMgr->clearBuffers(m_InputMgr->MOUSE_BUFFER);// clear mouse buffer.
		}
	}
}
Example #19
0
// writeTracks
void writeTracks() {
  // Create a filename and open a file
  char buffer[50];
  sprintf(buffer,"Tracks%d.dat",mSequenceLength);
  std::ofstream aFile(buffer);
  // Write number of frames considered
  aFile << mSequenceLength << std::endl;
  // Write number of tracks
  int aCount = mTracks.size();
  aFile << aCount << std::endl;
  // Write each track
  for (int i = 0; i < mTracks.size(); i++) {
    // Write label and length of track
    int aSize = mTracks[i].mPoints.size();
    aFile << mTracks[i].mLabel << " " << aSize << std::endl;
    // Write x,y coordinates and frame number of the tracked point 
    for (int j = 0; j < aSize; j++)
      aFile << mTracks[i].mPoints[j].x << " " << mTracks[i].mPoints[j].y << " " << mTracks[i].mPoints[j].frame << std::endl;
  }
}
void  cAppli_GenPTripleOneImage::GenerateHomFloat(cNewO_OneIm * anI1,cNewO_OneIm * anI2)
{
     std::string aNameH = mNM->NameHomFloat(anI1,anI2);
     if (ELISE_fp::exist_file(aNameH)) return;
     // std::cout << "NHH " << aNameH << "\n";


     cFixedMergeStruct<2,Pt2df>   aMap;
     AddOnePackOneSens(aMap,anI1,0,anI2);
     AddOnePackOneSens(aMap,anI2,1,anI1);

     std::vector<Pt2df> aVP1;
     std::vector<Pt2df> aVP2;
     std::vector<U_INT1> aVNb;

     aMap.DoExport();
     const  std::list<cFixedMergeTieP<2,Pt2df> *> &  aLM = aMap.ListMerged();
     for (std::list<cFixedMergeTieP<2,Pt2df> *>::const_iterator itM = aLM.begin() ; itM!=aLM.end() ; itM++)
     {
          const cFixedMergeTieP<2,Pt2df> & aM = **itM;
          if (aM.NbArc() >= mSeuilNbArc)
          {
              aVP1.push_back(aM.GetVal(0));
              aVP2.push_back(aM.GetVal(1));
              aVNb.push_back(aM.NbArc());
          }
     }


     ELISE_fp aFile(aNameH.c_str(),ELISE_fp::WRITE,false);

     int aNb = aVP1.size();
     aFile.write_INT4(NumHgRev());
     aFile.write_INT4(aNb);
     aFile.write(&(aVP1[0]),sizeof(aVP1[0]),aNb);
     aFile.write(&(aVP2[0]),sizeof(aVP2[0]),aNb);
     aFile.write(&(aVNb[0]),sizeof(aVNb[0]),aNb);
     aFile.close();

     aMap.Delete();
}
Example #21
0
Sample2D_Image::Sample2D_Image(Standard_CString& aFileName,
                               const Quantity_Length X,       // = 0.0
                               const Quantity_Length Y,       // = 0.0
                               const Quantity_Length adx,     // = 0.0
                               const Quantity_Length ady,     // = 0.0
                               const Aspect_CardinalPoints aTypeOfPlacement,// = Aspect_CP_Center
                               const Quantity_Factor aScale) // = 1.0)
    :AIS2D_InteractiveObject()
{
  TCollection_AsciiString TheDependentName(aFileName);
  OSD_Path aPath(TheDependentName);
  OSD_File aFile(aPath);
  myFile            = aFile            ;
  myX               = X                ;
  myY               = Y                ;
  myDx              = adx              ;  
  myDy              = ady              ;     
  myTypeOfPlacement = aTypeOfPlacement ;
  myScale           = aScale           ;

  //Attach a graphic view to this object
}
Example #22
0
qint64 memoryUsage()
{
#ifdef Q_OS_WIN
    HANDLE aProcess=GetCurrentProcess();

    PROCESS_MEMORY_COUNTERS aMemory;
    aMemory.cb=sizeof(PROCESS_MEMORY_COUNTERS);
    GetProcessMemoryInfo(aProcess, &aMemory, aMemory.cb);

    return aMemory.PagefileUsage;
#else
    QFile aFile("/proc/self/status");
    aFile.open(QIODevice::ReadOnly);

    QString aStat;

    do
    {
        QString aLine=QString::fromUtf8(aFile.readLine());

        if (aLine.startsWith("VmData:"))
        {
            aStat=aLine.mid(7).trimmed();
            aStat.remove(aStat.length()-3, 3);
            break;
        }

        if (aLine=="")
        {
            break;
        }
    } while (true);

    aFile.close();

    return aStat.toLongLong()*1024;
#endif
}
Example #23
0
void CLDS_File::x_SyncWithDir(const string& path,
                              CLDS_Set*     deleted,
                              CLDS_Set*     updated,
                              set<string>*  scanned_files,
                              TFlags        flags)
{
    CDir dir(path);
    if (!dir.Exists()) {
        LOG_POST_X(2, Info << "LDS: Directory is not found or access denied:" << path);
        return;
    } else {
        LOG_POST_X(3, Info << "LDS: scanning " << path);
    }

    CLDS_Query lds_query(m_DataBase);
    CChecksum checksum(CChecksum::eCRC32);


    // Scan the directory, compare it against File table
    // Here I intentionally take only files, skipping sub-directories,
    // Second pass scans for sub-dirs and implements recursion

    bool compute_check_sum =
        (flags & CLDS_Manager::fControlSumMask) == CLDS_Manager::fComputeControlSum;

    {{

    CDir::TEntries  content(dir.GetEntries());
    ITERATE(CDir::TEntries, i, content) {
        if (!(*i)->IsFile()) {
            continue;
        }
        (*i)->DereferenceLink();

        CTime modification;
        string entry = (*i)->GetPath();
        string name = (*i)->GetName();
        string ext = (*i)->GetExt();
        (*i)->GetTime(&modification);
        time_t tm = modification.GetTimeT();
        CFile aFile(entry);
        Int8 file_size = aFile.GetLength();

        if (ext == ".db" || ext == ".idx") {
            continue; // Berkeley DB file, no need to index it.
        }

        bool found = lds_query.FindFile(entry);

        scanned_files->insert(entry);

        if (!found) {  // new file arrived
            CFormatGuess fg;

            Uint4 crc = 0;

            if (compute_check_sum) {
                checksum.Reset();
                ComputeFileChecksum(entry, checksum);
                crc = checksum.GetChecksum();
            }

            CFormatGuess::EFormat format = fg.Format(entry);

            FindMaxRecId();
            ++m_MaxRecId;

            m_FileDB.file_id = m_MaxRecId;
            m_FileDB.file_name = entry.c_str();
            m_FileDB.format = format;
            m_FileDB.time_stamp = tm;
            m_FileDB.CRC = crc;
            m_FileDB.file_size = file_size;

            m_FileDB.Insert();

            m_DataBase.GetTables().file_filename_idx.file_id = m_MaxRecId;
            m_DataBase.GetTables().file_filename_idx.file_name = entry.c_str();
            m_DataBase.GetTables().file_filename_idx.UpdateInsert();

            updated->set(m_MaxRecId);

            LOG_POST_X(4, Info << "New LDS file found: " << entry);

            continue;
        }

        if (tm != m_FileDB.time_stamp || file_size != m_FileDB.file_size) {
            updated->set(m_FileDB.file_id);
            UpdateEntry(m_FileDB.file_id,
                        entry,
                        0,
                        tm,
                        file_size,
                        compute_check_sum);
        } else {

            Uint4 crc = 0;
            if (compute_check_sum) {
                checksum.Reset();
                ComputeFileChecksum(entry, checksum);
                crc = checksum.GetChecksum();

                if (crc != (Uint4)m_FileDB.CRC) {
                    updated->set(m_FileDB.file_id);
                    UpdateEntry(m_FileDB.file_id,
                                entry,
                                crc,
                                tm,
                                file_size,
                                compute_check_sum);
                }
            }
        }

    } // ITERATE

    }}

    if ( (flags & CLDS_Manager::fRecurseMask) == CLDS_Manager::fDontRecurse )
        return;

    // Scan sub-directories

    {{

    CDir::TEntries  content(dir.GetEntries());
    ITERATE(CDir::TEntries, i, content) {

        if ((*i)->IsDir()) {
            string name = (*i)->GetName();

            if (name == "LDS" || name == "." || name == "..") {
                continue;
            }
            string entry = (*i)->GetPath();

            x_SyncWithDir(entry,
                          deleted,
                          updated,
                          scanned_files,
                          flags);

        }
    } // ITERATE

    }}
}
Example #24
0
/*******************************************************************************
 * MAIN                                                                        *
 ******************************************************************************/
int main(int argc, char* argv[]) {

    // Welcome user with program info!
    program_info();

    if (argc <= REQUIRED_PARAMS_NUM) {
        usage(argv[0]);
    }

    const char* fileNameE = argv[1];
    const char* fileNameF = argv[2];
    const char* fileNameA = argv[3];
    std::string fileNameExtract = std::string(argv[4]);

    // Init lossy counters.
    std::string lossyCountersParams;
    int paramIdx = 5;
    
    while ( (argc > paramIdx) && (*argv[paramIdx] != '-') ) {
        std::string param = std::string(argv[paramIdx]);
        if ( !parse_lossy_counting_params(param) ) {
            usage(argv[0]);
        }
        lossyCountersParams += (" " + param);
        ++paramIdx;
    }

    if ( paramIdx == REQUIRED_PARAMS_NUM ) {
        std::cerr << "ERROR: no Lossy Counting parameters specified!" << std::endl;
        usage(argv[0]);
    }

    for ( size_t i = 1; i < lossyCounters.size(); ++i ) {
        if ( lossyCounters[i] == NULL ) {
            std::cerr << "ERROR: max phrase length set to " << maxPhraseLength << ", but no Lossy Counting parameters specified for phrase pairs of length " << i << "!" << std::endl;
            usage(argv[0]);
        }
    }
    
    if ( (argc > paramIdx) && (strcmp(argv[paramIdx], "--compact") == 0) ) {
        compactOutputFlag = true;
        ++paramIdx;
    }

    if ( (argc > paramIdx) && (strcmp(argv[paramIdx], "--sort") == 0) ) {
        sortedOutput = true;
        ++paramIdx;
    }

    //
    read_optional_params(argc, argv, paramIdx);

    std::cerr << "Starting epochal phrase table extraction with params:" << lossyCountersParams << std::endl;
    std::cerr << "Output will be " << (sortedOutput ? "sorted" : "unsorted") << "." << std::endl;

    // open input files
    std::ifstream eFile(fileNameE);
    std::ifstream fFile(fileNameF);
    std::ifstream aFile(fileNameA);

    // open output files
    if (translationFlag) {
        if (sortedOutput) {
            extractFile.open((fileNameExtract + ".sorted").c_str());
            extractFileInv.open((fileNameExtract + ".inv.sorted").c_str());
        }
        else {
            extractFile.open(fileNameExtract.c_str());
            extractFileInv.open((fileNameExtract + ".inv").c_str());
        }
    }
    if (orientationFlag) {
        extractFileOrientation.open((fileNameExtract + ".o").c_str());
    }

    //
    readInput(eFile, fFile, aFile);

    std::cerr << std::endl; // Leave the progress bar end on previous line.
    
    // close input files
    eFile.close();
    fFile.close();
    aFile.close();

    FlushingOutputProcessor processor(compactOutputFlag);
    processOutput(processor);

    // close output files
    if (translationFlag) {
        extractFile.close();
        extractFileInv.close();
    }
    if (orientationFlag) {
	extractFileOrientation.close();
    }

    printStats();

} // end of main()
Example #25
0
cElNuageLaser::cElNuageLaser
(
     const std::string & aNameFile,
     const char *  aNameOri,
     const char *  aNameGeomCible ,
     const char *  aNameGeomInit

)  :
   mVPts (),
   mQt   (0)
{
   std::string aNameBin = StdPrefix(aNameFile) + ".tif";
   if (! ELISE_fp::exist_file(aNameBin))
   {
       INT aNb = 3;
       FILE * aFP = ElFopen(aNameFile.c_str(),"r");
       ELISE_ASSERT(aFP!=0,"Cannot Open File for Laser Data");

       char Buf[10000];
       INT aCpt =0;
       while (aNb>=3)
       {
           aNb=0;
           char * got = fgets(Buf,10000,aFP);
           Pt3dr aP;
           if (got)
           {
              aNb = sscanf(Buf,"%lf %lf %lf",&aP.x,&aP.y,&aP.z);
           }
	   if (aNb>=3)
              mVPts.push_back(aP);
	   aCpt++;
       }

       INT aNbPts = (INT) mVPts.size();
       Im2D_REAL8 aImPts(aNbPts,3);
       REAL ** aData = aImPts.data();
       for (INT aK=0 ; aK<aNbPts ; aK++)
       {
	   Pt3dr aP = mVPts[aK];
           aData[0][aK] = aP.x;
           aData[1][aK] = aP.y;
           aData[2][aK] = aP.z;
       }

       Tiff_Im aFile
	       (
                  aNameBin.c_str(),
		  Pt2di(aNbPts,3),
		  GenIm::real8,
		  Tiff_Im::No_Compr,
		  Tiff_Im::BlackIsZero,
		     Tiff_Im::Empty_ARG
		  +  Arg_Tiff(Tiff_Im::ANoStrip())
               );
       ELISE_COPY(aImPts.all_pts(),aImPts.in(),aFile.out());
   }
   else
   {
       Tiff_Im aFile(aNameBin.c_str());
       Pt2di aSz = aFile.sz();
       Im2D_REAL8 aImPts(aSz.x,aSz.y);
       ELISE_COPY(aImPts.all_pts(),aFile.in(),aImPts.out());

       REAL ** aD = aImPts.data();
       mVPts.reserve(aSz.x);
       for (INT aK=0 ; aK<aSz.x ; aK++)
       {
           Pt3dr aP(aD[0][aK],aD[1][aK],aD[2][aK]);
           mVPts.push_back(aP);
       }
   }


   Ori3D_Std * aOri = 0;
   eModeConvGeom aMode = eConvId;

   if (aNameOri)
   {
       if (!strcmp(aNameGeomInit,"GeomCarto"))
       {
           if (!strcmp(aNameGeomCible,"GeomCarto"))
           {
               aMode = eConvId;
           }
           else if (!strcmp(aNameGeomCible,"GeomTerrain"))
           {
               aMode = eConvCarto2Terr;
           }
           else if (!strcmp(aNameGeomCible,"GeomTerIm1"))
           {
               aMode = eConvCarto2TerIm;
           }
           else
           {
              ELISE_ASSERT(false,"Bad GeomCible in cElNuageLaser::cElNuageLaser");
           }
       }
       else
       {
           ELISE_ASSERT(false,"Bad GeomInit in cElNuageLaser::cElNuageLaser");
       }
       if (aMode != eConvId)
          aOri = new Ori3D_Std (aNameOri) ;
   }

   for (INT aK=0 ; aK<INT( mVPts.size()); aK++)
   {
       Pt3dr aP = mVPts[aK];
       if (aOri)
       {
          if (aMode == eConvCarto2Terr)
             aP = aOri->carte_to_terr(aP);
          else if (aMode == eConvCarto2TerIm)
          {
             aP = aOri->carte_to_terr(aP);
             Pt2dr aP2 = aOri->to_photo(aP);
             aP.x = aP2.x;
             aP.y = aP2.y;
          }
          mVPts[aK] = aP;
       }

       REAL  aZ   =  aP.z;
       Pt2dr aP2 (aP.x,aP.y);
       if (aK==0)
       {
           mZMax = mZMin = aZ;
           mPInf =mPSup = aP2;
       }
       ElSetMin(mZMin,aZ);
       ElSetMax(mZMax,aZ);
       mPInf.SetInf(aP2);
       mPSup.SetSup(aP2);
   }
   delete aOri;
}
Example #26
0
bool CCompiler::compile(const string& cmdLine)
{
    if( !cmdLine.size() )
    {
        return false;
    }

    PROCESS_INFORMATION pi;
    ZeroMemory( &pi, sizeof(pi) );

    STARTUPINFO si;
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);

    //sec attributes for the output file
    SECURITY_ATTRIBUTES sao;
    sao.nLength=sizeof(SECURITY_ATTRIBUTES);
    sao.lpSecurityDescriptor=NULL;
    sao.bInheritHandle=1;

    string compilerTempFile(joinPath(mOutputPath, getFileNameNoExtension(mDLLFileName)));
    compilerTempFile.append("C.log");

    Poco::File aFile(compilerTempFile);
    if(aFile.exists())
    {
        aFile.remove();
    }

    HANDLE outFile;
      //Todo: there is a problem creating the logfile after first time creation..
    if((outFile=CreateFileA(compilerTempFile.c_str(),
                            GENERIC_WRITE,
                            FILE_SHARE_DELETE,
                            &sao,
                            OPEN_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL))==INVALID_HANDLE_VALUE)
    {
        // Retrieve the system error message for the last-error code
        DWORD errorCode = GetLastError();
        string anError = getWINAPIError(errorCode, TEXT("CreateFile"));
        Log(Logger::LOG_ERROR)<<"WIN API Error (after CreateFile): "<<anError;
        Log(Logger::LOG_ERROR)<<"Failed creating logFile for compiler output";
    }

    SetFilePointer(outFile, 0, NULL, FILE_END); //set pointer position to end file

    //init the STARTUPINFO struct
    si.dwFlags=STARTF_USESTDHANDLES;
    si.hStdOutput = outFile;
    si.hStdError  = outFile;

    //proc sec attributes
    SECURITY_ATTRIBUTES sap;
    sap.nLength=sizeof(SECURITY_ATTRIBUTES);
    sap.lpSecurityDescriptor=NULL;
    sap.bInheritHandle=1;

    //thread sec attributes
    SECURITY_ATTRIBUTES sat;
    sat.nLength=sizeof(SECURITY_ATTRIBUTES);
    sat.lpSecurityDescriptor=NULL;
    sat.bInheritHandle=1;

    // Start the child process.
    if( !CreateProcessA(
        NULL,                           // No module name (use command line)
        (char*) cmdLine.c_str(),        // Command line
        &sap,                           // Process handle not inheritable
        &sat,                           // Thread handle not inheritable
        TRUE,                          // Set handle inheritance
        CREATE_NO_WINDOW,               // Creation flags
        NULL,                           // Use parent's environment block
        NULL,                           // Use parent's starting directory
        &si,                            // Pointer to STARTUPINFO structure
        &pi )                           // Pointer to PROCESS_INFORMATION structure
    )
    {
        DWORD errorCode = GetLastError();

        string anError = getWINAPIError(errorCode, TEXT("CreateProcess"));
        Log(Logger::LOG_ERROR)<<"WIN API Error: (after CreateProcess) "<<anError;

        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        CloseHandle(outFile);
        return false;
    }

    // Wait until child process exits.
    WaitForSingleObject(pi.hProcess, INFINITE);

    CloseHandle(outFile);

    // Close process and thread handles.
    CloseHandle(pi.hProcess);
    DWORD errorCode = GetLastError();
    if(errorCode != 0)
    {
        string anError = getWINAPIError(errorCode, TEXT("CloseHandle"));
        Log(lDebug)<<"WIN API error: (pi.hProcess)"<<anError;
    }

    CloseHandle(pi.hThread);
    errorCode = GetLastError();
    if(errorCode != 0)
    {
        string anError = getWINAPIError(errorCode, TEXT("CloseHandle"));
        Log(lDebug)<<"WIN API error: (pi.hThread)"<<anError;
    }

    //Read the log file and log it
    if(fileExists(compilerTempFile))
    {
        string log = getFileContent(compilerTempFile.c_str());
        Log(lDebug)<<"Compiler output: "<<log<<endl;
    }

    return true;
}
Example #27
0
void ChatDlg::doFile()
{
	aFile(jid());
}
void cDbleGrid::write(const  std::string & aName)
{
  ELISE_fp aFile(aName.c_str(),ELISE_fp::WRITE);
  write(aFile);
  aFile.close();
}
Example #29
0
void Context::init(const Params& params)
{
	Poco::Crypto::OpenSSLInitializer::initialize();
	
	createSSLContext();

	try
	{
		int errCode = 0;
		if (!params.caLocation.empty())
		{
			Poco::File aFile(params.caLocation);
			if (aFile.isDirectory())
				errCode = SSL_CTX_load_verify_locations(_pSSLContext, 0, Poco::Path::transcode(params.caLocation).c_str());
			else
				errCode = SSL_CTX_load_verify_locations(_pSSLContext, Poco::Path::transcode(params.caLocation).c_str(), 0);
			if (errCode != 1)
			{
				std::string msg = Utility::getLastError();
				throw SSLContextException(std::string("Cannot load CA file/directory at ") + params.caLocation, msg);
			}
		}

		if (params.loadDefaultCAs)
		{
			errCode = SSL_CTX_set_default_verify_paths(_pSSLContext);
			if (errCode != 1)
			{
				std::string msg = Utility::getLastError();
				throw SSLContextException("Cannot load default CA certificates", msg);
			}
		}

		if (!params.privateKeyFile.empty())
		{
			errCode = SSL_CTX_use_PrivateKey_file(_pSSLContext, Poco::Path::transcode(params.privateKeyFile).c_str(), SSL_FILETYPE_PEM);
			if (errCode != 1)
			{
				std::string msg = Utility::getLastError();
				throw SSLContextException(std::string("Error loading private key from file ") + params.privateKeyFile, msg);
			}
		}

		if (!params.certificateFile.empty())
		{
			errCode = SSL_CTX_use_certificate_chain_file(_pSSLContext, Poco::Path::transcode(params.certificateFile).c_str());
			if (errCode != 1)
			{
				std::string errMsg = Utility::getLastError();
				throw SSLContextException(std::string("Error loading certificate from file ") + params.certificateFile, errMsg);
			}
		}

		if (isForServerUse())
			SSL_CTX_set_verify(_pSSLContext, params.verificationMode, &SSLManager::verifyServerCallback);
		else
			SSL_CTX_set_verify(_pSSLContext, params.verificationMode, &SSLManager::verifyClientCallback);

		SSL_CTX_set_cipher_list(_pSSLContext, params.cipherList.c_str());
		SSL_CTX_set_verify_depth(_pSSLContext, params.verificationDepth);
		SSL_CTX_set_mode(_pSSLContext, SSL_MODE_AUTO_RETRY);
		SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
		
		initDH(params.dhParamsFile);
		initECDH(params.ecdhCurve);
	}
	catch (...)
	{
		SSL_CTX_free(_pSSLContext);
		throw;
	}
}
Example #30
0
nsresult
nsMsgCopyService::DoNextCopy()
{
  nsresult rv = NS_OK;
  nsCopyRequest* copyRequest = nullptr;
  nsCopySource* copySource = nullptr;
  uint32_t i, j, scnt;

  uint32_t cnt = m_copyRequests.Length();
  if (cnt > 0)
  {
    nsCOMArray<nsIMsgFolder> activeTargets;

    // ** jt -- always FIFO
    for (i = 0; i < cnt; i++)
    {
      copyRequest = m_copyRequests.ElementAt(i);
      copySource = nullptr;
      scnt = copyRequest->m_copySourceArray.Length();
      if (!copyRequest->m_processed)
      {
        // if the target folder of this request already has an active
        // copy request, skip this request for now.
        if (activeTargets.IndexOfObject(copyRequest->m_dstFolder) != kNotFound)
        {
          copyRequest = nullptr;
          continue;
        }
        if (scnt <= 0)
            goto found; // must be CopyFileMessage
        for (j = 0; j < scnt; j++)
        {
          copySource = copyRequest->m_copySourceArray.ElementAt(j);
          if (!copySource->m_processed)
            goto found;
        }
        if (j >= scnt) // all processed set the value
          copyRequest->m_processed = true;
      }
      if (copyRequest->m_processed) // keep track of folders actively getting copied to.
        activeTargets.AppendObject(copyRequest->m_dstFolder);
    }
    found:
      if (copyRequest && !copyRequest->m_processed)
      {
          if (copyRequest->m_listener)
              copyRequest->m_listener->OnStartCopy();
          if (copyRequest->m_requestType == nsCopyMessagesType &&
              copySource)
          {
              copySource->m_processed = true;
              rv = copyRequest->m_dstFolder->CopyMessages
                  (copySource->m_msgFolder, copySource->m_messageArray,
                   copyRequest->m_isMoveOrDraftOrTemplate,
                   copyRequest->m_msgWindow, copyRequest->m_listener, false, copyRequest->m_allowUndo);   //isFolder operation false

          }
          else if (copyRequest->m_requestType == nsCopyFoldersType )
          {
              copySource->m_processed = true;
              rv = copyRequest->m_dstFolder->CopyFolder
                  (copySource->m_msgFolder,
                   copyRequest->m_isMoveOrDraftOrTemplate,
                   copyRequest->m_msgWindow, copyRequest->m_listener);
              // If it's a copy folder operation and the destination
              // folder already exists, CopyFolder() returns an error w/o sending
              // a completion notification, so clear it here.
              if (NS_FAILED(rv))
                ClearRequest(copyRequest, rv);

          }
          else if (copyRequest->m_requestType == nsCopyFileMessageType)
          {
            nsCOMPtr<nsIFile> aFile(do_QueryInterface(copyRequest->m_srcSupport, &rv));
            if (NS_SUCCEEDED(rv))
            {
                // ** in case of saving draft/template; the very first
                // time we may not have the original message to replace
                // with; if we do we shall have an instance of copySource
                nsCOMPtr<nsIMsgDBHdr> aMessage;
                if (copySource)
                {
                    aMessage = do_QueryElementAt(copySource->m_messageArray,
                                                 0, &rv);
                    copySource->m_processed = true;
                }
                copyRequest->m_processed = true;
                rv = copyRequest->m_dstFolder->CopyFileMessage
                    (aFile, aMessage,
                     copyRequest->m_isMoveOrDraftOrTemplate,
                     copyRequest->m_newMsgFlags,
                     copyRequest->m_newMsgKeywords,
                     copyRequest->m_msgWindow,
                     copyRequest->m_listener);
            }
          }
      }
    }
    return rv;
}