Exemplo n.º 1
0
void
FindWindow::FindResults(void)
{
	// This function is called from the FinderThread function, so locking is
	// required when accessing any member variables.
	Lock();
	bool canReplace = fReplaceButton->IsEnabled();
	EnableReplace(false);
	for (int32 i = fResultList->CountItems() - 1; i >= 0; i--)
	{
		// We don't want to hog the window lock, but we also don't want
		// tons of context switches, either. Yielding the lock every 5 items
		// should give us sufficient responsiveness.
		if (i % 5 == 0)
		{
			Unlock();
			Lock();
		}
		
		BListItem *item = fResultList->RemoveItem(i);
		delete item;
	}
	Unlock();

	ShellHelper shell;
	
	shell << "cd ";
	shell.AddEscapedArg(fWorkingDir);
	shell << "; pwd; find . -type f ";
	shell << "|xargs grep -n -H -s --binary-files=without-match ";
	// TODO check for PCRE invocation and pass in pcre flag to grep if so
	// TODO Ensure RE escaping also happens (E.g. open/close paran etc.)
	shell.AddEscapedArg(fFindBox->Text());
	
	if (fThreadQuitFlag)
		return;
	
	BString out;
	shell.RunInPipe(out, false);
	
	if (fThreadQuitFlag)
		return;
	
	BObjectList<BString> resultList(20, true);
	TokenizeToList(out.String(), resultList);
	
	Lock();
	
	for (int32 i = 0; i < resultList.CountItems(); i++)
	{
		// We don't want to hog the window lock, but we also don't want
		// tons of context switches, either. Yielding the lock every 5 items
		// should give us sufficient responsiveness.
		if (i % 5 == 0)
		{
			Unlock();
			Lock();
		}
		
		BString entryString(resultList.ItemAt(i)->String());
		
		BString filename(entryString);
		int32 pos = filename.FindFirst(":");
		if (pos < 0)
			continue;
		filename.Truncate(pos);
		if (filename.StartsWith("./"))
			filename.Remove(0,2);
		STRACE(2,("Truncated file name from grep: %s\n",filename.String()));
		
		BString lineString;
		entryString.CopyInto(lineString, pos + 1, entryString.CountChars() - pos);
		int32 pos2 = lineString.FindFirst(":");
		
		BString locationString;
		lineString.CopyInto(locationString, pos2 + 1, lineString.CountChars() - pos2);
		lineString.Truncate(pos2);
		
		DPath entryPath(fWorkingDir);
		entryPath << filename;
		
		BString fullPath(fWorkingDir);
		fullPath << "/" << filename;
		
		STRACE(2,("Full path: %s\n",fullPath.String()));
		
		DPath relPath(filename);
		
		fResultList->AddItem(new GrepListItem(fullPath,filename,
			entryPath.GetRef(), atol(lineString.String()),
			locationString.String()));
	}
	EnableReplace(true);
	
	if (fResultList->CountItems() == 0)
		fResultList->AddItem(new BStringItem(B_TRANSLATE("No matches found")));
	
	Unlock();
	
}
Exemplo n.º 2
0
bool ExperimentUnpackager::unpackageExperiment(Datum payload) {

    namespace bf = boost::filesystem;

    if(payload.getDataType() != M_DICTIONARY) {
        merror(M_NETWORK_MESSAGE_DOMAIN,
               "Invalid payload type for experiment package");
        return false;
    }

    Datum experimentFilePackage =
        payload.getElement(M_PACKAGER_EXPERIMENT_STRING);

    if(experimentFilePackage.getNElements() !=
            M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS_PER_UNIT ||
            experimentFilePackage.getDataType() != M_DICTIONARY)
        return false;

    Datum experimentFileName =
        experimentFilePackage.getElement(M_PACKAGER_FILENAME_STRING);
    if(experimentFileName.getDataType() != M_STRING ||
            experimentFileName.getStringLength() <= 0)
        return false;

    bf::path experimentName(experimentFileName.getString());

    loadedExperimentFilename = prependExperimentInstallPath(removeFileExtension(experimentName.string()),
                               experimentName.string());

    bf::path experimentPath = loadedExperimentFilename.branch_path();

    createExperimentInstallDirectoryStructure(experimentName.string());


    // create the XML file
    Datum experimentFileBuffer =
        experimentFilePackage.getElement(M_PACKAGER_CONTENTS_STRING);

    if(experimentFileBuffer.getDataType() != M_STRING ||
            experimentFileBuffer.getStringLength() <= 0)
        return false;

    if(!(createFile(Datum(loadedExperimentFilename.string().c_str()),
                    experimentFileBuffer))) {
        // failed to create experiment file
        merror(M_FILE_MESSAGE_DOMAIN,
               "Failed to create server side experiment file %s",
               loadedExperimentFilename.string().c_str());
        return false;
    }

    // create all of the other media files
    Datum mediaFileList = payload.getElement(M_PACKAGER_MEDIA_BUFFERS_STRING);

    if(mediaFileList.isList()) {

        for(int i=0; i<mediaFileList.getNElements(); ++i) {
            Datum mediaFilePackage = mediaFileList.getElement(i);

            if(mediaFilePackage.getDataType() != M_DICTIONARY |
                    mediaFilePackage.getNElements() != 2) {
                merror(M_FILE_MESSAGE_DOMAIN,
                       "incorrectly packaged media files");
                return false;
            }

            Datum mediaFileName =
                mediaFilePackage.getElement(M_PACKAGER_FILENAME_STRING);
            Datum mediaFileBuffer =
                mediaFilePackage.getElement(M_PACKAGER_CONTENTS_STRING);

            if(mediaFileName.getDataType() != M_STRING ||
                    mediaFileName.getStringLength() <= 0 ||
                    mediaFileBuffer.getDataType() != M_STRING) return false;

            std::string filename(mediaFileName.getString());
            std::string filenameWPath = experimentPath.string() + "/" + filename;

            if(!(createFile(Datum(filenameWPath.c_str()),
                            mediaFileBuffer))) {
                // failed to create experiment file
                merror(M_FILE_MESSAGE_DOMAIN,
                       "Failed to create server side experiment file %s",
                       filenameWPath.c_str());
                return false;
            }
        }
    }

    expandRangeReplicatorItems(loadedExperimentFilename);
    modifyExperimentMediaPaths(loadedExperimentFilename);

    return true;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void SimpleImportExample::runImport(const std::string &outputFilePath)
{
  // Create a DataModel
  MXADataModel::Pointer model = this->createSimpleModel();

  // Create some external files that our import delegate will read
  this->createTestFiles(model);

  // Create a DataFile object which will create the actual file on disk.
  IDataFile::Pointer dataFile = H5MXADataFile::CreateFileWithModel(outputFilePath, model);

  //Create the DataImport Class
  MXADataImport::Pointer dataImport(new MXADataImport());
  dataImport->setDataFile(dataFile);

  // Get an instance to the ImportDelegateManager
  ImportDelegateManager::Pointer idManagerPtr = ImportDelegateManager::instance();
  // Get a reference to an Import Delegate given the name of the class
  IImportDelegate::Pointer delegatePtr = ImportDelegateManager::createNewImportDelegate(ExampleImport::Detail::ClassName);

  // We have two dimensions for this model, create a loop to create data sets for each possible dimension value
  IDataDimension::Pointer dim0 = model->getDataDimension(0); // Get the first Dimension
  IDataDimension::Pointer dim1 = model->getDataDimension(1); // Get the second Dimension

  // Create a DataRecord entry for the Data Model
  IDataRecord::Pointer record = model->getDataRecordByNamedPath("DataRecordContainer/Test Data/Deep Nested Data");

  // Set the start/end/increment values for each Data Dimension
  int32_t dim0Start = dim0->getStartValue();
  int32_t dim0End = dim0->getEndValue();
  int32_t dim0Increment = dim0->getIncrement();

  int32_t dim1Start = dim1->getStartValue();
  int32_t dim1End = dim1->getEndValue();
  int32_t dim1Increment = dim1->getIncrement();

  // Create a nested loop to create the necessary DataSource objects that will
  //  be used to import the data into the HDF5 file
  for (int32_t i = dim0Start; i <= dim0End; i += dim0Increment)
  {
    for (int j = dim1Start; j <= dim1End; j = j + dim1Increment)
    {
      std::string filename(Examples::SimportImportDataInputFile);
      filename.append( StringUtils::numToString<int32_t>(i) );
      filename.append("_").append(StringUtils::numToString<int32_t>(j)).append(".data");

      //Create some Data Sources
      MXADataSource::Pointer ds(new MXADataSource());
      std::vector<int32_t> dimValues;
      dimValues.push_back(i);
      dimValues.push_back(j);
      ds->setDimensionValues(dimValues);
      ds->setDataRecord(record);
      ds->setSourcePath(filename); //Since we are doing everything in software, this is unused
      ds->setImportDelegate(delegatePtr);
      ds->setDataModel(model);
      dataImport->addDataSource(ds);
    }
  }

  // Import the Data into the HDF5 File
  // std::cout << "IMPORTING DATA NOW" << std::endl;
  int32_t err = dataImport->import();
  if (err < 0)
  {

  }
  dataFile->closeFile(false);
}
Exemplo n.º 4
0
void
ExporterVTK<MeshType>::readVTUFiles( exporterData_Type& dvar )
{
    ASSERT( this->M_numImportProc, "The number of pieces to be loaded was not specified." );

    UInt numPoints, numCells;
    std::vector<Real> inputValues;
    std::vector<Real> localDOF;

    const UInt start        ( dvar.start() );
    const UInt numGlobalDOF ( dvar.numDOF() );

    // Each processor will read all the files, and fill just its own component of the vectors
    for( UInt iProc = 0; iProc < this->M_numImportProc; ++iProc )
    {
        std::string filename( this->M_postDir + this->M_prefix + "_" + dvar.variableName() +
                              this->M_postfix + "." + iProc + ".vtu" );
        std::ifstream inputFile( filename.c_str() );

        if (!this->M_procId) std::cout << "\tfile "<< filename << std::endl;

        ASSERT(inputFile.is_open(), "There is an error while opening " + filename );

        // file parsing: line by line
        std::string line;
        size_t found;
        std::stringstream parseLine;

        while ( inputFile.good() && getline( inputFile, line ) )
        {
            // this is essentially a consistency check: the number of DOF is explicitly
            // written in the VTK files. We will check that the number of values read
            // from file matches this number
            found = line.find( "NumberOfPoints" );
            if ( found != std::string::npos )
            {
                // place the get pointer at the first " after NumberOfPoints
                found = line.find( "\"", found, 1 );
                // after the " we'll find the number: parse the substring
                parseLine.str( line.substr(found+1) );
                parseLine >> numPoints;

                // do the same for NumberOfCells
                found = line.find( "NumberOfCells" );
                found = line.find( "\"", found, 1 );
                parseLine.str( line.substr(found+1) );
                parseLine >> numCells;
            }

            // load all PointData arrays
            if ( line.find( "<PointData" ) != std::string::npos )
            {
                while ( inputFile.good() && getline( inputFile, line ) )
                {
                    if ( line.find( dvar.variableName() ) != std::string::npos )
                    {
                        inputValues.resize( dvar.fieldDim()*numPoints );

                        if ( line.find( "binary" ) != std::string::npos )
                        {
                            UInt numBitsFloat;
                            found = line.find( "Float" );
                            parseLine.str( line.substr(found+5) );
                            parseLine >> numBitsFloat;
                            ASSERT(inputFile.good(), "There is an error while opening " + filename );
                            getline( inputFile, line );
                            readBinaryData( line, inputValues, numBitsFloat );
                        }
                        else
                        {
                            ASSERT(inputFile.good(), "There is an error while opening " + filename );
                            getline( inputFile, line );
                            readASCIIData( line, inputValues );
                        }
                    }
                    if ( line.find( "GlobalId" ) != std::string::npos )
                    {
                        localDOF.resize( numPoints );
                        ASSERT(inputFile.good(), "There is an error while opening " + filename );
                        getline( inputFile, line );
                        readASCIIData( line, localDOF );
                    }
                }
Exemplo n.º 5
0
void FileCtl::io_err            // THROW I/O ERROR
    ( char const *msg )         // - message
{
    throw Exc( "I/O:", msg, filename(), 0 );
}
	// Adds the file specified by ``path`` to the file_storage object. In case ``path``
	// refers to a diretory, files will be added recursively from the directory.
	// 
	// If specified, the predicate ``p`` is called once for every file and directory that
	// is encountered. files for which ``p`` returns true are added, and directories for
	// which ``p`` returns true are traversed. ``p`` must have the following signature::
	// 
	// 	bool Pred(std::string const& p);
	// 
	// The path that is passed in to the predicate is the full path of the file or
	// directory. If no predicate is specified, all files are added, and all directories
	// are traveresed.
	// 
	// The ".." directory is never traversed.
	// 
	// The ``flags`` argument should be the same as the flags passed to the `create_torrent`_
	// constructor.
	template <class Pred> void add_files(file_storage& fs, std::string const& file, Pred p, boost::uint32_t flags = 0)
	{
		detail::add_files_impl(fs, parent_path(complete(file)), filename(file), p, flags);
	}
MemoryMappedFile::Flushable* MemoryMappedFile::prepareFlush() {
    return new WindowsFlushable(this, viewForFlushing(), fd, _uniqueId, filename(), _flushMutex);
}
Exemplo n.º 8
0
BOOL WINPROC EXPORT DlgOpenProc(
/************************************************************************/
HWND 	hDlg,
UINT 	msg,
WPARAM 	wParam,
LPARAM 	lParam)
{
BOOL Bool;
ITEMID id;
WORD wMsg, wIndex;
int i, ii, l, fp, hi, lo;
FNAME szDriveNDir, szFileName, szExtension;
HMENU hMenu;
STRING szString;
char cChar;
BOOL bModifySaveName;
static BOOL bDisableCancel;

switch (msg)
    {
    case WM_INITDIALOG:
	SET_CLASS_HBRBACKGROUND(hDlg, ( HBRUSH )GetStockObject(LTGRAY_BRUSH));
	CenterPopup( hDlg );
	if ( !DlgDirList(hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr) )
		{
		lstrcpy( szFileSpec, lstrchr( szFileSpec, '*' ) );
		DlgDirList(hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr);
		}
	SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, fSaving);
	CheckComboItem( hDlg, IDC_FILETYPES, IDC_ART, IDC_BMP,
		IDC_ART + (idFileType-IDN_ART) );
	SendDlgItemMessage(hDlg, IDC_FNAME, EM_LIMITTEXT, MAX_FNAME_LEN-1, 0L);

	LoadComboWithDrives( hDlg, IDC_DRIVES );
	LoadComboWithDirectories( hDlg, IDC_DIRS, NO );
	CheckDlgButton( hDlg, IDC_SAVEPATH, Save.OKtoSavePath );
	CheckDlgButton( hDlg, IDC_SAVECOMPRESS, Save.Compressed );
	for (i = IDC_ART; bImageOpen && i <= IDC_BMP; ++i)
		{
		ii = i-IDC_ART;
		if (lstrlen(Readers[ii].szDLL))
			{
			lstrcpy(szString, Control.ProgHome);
			lstrcat(szString, Readers[ii].szDLL);
			if (!FileExists(szString))
				{
				if ( GetPrivateProfileString( "Micrografx", "Libraries", "",
					szString, sizeof(STRING), "MGX.INI" ) > 2 )
						FixPath( szString );
				lstrcat(szString, Readers[ii].szDLL);
				if (!FileExists(szString))
					{
					ControlEnable( hDlg, i, NO);
					continue;
					}
				}
			}
		if (fSaving)
			ControlEnable( hDlg, i, lpImage &&
				Readers[ii].bSave[FrameDepth(ImgGetBaseEditFrame(lpImage))] );
		else
			ControlEnable( hDlg, i, Readers[ii].bOpen );
		}
	if ( bImageOpen && lpImage )
		{
		idDataType = lpImage->DataType;
		for (i = IDC_SAVECT; i <= IDC_SAVE24BITCOLOR; ++i)
			ControlEnable( hDlg, i,
			Readers[idFileType-IDN_ART].bTypes[i-IDC_SAVECT]);
		CheckComboItem( hDlg, IDC_DATATYPES, IDC_SAVECT,
			IDC_SAVE24BITCOLOR, idDataType );
		ControlEnable( hDlg, IDC_SAVECOMPRESS,
			Readers[idFileType-IDN_ART].bCompressed );
		}

	SetFocus( GetDlgItem( hDlg, IDC_FNAME ) );
	SendDlgItemMessage(hDlg, IDC_FNAME, EM_SETSEL,
		NULL, MAKELONG(0, 0x7fff));
	bNavigated = NO;
	bDisableCancel = NO;
	return( FALSE );

    case WM_PALETTECHANGED:
	break;

    case WM_MENUSELECT:
	lo = LOWORD(lParam);
	hi = HIWORD(lParam);
	if (hi == 0)
		break;
	if (lo == -1)
		break;
	if (lo & MF_SYSMENU)
		break;
	if (lo & MF_POPUP)
		{
		hMenu = (HMENU)wParam;
		while (GetSubMenu(hMenu, 0))
			hMenu = GetSubMenu(hMenu, 0);
		id = GetMenuItemID(hMenu, 0);
		if (id <= 0)
			break;
		wParam = id - 1;
		}
	HintLine( wParam );
	break;

    case WM_SETCURSOR:
	return( SetupCursor( wParam, lParam, idOpen ) );

    case WM_CLOSE:
	AstralDlgEnd( hDlg, FALSE|2 );
	break;

    case WM_MEASUREITEM:
    case WM_DRAWITEM:
	id = ((LPDRAWITEMSTRUCT)lParam)->CtlID;
	Bool = ( id == IDC_DRIVES || id == IDC_DIRS );
	return( OwnerDraw( hDlg, msg, lParam, Bool ) );
//	break;

    case WM_CTLCOLOR:
	return( (BOOL)SetControlColors( (HDC)wParam, hDlg, (HWND)LOWORD(lParam),
		HIWORD(lParam) ) );

    case WM_COMMAND:
	if (wParam != IDCANCEL)
		bDisableCancel = NO;
	switch(wParam)
	    {
	    case IDC_FILETYPES:
//	    case IDC_ART:
//	    case IDC_TIFF:
//	    case IDC_BMP:
		if ( !(wParam = HandleCombo( hDlg, wParam, lParam )) )
			break;
		idFileType = IDN_ART + (wParam-IDC_ART);
		if (bNavigated)
			{
			LookupExtension( idFileType, szFileSpec );
			}
		else	GetFileLocation( idFileType, szFileSpec );
		for (i = IDC_SAVECT; i <= IDC_SAVE24BITCOLOR; ++i)
			ControlEnable( hDlg, i,
			Readers[idFileType-IDN_ART].bTypes[i-IDC_SAVECT]);
		ControlEnable( hDlg, IDC_SAVECOMPRESS,
			Readers[idFileType-IDN_ART].bCompressed );
		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, NO );
		SendMessage( hDlg, WM_COMMAND, IDOK, 0L );
		break;

	    case IDC_DATATYPES:
//	    case IDC_SAVECT:
//	    case IDC_SAVELA:
//	    case IDC_SAVESP: // scatterprint
//	    case IDC_SAVE8BITCOLOR:
//	    case IDC_SAVE24BITCOLOR:
		if ( !(wParam = HandleCombo( hDlg, wParam, lParam )) )
			break;
		idDataType = wParam;
		break;

	    case IDC_SAVEPATH:
		Save.OKtoSavePath = (BOOL)SendDlgItemMessage (hDlg, IDC_SAVEPATH,
		  BM_GETCHECK, 0, 0L);
//		Save.OKtoSavePath = !Save.OKtoSavePath;
//		CheckDlgButton( hDlg, IDC_SAVEPATH, Save.OKtoSavePath );
		break;

	    case IDC_SAVECOMPRESS:
		Save.Compressed = (BOOL)SendDlgItemMessage (hDlg, IDC_SAVECOMPRESS,
		  BM_GETCHECK, 0, 0L);
//		Save.Compressed = !Save.Compressed;
//		CheckDlgButton( hDlg, IDC_SAVECOMPRESS, Save.Compressed );
		break;

	    case IDC_DRIVES:
		wMsg = HIWORD(lParam);
		if ( wMsg != CBN_SELCHANGE )
			break;
		wIndex = SendDlgItemMessage( hDlg, wParam, CB_GETCURSEL, 0, 0L);
		SendDlgItemMessage( hDlg, wParam, CB_GETLBTEXT, wIndex,
			(long)(LPSTR)szDriveNDir );
		id = ExtractStringID( szDriveNDir );
		if (CHDRIVE( *szDriveNDir - 'a' ))
			{
			LoadComboWithDrives(hDlg, IDC_DRIVES);
			break;
			}
		if (!CURRENTDIR(szString, sizeof(szString)))
			{
			GetDlgItemText(hDlg, IDC_FPATH, szString,
				 sizeof(szString));
			CHDRIVE(*szString - 'a');
			LoadComboWithDrives(hDlg, IDC_DRIVES);
			}
//12/15		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, NO);
		DlgDirList( hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr );
		LoadComboWithDirectories( hDlg, IDC_DIRS, YES );
		SetDlgItemText( hDlg, IDC_DISKSPACE,
			DriveSize( *szDriveNDir - 'a', szString ) );
		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, fSaving );
		bNavigated = YES;
		break;

	    case IDC_DIRS:
		wMsg = HIWORD(lParam);
		if ( wMsg == LBN_DBLCLK )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != LBN_SELCHANGE )
			break;
		wIndex = SendDlgItemMessage( hDlg, wParam, LB_GETCURSEL, 0, 0L);
		// Figure out how to build the path name based on the selection
		SendDlgItemMessage( hDlg, wParam, LB_GETTEXT, wIndex,
			(long)(LPSTR)szDriveNDir );
		id = ExtractStringID( szDriveNDir );
		if ( id == IDC_PATHICON_OPEN )
			i = 0; // Must start building the path from the root
		else
		if ( id == IDC_PATHICON_ACTIVE )
			i = 9999; // Don't build any path - we're there
		else	i = wIndex; // OK to build a relative path
		szFileName[0] = '\0';
		for ( ; i<=wIndex; i++ )
			{
			SendDlgItemMessage( hDlg, wParam, LB_GETTEXT, i,
				(long)(LPSTR)szDriveNDir );
			id = ExtractStringID( szDriveNDir );
			if ( id == IDC_PATHICON_CLOSED && i != wIndex )
				continue;
			lstrcat( szFileName, SkipSpaces(szDriveNDir) );
			if ( id != IDC_PATHICON_ROOT )
				lstrcat( szFileName, "\\" );
			}
		lstrcat( szFileName, szFileSpec );
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		bNavigated = YES;
		break;

	    case IDC_FLIST:
		wMsg = HIWORD(lParam);
		if ( wMsg == LBN_DBLCLK )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != LBN_SELCHANGE )
			break;
		/* If a directory is selected... */
		if (DlgDirSelectEx(hDlg, szFileName, sizeof(szFileName), wParam))
			lstrcat(szFileName, szFileSpec);
		// 1-2-92 - TMR - always use SetFileName for all FNAME sets
// 		SetDlgItemText(hDlg, IDC_FNAME, szFileName);
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		SendDlgItemMessage(hDlg, IDC_FNAME, EM_SETSEL,
			NULL, MAKELONG(0, 0x7fff));
//		SendDlgItemMessage(hDlg, IDC_FNAME, CB_SETEDITSEL,
//			NULL, MAKELONG(0, 0x7fff));
		break;

	    case IDC_FNAME:
		/* If the name is changed, disable OK if its length goes 0 */
		if (HIWORD(lParam) != EN_CHANGE)
//		if (HIWORD(lParam) != CBN_EDITCHANGE)
			break;
		ControlEnable( hDlg, IDOK,
			(BOOL)SendDlgItemMessage( hDlg, wParam,
			WM_GETTEXTLENGTH, 0, 0L));
		
		// 1-2-92 - TMR - make sure Edit Box has focus to make sure
		// that szSaveName only gets overwritten from user input
		// 1-3-92 - TMR - move this after ControlEnable
		if (GetFocus() != GetDlgItem(hDlg, IDC_FNAME))
			break;
		if (fSaving)
			{
			GetDlgItemText(hDlg, IDC_FNAME, szSaveName,
				MAX_FNAME_LEN);
			fUntitled = NO;
			}
		break;

	    case IDC_FPATH:
		wMsg = HIWORD(lParam);
		if ( wMsg == BN_DOUBLECLICKED )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != BN_CLICKED )
			break;
 		GetDlgItemText(hDlg, wParam, szFileName, sizeof(szFileName));
		if ( !szFileName[0] )
			break;
		FixPath( szFileName );
		lstrcat( szFileName, szFileSpec );
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		bNavigated = YES;
		break;

	    case IDOK:
		GetDlgItemText(hDlg, IDC_FNAME, szFileName,sizeof(szFileName));
		bModifySaveName = fSaving && StringsEqual(szFileName,
			szSaveName);
		/* Strip off the drive and directory to make */
		/* a DlgDirlist() call to switch over to them */
		/* Loop backwards over the file name */
		l = lstrlen(szFileName);
		while( --l >= 0 )
		   {
		   cChar = szFileName[l];
		   /* If we find a wildcard, the next DlgDirList() takes */
		   /* care of drive and directory switching; so get out */
		   if ( cChar == '?' || cChar == '*' )
			break;
		   /* If we find a drive or directory, handle it and get out */
		   if ( cChar == '\\' || cChar == ':' )
			{
			lstrcpy(szDriveNDir, szFileName);
			l++;
			szDriveNDir[l] = '\0';
			lstrcat(szDriveNDir, szFileSpec);
			// 1-3-92 - TMR - Handle directory change error
			if (DlgDirList(hDlg, szDriveNDir,
					 IDC_FLIST, IDC_FPATH, wFileAttr))
				lstrcpy( szFileName, &szFileName[l] );
			else
				{
				szDriveNDir[l] = '\0';
				Message(IDS_EDIRECTORYCHANGE,
					 Lowercase(szDriveNDir));
				szFileName[0] = '\0';
				}
			break;
			}
		   }

		// 1-3-92 - TMR add extension if none present
		/* Check to see if the file has an extension... */
		if ( !lstrchr( szFileName, '.' ) ) // if no extension...
		    if ( LookupExtension( idFileType, szExtension ) )
			{
			if (lstrlen(szFileName))
			    lstrcat( szFileName, extension(szExtension) );
			else
			    lstrcat( szFileName, szExtension);
			}
		if (bModifySaveName)
			lstrcpy(szSaveName, szFileName);

		/* Try to display a new list box */
		if ( !szFileName[0] )
			lstrcat(szFileName, szFileSpec);
		if (DlgDirList(hDlg, szFileName, IDC_FLIST, IDC_FPATH,
		    wFileAttr))
			{ /* A wildcard was found and a new list displayed */
			lstrcpy(szFileSpec, szFileName);
			SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName,
				fSaving );
			LoadComboWithDrives( hDlg, IDC_DRIVES );
			LoadComboWithDirectories( hDlg, IDC_DIRS, YES );
			
			break;
			}

		// If there is still a path or wildcards in the name, the
		// file specification must be invalid
		if (lstrchr(szFileName, '\\') || lstrchr(szFileName, ':') ||
		    lstrchr(szFileName, '?') || lstrchr(szFileName, '*'))
			{
			lstrcpy(szString, szFileName);
			stripfile(szString);
			Message(IDS_EDIRECTORYCHANGE, Lowercase(szString));
			lstrcpy(szFileSpec, filename(szFileName));
			lstrcpy(szFileName, szFileSpec); // is this needed?
			SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName,
				fSaving );
			break;
			}

		/* No wildcards, and the drive and dir have been changed */
		LoadComboWithDrives( hDlg, IDC_DRIVES );
		LoadComboWithDirectories( hDlg, IDC_DIRS, YES );

		/* Check to see if the file has 8 characters or less... */
		if ( fSaving )
			RemoveWhiteSpace( szFileName );
		FixFileName( szFileName );

		/* Check to see if the file has an extension... */
		if ( !lstrchr( szFileName, '.' ) ) // if no extension...
			if ( LookupExtension( idFileType, szExtension ) )
				lstrcat( szFileName, extension(szExtension) );

		// Build the fully qualified path name
		GetDlgItemText( hDlg, IDC_FPATH, szString, sizeof(szString) );
		FixPath( szString );
		lstrcat( szString, szFileName );

		/* Check to see if the file exists... */
		if ( (fp = _lopen( szString, OF_READ ) ) < 0 )
			{ /* The file does not exist */
			if ( !fSaving )
				{
				Message(IDS_EOPEN, Lowercase(szString));
				break;
				}
			}
		else	{
			_lclose( fp );
			if ( fSaving )
				{
				if ( !AstralAffirm( IDS_OVERWRITEIMAGE,
					Lowercase(szString) ) )
					break;
				}
			}

		lstrcpy( szFileSpec, szString );
		AstralDlgEnd(hDlg, TRUE|2);
		break;

	    case IDC_CANCEL:
	    case IDCANCEL:
		if ( bDisableCancel && !LOWORD(lParam) )
			break;
		GetDlgItemText(hDlg, IDC_FPATH, szFileSpec,sizeof(szFileSpec));
		AstralDlgEnd(hDlg, FALSE|2);
		break;

	    default:
		return( FALSE );
	    }
	break;

    default:
	return( FALSE );
    }

return( TRUE );
}
Exemplo n.º 9
0
void csvbuilder::open_table(const table_spec &spec) {
	csv.open(filename(spec).c_str());
}
Exemplo n.º 10
0
void MulticastHandler::dispatch(
	boost::asio::ip::address senderAddress,
	MulticastNetwork::Command command,
	char *args,
	unsigned char argsSize,
	bool forward)
{
	typedef MulticastNetwork::Command Command;

	m_senderAddress = &senderAddress;
	bool valid = false;

	if (Command::Candidate == command && sizeof(uint32_t) == argsSize) {
		valid = true;
		on_candidate(ntohl(*reinterpret_cast<uint32_t*>(args)));
	}
	else if (Command::ElectGateway == command && 0 == argsSize) {
		valid = true;
		on_electGateway();
	}
	else if (Command::Forward == command && 0 < argsSize)
	{
		valid = true;
		on_forward(static_cast<Command>(args[0]), args + 1, argsSize - 1);
	}
	else if (Command::Gateway == command && 0 == argsSize)
	{
		valid = true;
		on_gateway();
	}
	else if (Command::Hello == command && sizeof(float) < argsSize) {
		valid = true;
		uint32_t b = ntohl(*reinterpret_cast<uint32_t*>(args + argsSize - sizeof(float)));
		on_hello(std::string(args, argsSize - sizeof(float)),
			*reinterpret_cast<float*>(&b));
	}
	else if (Command::Message == command && 0 < argsSize) {
		valid = true;
		on_message(std::string(args, argsSize));
	}
	else if (Command::RemoteGateway == command && 0 == argsSize) {
		valid = true;
		on_remoteGateway();
	}
	else if (Command::SearchBlock == command && sizeof(uint32_t) < argsSize) {
		valid = true;
		on_searchBlock(std::string(args, argsSize - sizeof(uint32_t)),
			*reinterpret_cast<uint32_t*>(args + argsSize - sizeof(uint32_t)));
	}
	else if (Command::SearchFileName == command && 0 < argsSize) {
		valid = true;
		on_searchFileName(std::string(args, argsSize));
	}
	else if (Command::SearchFileNameReply == command && 0 < argsSize) {
		valid = true;
		std::map<std::string, std::pair<float, std::string>> results;

		int index = 0;
		while (index < argsSize) {
			float filesize;
			int stringLength = 0;
			for (int i = index + Hash::SIZE + sizeof filesize; i < argsSize; i++) {
				if (args[i] == '\0') {
					break;
				}

				++stringLength;
			}

			if (index + stringLength + Hash::SIZE + sizeof filesize >= argsSize) {
				break;
			}

			std::string hash(args + index, Hash::SIZE);
			filesize = *reinterpret_cast<float*>(args + index + Hash::SIZE);

			std::string filename(args + index + Hash::SIZE + sizeof filesize, stringLength);
			results[filename] = std::pair<float, std::string>(filesize, hash);
			index += Hash::SIZE + sizeof filesize + stringLength + 1;
		}

		on_searchFileNameReply(results);
	}

	if (valid && forward) {
		m_gateway->forward(*m_senderAddress, command, args, argsSize);
	}
}
Exemplo n.º 11
0
void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)
{
    const char * const tpaExtensions[] = {
                ".ni.dll",      // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
                ".dll",
                ".ni.exe",
                ".exe",
                };
                
    DIR* dir = opendir(directory);
    if (dir == nullptr)
    {
        return;
    }

    std::set<std::string> addedAssemblies;

    // Walk the directory for each extension separately so that we first get files with .ni.dll extension,
    // then files with .dll extension, etc.
    for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++)
    {
        const char* ext = tpaExtensions[extIndex];
        int extLength = strlen(ext);

        struct dirent* entry;

        // For all entries in the directory
        while ((entry = readdir(dir)) != nullptr)
        {
            // We are interested in files only
            switch (entry->d_type)
            {
            case DT_REG:
                break;

            // Handle symlinks and file systems that do not support d_type
            case DT_LNK:
            case DT_UNKNOWN:
                {
                    std::string fullFilename;

                    fullFilename.append(directory);
                    fullFilename.append("/");
                    fullFilename.append(entry->d_name);

                    struct stat sb;
                    if (stat(fullFilename.c_str(), &sb) == -1)
                    {
                        continue;
                    }

                    if (!S_ISREG(sb.st_mode))
                    {
                        continue;
                    }
                }
                break;

            default:
                continue;
            }

            std::string filename(entry->d_name);

            // Check if the extension matches the one we are looking for
            int extPos = filename.length() - extLength;
            if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))
            {
                continue;
            }

            std::string filenameWithoutExt(filename.substr(0, extPos));

            // Make sure if we have an assembly with multiple extensions present,
            // we insert only one version of it.
            if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())
            {
                addedAssemblies.insert(filenameWithoutExt);

                tpaList.append(directory);
                tpaList.append("/");
                tpaList.append(filename);
                tpaList.append(":");
            }
        }
        
        // Rewind the directory stream to be able to iterate over it for the next extension
        rewinddir(dir);
    }
    
    closedir(dir);
}
Exemplo n.º 12
0
CArchive *CDataFile::OpenAsCArchive( const char *pFilename )
{
	ASSERT( pFilename );

	//  Get the relative path of the file for which to search.
	CString filename( pFilename );
	CString path;
	path = "files\\" + filename;
	path.MakeLower ();

	//  Check to see if the file exists in the patch directory.
	if ( m_pPatchDir )
	{
		CString patchPath = *m_pPatchDir + "\\" + path;

		CFile	test;
		if ( test.Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) != FALSE )
		{
			//  Close the file so we can allocate a new CFile object to
			//  return to the caller.
			test.Close();

			//  Allocate a new CFile object.  By creating and opening the CFile
			//  this way, the CFile dtor will automagically close the file 
			//  handle for us.
			CFile *pNewFile = new CFile;
			if ( pNewFile->Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) == FALSE )
				ThrowError( ERR_PATCHFILE_OPEN );
			CArchive *pNewCArchive = new CArchive( pNewFile, CArchive::load );
			if ( pNewCArchive == NULL )
				ThrowError( ERR_OUT_OF_MEMORY );

			return pNewCArchive;
		}
	}

	//  If here, the file does not exist in the 
	//  patch directory or there is no patch directory.
	//  If a datafile was opened, look for it in the
	//  datafile.
	if ( m_pDataFile )
	{
		//  Look for the file path in the map.  If 
		//  it is not found, if searching for language 
		//  file try searching for US version;  otherwise,
		//  return NULL.
		void *	dummy;
		if ( m_pFileMap->Lookup( path, dummy ) == FALSE )
			ThrowError( ERR_DATAFILE_NO_ENTRY );

		//  If here, file was found in the map.  Seek to
		//  that position in the file.
		//  If negative seek checks between CMmio's are 
		//  desired, they should be done here.
		long fileOffset = ( long )dummy;
		long	offsetFromHere = fileOffset - ( long )m_pDataFile->GetPosition();

#ifdef _DEBUG
		if ( m_bNegativeSeekCheck == TRUE && fileOffset < m_lastPos )
			WarnNegativeSeek( pFilename, m_lastPos, fileOffset );
#endif

		m_pDataFile->Seek( offsetFromHere, CFile::current );

#ifdef _DEBUG
		m_lastPos = m_pDataFile->GetPosition();
#endif

		//  Create a new CFile object.  It will be positioned 
		//  at the current file offset.  Note that this dtor will
		//  not automagically close the file handle, which is what we
		//  want.
		CFile * pNewFile = new CFile ();
		if ( pNewFile == NULL )
			ThrowError( ERR_OUT_OF_MEMORY );
		if (pNewFile->Open( m_sFileName, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) == FALSE)
			ThrowError( ERR_OUT_OF_MEMORY );
		pNewFile->Seek (m_pDataFile->GetPosition (), CFile::begin);

		CArchive *pNewCArchive = new CArchive( pNewFile, CArchive::load );
		if ( pNewCArchive == NULL )
			ThrowError( ERR_OUT_OF_MEMORY );

		return pNewCArchive;
	}

	//  If here, file was not found in patch dir ( or
	//  no patch dir was given ), and no datafile was
	//  opened, so return NULL ( no file found ).
	ThrowError( ERR_DATAFILE_NO_ENTRY );
	return NULL;
}
Exemplo n.º 13
0
void CSHDispDialog::DisStart(const NewSHDispInfo& info)
{
	CString strText;
	if(m_peerMager->GetItemCount()>=100)
	{
		Clear();
	}
	strText.Format(_T("%d"),m_peerMager->GetItemCount()+1);
	int item	= m_peerMager->InsertItem(m_peerMager->GetItemCount(),strText);
	m_peerMager->SetSelectedItem(item);
	int subItem	= 1;
	CString filename(info.file_name);
	m_peerMager->SetItemText(item,subItem++,filename);
	//
	strText.Format(_T("%d"),info.num);
	m_peerMager->SetItemText(item,subItem++,strText);
	
	m_peerMager->SetItemText(item,subItem++,GetSizeDesc(info.size).c_str());
	
	strText.Format(_T("%ds"),info.duration);
	m_peerMager->SetItemText(item,subItem++,strText);

	subItem += 5;
	//
	strText.Format(_T("%d"),info.cdn_num);
	m_peerMager->SetItemText(item,subItem++,strText);
	
	subItem++;

	strText.Format(_T("%d/%d"),m_usablePeer,m_allUsablePeer);
	m_peerMager->SetItemText(item,subItem++,strText);

	time_t ti(info.start_time);
	tm temptm = *localtime(&ti);
	SYSTEMTIME st = {1900 + temptm.tm_year, 
		1 + temptm.tm_mon, 
		temptm.tm_wday, 
		temptm.tm_mday, 
		temptm.tm_hour, 
		temptm.tm_min, 
		temptm.tm_sec, 
		0};
	strText.Format(_T("%02d-%02d %02d:%02d:%02d"),st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
	m_peerMager->SetItemText(item,subItem++,strText);
	
	strText.Format(_T("-:-:-"));
	m_peerMager->SetItemText(item,subItem++,strText);
	
	m_peerMager->SetItemText(item,subItem++,_T("正在下载"));
	m_peerMager->SetItemData(item,info.ID);
	
	subItem += 3;

	if(info.type == 0)
	{
		m_peerMager->SetItemText(item,subItem++,_T("完整"));
	}
	else if(info.type == 1)
	{
		m_peerMager->SetItemText(item,subItem++,_T("拖拽"));
	}
	
	strText.Format(_T("%d"),info.play_start);
	m_peerMager->SetItemText(item,subItem++,strText);
	
	m_peerInfoHandle.insert(std::make_pair(info.ID,peer_list));

	if(IsVisable())
	{
		m_peerMager->EnsureVisible(m_peerMager->GetItemCount()-1,FALSE);
	}
	if(m_peerDlg != NULL && m_peerDlg->IsVisable() )
	{
		CString peerDlgText = _T("");
		peerDlgText.Format(_T("文件:%s 段号:%d"),info.file_name,info.num);
		m_peerDlg->SetCaptionName(peerDlgText.GetBuffer());
		m_peerDlg->Clear();
		m_peerDlg->SetDownState(false);
		m_peerDlg->SetDispItemID((int)info.ID);
		m_peerDlg->UpdatePeerInfo(&peer_list,(int)info.ID);
	}
}
Exemplo n.º 14
0
/**
 * Main function
 **/
int main()
{
	/**
	 * Initializing our input file stream
	 **/
	ifstream Stream;
	Stream.open("1.txt", ios::in);


	/**
	 * Initializing the list and the iterator
	 **/
	list<string>* Loaded = OrthodoxIterLoad(Stream);

	Stream.close();

	list<string>::iterator _i;

	StringStack Cont1;

	/**
	 * Just a test to show the correct work
	 * of the iterator
	 **/

	cout << "Data from Loaded list, using OrthodoxIterLoad()"
		<< endl;
	for (_i = Loaded->begin(); _i != Loaded->end(); _i++)
	{
		cout << *_i
			<< endl;

		Cont1.push(*_i);

	}

	/**
	 * Reversing and outputing our stack
	 **/
	Cont1.Reverse();

	cout << "stack Cont1 after reversing:"
		<< endl;

	while (!Cont1.empty())
	{
		cout << Cont1.OutputRemoval() << endl;
	}

	/**
	 * Outputing our vector to file using iterators
	 **/
	ofstream OutStream;
	OutStream.open("e:/paul/2.txt", ios::out);

	IterOutput(Loaded, OutStream);

	/**
	 * Testing the ifstrean - derived class;
	 **/
	Stringfstream SFS;

	SFS.open("1.txt", ios::in | ios::out);
	cout << "Testing the Stringfstream in work..."
		<< endl;

	string s;

	SFS >> s;

	cout << s << endl;

	SFS.close();

	/**
	 * Testing the NumberCopy class
	 **/

	cout << "Testing the NumberCopy class..."
		<< endl;

	NumberCopy f1;

	string filename("1.txt");

	f1.Load(filename);

	cout << f1.top();
	/**
	 * Post-execution issues
	 **/
	_getch();
	return EXIT_SUCCESS;
}
Exemplo n.º 15
0
Arquivo: path.hpp Projeto: gijs/PDAL
 path   leaf() const             { return filename(); }
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ModifiedLambertProjection::Pointer ModifiedLambertProjection::CreateProjectionFromXYZCoords(FloatArrayType* coords, int dimension, float sphereRadius)
{

  size_t npoints = coords->getNumberOfTuples();
  bool nhCheck = false;
  float sqCoord[2];
  //int sqIndex = 0;
  ModifiedLambertProjection::Pointer squareProj = ModifiedLambertProjection::New();
  squareProj->initializeSquares(dimension, sphereRadius);


#if WRITE_LAMBERT_SQUARE_COORD_VTK
  QString ss;
  QString filename("/tmp/");
  filename.append("ModifiedLambert_Square_Coords_").append(coords->getName()).append(".vtk");
  FILE* f = NULL;
  f = fopen(filename.toLatin1().data(), "wb");
  if(NULL == f)
  {
    ss.str("");
    QString ss = QObject::tr("Could not open vtk viz file %1 for writing. Please check access permissions and the path to the output location exists").arg(filename);
    return squareProj;
  }

  // Write the correct header
  fprintf(f, "# vtk DataFile Version 2.0\n");
  fprintf(f, "data set from DREAM3D\n");
  fprintf(f, "ASCII");
  fprintf(f, "\n");

  fprintf(f, "DATASET UNSTRUCTURED_GRID\nPOINTS %lu float\n", coords->getNumberOfTuples() );
#endif

  for(size_t i = 0; i < npoints; ++i)
  {
    sqCoord[0] = 0.0;
    sqCoord[1] = 0.0;
    //get coordinates in square projection of crystal normal parallel to boundary normal
    nhCheck = squareProj->getSquareCoord(coords->getPointer(i * 3), sqCoord);
#if WRITE_LAMBERT_SQUARE_COORD_VTK
    fprintf(f, "%f %f 0\n", sqCoord[0], sqCoord[1]);
#endif

    // Based on the XY coordinate, get the pointer index that the value corresponds to in the proper square
//    sqIndex = squareProj->getSquareIndex(sqCoord);
    if (nhCheck == true)
    {
      //north increment by 1
//      squareProj->addValue(ModifiedLambertProjection::NorthSquare, sqIndex, 1.0);
      squareProj->addInterpolatedValues(ModifiedLambertProjection::NorthSquare, sqCoord, 1.0);
    }
    else
    {
      // south increment by 1
//      squareProj->addValue(ModifiedLambertProjection::SouthSquare, sqIndex, 1.0);
      squareProj->addInterpolatedValues(ModifiedLambertProjection::SouthSquare, sqCoord, 1.0);
    }
  }
#if WRITE_LAMBERT_SQUARE_COORD_VTK
  fclose(f);
#endif

  return squareProj;
}
    /**
        Update ports for WebSphere

        Load XML file <disk path>/config/cells/<Cell Name>/nodes/<Node Name>/serverindex.xml
        
        Ger serverIndex/serverEntries node where serverName attribute is the name of the server
        For HTTP port get specialEndpoints node where endPointName is WC_defaulthost and 
          get port attribute from endPoint node
        For HTTPS port get specialEndpoints node where endPointName is WC_defaulthost_secure and 
          get port attribute from endPoint node
    */
    void WebSphereAppServerInstance::UpdatePorts()
    {
        const string cServerIndexNodeName("serverindex:ServerIndex");
        const string cServerEntriesNodeName("serverEntries");
        const string cServerNameAttributeName("serverName");
        const string cSpecialEndpointsNodeName("specialEndpoints");
        const string cEndPointNameAttributeName("endPointName");
        const string cWCdefaultHostName("WC_defaulthost");
        const string cWCdefaultHostSecureName("WC_defaulthost_secure");
        const string cEndPointNodeName("endPoint");
        const string cPortAttributeName("port");
        
        string xmlcontent;
        SCXFilePath filename(returnProfileDiskPath(m_diskPath));        

        filename.AppendDirectory(L"config");
        filename.AppendDirectory(L"cells");
        filename.AppendDirectory(m_cell);
        filename.AppendDirectory(L"nodes");
        filename.AppendDirectory(m_node);
        filename.SetFilename(L"serverindex.xml");

        try {
            SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get());
            GetStringFromStream(mystream, xmlcontent);

            // Load the XML, but don't honor namespaces
            XElementPtr serverIndexNode;
            XElement::Load(xmlcontent, serverIndexNode, false);

            if (serverIndexNode->GetName() == cServerIndexNodeName)
            {
                XElementList serverEntriesNodes;
                bool foundServer = false;

                serverIndexNode->GetChildren(serverEntriesNodes);

                for (size_t idx = 0; !foundServer && idx < serverEntriesNodes.size(); ++idx)
                {
                    string name;
                    if (serverEntriesNodes[idx]->GetName() == cServerEntriesNodeName && 
                        serverEntriesNodes[idx]->GetAttributeValue(cServerNameAttributeName, name) && 
                        m_server == StrFromUTF8(name))
                    {
                        XElementList childNodes;
                        bool foundHTTPnode = false;
                        bool foundHTTPSnode = false;
                        foundServer = true;

                        serverEntriesNodes[idx]->GetChildren(childNodes);

                        for (size_t idx2 = 0; !(foundHTTPnode && foundHTTPSnode) && idx2 < childNodes.size(); ++idx2)
                        {
                            if (childNodes[idx2]->GetName() == cSpecialEndpointsNodeName && 
                                childNodes[idx2]->GetAttributeValue(cEndPointNameAttributeName, name))
                            { 
                                if (cWCdefaultHostName == name)
                                {
                                    GetPortFromXml(childNodes[idx2], foundHTTPnode, m_httpPort);
                                }
                                else if (cWCdefaultHostSecureName == name)
                                {
                                    GetPortFromXml(childNodes[idx2], foundHTTPSnode, m_httpsPort);
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (SCXFilePathNotFoundException&)
        {
            SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - Could not find file: ").append(filename));
        }
        catch (SCXUnauthorizedFileSystemAccessException&)
        {
            SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - not authorized to open file: ").append(filename));
        }
        catch (XmlException&)
        {
            SCX_LOGERROR(m_log, wstring(L"WebSphereAppServerInstance::UpdatePorts() - ").append(GetId()).append(L" - Could not load XML from file: ").append(filename));
        }
    }
Exemplo n.º 18
0
    //=================================================================
    bool TileAssembler::convertRawFile(const std::string& pModelFilename)
    {
        bool success = true;
        std::string filename = iSrcDir;
        if (filename.length() >0)
            filename.push_back('/');
        filename.append(pModelFilename);
        FILE *rf = fopen(filename.c_str(), "rb");

        if (!rf)
        {
            printf("ERROR: Can't open model file in form: %s", pModelFilename.c_str());
            printf("...                          or form: %s", filename.c_str() );
            return false;
        }

        char ident[8];

        int readOperation = 1;

        // temporary use defines to simplify read/check code (close file and return at fail)
        #define READ_OR_RETURN(V, S) if (fread((V), (S), 1, rf) != 1) { \
                                        fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); }readOperation++;
        #define READ_OR_RETURN_WITH_DELETE(V, S) if (fread((V), (S), 1, rf) != 1) { \
                                        fclose(rf); printf("readfail, op = %i\n", readOperation); delete[] V; return(false); }readOperation++;
        #define CMP_OR_RETURN(V, S)  if (strcmp((V), (S)) != 0)        { \
                                        fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); }

        READ_OR_RETURN(&ident, 8);
        CMP_OR_RETURN(ident, "VMAP003");

        // we have to read one int. This is needed during the export and we have to skip it here
        uint32 tempNVectors;
        READ_OR_RETURN(&tempNVectors, sizeof(tempNVectors));

        uint32 groups;
        uint32 RootWMOID;
        char blockId[5];
        blockId[4] = 0;
        int blocksize;

        READ_OR_RETURN(&groups, sizeof(uint32));
        READ_OR_RETURN(&RootWMOID, sizeof(uint32));

        std::vector<GroupModel> groupsArray;

        for (uint32 g=0; g<groups; ++g)
        {
            std::vector<MeshTriangle> triangles;
            std::vector<Vector3> vertexArray;

            uint32 mogpflags, GroupWMOID;
            READ_OR_RETURN(&mogpflags, sizeof(uint32));
            READ_OR_RETURN(&GroupWMOID, sizeof(uint32));

            float bbox1[3], bbox2[3];
            READ_OR_RETURN(bbox1, sizeof(float)*3);
            READ_OR_RETURN(bbox2, sizeof(float)*3);

            uint32 liquidflags;
            READ_OR_RETURN(&liquidflags, sizeof(uint32));

            // will this ever be used? what is it good for anyway??
            uint32 branches;
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "GRP ");
            READ_OR_RETURN(&blocksize, sizeof(int));
            READ_OR_RETURN(&branches, sizeof(uint32));
            for (uint32 b=0; b<branches; ++b)
            {
                uint32 indexes;
                // indexes for each branch (not used jet)
                READ_OR_RETURN(&indexes, sizeof(uint32));
            }

            // ---- indexes
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "INDX");
            READ_OR_RETURN(&blocksize, sizeof(int));
            uint32 nindexes;
            READ_OR_RETURN(&nindexes, sizeof(uint32));
            if (nindexes >0)
            {
                uint16 *indexarray = new uint16[nindexes];
                READ_OR_RETURN_WITH_DELETE(indexarray, nindexes*sizeof(uint16));
                for (uint32 i=0; i<nindexes; i+=3)
                {
                    triangles.push_back(MeshTriangle(indexarray[i], indexarray[i+1], indexarray[i+2]));
                }
                delete[] indexarray;
            }

            // ---- vectors
            READ_OR_RETURN(&blockId, 4);
            CMP_OR_RETURN(blockId, "VERT");
            READ_OR_RETURN(&blocksize, sizeof(int));
            uint32 nvectors;
            READ_OR_RETURN(&nvectors, sizeof(uint32));

            if (nvectors >0)
            {
                float *vectorarray = new float[nvectors*3];
                READ_OR_RETURN_WITH_DELETE(vectorarray, nvectors*sizeof(float)*3);
                for (uint32 i=0; i<nvectors; ++i)
                {
                    vertexArray.push_back( Vector3(vectorarray + 3*i) );
                }
                delete[] vectorarray;
            }
            // ----- liquid
            WmoLiquid *liquid = 0;
            if (liquidflags& 1)
            {
                WMOLiquidHeader hlq;
                READ_OR_RETURN(&blockId, 4);
                CMP_OR_RETURN(blockId, "LIQU");
                READ_OR_RETURN(&blocksize, sizeof(int));
                READ_OR_RETURN(&hlq, sizeof(WMOLiquidHeader));
                liquid = new WmoLiquid(hlq.xtiles, hlq.ytiles, Vector3(hlq.pos_x, hlq.pos_y, hlq.pos_z), hlq.type);
                uint32 size = hlq.xverts*hlq.yverts;
                READ_OR_RETURN(liquid->GetHeightStorage(), size*sizeof(float));
                size = hlq.xtiles*hlq.ytiles;
                READ_OR_RETURN(liquid->GetFlagsStorage(), size);
            }

            groupsArray.push_back(GroupModel(mogpflags, GroupWMOID, AABox(Vector3(bbox1), Vector3(bbox2))));
            groupsArray.back().setMeshData(vertexArray, triangles);
            groupsArray.back().setLiquidData(liquid);

            // drop of temporary use defines
            #undef READ_OR_RETURN
            #undef READ_OR_RETURN_WITH_DELETE
            #undef CMP_OR_RETURN
        }
        fclose(rf);

        // write WorldModel
        WorldModel model;
        model.setRootWmoID(RootWMOID);
        if (!groupsArray.empty())
        {
            model.setGroupModels(groupsArray);

            std::string filename(iSrcDir);
            filename.push_back('/');
            filename.append(pModelFilename).append(".vmo");
            success = model.writeFile(filename);
        }

        //std::cout << "readRawFile2: '" << pModelFilename << "' tris: " << nElements << " nodes: " << nNodes << std::endl;
        return success;
    }
	inline void add_files(file_storage& fs, std::string const& file, boost::uint32_t flags = 0)
	{
		detail::add_files_impl(fs, parent_path(complete(file)), filename(file)
			, detail::default_pred, flags);
	}
Exemplo n.º 20
0
void pyne::Material::from_hdf5(char * fchar, char * dchar, int row, int protocol)
{
  std::string filename (fchar);
  std::string datapath (dchar);
  from_hdf5(filename, datapath, row, protocol);  
};
Exemplo n.º 21
0
void ExporterVTK<MeshType>::postProcess(const Real& time)
{
    // typedef std::list< ExporterData >::iterator Iterator;

    this->computePostfix();

    std::size_t found( this->M_postfix.find( "*" ) );
    if ( found == string::npos )
    {
        if (!this->M_procId) std::cout << "  X-  ExporterVTK post-processing" << std::flush;

        LifeChrono chrono;
        chrono.start();

        this->M_timeSteps.push_back(time);

        for (typename super::dataVectorIterator_Type iData=this->M_dataVector.begin();
             iData != this->M_dataVector.end(); ++iData)
        {
            std::ofstream vtkFile;
            std::stringstream buffer("");

            // a unique PVTU file + a time collection is produced by the leader process
            if(this->M_procId==0)
            {
                composePVTUStream(*iData, buffer);

                std::string vtkPFileName( this->M_postDir+this->M_prefix+"_" + iData->variableName()+
                                          this->M_postfix+".pvtu" );
                std::ofstream vtkPFile;
                vtkPFile.open( vtkPFileName.c_str() );
                ASSERT(vtkPFile.is_open(), "There is an error while opening " + vtkPFileName );
                ASSERT(vtkPFile.good(), "There is an error while writing to " + vtkPFileName );
                vtkPFile << buffer.str();
                vtkPFile.close();

                buffer.str("");

                this->M_pvtuFiles[iData->variableName()].push_back(vtkPFileName);

            }


            // redundant. should be done just the first time
            std::map<UInt,UInt> ltgPointsMap, gtlPointsMap;
            std::vector<Vector> pointsCoords;
            createPointsMaps( iData->feSpacePtr(), gtlPointsMap, ltgPointsMap, pointsCoords );

            composeVTUHeaderStream( gtlPointsMap.size(), buffer );
            composeVTUGeoStream( iData->feSpacePtr(), gtlPointsMap, pointsCoords, buffer );

            composeTypeDataHeaderStream(iData->where(), buffer);
            composeDataArrayStream(*iData, ltgPointsMap, buffer);
            composeTypeDataFooterStream(iData->where(), buffer);

            composeVTUFooterStream( buffer );

            // each process writes its own file
            std::string filename( this->M_postDir+this->M_prefix+"_" + iData->variableName()+
                                  this->M_postfix+"."+this->M_procId+".vtu" );
            vtkFile.open( filename.c_str() );
            ASSERT(vtkFile.is_open(), "There is an error while opening " + filename );
            ASSERT(vtkFile.good(), "There is an error while writing to " + filename );
            vtkFile << buffer.str();
            vtkFile.close();

            buffer.str("");

        }
        chrono.stop();
        if (!this->M_procId) std::cout << "...done in " << chrono.diff() << " s." << std::endl;
    }
}
Exemplo n.º 22
0
void pyne::Material::from_text(char * fchar)
{
  std::string filename (fchar);
  from_text(filename);
};
Exemplo n.º 23
0
 ///
 /// Creates a new project from an IMPACT base
 ///
 /// This program is designed to make a new IllinoisRocstar
 /// software project starting from an intallation of the
 /// IMPACT project template.
 ///
 /// Usage of this program should go like the following:
 /// 1. Get and Install the IMPACT template.
 /// <blockquote>
 ///  svn co $IRREPO/IMPACT/trunk IMPACT\n
 ///  mkdir impact_build\n
 ///  cd impact_build\n
 ///  cmake ../IMPACT\n
 ///  make\n
 ///  cd ../\n
 /// </blockquote>
 /// 2. Create the new project, <NewProject>,  with the "make_project" command.
 /// <blockquote>
 ///  impact_build/bin/make_project IMPACT <NewProject>\n
 /// </blockquote>
 ///
 /// @note Be sure to replace <NewProject> with your new project name.
 ///
 /// The usage for the make_project command is: 
 /// <blockquote>
 ///       make_project usage:\n
 /// 
 ///       make_project \<template name\> \<new project\> [verb level]\n
 ///
 ///       This program will read the project template from the \<template name\>\n 
 ///       directory and create a new "blank" IllinoisRocstar project\n
 ///       named \<new name\>, in a directory named \<new name\>.\n
 ///       An optional verblevel of 1 or 2 can be given to make the process\n
 ///       more verbose.\n
 /// </blockquote>
 ///
 int MakeProject(int argc,char *argv[])
 {
   if(argc < 3){
     std::cout << "Usage:" << std::endl << std::endl
               << argv[0] << " <template name> <new name> [verb level]" << std::endl
               << std::endl
               << "This program will read the project template from the <template name> "
               << std::endl
               << "directory and create a new \"blank\" IllinoisRocstar project"
               << std::endl
               << "named <new name>, in a directory named <new name>."
               << std::endl
               << "An optional verblevel of 1 or 2 can be given to make the process"
               << std::endl << "more verbose." << std::endl;
     return(0);
   }
   std::string OriginalName(argv[1]);
   std::string NewName(argv[2]);
   int verb = 0;
   if(argv[3]){
     verb = 1;
     int v = atoi(argv[3]);
     if(v > 0)
       verb = v;
   }
   std::vector<std::string> ProtectedFiles;
   ProtectedFiles.push_back("AUTHORS");
   ProtectedFiles.push_back("CTestConfig.cmake");
   ProtectedFiles.push_back("LICENSE");
   ProtectedFiles.push_back(".svn");
   std::vector<std::string> CommonFiles;
   CommonFiles.push_back("CMakeLists.txt");
   int syserr = 0;
   std::string olower(OriginalName);
   std::string oupper(OriginalName);
   std::string nlower(NewName);
   std::string nupper(NewName);
   std::transform(olower.begin(),olower.end(),olower.begin(),tolower);
   std::transform(oupper.begin(),oupper.end(),oupper.begin(),toupper);
   std::transform(nlower.begin(),nlower.end(),nlower.begin(),tolower);
   std::transform(nupper.begin(),nupper.end(),nupper.begin(),toupper);
 
   if(verb)
     std::cout << "Creating a new project (" << NewName 
               << ") from project template (" << OriginalName
               << ")." << std::endl << std::endl
               << "Creating top level project directories...";
   std::string dirname(NewName);
   if(!IRAD::Sys::FILEEXISTS(NewName)){
     if(verb > 1)
       std::cout << "   Creating directory " << dirname << "...";
     syserr = IRAD::Sys::CreateDirectory(dirname);
     if(syserr){
       std::cout << "Unable to create directory " << dirname << "."
                 << std::endl;
       return(1);
     }
     if(verb > 1)
       std::cout << "done." << std::endl;
   }
   dirname += "/branches";
   if(!IRAD::Sys::FILEEXISTS(dirname)){
     if(verb > 1)
       std::cout << "   Creating directory " << dirname << "...";
     syserr = IRAD::Sys::CreateDirectory(dirname);
     if(syserr){
       std::cout << "Unable to create directory " << dirname << "."
                 << std::endl;
       return(1);
     }
     if(verb > 1)
       std::cout << "done." << std::endl;
   }
   dirname = NewName+"/tags";
   if(!IRAD::Sys::FILEEXISTS(dirname)){
     if(verb > 1)
       std::cout << "   Creating directory " << dirname << "...";
     syserr = IRAD::Sys::CreateDirectory(dirname);
     if(syserr){
       std::cout << "Unable to create directory " << dirname << "."
                 << std::endl;
       return(1);
     }
     if(verb > 1)
       std::cout << "done." << std::endl;
   }
   dirname.assign(NewName+"/examples");
   if(!IRAD::Sys::FILEEXISTS(dirname)){
     if(verb > 1)
       std::cout << "   Creating directory " << dirname << "...";
     syserr = IRAD::Sys::CreateDirectory(dirname);
     if(syserr){
       std::cout << "Unable to create directory " << dirname << "."
                 << std::endl;
       return(1);
     }
     if(verb > 1)
       std::cout << "done." << std::endl;
   }
   bool protect_svn = false;
   dirname = NewName+"/trunk";
   std::vector<std::string>::iterator pfi = ProtectedFiles.begin();
   while(pfi != ProtectedFiles.end()){
     std::string ProtectThisFile(dirname+"/"+*pfi++);
     std::string ProtectedFile(ProtectThisFile+".backup");
     if(IRAD::Sys::FILEEXISTS(ProtectThisFile))
       IRAD::Sys::Rename(ProtectThisFile,ProtectedFile);
   }
   pfi = CommonFiles.begin();
   while(pfi != CommonFiles.end()){
     std::string ProtectThisFile(dirname+"/"+*pfi++);
     std::string ProtectedFile(ProtectThisFile+".backup");
     if(IRAD::Sys::FILEEXISTS(ProtectThisFile))
       IRAD::Sys::Rename(ProtectThisFile,ProtectedFile);
   }
   std::ostringstream ComStr;
   if(!IRAD::Sys::FILEEXISTS(dirname)){
     if(verb > 1)
       std::cout << "   Creating directory " << dirname << "...";
     ComStr << "cp -r " << OriginalName << " " << dirname;
   } else {
     if(verb > 1)
       std::cout <<   "   Making project files from template ...";
     ComStr << "cp -r " << OriginalName << "/* " << dirname;
   }
   IRAD::Sys::InProcess System(ComStr.str());
   std::string comline;
   while(std::getline(System,comline)){
     if(verb > 1)
       std::cout << comline << std::endl;
   }
   if(verb)
     std::cout << "done." << std::endl;
   if(verb)
     std::cout << "Cleaning up ...";
   ComStr.str("");
   ComStr << "rm -rf " << dirname << "/.svn";
   System.Execute(ComStr.str());
   int n = 0;
   while(std::getline(System,comline))
     n++;
   pfi = ProtectedFiles.begin();
   while(pfi != ProtectedFiles.end()){
     std::string ProtectThisFile(dirname+"/"+*pfi++);
     std::string ProtectedFile(ProtectThisFile+".backup");
     if(IRAD::Sys::FILEEXISTS(ProtectedFile)){
       if(IRAD::Sys::FILEEXISTS(ProtectThisFile))
         IRAD::Sys::Remove(ProtectThisFile);
       IRAD::Sys::Rename(ProtectedFile,ProtectThisFile);
     }
   }
   pfi = CommonFiles.begin();
   while(pfi != CommonFiles.end()){
     std::string ProtectThisFile(dirname+"/"+*pfi++);
     std::string ProtectedFile(ProtectThisFile+".backup");
     std::string CommonFileTemplate(ProtectThisFile+".template");
     if(IRAD::Sys::FILEEXISTS(ProtectedFile)){
       if(IRAD::Sys::FILEEXISTS(ProtectThisFile))
         IRAD::Sys::Rename(ProtectThisFile,CommonFileTemplate);
       IRAD::Sys::Rename(ProtectedFile,ProtectThisFile);
     }
   }
   if(verb)
     std::cout << "done." << std::endl;
   if(verb > 1)
     std::cout << "Done creating new project files." 
               << std::endl;
   if(verb)
     std::cout << "Renaming project...";
   if(IRAD::Sys::ChDir(dirname)){
     std::cout << "Something went wrong, cannot find new project directory." 
               << std::endl;
     return(1);
   }
   ComStr.str("");
   ComStr << "grep -i " << OriginalName << " -r * | cut -d \":\" -f 1 | sort | uniq";
   if(verb > 1)
     std::cout << "   " << ComStr.str() << std::endl;
   System.Execute(ComStr.str());
   std::vector<std::string> filenames;
   if(verb > 1)
     std::cout << "   Files to change:" << std::endl;
   while(std::getline(System,comline)){
     if(!Excluded(comline)){
       filenames.push_back(comline);
       if(verb > 1)
         std::cout << "     " << comline << std::endl;
     }
   }
   std::vector<std::string>::iterator fni = filenames.begin();
   if(verb > 1)
     std::cout << "   Processing files...."; 
   while(fni != filenames.end()){
     std::string filename(*fni++);
     if(verb > 1)
       std::cout << "     File: " << filename << std::endl;
     ComStr.str("");
     ComStr << "sed -i 's/" << OriginalName << "/" << NewName << "/g' " << filename;
     if(verb > 1)
       std::cout << "       " << ComStr.str() << std::endl;
     System.Execute(ComStr.str());
     int n = 0;
     while(std::getline(System,comline))
       n++;
     ComStr.str("");
     ComStr << "sed -i 's/" << oupper << "/" << nupper << "/g' " << filename;
     if(verb > 1)
       std::cout << "       " << ComStr.str() << std::endl;
     //    std::cout << ComStr.str() << std::endl;
     System.Execute(ComStr.str());
     while(std::getline(System,comline))
       n++;
     ComStr.str("");
     ComStr << "sed -i 's/" << olower << "/" << nlower << "/g' " << filename;
     if(verb > 1)
       std::cout << "       " << ComStr.str() << std::endl;
     //    std::cout << ComStr.str() << std::endl;
     System.Execute(ComStr.str());
     while(std::getline(System,comline))
       n++;
   }
   if(verb > 1)
     std::cout << "   Done processing file contents." << std::endl
               << "   Renaming files..." << std::endl;
   ComStr.str("");
   // Now the inside of all files is fixed, need to fix filenames
   ComStr << "find . -name \"*" << OriginalName << "*\"";
   System.Execute(ComStr.str());
   std::string::size_type olen = OriginalName.length();
   std::string::size_type nlen = NewName.length();
   while(std::getline(System,comline)){
     if(verb > 1) 
       std::cout << "     Renaming " << comline << " to ";
     std::string newname(comline);
     std::string::size_type x = newname.find(OriginalName);
     while(x != std::string::npos){
       newname.replace(x,olen,NewName);
       x = newname.find(OriginalName);
     }
     ComStr.str("");
     if(verb > 1)
       std::cout << newname << std::endl;
     ComStr << "mv " << comline << " " << newname;
     //    std::cout << ComStr.str() << std::endl;
     IRAD::Sys::InProcess MV(ComStr.str());
   }
   if(verb > 1)
     std::cout << "done." << std::endl;
   return(0);  
 }
Exemplo n.º 24
0
void pyne::Material::write_text(char * fchar)
{
  std::string filename (fchar);
  write_text(filename);
};
Exemplo n.º 25
0
static file_entry &compute_dependencies(int srcrootlen, astring &srcfile)
{
	// see if we already have an entry
	astring normalfile(srcfile);
	normalfile.replacechr(PATH_SEPARATOR[0], '/');
	file_entry *foundfile = file_map.find(normalfile);
	if (foundfile != NULL)
		return *foundfile;

	// create a new header entry
	file_entry &file = *new file_entry;
	file.deplist = NULL;
	file.name = normalfile;
	file_map.add(file.name, &file);

	// read the source file
	UINT32 filelength;
	char *filedata;
	if (core_fload(srcfile, (void **)&filedata, &filelength) != FILERR_NONE)
	{
		fprintf(stderr, "Unable to read file '%s'\n", srcfile.cstr());
		return file;
	}

	// find the #include directives in this file
	for (int index = 0; index < filelength; index++)
		if (filedata[index] == '#' && strncmp(&filedata[index + 1], "include", 7) == 0)
		{
			// first make sure we're not commented or quoted
			bool just_continue = false;
			for (int scan = index; scan > 2 && filedata[scan] != 13 && filedata[scan] != 10; scan--)
				if ((filedata[scan] == '/' && filedata[scan - 1] == '/') || filedata[scan] == '"')
				{
					just_continue = true;
					break;
				}
			if (just_continue)
				continue;

			// scan forward to find the quotes or bracket
			index += 7;
			int scan;
			for (scan = index; scan < filelength && filedata[scan] != '<' && filedata[scan] != '"' && filedata[scan] != 13 && filedata[scan] != 10; scan++) ;

			// ignore if not found or if it's bracketed
			if (scan >= filelength || filedata[scan] != '"')
				continue;
			int start = ++scan;

			// find the closing quote
			while (scan < filelength && filedata[scan] != '"')
				scan++;
			if (scan >= filelength)
				continue;

			// find the include file
			astring filename(&filedata[start], scan - start);
			astring target;

			// create a new dependency
			if (find_include_file(target, srcrootlen, srcfile, filename))
			{
				dependency *dep = new dependency;
				dep->next = file.deplist;
				file.deplist = dep;
				dep->file = &compute_dependencies(srcrootlen, target);
			}
		}

	osd_free(filedata);
	return file;
}
Exemplo n.º 26
0
void wxGenericFileCtrl::HandleAction( const wxString &fn )
{
    if ( m_ignoreChanges )
        return;

    wxString filename( fn );
    if ( filename.empty() )
    {
        return;
    }
    if ( filename == wxT( "." ) ) return;

    wxString dir = m_list->GetDir();

    // "some/place/" means they want to chdir not try to load "place"
    const bool want_dir = filename.Last() == wxFILE_SEP_PATH;
    if ( want_dir )
        filename = filename.RemoveLast();

    if ( filename == wxT( ".." ) )
    {
        m_ignoreChanges = true;
        m_list->GoToParentDir();

        GenerateFolderChangedEvent( this, this );

        UpdateControls();
        m_ignoreChanges = false;
        return;
    }

#ifdef __UNIX__
    if ( filename == wxT( "~" ) )
    {
        m_ignoreChanges = true;
        m_list->GoToHomeDir();

        GenerateFolderChangedEvent( this, this );

        UpdateControls();
        m_ignoreChanges = false;
        return;
    }

    if ( filename.BeforeFirst( wxT( '/' ) ) == wxT( "~" ) )
    {
        filename = wxString( wxGetUserHome() ) + filename.Remove( 0, 1 );
    }
#endif // __UNIX__

    if ( !( m_style & wxFC_SAVE ) )
    {
        if ( ( filename.Find( wxT( '*' ) ) != wxNOT_FOUND ) ||
                ( filename.Find( wxT( '?' ) ) != wxNOT_FOUND ) )
        {
            if ( filename.Find( wxFILE_SEP_PATH ) != wxNOT_FOUND )
            {
                wxMessageBox( _( "Illegal file specification." ),
                              _( "Error" ), wxOK | wxICON_ERROR, this );
                return;
            }
            m_list->SetWild( filename );
            return;
        }
    }

    if ( !IsTopMostDir( dir ) )
        dir += wxFILE_SEP_PATH;
    if ( !wxIsAbsolutePath( filename ) )
    {
        dir += filename;
        filename = dir;
    }

    if ( wxDirExists( filename ) )
    {
        m_ignoreChanges = true;
        m_list->GoToDir( filename );
        UpdateControls();

        GenerateFolderChangedEvent( this, this );

        m_ignoreChanges = false;
        return;
    }

    // they really wanted a dir, but it doesn't exist
    if ( want_dir )
    {
        wxMessageBox( _( "Directory doesn't exist." ), _( "Error" ),
                      wxOK | wxICON_ERROR, this );
        return;
    }

    // append the default extension to the filename if it doesn't have any
    //
    // VZ: the logic of testing for !wxFileExists() only for the open file
    //     dialog is not entirely clear to me, why don't we allow saving to a
    //     file without extension as well?
    if ( !( m_style & wxFC_OPEN ) || !wxFileExists( filename ) )
    {
        filename = wxFileDialogBase::AppendExtension( filename, m_filterExtension );
        GenerateFileActivatedEvent( this, this, wxFileName( filename ).GetFullName() );
        return;
    }

    GenerateFileActivatedEvent( this, this );
}
Exemplo n.º 27
0
ID3Tags::ID3Tags(EntryRefItem * ref_item)
	:	AudioInfo	(),
		m_file		(NULL),
		m_tag		(NULL),
		m_artist	(NULL),
		m_album		(NULL),
		m_title		(NULL),
		m_year		(NULL),
		m_comment	(NULL),
		m_track		(NULL),
		m_genre		(NULL),
		m_write_on_exit	(false)
{
	PRINT(("ID3Tags::ID3Tags()\n"));

	status_t status = B_OK;
	bool fileref_created_ok = false;

	BPath filename(ref_item->EntryRef());
	
	if (ref_item->IsMP3())
	{
		PRINT(("Filetype == MPEG\n"));
		m_file = new TagLib::FileRef(new TagLib::MPEG::File(filename.Path()));
		fileref_created_ok = true;
	}
	else if (ref_item->IsOGG())
	{
		PRINT(("Filetype == VORBIS\n"));
		m_file = new TagLib::FileRef(new TagLib::Vorbis::File(filename.Path()));
		fileref_created_ok = true;
	}
	else if (ref_item->IsFLAC())
	{
		PRINT(("Filetype == FLAC\n"));
		m_file = new TagLib::FileRef(new TagLib::FLAC::File(filename.Path()));
		fileref_created_ok = true;
	}
	
	// XXX this needs more work
	
	if (! fileref_created_ok)
	{
		this->m_file = new TagLib::FileRef (filename.Path());
		// XXX error checking
	}
	
	if (m_file == NULL)
	{
		PRINT(("ID3Tags::ID3Tags() :: file == NULL\n"));
		return;
	}

	if (m_file->isNull())
	{
		PRINT(("ID3Tags::ID3Tags() :: file->isNull()\n"));
		return;
	}
	
	
	if (! m_file->tag())
	{
		PRINT(("ID3Tags::ID3Tags() :: !file->tag()\n"));
		return;
	}
	
	if (this->m_file != NULL)
		this->m_tag	= this->m_file->tag();
	else
		this->m_tag = NULL;


	m_artist = new ID3Tag(m_file, m_tag, ARTIST_TAG);
	m_album = new ID3Tag(m_file, m_tag, ALBUM_TAG);
	m_title = new ID3Tag(m_file, m_tag, TITLE_TAG);
	m_year = new ID3Tag(m_file, m_tag, YEAR_TAG);
	m_comment = new ID3Tag(m_file, m_tag, COMMENT_TAG);
	m_track = new ID3Tag(m_file, m_tag, TRACK_TAG);
	m_genre = new ID3Tag(m_file, m_tag, GENRE_TAG);

	Read();

}
Exemplo n.º 28
0
 /* subclass must call in destructor (or at close).
     removes this from pathToFile and other maps
     safe to call more than once, albeit might be wasted work
     ideal to call close to the close, if the close is well before object destruction
 */
 void MongoFile::destroyed() {
     RWLockRecursive::Exclusive lk(mmmutex);
     mmfiles.erase(this);
     pathToFile.erase( filename() );
 }
Exemplo n.º 29
0
KAQueryList &
KAQuery::getFileList() const
{
  KAQueryFile *file;
  KAQueryList *filelist = new KAQueryList;
  QDate date;
  QTime time;
  //  QDateTime datetime;
  VLINK tmplink = queryresult;
  /* (from archie/procquery.c)         */
  PATTRIB     ap;
  int         size = 0;
  char        *modes = "";
  char        *gt_date = "";
  int         gt_year = 0;
  int         gt_mon = 0;
  int         gt_day = 0;
  int         gt_hour = 0;
  int         gt_min = 0;

  while (tmplink != 0) {
    /* Parse the attibutes of this link
     * (from archie/procquery.c)         */
    for (ap = tmplink->lattrib; ap; ap = ap->next) {
	if (strcmp(ap->aname,"SIZE") == 0) {
#ifdef MSDOS
	  sscanf(ap->value.ascii,"%lu",&size);
#else
	  sscanf(ap->value.ascii,"%d",&size);
#endif
	} else if(strcmp(ap->aname,"UNIX-MODES") == 0) {
	    modes = ap->value.ascii;
	} else if(strcmp(ap->aname,"LAST-MODIFIED") == 0) {
	    gt_date = ap->value.ascii;
	    sscanf(gt_date,"%4d%2d%2d%2d%2d", &gt_year,
		   &gt_mon, &gt_day, &gt_hour, &gt_min);
	    /*
	    if ((12 * (presenttime->tm_year + 1900 - gt_year) + 
					presenttime->tm_mon - gt_mon) > 6) 
		sprintf(archie_date,"%s %2d %4d",month_sname(gt_mon),
			gt_day, gt_year);
	    else
		sprintf(archie_date,"%s %2d %02d:%02d",month_sname(gt_mon),
			 gt_day, gt_hour, gt_min);
			 */
	}
    }
    
    date.setYMD(gt_year, gt_mon, gt_day);
    time.setHMS(gt_hour, gt_min, 0);
    //datetime.setTime( time );
    //datetime.setDate( date );
    QString host(tmplink->host);
    QString path(tmplink->filename);
    int slash_index = path.findRev('/');
    QString filename( path.right( path.length() - slash_index -1 ));
    path.resize( slash_index +2 );
    file = new KAQueryFile( host, path, filename, size, modes, date, time );
    filelist->append( file );
    tmplink = tmplink->next;
  }

  return *filelist;
}
Exemplo n.º 30
0
void bsodFatal(const char *component)
{
	/* show no more than one bsod while shutting down/crashing */
	if (bsodhandled) return;
	bsodhandled = true;

	std::string lines = getLogBuffer();

		/* find python-tracebacks, and extract "  File "-strings */
	size_t start = 0;

	std::string crash_emailaddr = CRASH_EMAILADDR;
	std::string crash_component = "enigma2";

	if (component)
		crash_component = component;
	else
	{
		while ((start = lines.find("\n  File \"", start)) != std::string::npos)
		{
			start += 9;
			size_t end = lines.find("\"", start);
			if (end == std::string::npos)
				break;
			end = lines.rfind("/", end);
				/* skip a potential prefix to the path */
			unsigned int path_prefix = lines.find("/usr/", start);
			if (path_prefix != std::string::npos && path_prefix < end)
				start = path_prefix;

			if (end == std::string::npos)
				break;

			std::string filename(lines.substr(start, end - start) + INFOFILE);
			std::ifstream in(filename.c_str());
			if (in.good()) {
				std::getline(in, crash_emailaddr) && std::getline(in, crash_component);
				in.close();
			}
		}
	}

	FILE *f;
	const char* crashlog_name;
	std::ostringstream os;
	os << "/media/hdd/enigma2_crash_";
	os << time(0);
	os << ".log";
	crashlog_name = os.str().c_str();
	f = fopen(crashlog_name, "wb");

	if (f == NULL)
	{
		/* No hardisk. If there is a crash log in /home/root, leave it
		 * alone because we may be in a crash loop and writing this file
		 * all night long may damage the flash. Also, usually the first
		 * crash log is the most interesting one. */
		crashlog_name = "/home/root/enigma2_crash.log";
		if ((access(crashlog_name, F_OK) == 0) ||
		    ((f = fopen(crashlog_name, "wb")) == NULL))
		{
			/* Re-write the same file in /tmp/ because it's expected to
			 * be in RAM. So the first crash log will end up in /home
			 * and the last in /tmp */
			crashlog_name = "/tmp/enigma2_crash.log";
			f = fopen(crashlog_name, "wb");
		}
	}

	if (f)
	{
		time_t t = time(0);
		struct tm tm;
		char tm_str[32];

		localtime_r(&t, &tm);
		strftime(tm_str, sizeof(tm_str), "%a %b %_d %T %Y", &tm);

		XmlGenerator xml(f);

		xml.open("openMips");

		xml.open("enigma2");
		xml.string("crashdate", tm_str);
		xml.string("compiledate", __DATE__);
		xml.string("contactemail", crash_emailaddr);
		xml.comment("Please email this crashlog to above address. Check all sections to remove any sensitive private data!");
		xml.string("skin", getConfigString("config.skin.primary_skin", "Default Skin"));
		xml.string("sourcedate", enigma2_date);
		xml.string("branch", enigma2_branch);
		xml.string("rev", enigma2_rev);
		xml.string("version", PACKAGE_VERSION);
		xml.close();

		xml.open("image");
		if(access("/proc/stb/info/boxtype", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/boxtype");
		}
		else if (access("/proc/stb/info/model", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/model");
		}
		xml.cDataFromFile("imageversion", "/etc/image-version");
		xml.cDataFromCmd("kernelversion", "uname -a");
		xml.stringFromFile("kernelcmdline", "/proc/cmdline");
		xml.cDataFromCmd("memory", "free -l");
		xml.cDataFromCmd("filesystems", "df -h");
		xml.cDataFromCmd("mounts", "mount");
		xml.cDataFromCmd("nimsockets", "cat /proc/bus/nim_sockets");
		xml.cDataFromCmd("networkifconfig", "ifconfig");
		xml.cDataFromFile("networkinterfaces", "/etc/network/interfaces");
		xml.cDataFromFile("dns", "/etc/resolv.conf");
		xml.cDataFromFile("defaultgateway", "/etc/default_gw");
		xml.close();

		xml.open("settings");
		xml.cDataFromCmd("enigma2settings", "cat /etc/enigma2/settings");
		xml.close();

		xml.open("software");
		xml.cDataFromCmd("enigma2software", "opkg list-installed 'enigma2*'");
		xml.cDataFromCmd("gstreamersoftware", "opkg list-installed 'gst*'");
		xml.close();

		xml.open("crashlogs");
		xml.cDataFromString("enigma2crashlog", getLogBuffer());
		xml.close();

		xml.close();
		fclose(f);
	}

	ePtr<gMainDC> my_dc;
	gMainDC::getInstance(my_dc);

	gPainter p(my_dc);
	p.resetOffset();
	p.resetClip(eRect(ePoint(0, 0), my_dc->size()));
	p.setBackgroundColor(gRGB(0x27408B));
	p.setForegroundColor(gRGB(0xFFFFFF));

	int hd =  my_dc->size().width() == 1920;
	ePtr<gFont> font = new gFont("Regular", hd ? 30 : 20);
	p.setFont(font);
	p.clear();

	eRect usable_area = eRect(hd ? 30 : 100, hd ? 30 : 70, my_dc->size().width() - (hd ? 60 : 150), hd ? 150 : 100);

	os.str("");
	os.clear();
	os << "We are really sorry. Your STB encountered "
		"a software problem, and needs to be restarted.\n"
		"Please attach " << crashlog_name << " " << crash_emailaddr << ".\n"
		"Your STB restarts in 10 seconds!\n"
		"Component: " << crash_component;

	p.renderText(usable_area, os.str().c_str(), gPainter::RT_WRAP|gPainter::RT_HALIGN_LEFT);

	usable_area = eRect(hd ? 30 : 100, hd ? 180 : 170, my_dc->size().width() - (hd ? 60 : 180), my_dc->size().height() - (hd ? 30 : 20));

	int i;

	start = std::string::npos + 1;
	for (i=0; i<20; ++i)
	{
		start = lines.rfind('\n', start - 1);
		if (start == std::string::npos)
		{
			start = 0;
			break;
		}
	}

	font = new gFont("Regular", hd ? 21 : 14);
	p.setFont(font);

	p.renderText(usable_area,
		lines.substr(start), gPainter::RT_HALIGN_LEFT);
	sleep(10);

	/*
	 * When 'component' is NULL, we are called because of a python exception.
	 * In that case, we'd prefer to to a clean shutdown of the C++ objects,
	 * and this should be safe, because the crash did not occur in the
	 * C++ part.
	 * However, when we got here for some other reason, a segfault probably,
	 * we prefer to stop immediately instead of performing a clean shutdown.
	 * We'd risk destroying things with every additional instruction we're
	 * executing here.
	 */
	if (component) raise(SIGKILL);
}