Esempio n. 1
0
bool DebuggerMgr::LoadDebuggers()
{
    wxString ext;

#if defined(__WXMSW__)
    ext = wxT("dll");

#elif defined(__WXMAC__)
    ext = wxT("dylib");

#else
    ext = wxT("so");

#endif

    wxString fileSpec(wxT("*.") + ext);

    // get list of dlls
    wxArrayString files;
#ifdef __WXGTK__
    wxString debuggersPath(PLUGINS_DIR, wxConvUTF8);
    debuggersPath += wxT("/debuggers");
#elif defined(__WXMSW__)
#ifdef USE_POSIX_LAYOUT
    wxString debuggersPath(clStandardPaths::Get().GetPluginsDirectory() + wxT("/debuggers"));
#else
    wxString debuggersPath(m_baseDir + wxT("/debuggers"));
#endif
#else
    // OSX
    wxFileName debuggersFolder(clStandardPaths::Get().GetDataDir(), "");
    debuggersFolder.AppendDir("debuggers");
    wxString debuggersPath(debuggersFolder.GetPath());
#endif

    CL_DEBUG("Loading debuggers from: %s", debuggersPath);
    wxDir::GetAllFiles(debuggersPath, &files, fileSpec, wxDIR_FILES);

    for(size_t i = 0; i < files.GetCount(); i++) {
        clDynamicLibrary* dl = new clDynamicLibrary();
        wxString fileName(files.Item(i));
        CL_DEBUG("Attempting to load debugger: %s", fileName);
#if defined(__WXMSW__) && !defined(NDEBUG)
        // Under MSW loading a release plugin while in debug mode will cause a crash
        if(!fileName.EndsWith("-dbg.dll")) {
            wxDELETE(dl);
            continue;
        }
#elif defined(__WXMSW__)

        // filter debug plugins
        if(fileName.EndsWith("-dbg.dll")) {
            wxDELETE(dl);
            continue;
        }
#endif
        if(!dl->Load(fileName)) {
            CL_WARNING("Failed to load debugger: %s", fileName);
            if(!dl->GetError().IsEmpty()) { CL_WARNING("%s", dl->GetError()); }
            wxDELETE(dl);
            continue;
        }

        bool success(false);
        GET_DBG_INFO_FUNC pfn = (GET_DBG_INFO_FUNC)dl->GetSymbol(wxT("GetDebuggerInfo"), &success);
        if(!success) {
            clLogMessage(wxT("Failed to find GetDebuggerInfo() in dll: ") + fileName);
            if(!dl->GetError().IsEmpty()) { clLogMessage(dl->GetError()); }
            // dl->Unload();
            delete dl;
            continue;
        }

        DebuggerInfo info = pfn();
        // Call the init method to create an instance of the debugger
        success = false;
        GET_DBG_CREATE_FUNC pfnInitDbg = (GET_DBG_CREATE_FUNC)dl->GetSymbol(info.initFuncName, &success);
        if(!success) {
            clLogMessage(wxT("Failed to find init function in dll: ") + fileName);
            if(!dl->GetError().IsEmpty()) { clLogMessage(dl->GetError()); }
            dl->Detach();
            delete dl;
            continue;
        }

        clLogMessage(wxT("Loaded debugger: ") + info.name + wxT(", Version: ") + info.version);
        IDebugger* dbg = pfnInitDbg();

        // set the environment
        dbg->SetEnvironment(m_env);

        m_debuggers[info.name] = dbg;

        // keep the dynamic load library
        m_dl.push_back(dl);
    }

    // Load all debuggers in the form of plugin (i.e. they dont implement the IDebugger interface)
    // and append them to a special list
    clDebugEvent queryPlugins(wxEVT_DBG_IS_PLUGIN_DEBUGGER);
    EventNotifier::Get()->ProcessEvent(queryPlugins);
    m_pluginsDebuggers.swap(queryPlugins.GetStrings());
    return true;
}
Esempio n. 2
0
void CJobRunner::doNext()
{
    if(itsIt==itsEnd/* || CMD_UPDATE==itsCmd*/)
    {
        if(itsModified)
        {
            // Force reconfig if command was already set to update...
            dbus()->reconfigure(getpid(), CMD_UPDATE==itsCmd);
            itsCmd=CMD_UPDATE;
            itsStatusLabel->setText(i18n("Updating font configuration. Please wait..."));
            itsProgress->setValue(itsProgress->maximum());
            emit configuring();
        }
        else
        {
            itsActionLabel->stopAnimation();
            if(PAGE_ERROR!=itsStack->currentIndex())
                reject();
        }
    }
    else
    {
        Misc::TFont font;
        bool        system;

        switch(itsCmd)
        {
            case CMD_INSTALL:
            {
                itsCurrentFile=fileName((*itsIt).url());

                if(itsCurrentFile.isEmpty()) // Failed to download...
                    dbusStatus(getpid(), constDownloadFailed);
                else
                {
                    // Create AFM if this is a PFM, and the previous was not the AFM for this font...
                    bool createAfm=Item::TYPE1_PFM==(*itsIt).type && 
                                   (itsPrev==itsEnd || (*itsIt).fileName!=(*itsPrev).fileName || Item::TYPE1_AFM!=(*itsPrev).type);
 
                    dbus()->install(itsCurrentFile, createAfm, itsDestIsSystem, getpid(), false);
                }
                break;
            }
            case CMD_DELETE:
                decode(*itsIt, font, system);
                dbus()->uninstall(font.family, font.styleInfo, system, getpid(), false);
                break;
            case CMD_ENABLE:
                decode(*itsIt, font, system);
                dbus()->enable(font.family, font.styleInfo, system, getpid(), false);
                break;
            case CMD_DISABLE:
                decode(*itsIt, font, system);
                dbus()->disable(font.family, font.styleInfo, system, getpid(), false);
                break;
            case CMD_MOVE:
                decode(*itsIt, font, system);
                // To 'Move' a disabled font, we first need to enable it. To accomplish this, JobRunner creates a 'fake' entry
                // with the filename "--"
                if((*itsIt).fileName==QLatin1String("--"))
                {
                    setCaption(i18n("Enabling"));
                    dbus()->enable(font.family, font.styleInfo, system, getpid(), false);
                }
                else
                {
                    if(itsPrev!=itsEnd && (*itsPrev).fileName==QLatin1String("--"))
                        setCaption(i18n("Moving"));
                    dbus()->move(font.family, font.styleInfo, itsDestIsSystem, getpid(), false);
                }
                break;
            case CMD_REMOVE_FILE:
                decode(*itsIt, font, system);
                dbus()->removeFile(font.family, font.styleInfo, (*itsIt).fileName, system, getpid(), false);
                break;
            default:
                break;
        }
        itsStatusLabel->setText(CMD_INSTALL==itsCmd ? (*itsIt).prettyUrl() : FC::createName(FC::decode(*itsIt)));
        itsProgress->setValue(itsProgress->value()+1);
        
        // Keep copy of this iterator - so that can check whether AFM should be created.
        itsPrev=itsIt;
    }
}
Esempio n. 3
0
// --------------------------------------------------------------------------------
// void doNSmlDebugDumpL( void* aData, TInt aLength, TText8* aFile, TInt aLine, const TText8* aMsg )
// --------------------------------------------------------------------------------
void doNSmlDebugDumpL( void* aData, TInt aLength, TText8* aFile, TInt aLine, const TText8* aMsg )
	{
	TInt pushed(0);
	HBufC8* pDateBuffer8 = HBufC8::NewLC(64);
	pushed++;
	TPtr8 dateBuffer8 = pDateBuffer8->Des();
	HBufC8* pTimeBuffer8 = HBufC8::NewLC(64);
	pushed++;
	TPtr8 timeBuffer8 = pTimeBuffer8->Des();
	NSmlGetDateAndTimeL(dateBuffer8, timeBuffer8);
	TPtrC8 data(REINTERPRET_CAST(TUint8*, aData), aLength);
	TPtrC8 fileName(aFile);
	HBufC8* buffer8 = HBufC8::NewLC(KBufferSize);
	pushed++;
	TPtr8 ptrBuffer8 = buffer8->Des();
	TPtrC8 msg(aMsg);
	if( !msg.Length() )
		{
#if !defined(__SML_DEVELOPER_DEBUG__)
		ptrBuffer8.Format(_L8("[%S %S File: %S Line: %d Length: %d]\r\n"), &dateBuffer8, &timeBuffer8, &fileName, aLine, aLength);
#else
		ptrBuffer8.Format(_L8("[%S %S Length: %d]\r\n"), &dateBuffer8, &timeBuffer8, aLength);
#endif
		}
	else
		{
#if !defined(__SML_DEVELOPER_DEBUG__)
		ptrBuffer8.Format(_L8("[%S %S File: %S Line: %d Length: %d] %S\r\n"), &dateBuffer8, &timeBuffer8, &fileName, aLine, aLength, &msg);
#else
		ptrBuffer8.Format(_L8("[%S %S Length: %d] %S\r\n"), &dateBuffer8, &timeBuffer8, aLength, &msg);
#endif
		}
	// Now we're ready to write into file
	RFs fileSession;
	if( fileSession.Connect() == KErrNone )
		{
		CleanupClosePushL(fileSession);
		pushed++;
		RFile file;
#ifdef __WINS__
		if( file.Open(fileSession, KNSmlDebugDumpName(), EFileShareAny|EFileWrite) == KErrNone )
#else
		HBufC* outputDumpName = HBufC::NewLC( KNSmlDebugDumpName().Length()+1 );
		pushed++;
		TPtr nameDumpPtr = outputDumpName->Des();
		TDriveInfo driveInfo;
		for ( TUint driveNumber = EDriveA; driveNumber <= EDriveZ; driveNumber++ ) 
			{
			fileSession.Drive( driveInfo, driveNumber );
			if ( KDriveAttRemovable & driveInfo.iDriveAtt ) 
				{
				// this is MMC
				nameDumpPtr.Insert( 0, KNSmlDebugDriveLetters().Mid( driveNumber, 1 ));
				nameDumpPtr.Insert( 1, KNSmlDebugDumpName() );
				break;
				}
			}
		if( file.Open(fileSession, *outputDumpName, EFileShareAny|EFileWrite) == KErrNone )
#endif

			{
			CleanupClosePushL(file);
			TInt pos(0);
			file.Seek(ESeekEnd, pos);
			RMutex mutex;
			NSmlGrabMutexLC(mutex, KNSmlDebugMutexNameDump());
			TInt result1 = file.Write(ptrBuffer8);
			TInt result2 = file.Write(data);
			TInt result3 = file.Write(_L8("\r\n\r\n"));
			TInt result4 = file.Flush();
			mutex.Signal();
			CleanupStack::PopAndDestroy(2); // file, mutex
			User::LeaveIfError(result1);
			User::LeaveIfError(result2);
			User::LeaveIfError(result3);
			User::LeaveIfError(result4);
			}
		}
	CleanupStack::PopAndDestroy( pushed ); // buffer8, pDateBuffer8, pTimeBuffer8
	}
void MainFrame::OnTestBatchFileSerialization(wxCommandEvent& event)
{
    // Menu Test -> Batch File Serialization
    //------Last Checked------//
    // - Dec 31, 2004
    WXUNUSED(event);

    // Display critical warning!!!
    if (wxMessageBox(wxT("CRITICAL WARNING: Do NOT perform this test on your original Power Tab files. Make a copy of files, place them in a temporary folder, and perform the test on the copied files instead.\n\nProceed with the the test?"),
                     wxT("Batch File Serialization Test"),
                     wxYES_NO | wxICON_ERROR) == wxNO)
        return;

    // Notes: This function will load (individually) all .ptb files
    // in a folder (and its subfolders), to ensure deserialization
    // is working correctly.  If a file is the most recent file
    // format (v1.7), the file is saved to a memory stream, and
    // then compared with the original file to ensure serialization
    // is working correctly. If any errors occur, you will be prompted
    // to save the errors to a text file.

    wxArrayString errors;

    const wxString& dir = wxDirSelector(wxT("Select the folder where your Power Tab files (.ptb) reside, and then click OK."));
    if (!dir.empty())
    {
        const wxChar* errorMessageFormat = wxT("%s - [%s]");

        // Get all .ptb files in the folder and its subfolders
        // This can take some time if you have alot of files or a slow machine
        wxArrayString files;
        {
            wxProgressDialog progressDialog(wxT("Scanning for Files"), wxT("Please wait. Scanning folders for Power Tab files..."), 0, this, wxPD_AUTO_HIDE | wxPD_APP_MODAL);

            wxDir::GetAllFiles(dir, &files, wxT("*.ptb"));
            progressDialog.Show(false);
        }

        // Process each file
        size_t i = 0;
        size_t fileCount = files.GetCount();

        wxProgressDialog progressDialog(wxT("Batch File Serialization Test Progress"), wxT(""), fileCount, this, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);

        bool cancelled = false;  // If true, user pressed Cancel button

        for (; i < fileCount; i++)
        {
            wxFileName fileName(files[i]);

            // Update progress status
            if (!progressDialog.Update(i, wxString::Format(wxT("Testing file %d of %d\n%s..."), i + 1, fileCount, fileName.GetFullName().c_str())))
            {
                cancelled = true;
                break;
            }

            // Open the file
            wxFileInputStream stream(files[i]);
            if (stream.IsOk())
            {
                PowerTabInputStream input_stream(stream);

                // Load the file
                PowerTabDocument document;
                if (!document.Load(input_stream))
                {
                    errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), input_stream.GetLastErrorMessage().c_str()));
                    document.DeleteContents();
                    continue;
                }

                // If file version is the most current, we can perform a memory save test; if not, continue
                if (document.GetHeaderRef().GetVersion() != PowerTabFileHeader::FILEVERSION_CURRENT)
                {
                    document.DeleteContents();
                    continue;
                }

                // Save the document to memory
                wxMemoryOutputStream memory_stream;
                document.SaveObject(memory_stream);

                // Size should be the same
                if (stream.GetSize() != memory_stream.GetSize())
                {
                    errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));
                    document.DeleteContents();
                    continue;
                }

                // Compare each byte in the file to each byte of the saved memory data
                wxStreamBuffer* streamBuffer = memory_stream.GetOutputStreamBuffer();
                if ((stream.GetSize() > 0) && (streamBuffer != NULL))
                {
                    // Set file position to start of file
                    stream.SeekI(0);

                    // Get a pointer to the memory stream buffer
                    wxUint8* ptr = (wxUint8*)streamBuffer->GetBufferStart();

                    // Get number of bytes left to read from the file
                    wxUint32 bytesLeft = stream.GetSize();

                    while (bytesLeft > 0)
                    {
                        // Read a chunk of data from the file
                        const wxUint32 bufferSize = 4096;
                        wxUint8 buffer[bufferSize];
                        wxUint32 bytesRead = min(bytesLeft, bufferSize);
                        stream.Read(buffer, bufferSize);

                        // Compare each byte in the chunk to the corresponding byte in the memory stream buffer
                        wxUint32 b = 0;
                        for (; b < bytesRead; b++)
                        {
                            if (buffer[b] != *ptr)
                            {
                                errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));
                                document.DeleteContents();
                                // This line will force the while statement to fail
                                bytesRead = bytesLeft;
                                break;
                            }
                            ptr++;
                        }
                        bytesLeft -= bytesRead;
                    }
                }
                else
                    errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Memory Save Test failure")));

                document.DeleteContents();
            }
            else
                errors.Add(wxString::Format(errorMessageFormat, files[i].c_str(), wxT("Could not open file")));

            // Update progress
            if (!progressDialog.Update(i + 1))
            {
                cancelled = true;
                break;
            }
        }

        // User didn't cancel
        if (!cancelled)
        {
            wxString message = wxString::Format(wxT("Testing complete\n\nFiles tested: %d\nErrors: %d"), fileCount, errors.GetCount());
            int style = wxICON_INFORMATION;

            // Add text to allow user to save error messages
            if (errors.GetCount() > 0)
            {
                message += wxT("\n\nThere were errors that occurred during the testing process. Would you like to save them to file?");
                style |= wxYES_NO;
            }

            // Display results of test to user; If user clicks Yes, save errors to file
            if (wxMessageBox(message, wxT("Batch File Serialization Test"), style) == wxYES)
            {
                wxFileDialog fileDialog(this, wxT("Save Results"), wxT(""), wxT("results.txt"), wxT("Text files (*.txt)|*.txt"), wxSAVE | wxHIDE_READONLY | wxOVERWRITE_PROMPT);
                if (fileDialog.ShowModal() == wxID_OK)
                {
                    wxString pathName = fileDialog.GetPath();

                    // Create a new file
                    wxTextFile file;
                    file.Create(pathName);

                    // Write the errors
                    size_t e = 0;
                    size_t count = errors.GetCount();
                    for (; e < count; e++)
                        file.AddLine(errors[e]);

                    file.Write();
                    file.Close();
                }
            }
        }
    }
}
Esempio n. 5
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> WZAnalysis::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  std::string fileName(argv[1]);
  boost::shared_ptr<edm::ParameterSet> parameterSet = edm::readConfig(fileName);
  
  
  // "Input"
  edm::ParameterSet Input =  parameterSet -> getParameter<edm::ParameterSet>("Input");
  std::string inputFileList = Input.getParameter<std::string>("inputFileList");
  std::string jsonFileName  = Input.getParameter<std::string>("jsonFileName");
  
  
  // "Output"
  edm::ParameterSet Output =  parameterSet -> getParameter<edm::ParameterSet>("Output");
  std::string outputRootFilePath = Output.getParameter<std::string>("outputRootFilePath");
  std::string outputRootFileName = Output.getParameter<std::string>("outputRootFileName");
  std::string outputRootFullFileName = outputRootFilePath + "/" + outputRootFileName + ".root";
  
  
  // "Options"
  edm::ParameterSet Options =  parameterSet -> getParameter<edm::ParameterSet>("Options");
  int entryMIN       = Options.getParameter<int>("entryMIN");
  int entryMAX       = Options.getParameter<int>("entryMAX");
  int entryMODULO    = Options.getParameter<int>("entryMODULO");
  int jsonFlag       = Options.getParameter<int>("jsonFlag");
  int verbosity      = Options.getParameter<int>("verbosity");
  
  
  // Get total number of events
  std::cout << ">>> WZAnalysis::Get number of events" << std::endl;
  std::map<int, int> beginEvents      = GetTotalEvents("AllPassFilterBegin/passedEvents",            inputFileList.c_str());
  std::map<int, int> goodVertexEvents = GetTotalEvents("AllPassFilterGoodVertexFilter/passedEvents", inputFileList.c_str());
  std::map<int, int> noScrapingEvents = GetTotalEvents("AllPassFilterNoScrapingFilter/passedEvents", inputFileList.c_str());
  std::map<int, int> HBHENoiseEvents  = GetTotalEvents("AllPassFilterHBHENoiseFilter/passedEvents",  inputFileList.c_str());
  std::map<int, int> electronEvents   = GetTotalEvents("AllPassFilterElectronFilter/passedEvents",   inputFileList.c_str());
  
  
  
  // Get run/LS map from JSON file
  std::cout << ">>> WZPreselection::Get run/LS map from JSON file" << std::endl;
  std::map<int, std::vector<std::pair<int, int> > > jsonMap;
  jsonMap = readJSONFile(jsonFileName);
  
  
  
  // define HLT paths
  std::vector<std::pair<std::string,std::pair<int,int> > > HLTPathNames;
  
  std::pair<int,int> runRanges1(160404,161176);
  std::pair<std::string,std::pair<int,int> > HLTPathName1("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v1",runRanges1);
  std::pair<int,int> runRanges2(161216,163261);
  std::pair<std::string,std::pair<int,int> > HLTPathName2("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v2",runRanges2);
  std::pair<int,int> runRanges3(163269,163869);
  std::pair<std::string,std::pair<int,int> > HLTPathName3("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v3",runRanges3);
  std::pair<int,int> runRanges4(165088,165633);
  std::pair<std::string,std::pair<int,int> > HLTPathName4("HLT_Ele32_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v3",runRanges4);
  std::pair<int,int> runRanges5(165970,166967);
  std::pair<std::string,std::pair<int,int> > HLTPathName5("HLT_Ele25_WP80_PFMT40_v1",runRanges5);
  std::pair<int,int> runRanges6(167039,167913);
  std::pair<std::string,std::pair<int,int> > HLTPathName6("HLT_Ele27_WP80_PFMT50_v1",runRanges6);
  std::pair<int,int> runRanges7(170249,173198);
  std::pair<std::string,std::pair<int,int> > HLTPathName7("HLT_Ele32_WP70_PFMT50_v3",runRanges7);
  std::pair<int,int> runRanges8(173236,999999);
  std::pair<std::string,std::pair<int,int> > HLTPathName8("HLT_Ele32_WP70_PFMT50_v4",runRanges8);
  
  HLTPathNames.push_back(HLTPathName1);
  HLTPathNames.push_back(HLTPathName2);
  HLTPathNames.push_back(HLTPathName3);
  HLTPathNames.push_back(HLTPathName4);
  HLTPathNames.push_back(HLTPathName5);
  HLTPathNames.push_back(HLTPathName6);
  HLTPathNames.push_back(HLTPathName7);
  HLTPathNames.push_back(HLTPathName8);
  
  
  
  // Open tree
  std::cout << ">>> WZAnalysis::Open old tree" << std::endl;
  std::string treeName = "simpleNtuple/SimpleNtuple";
  TChain* chain = new TChain(treeName.c_str());
  if(!FillChain(*chain, inputFileList.c_str())) return 1;
  treeReader reader((TTree*)(chain), false);
  
  
  
  // Open output root file
  outputRootFileName += ".root";
  
  
  
  // define histograms
  std::cout << ">>> WZAnalysis::Define histograms" << std::endl;
  
  int nStep = 10;
  TH1F* events = new TH1F("events", "events", nStep, 0., 1.*nStep);
  std::map<int, int> stepEvents;
  std::map<int, std::string> stepNames;
  
  
  
  // define the reduced ntuple 
  WZAnalysisVariablesNoLC vars;
  InitializeWZAnalysisTree(vars,outputRootFullFileName);
  
  
   
  //**********************
  // STEP 1 - Begin events
  int step = 1;
  SetStepNames(stepNames, "All events", step, verbosity);
  stepEvents[step] = beginEvents[1];
  
  
  
  //****************************
  // STEP 2 - Good Vertex events
  step = 2;
  SetStepNames(stepNames, "Good vertex", step, verbosity);
  stepEvents[step] = goodVertexEvents[1];
  
  
  
  //*********************
  // STEP 3 - No Scraping
  step = 3;
  SetStepNames(stepNames, "No scraping", step, verbosity);
  stepEvents[step] = noScrapingEvents[1];
  
  
  
  //*********************
  // STEP 4 - HBHE Noise
  step = 4;
  SetStepNames(stepNames, "HBHE Noise", step, verbosity);
  stepEvents[step] = HBHENoiseEvents[1];
  
  
  
  //******************
  // STEP 5 - Electron
  step = 5;
  SetStepNames(stepNames, "Electron", step, verbosity);
  stepEvents[step] = electronEvents[1];
   
  
  
  //*********************
  // LOOP OVER THE EVENTS
  std::cout << ">>>>> WZAnalysis::Read " << chain -> GetEntries() << " entries" << std::endl;  
  for(int entry = entryMIN ; entry < chain -> GetEntries() ; ++entry)
  {
    reader.GetEntry(entry);
    if((entry%entryMODULO) == 0) std::cout << ">>>>> WZAnalysis::GetEntry " << entry << std::endl;   
    if(entry == entryMAX) break;
      
    // clear variables
    ClearWZAnalysisVariables(vars);    
    
    // event variables
    vars.runId   = reader.GetInt("runId")->at(0);
    vars.lumiId  = reader.GetInt("lumiId")->at(0);
    vars.timeStampLow   = reader.GetInt("timeStampLow")->at(0);
    vars.timeStampHigh  = reader.GetInt("timeStampHigh")->at(0);
    
    
    //**************************
    // STEP 6 - run/LS selection
    step = 6;
    SetStepNames(stepNames, "run/LS", step, verbosity);
    
    bool skipEvent = false;
    
    if(AcceptEventByRunAndLumiSection(vars.runId,vars.lumiId,jsonMap) == false)
      skipEvent = true;

    if( (jsonFlag == 1) && (skipEvent == true) ) continue;
    stepEvents[step] += 1;
    
    //***********************
    // STEP 7 - HLT selection
    step += 1;
    SetStepNames(stepNames, "HLT", step, verbosity);
    
    
    skipEvent = true;
 
    if( verbosity == 1 )
    {
      std::vector<std::string> HLT_names = *(reader.GetString("HLT_Names"));
      for(unsigned int HLTIt = 0; HLTIt < HLT_names.size(); ++HLTIt)
	std::cout << "HLT bit " << HLTIt 
                  << ":   "     << HLT_names.at(HLTIt)
                  << std::endl;
    }
    
    for(unsigned int HLTIt = 0; HLTIt < HLTPathNames.size(); ++HLTIt)
    {
      if( AcceptHLTPath(reader, HLTPathNames.at(HLTIt)) == true )
        skipEvent = false;
    }
    
    //if( skipEvent == true ) continue;
    stepEvents[step] += 1;    
        
    
    
    
    
    
    //**************************
    // STEP 8 - cut on electrons
    step += 1;
    SetStepNames(stepNames, "1/2 ele", step, verbosity);
    
    
    int nTightEle = 0;
    int nLooseEle = 0;
    std::map<float,int> eleIts;
    
    // loop on electrons
    for(unsigned int eleIt = 0; eleIt < (reader.Get4V("electrons")->size()); ++eleIt)
    {
      ROOT::Math::XYZTVector ele = reader.Get4V("electrons")->at(eleIt);
      float pt = ele.pt();
      float eta = ele.eta();
      
      float tkIso  = reader.GetFloat("electrons_tkIso03")->at(eleIt);
      float emIso  = reader.GetFloat("electrons_emIso03")->at(eleIt);
      float hadIso = reader.GetFloat("electrons_hadIso03_1")->at(eleIt) + 
                     reader.GetFloat("electrons_hadIso03_2")->at(eleIt);
      float combIso = tkIso + emIso + hadIso;
      
      int isEB = reader.GetInt("electrons_isEB")->at(eleIt);
      
      float sigmaIetaIeta = reader.GetFloat("electrons_sigmaIetaIeta")->at(eleIt);
      float DetaIn        = reader.GetFloat("electrons_deltaEtaIn")->at(eleIt);
      float DphiIn        = reader.GetFloat("electrons_deltaPhiIn")->at(eleIt);
      float HOverE        = reader.GetFloat("electrons_hOverE")->at(eleIt);
      
      int mishits             = reader.GetInt("electrons_mishits")->at(eleIt);
      int nAmbiguousGsfTracks = reader.GetInt("electrons_nAmbiguousGsfTracks")->at(eleIt);
      float dist = reader.GetFloat("electrons_dist")->at(eleIt);
      float dcot = reader.GetFloat("electrons_dcot")->at(eleIt);
      
      
      bool isTightElectron = false;
      
      // tight electrons
      if(
          (pt > 20.) &&
          (fabs(eta) < 2.5) &&
          ( ( (isEB == 1) && (combIso/pt    < 0.070) ) || ( (isEB == 0) && (combIso/pt    < 0.060) ) ) &&
          ( ( (isEB == 1) && (sigmaIetaIeta < 0.010) ) || ( (isEB == 0) && (sigmaIetaIeta < 0.030) ) ) &&
          ( ( (isEB == 1) && (fabs(DphiIn)  < 0.060) ) || ( (isEB == 0) && (fabs(DphiIn)  < 0.030) ) ) &&
          ( ( (isEB == 1) && (fabs(DetaIn)  < 0.004) ) || ( (isEB == 0) && (fabs(DetaIn)  < 0.007) ) ) &&
          ( ( (isEB == 1) && (HOverE        < 0.040) ) || ( (isEB == 0) && (HOverE        < 0.025) ) ) &&
          ( mishits == 0 ) &&
          ( nAmbiguousGsfTracks == 0 ) &&
          ( ( fabs(dist) > 0.02 ) || ( fabs(dcot) > 0.02 ) )
        )
      {
        isTightElectron = true;
        ++nTightEle;
        eleIts[1./pt] = eleIt;
      }
      
      
      // loose electrons
      if( isTightElectron == true ) continue;
      if( 
          (pt > 10.) &&
          (fabs(eta) < 2.5) &&
          ( ( (isEB == 1) && (combIso/pt    < 0.150) ) || ( (isEB == 0) && (combIso/pt    < 0.100) ) ) &&
          ( ( (isEB == 1) && (sigmaIetaIeta < 0.010) ) || ( (isEB == 0) && (sigmaIetaIeta < 0.030) ) ) &&
          ( ( (isEB == 1) && (fabs(DphiIn)  < 0.800) ) || ( (isEB == 0) && (fabs(DphiIn)  < 0.700) ) ) &&
          ( ( (isEB == 1) && (fabs(DetaIn)  < 0.007) ) || ( (isEB == 0) && (fabs(DetaIn)  < 0.010) ) ) &&
          ( ( (isEB == 1) && (HOverE        < 0.150) ) || ( (isEB == 0) && (HOverE        < 0.070) ) )
        )
      {
        ++nLooseEle;
      }
      
    } // loop on electrons
    
        
    int nLooseMu = 0;
    
    // loop on muons
    for(unsigned int muIt = 0; muIt < (reader.Get4V("muons")->size()); ++muIt)
    {
      ROOT::Math::XYZTVector mu = reader.Get4V("muons")->at(muIt);
      float pt = mu.pt();
      float eta = mu.eta();
      
      float tkIso  = reader.GetFloat("muons_tkIso03")->at(muIt);
      float emIso  = reader.GetFloat("muons_emIso03")->at(muIt);
      float hadIso = reader.GetFloat("muons_hadIso03")->at(muIt);
      float combIso = tkIso + emIso + hadIso;
      
      int global = reader.GetInt("muons_global")->at(muIt);

      if( (pt > 10.) &&
          (fabs(eta) < 2.5) &&
          (combIso/pt < 0.20) &&
          (global == 1) )
      {
        ++nLooseMu;
      }
    }
    
    
    // cuts
    if( verbosity == 1 )
      std::cout << " nTightEle = "  << nTightEle
                << " nLooseEle = " << nLooseEle
                << " nLooseMu = "  << nLooseMu
                << std::endl;
    if( nTightEle < 1 ) continue;
    if( nTightEle > 2 ) continue;
    if( nLooseEle > 0 ) continue;
    if( nLooseMu > 0 ) continue;
    stepEvents[step] += 1;
    
    
    
    // set electron variables
    std::map<float,int>::const_iterator mapIt = eleIts.begin();
    
    if( nTightEle == 1 )
    {
      SetElectron1Variables(vars,reader,mapIt->second);
    }
    
    int firstEle, secondEle;
    if( nTightEle == 2 )
    {
      firstEle = mapIt->second;
      SetElectron1Variables(vars,reader,mapIt->second);
      ++mapIt;
      secondEle = mapIt->second;
      SetElectron2Variables(vars,reader,mapIt->second);
    }
    
    // set met variables
    SetMetVariables(vars,reader);

    // set di-electron variables
    if( nTightEle == 2)
    {
      SetDiElectronVariables(vars,reader,firstEle,secondEle);
    }

    
    //***********************
    // STEP 9 - W selection
    step += 1;
    SetStepNames(stepNames, "W selection", step, verbosity);
    
    
    if( nTightEle == 1 )
    {
      if( vars.ele1_pt < 30. ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( (vars.ele1_tkIso+vars.ele1_emIso+vars.ele1_hadIso)/vars.ele1_pt > 0.04 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( fabs(vars.ele1_DphiIn) > 0.030 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( fabs(vars.ele1_DetaIn) > 0.004 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( vars.ele1_HOverE > 0.025 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( (vars.ele1_tkIso+vars.ele1_emIso+vars.ele1_hadIso)/vars.ele1_pt > 0.03 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( fabs(vars.ele1_DphiIn) > 0.020 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( fabs(vars.ele1_DetaIn) > 0.005 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( vars.ele1_HOverE > 0.025 ) ) continue;
      
      if( vars.met_et       < 25.00 ) continue;
      if( vars.ele1Met_mt   < 50.00 ) continue;
      if( vars.ele1Met_Dphi <  1.57 ) continue;
      stepEvents[step] += 1;
      
      
      vars.isW = 1;
      vars.isZ = 0;
      
      
      // fill the reduced tree
      FillWZAnalysisTree(vars);
    }
    
    
    
    
    
    
    //***********************
    // STEP 10 - Z selection
    step += 1;
    SetStepNames(stepNames, "Z selection", step, verbosity);
    
    
    if( nTightEle == 2 )
    {
      if( vars.met_et     > 30. ) continue;
      if( vars.ele1ele2_m <  70. ) continue;
      if( vars.ele1ele2_m > 110. ) continue;
      if( (vars.ele1_charge * vars.ele2_charge) != -1. ) continue;
      stepEvents[step] += 1;
      
      
      vars.isW = 0;
      vars.isZ = 1;
      
      
      // fill the reduced tree
      FillWZAnalysisTree(vars);
    }
    
    
    
  } // loop over the events
  
  // save the reduced tree
  DeleteWZAnalysisVariables(vars);
    
  // save the histograms
  TFile* outputRootFile = new TFile((outputRootFullFileName).c_str(), "UPDATE");
  outputRootFile -> cd();
  
  for(step = 1; step <= nStep; ++step)
  {
    events -> SetBinContent(step, stepEvents[step]);
    events -> GetXaxis() -> SetBinLabel(step, stepNames[step].c_str());
  }

  events -> Write();
  outputRootFile -> Close();
  
  
  return 0;
}
Esempio n. 6
0
QString XMLerLoadFileThread::progressMessage () const
{
  QString msg = tr("%1 file loaded...").arg( fileName() );;
  return msg;
}
Esempio n. 7
0
int
main( int argc, char** argv )
{
	clock_t totalTime;
	totalTime = clock();

	std::map< std::string, std::vector< cv::Rect > > showSigns;

	// --------------------------------------------- read image --------------------------------------------- //
	std::vector< std::string > validExtensions;
	validExtensions.push_back("jpg");
	validExtensions.push_back("png");
	validExtensions.push_back("ppm");
	validExtensions.push_back("jp2");
	Files fh = Files( validExtensions );

	std::vector< std::string > fileNames;
	int nFiles = fh.getFilesInDirectory( benchmarkDir, fileNames );

	std::ofstream File;
	File.open( benchmarkFile );
	int n = 1;

	for( std::vector< std::string >::iterator it = fileNames.begin(); it != fileNames.end(); it++, n++ )
	{
		std::string fileName( (*it) );
		Log::notice( "Processing image: '" + fileName + "' (" + Log::to_string(n) + " of " + Log::to_string(nFiles) + " ).." );

		clock_t t;
		t = clock();

		cv::Mat image = cv::imread( fileName );
		std::vector< std::vector< cv::Point > > data;
		std::vector< cv::Rect > signs;

		RSDS rsd = RSDS( image );

		for( int nm = 0; nm < RSDS::nColorModes; nm ++ )
		{
			// ------------------------------------------- convert to nhs ------------------------------------------- //
			// The second argument of convert_ihls_to_nhs means if it's red or blue. 0 is red, blue is 1.
			// You can put 2 here for others, but then you have to provide the hue max and min, sat min values.
			cv::Mat nhs_image;
			rsd.colorSegmentation( nm, nhs_image );

			// ------------------------------------------- PostProcessing ------------------------------------------- //
			cv::Mat nhs_image_for_post = nhs_image.clone();
			cv::Mat eimg;
			rsd.noiseElimination( nhs_image_for_post, eimg );

			// -------------------------------------- PostProcessing - Convex --------------------------------------- //
			// ------------------------------------ PostProcessing - Get contour ------------------------------------ //
			cv::Mat cimg;
			rsd.convexHullContours( eimg, cimg, data );
		}
		rsd.processCountours( image, data, signs );

		t = clock() - t;
		float calcDuration = ( (float) t ) / CLOCKS_PER_SEC;

		for( std::vector< cv::Rect >::iterator sit = signs.begin(); sit != signs.end(); sit ++ )
		{
//			std::cout << fileName << ";" << (*sit).x << ";" << (*sit).y << ";" << (*sit).x + (*sit).width << ";"
//					<< (*sit).y + (*sit).height << ";" << "-1" << ";" << calcDuration << std::endl;

			fh.saveSignBlobToFile( fileName, (*sit), -1, calcDuration, File );

			std::map< std::string, std::vector< cv::Rect > >::iterator it = showSigns.find(fileName);
			if( it != showSigns.end() )
			{
				it->second.push_back( (*sit) );
			}
			else
			{
				std::vector< cv::Rect > sr;
				sr.push_back( (*sit) );
				showSigns.insert( std::pair< std::string, std::vector< cv::Rect > >( fileName, sr ) );
			}
		}
	}

	File.flush();
	File.close();

	totalTime = clock() - totalTime;
	float calcDuration = ( (float) totalTime ) / CLOCKS_PER_SEC;
	std::cout << "Benchmark processed in " << calcDuration << " seconds." << std::endl;

	std::cout << "The following images have signs in them:" << std::endl;
	for( std::map< std::string, std::vector< cv::Rect > >::iterator it = showSigns.begin(); it != showSigns.end(); it++ )
	{
		cv::Mat result = cv::imread( it->first );

		for( std::vector< cv::Rect >::iterator sit = it->second.begin(); sit != it->second.end(); sit ++ )
		{
			cv::Point2f rect_points[4];
			rect_points[0] = cv::Point2f( (*sit).x, (*sit).y );
			rect_points[1] = cv::Point2f( (*sit).x, (*sit).y + (*sit).width );
			rect_points[2] = cv::Point2f( (*sit).x + (*sit).height, (*sit).y + (*sit).width );
			rect_points[3] = cv::Point2f( (*sit).x + (*sit).height, (*sit).y );
			for( int j = 0; j < 4; j++ )
				line( result, rect_points[j], rect_points[(j+1)%4], cv::Scalar(0, 255, 0), 2, 8 );
		}

		cv::namedWindow( "result", CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED );
		cv::imshow( "result", result );

		std::cout << '\t' << it->first << std::endl;

		cv::waitKey(0);
	}

	return 0;
}
Esempio n. 8
0
    //-------------- Message Handler --------------//
    LRESULT Window::handleMessage(UINT msg, WPARAM wParam, LPARAM lParam)
    {
        switch (msg)
        {
            case WM_KEYDOWN:
            {
                if (keyEventProcessor)
                    keyEventProcessor->KeyDown(wParam);
            } return 0;

            case WM_DROPFILES:
            {
                if (keyEventProcessor)
                {
                    HDROP hDrop = (HDROP)wParam;
                    const size_t size = 1000;
                    TCHAR file[size];
                    int fileNum = DragQueryFile(hDrop, -1, 0, 0);

                    if (fileNum > 2)
                    {
                        MessageBox(0, TEXT("To many files dropped."),
                                   TEXT("ERROR"), MB_OK);
                    }
                    else
                    {
                        // Go through all drag and dropped files.
                        for (int i = 0; i < fileNum; i++)
                        {
                            // Get the name of the file.
                            DragQueryFile(hDrop, i, file, size);

                            // That's why the whole
                            // project cannot work with UNICODE.
                            string fileName(file);

                            size_t dotPos = fileName.rfind(".");
                            if (dotPos == string::npos)
                            {
                                MessageBox(0, TEXT("File has bad extension."),
                                           TEXT("ERROR"), MB_OK);

                                break;
                            }

                            string name = fileName.substr(0, dotPos);
                            string ext = fileName.substr(dotPos);

                            keyEventProcessor->FileDropped(name, ext);
                        }
                    }

                    DragFinish(hDrop); // Release resources.
                }
            } return 0;

            case WM_LBUTTONDOWN:
            {
                size_t x = GET_X_LPARAM(lParam);
                size_t y = GET_Y_LPARAM(lParam);
                keyEventProcessor->LButtonDown(x, y);
            } return 0;

            case WM_LBUTTONUP:
            {
                size_t x = GET_X_LPARAM(lParam);
                size_t y = GET_Y_LPARAM(lParam);
                keyEventProcessor->LButtonUp(x, y);
            } return 0;

            case WM_MOUSEMOVE:
            {
                size_t x = GET_X_LPARAM(lParam);
                size_t y = GET_Y_LPARAM(lParam);
                keyEventProcessor->MouseMove(x, y);
            } return 0;

            case WM_DESTROY:
            {
                ::PostQuitMessage(0);
            } return 0;

            default:
                return DefWindowProc(hwnd, msg, wParam, lParam);
        }

        // Something is wrong.
        return true;
    }
Esempio n. 9
0
int XmlGspInterface::write(std::ostream& stream)
{
	GEOLIB::GEOObjects* geoObjects = _project->getGEOObjects();
	QFileInfo fi(QString::fromStdString(_filename));
	std::string path((fi.absolutePath()).toStdString() + "/");

	stream << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"; // xml definition
	stream << "<?xml-stylesheet type=\"text/xsl\" href=\"OpenGeoSysProject.xsl\"?>\n\n"; // stylefile definition

	QDomDocument doc("OGS-PROJECT-DOM");
	QDomElement root = doc.createElement("OpenGeoSysProject");
	root.setAttribute( "xmlns:ogs", "http://www.opengeosys.org" );
	root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" );
	root.setAttribute( "xsi:noNamespaceSchemaLocation", "http://www.opengeosys.org/images/xsd/OpenGeoSysProject.xsd" );

	doc.appendChild(root);

	// GLI
	std::vector<std::string> geoNames;
	geoObjects->getGeometryNames(geoNames);
	for (std::vector<std::string>::const_iterator it(geoNames.begin()); it != geoNames.end();
	     ++it)
	{
		// write GLI file
		XmlGmlInterface gml(_project, path + "OpenGeoSysGLI.xsd");
		std::string name(*it);
		gml.setNameForExport(name);
		if (gml.writeToFile(std::string(path + name + ".gml")))
		{
			// write entry in project file
			QDomElement geoTag = doc.createElement("geo");
			root.appendChild(geoTag);
			QDomElement fileNameTag = doc.createElement("file");
			geoTag.appendChild(fileNameTag);
			QDomText fileNameText = doc.createTextNode(QString::fromStdString(name + ".gml"));
			fileNameTag.appendChild(fileNameText);
		}
	}

	// MSH
	const std::map<std::string, MeshLib::CFEMesh*> msh_vec = _project->getMeshObjects();
	for (std::map<std::string, MeshLib::CFEMesh*>::const_iterator it(msh_vec.begin());
	     it != msh_vec.end(); ++it)
	{
		// write mesh file
		std::string fileName(path + it->first);
		FileIO::OGSMeshIO meshIO;
		meshIO.setMesh(it->second);
		meshIO.writeToFile(fileName);

		// write entry in project file
		QDomElement mshTag = doc.createElement("msh");
		root.appendChild(mshTag);
		QDomElement fileNameTag = doc.createElement("file");
		mshTag.appendChild(fileNameTag);
		QDomText fileNameText = doc.createTextNode(QString::fromStdString(it->first));
		fileNameTag.appendChild(fileNameText);
	}

	// STN
	std::vector<std::string> stnNames;
	geoObjects->getStationVectorNames(stnNames);
	for (std::vector<std::string>::const_iterator it(stnNames.begin()); it != stnNames.end();
	     ++it)
	{
		// write STN file
		XmlStnInterface stn(_project, path + "OpenGeoSysSTN.xsd");
		std::string name(*it);
		stn.setNameForExport(name);

		if (stn.writeToFile(path + name + ".stn"))
		{
			// write entry in project file
			QDomElement geoTag = doc.createElement("stn");
			root.appendChild(geoTag);
			QDomElement fileNameTag = doc.createElement("file");
			geoTag.appendChild(fileNameTag);
			QDomText fileNameText = doc.createTextNode(QString::fromStdString(name + ".stn"));
			fileNameTag.appendChild(fileNameText);
		}
		else
			std::cout << "XmlGspInterface::writeFile() -  Error writing file: " << name << "\n";
	}

	std::string xml = doc.toString().toStdString();
	stream << xml;
	return 1;
}
Esempio n. 10
0
void createCurveIcons()
{
    QDir dir(QDir::current());
    if (dir.dirName() == QLatin1String("debug") || dir.dirName() == QLatin1String("release")) {
        dir.cdUp();
    }
    dir.cdUp();
    dir.cdUp();
    dir.cdUp();
    QSize iconSize(128, 128);
    QPixmap pix(iconSize);
    QPainter painter(&pix);
    QLinearGradient gradient(0,0, 0, iconSize.height());
    gradient.setColorAt(0.0, QColor(240, 240, 240));
    gradient.setColorAt(1.0, QColor(224, 224, 224));
    QBrush brush(gradient);
    const QMetaObject &mo = QEasingCurve::staticMetaObject;
    QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type"));
    QFont oldFont = painter.font();
    // Skip QEasingCurve::Custom
    QString output(QString::fromAscii("%1/images").arg(dir.absolutePath()));
    printf("Generating images to %s\n", qPrintable(output));
    for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) {
        painter.setFont(oldFont);
        QString name(QLatin1String(metaEnum.key(i)));
        painter.fillRect(QRect(QPoint(0, 0), iconSize), brush);
        QEasingCurve curve((QEasingCurve::Type)i);
        painter.setPen(QColor(0, 0, 255, 64));
        qreal xAxis = iconSize.height()/1.5;
        qreal yAxis = iconSize.width()/3;
        painter.drawLine(0, xAxis, iconSize.width(),  xAxis); // hor
        painter.drawLine(yAxis, 0, yAxis, iconSize.height()); // ver

        qreal curveScale = iconSize.height()/2;

        painter.drawLine(yAxis - 2, xAxis - curveScale, yAxis + 2, xAxis - curveScale); // hor
        painter.drawLine(yAxis + curveScale, xAxis + 2, yAxis + curveScale, xAxis - 2); // ver
        painter.drawText(yAxis + curveScale - 8, xAxis - curveScale - 4, QLatin1String("(1,1)"));

        painter.drawText(yAxis + 42, xAxis + 10, QLatin1String("progress"));
        painter.drawText(15, xAxis - curveScale - 10, QLatin1String("value"));

        painter.setPen(QPen(Qt::red, 1, Qt::DotLine));
        painter.drawLine(yAxis, xAxis - curveScale, yAxis + curveScale, xAxis - curveScale); // hor
        painter.drawLine(yAxis + curveScale, xAxis, yAxis + curveScale, xAxis - curveScale); // ver

        QPoint start(yAxis, xAxis - curveScale * curve.valueForProgress(0));

        painter.setPen(Qt::black);
        QFont font = oldFont;
        font.setPixelSize(oldFont.pixelSize() + 15);
        painter.setFont(font);
        painter.drawText(0, iconSize.height() - 20, iconSize.width(), 20, Qt::AlignHCenter, name);

        QPainterPath curvePath;
        curvePath.moveTo(start);
        for (qreal t = 0; t <= 1.0; t+=1.0/curveScale) {
            QPoint to;
            to.setX(yAxis + curveScale * t);
            to.setY(xAxis - curveScale * curve.valueForProgress(t));
            curvePath.lineTo(to);
        }
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.strokePath(curvePath, QColor(32, 32, 32));
        painter.setRenderHint(QPainter::Antialiasing, false);

        QString fileName(QString::fromAscii("qeasingcurve-%1.png").arg(name.toLower()));
        printf("%s\n", qPrintable(fileName));
        pix.save(QString::fromAscii("%1/%2").arg(output).arg(fileName), "PNG");
    }
}
Esempio n. 11
0
void LatexDocVisitor::visit(DocVerbatim *s)
{
    if (m_hide) return;
    QCString lang = m_langExt;
    if (!s->language().isEmpty()) // explicit language setting
    {
        lang = s->language();
    }
    SrcLangExt langExt = getLanguageFromFileName(lang);
    switch(s->type())
    {
    case DocVerbatim::Code:
    {
        m_t << "\n\\begin{DoxyCode}\n";
        Doxygen::parserManager->getParser(lang)
        ->parseCode(m_ci,s->context(),s->text(),langExt,
                    s->isExample(),s->exampleFile());
        m_t << "\\end{DoxyCode}\n";
    }
    break;
    case DocVerbatim::Verbatim:
        m_t << "\\begin{DoxyVerb}";
        m_t << s->text();
        m_t << "\\end{DoxyVerb}\n";
        break;
    case DocVerbatim::HtmlOnly:
    case DocVerbatim::XmlOnly:
    case DocVerbatim::ManOnly:
    case DocVerbatim::RtfOnly:
    case DocVerbatim::DocbookOnly:
        /* nothing */
        break;
    case DocVerbatim::LatexOnly:
        m_t << s->text();
        break;
    case DocVerbatim::Dot:
    {
        static int dotindex = 1;
        QCString fileName(4096);

        fileName.sprintf("%s%d%s",
                         (Config_getString("LATEX_OUTPUT")+"/inline_dotgraph_").data(),
                         dotindex++,
                         ".dot"
                        );
        QFile file(fileName);
        if (!file.open(IO_WriteOnly))
        {
            err("Could not open file %s for writing\n",fileName.data());
        }
        else
        {
            file.writeBlock( s->text(), s->text().length() );
            file.close();

            startDotFile(fileName,s->width(),s->height(),s->hasCaption());
            visitCaption(this, s->children());
            endDotFile(s->hasCaption());

            if (Config_getBool("DOT_CLEANUP")) file.remove();
        }
    }
    break;
    case DocVerbatim::Msc:
    {
        static int mscindex = 1;
        QCString baseName(4096);

        baseName.sprintf("%s%d",
                         (Config_getString("LATEX_OUTPUT")+"/inline_mscgraph_").data(),
                         mscindex++
                        );
        QFile file(baseName+".msc");
        if (!file.open(IO_WriteOnly))
        {
            err("Could not open file %s.msc for writing\n",baseName.data());
        }
        else
        {
            QCString text = "msc {";
            text+=s->text();
            text+="}";
            file.writeBlock( text, text.length() );
            file.close();

            writeMscFile(baseName, s);

            if (Config_getBool("DOT_CLEANUP")) file.remove();
        }
    }
    break;
    case DocVerbatim::PlantUML:
    {
        QCString latexOutput = Config_getString("LATEX_OUTPUT");
        QCString baseName = writePlantUMLSource(latexOutput,s->exampleFile(),s->text());

        writePlantUMLFile(baseName, s);
    }
    break;
    }
}
void CStarNetServerThread::run()
{
    // Truncate the old StarNet.log file
    wxFileName fileName(m_logDir, STARNET_BASE_NAME, wxT("log"));
    wxLogMessage(wxT("Truncating %s"), fileName.GetFullPath().c_str());

    wxFFile file;
    bool ret = file.Open(fileName.GetFullPath(), wxT("wt"));
    if (ret)
        file.Close();

#if defined(DEXTRA_LINK)
    m_dextraHandler = new CDExtraProtocolHandler(DEXTRA_PORT, m_address);
    ret = m_dextraHandler->open();
    if (!ret) {
        wxLogError(wxT("Could not open the DExtra protocol handler"));
        delete m_dextraHandler;
        m_dextraHandler = NULL;
    }
#endif

#if defined(DCS_LINK)
    m_dcsHandler = new CDCSProtocolHandler(DCS_PORT, m_address);
    ret = m_dcsHandler->open();
    if (!ret) {
        wxLogError(wxT("Could not open the DCS protocol handler"));
        delete m_dcsHandler;
        m_dcsHandler = NULL;
    }
#endif

    m_g2Handler = new CG2ProtocolHandler(G2_DV_PORT, m_address);
    ret = m_g2Handler->open();
    if (!ret) {
        wxLogError(wxT("Could not open the G2 protocol handler"));
        delete m_g2Handler;
        m_g2Handler = NULL;
    }

    // Wait here until we have the essentials to run
#if defined(DEXTRA_LINK)
    while (!m_killed && (m_g2Handler == NULL || m_dextraHandler == NULL || m_irc == NULL || m_callsign.IsEmpty()))
        ::wxMilliSleep(500UL);		// 1/2 sec
#elif defined(DCS_LINK)
    while (!m_killed && (m_g2Handler == NULL || m_dcsHandler == NULL || m_irc == NULL || m_callsign.IsEmpty()))
        ::wxMilliSleep(500UL);		// 1/2 sec
#else
    while (!m_killed && (m_g2Handler == NULL || m_irc == NULL || m_callsign.IsEmpty()))
        ::wxMilliSleep(500UL);		// 1/2 sec
#endif

    if (m_killed)
        return;

    m_stopped = false;

    wxLogMessage(wxT("Starting the StarNet Server thread"));

    CHeaderLogger* headerLogger = NULL;
    if (m_logEnabled) {
        headerLogger = new CHeaderLogger(m_logDir);
        bool ret = headerLogger->open();
        if (!ret) {
            delete headerLogger;
            headerLogger = NULL;
        }
    }

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
    loadReflectors();
#endif

    CG2Handler::setG2ProtocolHandler(m_g2Handler);
    CG2Handler::setHeaderLogger(headerLogger);

#if defined(DEXTRA_LINK)
    CDExtraHandler::setCallsign(m_callsign);
    CDExtraHandler::setDExtraProtocolHandler(m_dextraHandler);
    CDExtraHandler::setHeaderLogger(headerLogger);
#endif
#if defined(DCS_LINK)
    CDCSHandler::setDCSProtocolHandler(m_dcsHandler);
    CDCSHandler::setHeaderLogger(headerLogger);
#endif

    CStarNetHandler::setCache(&m_cache);
    CStarNetHandler::setGateway(m_callsign);
    CStarNetHandler::setG2Handler(m_g2Handler);
    CStarNetHandler::setIRC(m_irc);
    CStarNetHandler::setLogging(m_logEnabled, m_logDir);
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
    CStarNetHandler::link();
#endif

    if (m_remoteEnabled && !m_remotePassword.IsEmpty() && m_remotePort > 0U) {
        m_remote = new CRemoteHandler(m_remotePassword, m_remotePort);
        bool res = m_remote->open();
        if (!res) {
            delete m_remote;
            m_remote = NULL;
        }
    }

    wxStopWatch stopWatch;
    stopWatch.Start();

    m_statusTimer.start();

    while (!m_killed) {
        processIrcDDB();
        processG2();
#if defined(DEXTRA_LINK)
        processDExtra();
#endif
#if defined(DCS_LINK)
        processDCS();
#endif
        if (m_remote != NULL)
            m_remote->process();

        unsigned long ms = stopWatch.Time();
        stopWatch.Start();

        m_statusTimer.clock(ms);

        CG2Handler::clock(ms);
        CStarNetHandler::clock(ms);
#if defined(DEXTRA_LINK)
        CDExtraHandler::clock(ms);
#endif
#if defined(DCS_LINK)
        CDCSHandler::clock(ms);
#endif

        ::wxMilliSleep(TIME_PER_TIC_MS);
    }

    wxLogMessage(wxT("Stopping the StarNet Server thread"));

#if defined(DEXTRA_LINK)
    // Unlink from all reflectors
    CDExtraHandler::unlink();

    m_dextraHandler->close();
    delete m_dextraHandler;
#endif

#if defined(DCS_LINK)
    // Unlink from all reflectors
    CDCSHandler::unlink();

    m_dcsHandler->close();
    delete m_dcsHandler;
#endif

    m_g2Handler->close();
    delete m_g2Handler;

    m_irc->close();
    delete m_irc;

    if (m_remote != NULL) {
        m_remote->close();
        delete m_remote;
    }

    if (headerLogger != NULL) {
        headerLogger->close();
        delete headerLogger;
    }
}
Esempio n. 13
0
 long long Database::fileSize() const {
     long long size=0;
     for (int n=0; exists(n); n++)
         size += boost::filesystem::file_size( fileName(n) );
     return size;
 }
Esempio n. 14
0
 bool Database::exists(int n) const { 
     return boost::filesystem::exists( fileName( n ) ); 
 }
Esempio n. 15
0
int 
main(int argc, char** argv)
{
    try {
        int offset = 96;
        int height = 96;
        int width;
        int heightCount = 8;
        int frame = 0;
        int frameCount = 10;
        
        if (argc < 2) {
            std::cerr <<
                "Usage: squareWheel fileName frame offset frameCount repeat height\n";
            throw EXIT_FAILURE;
        }
        std::string fileName(argv[1]);
        if (argc > 2)
            frame = eval(argv[2]);
        if (argc > 3)
            offset = eval(argv[3]);
        if (argc > 4)
            frameCount = eval(argv[4]);
        if (argc > 5)
            heightCount = eval(argv[5]);
        if (argc > 6)
            height = eval(argv[6]);
  
        if (frameCount < 1 || frame < 0 || frame >= frameCount) {
            std::cerr << frame << "/" << frameCount << " not a valid image.\n";
            throw EXIT_FAILURE;
        }

        if (offset < 0 || offset >= height) {
            std::cerr << "Offset should be between 0 and " << height << '\n';
            throw EXIT_FAILURE;
        }
        
        // total width of the image
        width = height*(heightCount+2);

        Image image(width, height);

        // half of the square side
        double D = height*0.45;
        double R = D/sqrt(2.0);

        // the period
        int period = 2*R*log(1 + sqrt (2.0));

        // draw the road
        for (int s = 0; s < period; ++s) {
            double x = s - period/2;
            double y = height/2-R*cosh(x/R);
            for (int i = s; i < width; i += period) {
                image.line(i, 0, i, y, 1);
            }
        }

        // draw the squares
        double alpha = 2*pi*frame/frameCount;
        int start = 0;
        while (alpha > pi/4) {
            alpha -= pi/2;
            start++;
        }
        double y = height/2-R/cos(alpha);
        double x = R*log((1+sin(alpha))/cos(alpha))+period/2;
        double dy1 = D*cos(alpha+pi/4);
        double dx1 = D*sin(alpha+pi/4);
        double dy2 = D*cos(alpha+3*pi/4);
        double dx2 = D*sin(alpha+3*pi/4);
        for (int i = start; i < width/period+1; i+=4) {
            double cx = x + i*period;
            double cy = height/2;
            image.line(cx+dx1, cy+dy1, cx+dx2, cy+dy2, 2);
            image.line(cx+dx2, cy+dy2, cx-dx1, cy-dy1, 2);
            image.line(cx-dx1, cy-dy1, cx-dx2, cy-dy2, 2);
            image.line(cx-dx2, cy-dy2, cx+dx1, cy+dy1, 2);
            image.fill(cx, cy, 2);
            image.plot(cx, cy, 1);
            image.plot(cx, cy+1, 1);
            image.plot(cx+1, cy, 1);
            image.plot(cx+1, cy+1, 1);
        }
        
        image.saveAsPPM(fileName.c_str(),
                        offset, 0,
                        offset+height*heightCount, height);
    } catch (int status) {
        return status;
    }
}
Esempio n. 16
0
void RTFDocVisitor::visit(DocVerbatim *s)
{
  if (m_hide) return;
  DBG_RTF("{\\comment RTFDocVisitor::visit(DocVerbatim)}\n");
  QCString lang = m_langExt;
  if (!s->language().isEmpty()) // explicit language setting
  {
    lang = s->language();
  }
  SrcLangExt langExt = getLanguageFromFileName(lang);
  switch(s->type())
  {
    case DocVerbatim::Code: // fall though
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      Doxygen::parserManager->getParser(lang)
                            ->parseCode(m_ci,s->context(),s->text(),langExt,
                                        s->isExample(),s->exampleFile());
      //m_t << "\\par" << endl; 
      m_t << "}" << endl;
      break;
    case DocVerbatim::Verbatim: 
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      filter(s->text(),TRUE);
      //m_t << "\\par" << endl; 
      m_t << "}" << endl;
      break;
    case DocVerbatim::RtfOnly: 
      m_t << s->text(); 
      break;
    case DocVerbatim::HtmlOnly: 
    case DocVerbatim::LatexOnly: 
    case DocVerbatim::XmlOnly: 
    case DocVerbatim::ManOnly:
    case DocVerbatim::DocbookOnly:
      /* nothing */
      break;
    case DocVerbatim::Dot: 
      {
        static int dotindex = 1;
        QCString fileName(4096);

        fileName.sprintf("%s%d%s", 
            (Config_getString(RTF_OUTPUT)+"/inline_dotgraph_").data(), 
            dotindex++,
            ".dot"
           );
        QFile file(fileName);
        if (!file.open(IO_WriteOnly))
        {
          err("Could not open file %s for writing\n",fileName.data());
        }
        file.writeBlock( s->text(), s->text().length() );
        file.close();

        writeDotFile(fileName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());

        if (Config_getBool(DOT_CLEANUP)) file.remove();
      }
      break;
    case DocVerbatim::Msc: 
      {
        static int mscindex = 1;
        QCString baseName(4096);

        baseName.sprintf("%s%d%s",
            (Config_getString(RTF_OUTPUT)+"/inline_mscgraph_").data(), 
            mscindex++,
            ".msc"
           );
        QFile file(baseName);
        if (!file.open(IO_WriteOnly))
        {
          err("Could not open file %s for writing\n",baseName.data());
        }
        QCString text = "msc {";
        text+=s->text();
        text+="}";
        file.writeBlock( text, text.length() );
        file.close();

        writeMscFile(baseName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());

        if (Config_getBool(DOT_CLEANUP)) file.remove();
      }
      break;
    case DocVerbatim::PlantUML:
      {
        static QCString rtfOutput = Config_getString(RTF_OUTPUT);
        QCString baseName = writePlantUMLSource(rtfOutput,s->exampleFile(),s->text());

        writePlantUMLFile(baseName, s->hasCaption());
        visitCaption(this, s->children());
        includePicturePostRTF(true, s->hasCaption());
      }
      break;
  }
  m_lastIsPara=FALSE;
}
Esempio n. 17
0
QString DatabaseUrl::name() const
{
    // do not ignore trailing slash in the path - albums have a trailing slash
    return fileName(KUrl::ObeyTrailingSlash);
}
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
        QDesignerWidgetBoxInterface *widgetBox = 0:
        widgetBox = formEditor->widgetBox();

        widgetBox->load();
//! [0]


//! [1]
        QString originalFile = widgetBox->fileName();

        widgetBox->setFileName("myWidgetBox.xml");
        widgetBox->save();
//! [1]


//! [2]
        widgetBox->setFileName(originalFile);
        widgetBox->load();
//! [2]


//! [3]
        if (widgetBox->filename() != "myWidgetBox.xml") {
            widgetBox->setFileName("myWidgetBox.xml");
Esempio n. 19
0
bool SpatialAverageSpotter::train(string dirPath)
{
    
    int count=0;
    vector<vector<tuple<int,Point2f> > > features;
    featureAverages.resize(codebook->size());
    for (int i =0; i<codebook->size(); i++)
        featureAverages[i]=Mat(BASE_SIZE,BASE_SIZE,CV_32F,Scalar(0));
    
    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir (dirPath.c_str())) != NULL) {
      /* print all the files and directories within directory */
//      Mat img;
      while ((ent = readdir (dir)) != NULL) {
          
          string fileName(ent->d_name);
//          cout << "examining " << fileName << endl;
          if (fileName[0] == '.' || fileName[fileName.size()-1]!='G')
              continue;
          
          Mat img = imread(dirPath+fileName, CV_LOAD_IMAGE_GRAYSCALE);
//          resize(img,img,Size(0,0),2,2);
          threshold(img,img,120.0,255,THRESH_BINARY);
//          windowWidth += img.cols;
//          windowHeight += img.rows;
//          int avg=0;
//          for (int x=0; x<img.cols; x++)
//              for (int  y=0; y<img.rows; y++)
//                  avg += (int)img.at<unsigned char>(y,x);
////          cout << "avg="<<avg<<"/"<<img.cols*img.rows<<" = "<<avg/(img.cols*img.rows)<<endl;
//          avg /= img.cols*img.rows;
          
          resize(img,img,Size(PRE_BASE_SIZE,PRE_BASE_SIZE*((0.0+img.rows)/img.cols)));
          
          
          copyMakeBorder( img, img, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_CONSTANT, 255 );
          assert(img.cols > 1 && img.rows > 1);
          adjustedTrainingImages.push_back(img.clone());
          
          Point2f centerOfMass = findCenterOfMass(img);
          int offsetx=(img.cols/2)-centerOfMass.x;
          int offsety=(img.rows/2)-centerOfMass.y;
          translateImg(img,offsetx,offsety);
          
        
          vector<KeyPoint> keypoints;
          Mat desc;
          detectKeypoints( img,keypoints, desc);
          Mat out;
          cvtColor(img,out,CV_GRAY2RGB);
          circle(out,centerOfMass,1,Scalar(0,0,255));
          
          features.resize(count+1);
          //double scaling = BASE_SIZE/img
          for (int r=0; r<desc.rows; r++)
          {
              int f = codebook->quantize(desc.row(r));
              Point2f offsetPoint(keypoints[r].pt.x - centerOfMass.x, keypoints[r].pt.y - centerOfMass.y);
              features[count].push_back(make_tuple(f,offsetPoint));//we're ignoring the keypoint scale.. 
              
              
//              circle(out,keypoints[r].pt,keypoints[r].size,Scalar(colorTable[f]));
              Rect rec(keypoints[r].pt.x-(keypoints[r].size/2),keypoints[r].pt.y-(keypoints[r].size/2),keypoints[r].size,keypoints[r].size);
              rectangle(out,rec,Scalar(colorTable[f]));
              
          }
          guassColorIn(features[count]);
          
          
          imshow("learning keypoints",out);
          cout << "image "<<count<<endl;
          waitKey(5);
          
          count++;
//          img.release();
      }
      closedir (dir);
    } else {
      /* could not open directory */
      perror ("");
      return false;
    }
    
    //We now step through adjusting the scales of the various images so the guass coloring is maximized
    //But we may still want to look at tfidf to see which ones should be weighted more, etc.
    maximizeAlignment(features);
    
    float max=0;
    float min =99999;
    float avg_max=0;
    
    int firstx=9999;
    int lastx=0;
    int firsty=9999;
    int lasty=0;
    
    for (int f=0; f<codebook->size(); f++)
    {
        float local_max=0;
        
        bool hitFirst=false;
        
        for (int x=0; x<featureAverages[f].cols; x++)
            for (int y=0; y<featureAverages[f].rows; y++)
            {
                float val = featureAverages[f].at<float>(y,x);
                if (val > 300 || val < -300)
                    cout << "val (" << x <<","<<y<<") " << val << endl;
                if (val>max) max=val;
                if (val<min) min=val;
                if (val>local_max) local_max=val;
                
                if (val>WINDOW_THRESH)
                {
                    if (!hitFirst)
                    {
                        hitFirst=true;
                        if (x<firstx) firstx=x;
                        if (y<firsty) firsty=y;
                    }
                    if (x>lastx) lastx=x;
                    if (y>lasty) lasty=y;
                }
            }
        avg_max+=local_max;
    }
//    penalty=min+(max-min)*.2;
    avg_max /= codebook->size();
    penalty=avg_max*.15;//.2
    
//    windowWidth/=count;
//    windowHeight/=count;
    windowWidth = lastx-firstx;
    windowHeight = lasty-firsty;
    cout << "window size is "<<windowWidth<<"x"<<windowHeight<<endl;
    
    //show averages
    showAverages();
    
    return true;
}
Esempio n. 20
0
// Class functions.
TPresError
TGUIView::SetStyle( const char  *inStyleName )
{
  // Load the colors and widths of view elements from a bitmap resource or file.
  // The rows of the bitmap represent the elements in the order given by
  // the TGUIElements enumeration in GUI.h. An element's width is taken
  // by counting the number of pixels in its row that have the same color
  // as the leftmost one.

  if( inStyleName == NULL || *inStyleName == '\0' )
    return presNoError;

  TPresError  result = presNoError;
  Graphics::TBitmap   *bitmap = new Graphics::TBitmap();

  std::string fileName( inStyleName );
  for( std::string::iterator i = fileName.begin(); i != fileName.end(); ++i )
    *i = toupper( *i );
  fileName += ".BMP";

  // Look for a bitmap resource for the style given.
  try
  {
    bitmap->LoadFromResourceName( ( int )HInstance, fileName.c_str() );
  }
  catch( const EResNotFound& )
  {
    result = presResNotFoundError;
  }

  // No resource found, look for a bitmap file in the application default path.
  if( result == presResNotFoundError )
  {
    result = presNoError;
    try
    {
      bitmap->LoadFromFile( fileName.c_str() );
    }
    catch( ... )
    {
      result = presFileOpeningError;
    }
  }

  // No file found, look in the resource directory.
  if( result == presFileOpeningError )
  {
    result = presNoError;

    Util::TPath curPath;
    fileName = curPath + fileName;

    try
    {
      bitmap->LoadFromFile( fileName.c_str() );
    }
    catch( ... )
    {
      result = presFileOpeningError;
      gPresErrors.AddError( result, fileName.c_str() );
    }
  }

  if( result == presNoError )
  {
    for( int i = 0; i < MIN( int( numGUIElements ), bitmap->Height ); ++i )
    {
      TColor  curColor = bitmap->Canvas->Pixels[ 0 ][ i ];
      ElementColors[ i ].cl = curColor;
      int j = 0;
      while( j < bitmap->Width && bitmap->Canvas->Pixels[ j ][ i ] == curColor )
        ++j;
      ElementWidths[ i ] = j;
    }
  }

  delete bitmap;
  return result;
}
void DebugLogger::StartDebug() {
  #pragma pack(push)
  #pragma pack(1)
  struct RecordData {
    char            appVersion[16];
    char            sn[SERIAL_NUMBER_LENGTH];
    char            op[64];
    char            offline;
	char			modelID[4];
	char			terminalID[200];
    char            firmwareVersion[FIRMWARE_VERSION_LENGTH];
    int             selfTestState;
    int             debugState[16];
	char			mac[20];
  };
  #pragma pack(pop)

  if (logFile_.m_hFile != INVALID_HANDLE_VALUE) {
    logFile_.Close();
  }

  // 根据可变配置文件中的配置项决定是否上传数据 lux
  VariableConfigBlock *config = WorkingParameters::GetInstance()->GetCurrentConfigParameters();
  int uploadLevel = config->GetIntParameter(_T("UploadLevel"), 1);
  if (uploadLevel == 0)
  {
	  return;
  }

  DeviceInfo deviceInfo;
  if (!DeviceProxy::GetInstance()->GetDeviceInfo(&deviceInfo)) {
    return;
  }

  CString fileName(logPath_);
  fileName.AppendChar(_T('\\'));
  for (int i = 0; i < _countof(deviceInfo.sn) && deviceInfo.sn[i] != '\0'; i++) {
    char ch = deviceInfo.sn[i];
    if (ch == ' ' || 
        ch == '\\' || 
        ch == '//' ||
        ch == ':' ||
        ch == '*' || 
        ch == '|' || 
        ch == '?' || 
        ch == '<' || 
        ch == '>') {
      fileName.AppendChar(_T('_'));
    } else {
      fileName.AppendChar(ch);
    }
  }
  fileName.AppendChar(_T('_'));   
  SYSTEMTIME now;
  GetLocalTime(&now);
  fileName.AppendFormat(_T("%04d%02d%02d_%02d%02d%02d.dat"), 
      (int)now.wYear, (int)now.wMonth, (int)now.wDay, 
      (int)now.wHour, (int)now.wMinute, (int)now.wSecond);

  try {
    logFile_.Open(fileName, CFile::typeBinary | CFile::modeCreate | CFile::shareExclusive | CFile::modeWrite);
  } catch (CFileException *e) {
    e->Delete();
  }

  RecordData data;
  ZeroMemory(&data, sizeof(data));
  CString appVersion = AfxGetApp()->GetProfileString(_T(""), _T("Version"));
  strncpy(data.appVersion, CT2A(appVersion, CP_UTF8), _countof(data.appVersion));
  strncpy(data.sn, deviceInfo.sn, _countof(data.sn));
  strncpy(data.op, CT2A(WorkingParameters::GetInstance()->GetUserName(), CP_UTF8), _countof(data.op));
  int curID = WorkingParameters::GetInstance()->GetCurrentModelId();
  strncpy(data.modelID, (char *)&curID, _countof(data.modelID));
  TCHAR terminalID[200] = { 0 };
  GetTerminalID(terminalID);
  strncpy(data.terminalID, CT2A(terminalID, CP_UTF8), _countof(data.terminalID));
  strncpy(data.firmwareVersion, deviceInfo.firmwareVersion, _countof(data.firmwareVersion));
  data.offline = WorkingParameters::GetInstance()->IsOffline() ? 1 : 0;
  data.selfTestState = deviceInfo.selfTestState;
  ASSERT(sizeof(data.debugState) == sizeof(deviceInfo.debugState));
  memcpy(data.debugState, deviceInfo.debugState, sizeof(data.debugState));
  if (!DeviceProxy::GetInstance()->GetMacAddr(data.mac, _countof(data.mac)))
  {
	  memset(data.mac, 0, _countof(data.mac));
  }

  WriteRecord("SDG ", &data, sizeof(data));
}
Esempio n. 22
0
int main (int argc, char** argv)
{
  std::vector<coral::Option> secondaryOptions;
  //
  coral::Option csPar("conn_string");
  csPar.flag = "-c";
  csPar.helpEntry = "the database connection string";
  csPar.type = coral::Option::STRING;
  secondaryOptions.push_back(csPar);
  //
  coral::Option contPar("container");
  contPar.flag = "-cn";
  contPar.helpEntry = "the selected container name";
  contPar.type = coral::Option::STRING;
  secondaryOptions.push_back(contPar);
  //
  coral::Option mvPar("mapping_version");
  mvPar.flag = "-mv";
  mvPar.helpEntry ="the mapping version";
  mvPar.type = coral::Option::STRING;
  secondaryOptions.push_back(mvPar);
  //
  coral::Option cvPar("class_versions");
  cvPar.flag = "-cv";
  cvPar.helpEntry ="specify the class versions";
  cvPar.type = coral::Option::BOOLEAN;
  secondaryOptions.push_back(cvPar);
  //
  coral::Option outPar("output_file");
  outPar.flag = "-f";
  outPar.helpEntry = "the database host name";
  outPar.type = coral::Option::STRING;
  secondaryOptions.push_back(outPar);
  //
  coral::Option authPar("authentication_path");
  authPar.flag = "-a";
  authPar.helpEntry = "the authentication path";
  authPar.type = coral::Option::STRING;
  secondaryOptions.push_back(authPar);
  //
  coral::Option classPar("type_name");
  classPar.flag = "-t";
  classPar.helpEntry = "the container type name";
  classPar.type = coral::Option::STRING;
  secondaryOptions.push_back(classPar);
  //
  coral::Option dictPar("dictionary");
  dictPar.flag = "-D";
  dictPar.helpEntry = "the list of dictionary libraries";
  dictPar.type = coral::Option::STRING;
  secondaryOptions.push_back(dictPar);
  //
  coral::Option debugPar("debug");
  debugPar.flag = "-debug";
  debugPar.helpEntry ="print the debug messages";
  debugPar.type = coral::Option::BOOLEAN;
  secondaryOptions.push_back(debugPar);
  //
  std::vector<coral::Command> mainSet;
  //
  coral::Command listCont("list_containers");
  listCont.flag = "-list";
  listCont.helpEntry = "listing the available containers";
  listCont.type = coral::Option::BOOLEAN;
  listCont.exclusive = true;
  listCont.addOption(csPar.name);
  listCont.addOption(authPar.name);
  listCont.addOption(debugPar.name);
  mainSet.push_back(listCont);
  //
  coral::Command createCont("create");
  createCont.flag = "-create";
  createCont.helpEntry = "create a database or a container";
  createCont.type = coral::Option::BOOLEAN;
  createCont.exclusive = true;
  createCont.addOption(csPar.name);
  createCont.addOption(contPar.name);
  createCont.addOption(classPar.name);
  createCont.addOption(dictPar.name);
  createCont.addOption(authPar.name);
  createCont.addOption(debugPar.name);
  mainSet.push_back(createCont);
  //
  coral::Command eraseCont("erase");
  eraseCont.flag = "-erase";
  eraseCont.helpEntry = "erase a database or a container";
  eraseCont.type = coral::Option::BOOLEAN;
  eraseCont.exclusive = true;
  eraseCont.addOption(csPar.name);
  eraseCont.addOption(contPar.name);
  eraseCont.addOption(authPar.name);
  eraseCont.addOption(debugPar.name);
  mainSet.push_back(eraseCont);
  //
  coral::Command listMapp("list_mappings");
  listMapp.flag = "-lm";
  listMapp.helpEntry = "listing the available mapping versions";
  listMapp.type = coral::Option::BOOLEAN;
  listMapp.exclusive = true;
  listMapp.addOption(csPar.name);
  listMapp.addOption(contPar.name);
  listMapp.addOption(cvPar.name);
  listMapp.addOption(authPar.name);
  listMapp.addOption(debugPar.name);
  mainSet.push_back(listMapp);
  //
  coral::Command dumpMapp("dump_mapping");
  dumpMapp.flag = "-dm";
  dumpMapp.helpEntry = "dump the specified mapping in xml format";
  dumpMapp.type = coral::Option::BOOLEAN;
  dumpMapp.exclusive = true;
  dumpMapp.addOption(csPar.name);
  dumpMapp.addOption(mvPar.name);
  dumpMapp.addOption(outPar.name);
  dumpMapp.addOption(authPar.name);
  dumpMapp.addOption(debugPar.name);
  mainSet.push_back(dumpMapp);
  //
  try{
    edmplugin::PluginManager::Config config;
    edmplugin::PluginManager::configure(edmplugin::standard::config());
  
    std::vector<edm::ParameterSet> psets;
    edm::ParameterSet pSet;
    pSet.addParameter("@service_type",std::string("SiteLocalConfigService"));
    psets.push_back(pSet);
    static const edm::ServiceToken services(edm::ServiceRegistry::createSet(psets));
    static const edm::ServiceRegistry::Operate operate(services);

    std::string connectionString("");
    std::string authenticationPath("CORAL_AUTH_PATH=");
    std::string containerName("");
    std::string mappingVersion("");
    std::string fileName("");
    std::string className("");
    std::string dictionary("");
    bool withClassVersion = false;
    bool debug = false;
    coral::CommandLine cmd(secondaryOptions,mainSet);
    cmd.parse(argc,argv);
    const std::map<std::string,std::string>& ops = cmd.userOptions();
    if(cmd.userCommand()==coral::CommandLine::helpOption().name || ops.size()==0){
      cmd.help(std::cout);
      return 0;
    } else {
      std::map<std::string,std::string>::const_iterator iO=ops.find(coral::CommandLine::helpOption().name);
      if(iO!=ops.end()){
        cmd.help(cmd.userCommand(),std::cout);
        return 0;
      } else {
        iO = ops.find(csPar.name);
        if(iO!=ops.end()) {
          connectionString = iO->second;
        } else {
          throw coral::MissingRequiredOptionException(csPar.name);
        }
        iO = ops.find(contPar.name);
        if(iO!=ops.end()) containerName = iO->second;
        iO = ops.find(mvPar.name);
        if(iO!=ops.end()) mappingVersion = iO->second;
        iO = ops.find(authPar.name);
        if(iO!=ops.end()) {
          authenticationPath.append(iO->second);
          ::putenv( (char*)authenticationPath.c_str() );
        }
        iO = ops.find(outPar.name);
        if(iO!=ops.end()) fileName = iO->second;
        iO = ops.find(classPar.name);
        if(iO!=ops.end()) className = iO->second;
        iO = ops.find(dictPar.name);
        if(iO!=ops.end()) dictionary = iO->second;
        iO = ops.find(cvPar.name);
        if(iO!=ops.end()) withClassVersion = true;
        iO = ops.find(debugPar.name);
        if(iO!=ops.end()) debug = true;

        boost::shared_ptr<ora::ConnectionPool> connection( new ora::ConnectionPool );
        connection->configuration().disablePoolAutomaticCleanUp();
        ora::Database db( connection );
        if( debug ) db.configuration().setMessageVerbosity( coral::Debug );

        std::string contTag("container.name");
        std::string classTag("type");
        std::string nobjTag("n.objects");
        std::string mapVerTag("mapping.id");
        std::string classVerTag("class.version");
        std::string space("  ");
        size_t contMax = contTag.length();
        size_t classMax = classTag.length();
        size_t nobjMax = nobjTag.length();
        size_t mapVerMax = mapVerTag.length();
        size_t classVerMax = classVerTag.length();

        if(cmd.userCommand()==listCont.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( ! db.exists() ){
	    std::cout << "ORA database does not exists in \""<<connectionString<<"\"."<<std::endl;
	    return 0;
	  }
          std::set<std::string> conts = db.containers();

          std::cout << "ORA database in \""<<connectionString<<"\" has "<<conts.size()<<" container(s)."<<std::endl;
          std::cout <<std::endl;
          if( conts.size() ){
            // first find the max lenghts
            for(std::set<std::string>::const_iterator iC = conts.begin(); iC != conts.end(); ++iC ){
              ora::Container cont = db.containerHandle( *iC );
              if(cont.name().length()>contMax ) contMax = cont.name().length();
              if(cont.className().length()>classMax ) classMax = cont.className().length();
            }
            std::cout << std::setiosflags(std::ios_base::left);
            std::cout <<space<<std::setw(contMax)<<contTag;
            std::cout <<space<<std::setw(classMax)<<classTag;
            std::cout <<space<<std::setw(nobjMax)<<nobjTag;
            std::cout <<std::endl;
            
            std::cout <<space<<std::setfill('-');
            std::cout<<std::setw(contMax)<<"";
            std::cout <<space<<std::setw(classMax)<<"";
            std::cout <<space<<std::setw(nobjMax)<<"";
            std::cout <<std::endl;

            std::cout << std::setfill(' ');
            for(std::set<std::string>::const_iterator iC = conts.begin(); iC != conts.end(); ++iC ){
              ora::Container cont = db.containerHandle( *iC );
              std::cout <<space<<std::setw(contMax)<<cont.name();
              std::cout <<space<<std::setw(classMax)<<cont.className();
              std::stringstream ss;
              ss << std::setiosflags(std::ios_base::right);
              ss <<space<<std::setw(nobjMax)<<cont.size();
              std::cout << ss.str();
              std::cout <<std::endl;
            }
          }
          
          transaction.commit();
          return 0;
        }
        if(cmd.userCommand()==createCont.name){
	  db.connect( connectionString );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start(false);
          if( className.empty() ){
            throw coral::MissingRequiredOptionException(classPar.name);
          }
          if( !dictionary.empty() ){
	    ora::SharedLibraryName libName;
            edmplugin::SharedLibrary shared( libName(dictionary)  );
          }
          if( !db.exists() ){
            db.create();
          } else {
            std::set<std::string> conts = db.containers();
            if( conts.find( containerName )!=conts.end() ){
              std::cout << "ERROR: container \"" << containerName << "\" already exists in the database."<<std::endl;
              return -1;
            }
          }
          db.createContainer( className, containerName );
          transaction.commit();
          return 0;
        }
        if(cmd.userCommand()==eraseCont.name){
	  db.connect( connectionString );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start(false);
          if( containerName.empty() ){
            throw coral::MissingRequiredOptionException(contPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            std::set<std::string> conts = db.containers();
            if( conts.find( containerName )==conts.end() ){
              std::cout << "ERROR: container \"" << containerName << "\" does not exists in the database."<<std::endl;
              return -1;
            }
            db.dropContainer( containerName );
            transaction.commit();
            return 0;
          }
        }
        if(cmd.userCommand()==listMapp.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( containerName.empty() ){
            throw coral::MissingRequiredOptionException(contPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            ora::DatabaseUtility util = db.utility();
            if(withClassVersion){
              std::map<std::string,std::string> vers = util.listMappings( containerName );

              std::cout << "ORA database in \""<<connectionString<<"\" has "<<vers.size()<<" class version(s) for container \""<<containerName<<"\"."<<std::endl;
              std::cout <<std::endl;
              if( vers.size() ){
                // first find the max lenghts
                for( std::map<std::string,std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  if( iM->first.length() > classVerMax ) classVerMax = iM->first.length();
                  if( iM->second.length() > mapVerMax ) mapVerMax = iM->second.length();
                }

                std::cout << std::setiosflags(std::ios_base::left);
                std::cout <<space<<std::setw(classVerMax)<<classVerTag;
                std::cout <<space<<std::setw(mapVerMax)<<mapVerTag;
                std::cout <<std::endl;

                std::cout <<space<<std::setfill('-');
                std::cout<<std::setw(classVerMax)<<"";
                std::cout <<space<<std::setw(mapVerMax)<<"";
                std::cout <<std::endl;

                std::cout << std::setfill(' ');
                for( std::map<std::string,std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  std::cout <<space<<std::setw(classVerMax)<<iM->first;
                  std::cout <<space<<std::setw(mapVerMax)<<iM->second;
                  std::cout <<std::endl;
                }
              }              
            } else {
              std::set<std::string> vers = util.listMappingVersions( containerName );

              std::cout << "ORA database in \""<<connectionString<<"\" has "<<vers.size()<<" mapping version(s) for container \""<<containerName<<"\"."<<std::endl;
              std::cout <<std::endl;
              if( vers.size() ){
                // first find the max lenghts
                for( std::set<std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  if( iM->length() > mapVerMax ) mapVerMax = iM->length();
                }

                std::cout << std::setiosflags(std::ios_base::left);
                std::cout <<space<<std::setw(mapVerMax)<<mapVerTag;
                std::cout <<std::endl;

                std::cout <<space<<std::setfill('-');
                std::cout <<std::setw(mapVerMax)<<"";
                std::cout <<std::endl;

                std::cout << std::setfill(' ');
                for( std::set<std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  std::cout <<space<<std::setw(mapVerMax)<<*iM;
                  std::cout <<std::endl;
                }
              }
            }
            transaction.commit();
            return 0;
          }
        }
        if(cmd.userCommand()==dumpMapp.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( mappingVersion.empty() ){
            throw coral::MissingRequiredOptionException(mvPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            ora::DatabaseUtility util = db.utility();
            std::auto_ptr<std::fstream> file;
            std::ostream* outputStream = &std::cout;
            if( !fileName.empty() ){
              file.reset(new std::fstream);
              file->open( fileName.c_str(),std::fstream::out );
              outputStream = file.get();
            }
            bool dump = util.dumpMapping( mappingVersion, *outputStream );
            if(!dump){
              std::cout << "Mapping with id=\""<<mappingVersion<<"\" has not been found in the database."<<std::endl;
            }
            if( !fileName.empty() ){
              if( dump ) std::cout << "Mapping with id=\""<<mappingVersion<<"\" dumped in file =\""<<fileName<<"\""<<std::endl;
              file->close();
            }
            transaction.commit();
            return 0;
          }
        }
      }
    }

  } catch (const std::exception& e){
    std::cout << "ERROR: " << e.what() << std::endl;
    return -1;
  } catch (...){
    std::cout << "UNEXPECTED FAILURE." << std::endl;
    return -1;
  }
}
Esempio n. 23
0
CRepeaterDataSet::CRepeaterDataSet(wxWindow* parent, int id, const wxString& title, const wxString& band, HW_TYPE type, const wxString& address, unsigned int port, unsigned char band1, unsigned char band2, unsigned char band3, bool dplusEnabled, bool dExtraEnabled, bool dcsEnabled, const wxString& reflector, bool atStartup, RECONNECT reconnect) :
wxPanel(parent, id),
m_title(title),
m_band(NULL),
m_type(NULL),
m_address(NULL),
m_port(NULL),
m_band1(NULL),
m_band2(NULL),
m_band3(NULL),
m_reflector(NULL),
m_channel(NULL),
m_startup(NULL),
m_reconnect(NULL)
{
	wxFlexGridSizer* sizer = new wxFlexGridSizer(3);

	wxStaticText* bandLabel = new wxStaticText(this, -1, _("Band"));
	sizer->Add(bandLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_band = new wxChoice(this, CHOICE_BAND, wxDefaultPosition, wxSize(CONTROL_WIDTH2, -1));
	m_band->Append(_("None"));
	m_band->Append(wxT("A"));
	m_band->Append(wxT("B"));
	m_band->Append(wxT("C"));
	m_band->Append(wxT("D"));
	m_band->Append(wxT("E"));
	m_band->Append(wxT("AD"));
	m_band->Append(wxT("BD"));
	m_band->Append(wxT("CD"));
	m_band->Append(wxT("DD"));
	m_band->Append(wxT("ED"));
	sizer->Add(m_band, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	bool res = m_band->SetStringSelection(band);
	if (!res)
		m_band->SetSelection(0);

	wxStaticText* dummy1Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy1Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* hardwareTypeLabel = new wxStaticText(this, -1, _("Type"));
	sizer->Add(hardwareTypeLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_type = new wxChoice(this, CHOICE_TYPE, wxDefaultPosition, wxSize(CONTROL_WIDTH1, -1));
	m_type->Append(_("Homebrew"));
	m_type->Append(wxT("Icom"));
	m_type->Append(_("Dummy"));
	sizer->Add(m_type, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_type->SetSelection(int(type));

	wxStaticText* dummy2Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy2Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* addressLabel = new wxStaticText(this, -1, _("Address"));
	sizer->Add(addressLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_address = new CAddressTextCtrl(this, -1, address, wxDefaultPosition, wxSize(CONTROL_WIDTH1, -1));
	m_address->SetMaxLength(ADDRESS_LENGTH);
	sizer->Add(m_address, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);

	wxStaticText* dummy3Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy3Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* portLabel = new wxStaticText(this, -1, _("Port"));
	sizer->Add(portLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxString buffer;
	buffer.Printf(wxT("%u"), port);

	m_port = new CPortTextCtrl(this, -1, buffer, wxDefaultPosition, wxSize(CONTROL_WIDTH2, -1));
	m_port->SetMaxLength(PORT_LENGTH);
	sizer->Add(m_port, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);

	wxStaticText* dummy4Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy4Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* icomBandsLabel = new wxStaticText(this, -1, _("Bands"));
	sizer->Add(icomBandsLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxBoxSizer* bandSizer = new wxBoxSizer(wxHORIZONTAL);

	buffer.Printf(wxT("%u"), band1);
	m_band1 = new CPortTextCtrl(this, -1, buffer, wxDefaultPosition, wxSize(CONTROL_WIDTH3, -1));
	m_band1->SetMaxLength(2U);
	bandSizer->Add(m_band1, 0, wxALIGN_LEFT, BORDER_SIZE);

	buffer.Printf(wxT("%u"), band2);
	m_band2 = new CPortTextCtrl(this, -1, buffer, wxDefaultPosition, wxSize(CONTROL_WIDTH3, -1));
	m_band2->SetMaxLength(2U);
	bandSizer->Add(m_band2, 0, wxLEFT | wxALIGN_LEFT, BORDER_SIZE);

	buffer.Printf(wxT("%u"), band3);
	m_band3 = new CPortTextCtrl(this, -1, buffer, wxDefaultPosition, wxSize(CONTROL_WIDTH3, -1));
	m_band3->SetMaxLength(2U);
	bandSizer->Add(m_band3, 0, wxLEFT | wxALIGN_LEFT, BORDER_SIZE);

	sizer->Add(bandSizer, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* dummy0Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy0Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* reflectorLabel = new wxStaticText(this, -1, _("Reflector"));
	sizer->Add(reflectorLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_reflector = new wxChoice(this, -1, wxDefaultPosition, wxSize(CONTROL_WIDTH1, -1));
	m_reflector->Append(_("None"));

	if (dplusEnabled) {
		wxFileName fileName(wxFileName::GetHomeDir(), DPLUS_HOSTS_FILE_NAME);
		if (!fileName.IsFileReadable()) {
#if defined(__WINDOWS__)
			fileName.Assign(::wxGetCwd(), DPLUS_HOSTS_FILE_NAME);
#else
			fileName.Assign(wxT(DATA_DIR), DPLUS_HOSTS_FILE_NAME);
#endif
		}

		CHostFile file(fileName.GetFullPath(), true);

		for (unsigned int i = 0U; i < file.getCount(); i++)
			m_reflector->Append(file.getName(i));
	}

	if (dExtraEnabled) {
		wxFileName fileName(wxFileName::GetHomeDir(), DEXTRA_HOSTS_FILE_NAME);
		if (!fileName.IsFileReadable()) {
#if defined(__WINDOWS__)
			fileName.Assign(::wxGetCwd(), DEXTRA_HOSTS_FILE_NAME);
#else
			fileName.Assign(wxT(DATA_DIR), DEXTRA_HOSTS_FILE_NAME);
#endif
		}

		CHostFile file(fileName.GetFullPath(), true);

		for (unsigned int i = 0U; i < file.getCount(); i++)
			m_reflector->Append(file.getName(i));
	}

	if (dcsEnabled) {
		wxFileName fileName(wxFileName::GetHomeDir(), DCS_HOSTS_FILE_NAME);
		if (!fileName.IsFileReadable()) {
#if defined(__WINDOWS__)
			fileName.Assign(::wxGetCwd(), DCS_HOSTS_FILE_NAME);
#else
			fileName.Assign(wxT(DATA_DIR), DCS_HOSTS_FILE_NAME);
#endif
		}

		CHostFile file(fileName.GetFullPath(), true);

		for (unsigned int i = 0U; i < file.getCount(); i++)
			m_reflector->Append(file.getName(i));
	}

	sizer->Add(m_reflector, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);

	if (reflector.IsEmpty()) {
		m_reflector->SetSelection(0);
	} else {
		wxString name = reflector;
		name.SetChar(LONG_CALLSIGN_LENGTH - 1U, wxT(' '));
		bool res = m_reflector->SetStringSelection(name);
		if (!res)
			m_reflector->SetSelection(0);
	}

	m_channel = new wxChoice(this, -1, wxDefaultPosition, wxSize(CONTROL_WIDTH2, -1));
	m_channel->Append(wxT("A"));
	m_channel->Append(wxT("B"));
	m_channel->Append(wxT("C"));
	m_channel->Append(wxT("D"));
	m_channel->Append(wxT("E"));
	m_channel->Append(wxT("F"));
	m_channel->Append(wxT("G"));
	m_channel->Append(wxT("H"));
	m_channel->Append(wxT("I"));
	m_channel->Append(wxT("J"));
	m_channel->Append(wxT("K"));
	m_channel->Append(wxT("L"));
	m_channel->Append(wxT("M"));
	m_channel->Append(wxT("N"));
	m_channel->Append(wxT("O"));
	m_channel->Append(wxT("P"));
	m_channel->Append(wxT("Q"));
	m_channel->Append(wxT("R"));
	m_channel->Append(wxT("S"));
	m_channel->Append(wxT("T"));
	m_channel->Append(wxT("U"));
	m_channel->Append(wxT("V"));
	m_channel->Append(wxT("W"));
	m_channel->Append(wxT("X"));
	m_channel->Append(wxT("Y"));
	m_channel->Append(wxT("Z"));
	sizer->Add(m_channel, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	res = m_channel->SetStringSelection(reflector.Right(1U));
	if (!res)
		m_channel->SetSelection(0);

	wxStaticText* startupLabel = new wxStaticText(this, -1, _("Startup"));
	sizer->Add(startupLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_startup = new wxChoice(this, -1, wxDefaultPosition, wxSize(CONTROL_WIDTH1, -1));
	m_startup->Append(_("No"));
	m_startup->Append(_("Yes"));
	sizer->Add(m_startup, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_startup->SetSelection(atStartup ? 1 : 0);

	wxStaticText* dummy5Label = new wxStaticText(this, -1, wxEmptyString);
	sizer->Add(dummy5Label, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	wxStaticText* reconnectLabel = new wxStaticText(this, -1, _("Reconnect"));
	sizer->Add(reconnectLabel, 0, wxALL | wxALIGN_RIGHT, BORDER_SIZE);

	m_reconnect = new wxChoice(this, -1, wxDefaultPosition, wxSize(CONTROL_WIDTH1, -1));
	m_reconnect->Append(_("Never"));
	m_reconnect->Append(_("Fixed"));
	m_reconnect->Append(_("5 minutes"));
	m_reconnect->Append(_("10 minutes"));
	m_reconnect->Append(_("15 minutes"));
	m_reconnect->Append(_("20 minutes"));
	m_reconnect->Append(_("25 minutes"));
	m_reconnect->Append(_("30 minutes"));
	m_reconnect->Append(_("60 minutes"));
	m_reconnect->Append(_("90 minutes"));
	m_reconnect->Append(_("120 minutes"));
	m_reconnect->Append(_("180 minutes"));
	sizer->Add(m_reconnect, 0, wxALL | wxALIGN_LEFT, BORDER_SIZE);
	m_reconnect->SetSelection(int(reconnect));

	if (isDDMode()) {
		m_type->SetSelection(1);
		m_reflector->SetSelection(0);
		m_channel->SetSelection(0);
		m_startup->SetSelection(0);
		m_reconnect->SetSelection(0);

		m_type->Disable();
		m_reflector->Disable();
		m_channel->Disable();
		m_startup->Disable();
		m_reconnect->Disable();
	} else {
		m_type->Enable();
		m_reflector->Enable();
		m_channel->Enable();
		m_startup->Enable();
		m_reconnect->Enable();
	}

	if (type == HW_ICOM) {
		m_band1->Enable();
		m_band2->Enable();
		m_band3->Enable();
	} else {
		m_band1->Disable();
		m_band2->Disable();
		m_band3->Disable();
	}

	SetAutoLayout(true);

	SetSizer(sizer);
}
Esempio n. 24
0
bool QFileInfo::isHidden() const
{
    return fileName()[ 0 ] == QChar( '.' );
}
Esempio n. 25
0
void IJoystickManager::loadMetaData(const std::string& joyName)
{
    // If it's already loaded there is no need to load it again
    if (hasMetaData(joyName))
        return;

    // Iterate through each controller definition and check the name
    // TODO: Load all controller definitions at start?
    char** fileList = PHYSFS_enumerateFiles("controller_definitions");
    // cache the start of the list
    char** listBeg = fileList;
    TiXmlDocument document;

    char* xmlData = nullptr;
    for (; *fileList != nullptr; fileList++)
    {
        std::string fileName(*fileList);
        std::string tmp(fileName);
        Athena::utility::tolower(tmp);
        std::string::size_type iter = tmp.find_last_of(".xml");
        if (iter == std::string::npos || iter != tmp.size() - 1)
            continue;

        fileName = "controller_definitions/" + fileName;
        PHYSFS_File* file = PHYSFS_openRead(fileName.c_str());
        if (file)
        {
            xmlData = new char[PHYSFS_fileLength(file)];
            PHYSFS_read(file, xmlData, 1, PHYSFS_fileLength(file));
            document.Parse(xmlData);
            TiXmlElement* elem = document.FirstChildElement();
            if (elem->Attribute("name") == joyName)
                break;

            delete[] xmlData;
            xmlData = nullptr;
        }
    }
    fileList = listBeg;
    PHYSFS_freeList(fileList);

    // Do we have valid data?
    if (xmlData)
    {
        TiXmlElement* root = document.FirstChildElement();
        JoyMetaData jmd;
        jmd.name = root->Attribute("name");
        TiXmlElement* btnInfo = root->FirstChildElement();
        while (btnInfo != nullptr)
        {
            JoyButtonInfo jbi;
            btnInfo->Attribute("id", &jbi.id);
            jbi.name  = btnInfo->Attribute("name");
            jbi.image = btnInfo->Attribute("img");
            jmd.buttonInfo.push_back(jbi);
            btnInfo = btnInfo->NextSiblingElement();
        }
        m_metaData.push_back(jmd);
        delete[] xmlData;
    }
}
Esempio n. 26
0
void Img::fileOffset (std::istream &f, unsigned long i) const
{
        f.seekg(fileOffset(i)); 
        APP_ASSERT_IO_SUCCESSFUL(f,"seeking to: "+fileName(i));
}
Esempio n. 27
0
Enemy::Enemy(int unsigned startX, unsigned int startY, std::string nam, Switch *sw, bool flip)
	: PhysicObject( startX, startY, 0, 0, 0)
{
	swtch = sw;
	react = true;
	name = nam;

	std::string fileName ("resources/config/enemies/");
	fileName += nam;
	fileName += ".cfg";

  std::fstream loadFile;
  std::string line;
	std::string text;
  loadFile.open(fileName.c_str());

  const char *temp;

  //Set the animations.
  getline(loadFile, line);
  temp = line.data();
  int numAnimations = atoi(temp);

  animationVector.resize(numAnimations);

  for (short int i = 0; i < numAnimations; i++)
  {
    getline(loadFile, line);
    temp = line.data();
    int numImgs = atoi(temp);
    animationVector[i].imageList.clear();

    for (; numImgs; numImgs--)
    {
      getline(loadFile, line);
      temp = line.data();
      animationVector[i].imageList.push_back(temp);
    }
  }

  getline(loadFile, line);
  temp = line.data();
  strength = atoi(temp);

  getline(loadFile, line);
  temp = line.data();
  agility = atoi(temp);

  getline(loadFile, line);
  temp = line.data();
  intelligence = atoi(temp);

  getline(loadFile, line);
  temp = line.data();
  resistance = atoi(temp);

  setStats();

  getline(loadFile, line);
  temp = line.data();
  unsigned int x = atoi(temp);

  getline(loadFile, line);
  temp = line.data();
  unsigned int y = atoi(temp);

  getline(loadFile, line);
  temp = line.data();
  unsigned int w = atoi(temp);
  oWidth = w;

  getline(loadFile, line);
  temp = line.data();
  unsigned int h = atoi(temp);
  oHeight = h;

	animationVector[0].horizontalFlip = flip;
	animationVector[0].verticalFlip = false;
	animationVector[ATTACK_ANIM].horizontalFlip = false;
	animationVector[ATTACK_ANIM].verticalFlip = false;
	animationVector[ATTACK_ANIM_FLIP].horizontalFlip = true;
	animationVector[ATTACK_ANIM_FLIP].verticalFlip = false;

  //create enemy colition box.

	colitionBoxes.resize(1);
  colitionBoxes[0].x = x;
  colitionBoxes[0].y = y;
  colitionBoxes[0].w = w;
  colitionBoxes[0].h = h;

  ResetBoxes();
}
Esempio n. 28
0
TiXmlElement* CXmlFile::Load(const wxString& name)
{
	wxFileName fileName(wxGetApp().GetSettingsDir(), name + _T(".xml"));
	return Load(fileName);
}
Esempio n. 29
0
int main(int argc, char **argv)
{
	MStatus stat;

	argc--, argv++;

	if (argc == 0) {
		cerr << usage;
		return(1);
	}

	for (; argc && argv[0][0] == '-'; argc--, argv++) {
		if (!strcmp(argv[0], "-h") || !strcmp(argv[0], "-help")) {
			cerr << usage;
			return(1);
		}
		// Check for other valid flags

		if (argv[0][0] == '-') {
			// Unknown flag
			cerr << usage;
			return(1);
		}
	}

	stat = MLibrary::initialize (argv[0]);
	if (!stat) {
		stat.perror("MLibrary::initialize");
		return 1;
	}

	for (; argc; argc--, argv++) {
		MString	fileName(argv[0]);
		MString fileType;

		MFileIO::newFile(true);

		// Load the file into Maya
		stat = MFileIO::open(fileName);
		if ( !stat ) {
			stat.perror(fileName.asChar());
			continue;
		}

		// Check to see if file is already in binary format
		fileType = MFileIO::fileType();
		if (fileType == MString("mayaBinary")) {
			cerr << fileName << ": already in mayaBinary format\n";
			continue;
		}

		// Check for a file extension, and if one exists, change it
		// to .mb.  If an extension does not exist, append a .mb to
		// the fileName.
		MString newFile;

		int loc = fileName.rindex('.');
		if (loc == -1) {
			newFile = fileName;
		} else {
			newFile = fileName.substring(0, loc-1);
		}
		newFile += ".mb";

		stat = MFileIO::saveAs(newFile, "mayaBinary");
		if (stat)
			cerr << fileName
				 << ": resaved as "
			     << MFileIO::currentFile()
				 << endl;
		else
			stat.perror(newFile.asChar());

	}

	MLibrary::cleanup();
	return 0;
}
Esempio n. 30
0
//-----------------------------------------------------------------------------
//Function Name : void* __dlopen_r(const char* filename, int flag)
//Description   : To open the given dll filename.
//Return Value  : Valid handle value if no error, Null if dll couldn't be loaded 
//-----------------------------------------------------------------------------
void* __dlopen_r(const char* filename,const int flag)
	{
	//convert filename to TFileName
	TPtrC8 ptr8( (unsigned char*)filename);
	TFileName fileNameBuf;
	CnvUtfConverter::ConvertToUnicodeFromUtf8(fileNameBuf, ptr8);
	TParsePtr filePathName(fileNameBuf);
	
	//if file name contains wild character
	if ( filePathName.IsWild() )
		{
		SetError(KDlOpenErrNoSupport);
		return NULL;
		}
	//to load dll	
	RLibrary library;	
	TInt err;
	TBool isLibraryLoaded = EFalse;
	RFs fs;
	err = fs.Connect();
	if ( KErrNone == err )
		{
		TUint tempAtt;
		//if path is there load from this path
		if ( filePathName.PathPresent() )
			{
			err = fs.Att(filePathName.FullName(), tempAtt);
			fs.Close();	
			if ( KErrNotFound != err && KErrPathNotFound != err)
				{
				err = library.Load(filePathName.FullName());
				if ( KErrNone != err )
					{
					SetError(KDlOpenErrLoading);
					return NULL;
					}
				isLibraryLoaded = ETrue;	
				}
			}
		else//if there is no path its only file name
			{
			TPtrC fileName(filePathName.NameAndExt());
			char* envPathName = getenv("LD_LIBRARY_PATH");
			if ( envPathName )
				{
				TPtrC8 tempPtr8((unsigned char*)envPathName);
				TFileName envPathBuf;
				CnvUtfConverter::ConvertToUnicodeFromUtf8(envPathBuf, tempPtr8);
				TPtrC envPath(envPathBuf);
				TChar delim(';');
				TFileName fileToLoad;
				TInt pos = envPath.Locate(delim);
				//if delim does not found and still envPath contains value
				//i.e. this one is last path without delim(';') so take 
				//this also, for this length is checked
				while ( KErrNotFound != pos || envPath.Length())
					{
					//if there is no delim
					if (KErrNotFound == pos )
						{// so last path without delim
						pos = envPath.Length();
						}
					TPtrC thisPath(envPath.Left(pos));
					fileToLoad = thisPath;
					fileToLoad.Trim();
					//to check ";;" and ";   ;"
					if (fileToLoad.Length())
						{
						//if path does not conatin trailing \ add one
						if ( L'\\' != fileToLoad[fileToLoad.Length()-1] )
							{
							fileToLoad.Append(TChar(L'\\'));					
							}
						fileToLoad.Append(fileName);
					
						err = fs.Att(fileToLoad, tempAtt);
						if ( KErrNotFound != err && KErrPathNotFound != err)
							{
							//load file from this path
							err = library.Load(fileToLoad);
							if ( KErrNone == err )
								{
								// dll loaded successfully from thispath
								isLibraryLoaded = ETrue;	
								break;
								}	
							}
						}
					if ( pos == envPath.Length())		
						{
						break;
						}
					else
						{
						envPath.Set(envPath.Mid(pos + 1));
						}
					pos = envPath.Locate(delim);
					}
				fs.Close();	
				}
			else//load dll if only name is there and LD_LIBRARY_PATH path not set
				{
				fs.Close();	
				TInt err = library.Load(filePathName.NameAndExt());
				if ( KErrNone != err )
					{
					SetError(KDlOpenErrLoading);
					return NULL;
					}
				isLibraryLoaded = ETrue;		
				}
			}
	
		//if library is loaded	
		if ( isLibraryLoaded )	
			{
			//handle value to return 
			void* handle  = NULL;
			//lock list before any operation
			LoadedDlls()->Lock();
			//is this dll already there
			TInt listIdx = LoadedDlls()->Find(library);
			//if not already open
			if ( KErrNotFound == listIdx )
				{				
				TDllEntry dllEntry(library, flag);
				dllEntry.iSymbolHeader = (TE32ExpSymInfoHdr*)library.Lookup(0);
				
				err = dllEntry.iLibrary.Duplicate(RThread());	
				//Close the library irrespective of the result of duplicate
				library.Close();
				if ( KErrNone != err )
					{
					SetError(KDlOpenErrLoading);
					LoadedDlls()->UnLock();
					return NULL;
					}
				//add to list	
				err = LoadedDlls()->Add(dllEntry);
				handle = (void*) dllEntry.iLibrary.Handle();
				LoadedDlls()->UnLock();
				if ( KErrNone != err )
					{
					SetError(KDlOpenErrNoMemory);
					dllEntry.iLibrary.Close();
					return NULL;
					}
				}
			else//if this dll is already in list.
				{
				//close library we already have loaded
				library.Close();
				TDllEntry& dllEntry = LoadedDlls()->At(listIdx);
				//if flag is RTLD_GLOBAL store it otherwise ignore
				//as RTLD_LAZY and RTLD_NOW both means RTLD_NOW
				//so can be ignored. RTLD_LOCAL does not change previous flag
				if ( flag & RTLD_GLOBAL )
					{
					dllEntry.iFlags |= RTLD_GLOBAL;
					}
				dllEntry.iRefCount++;	
				handle = (void*) dllEntry.iLibrary.Handle();
				LoadedDlls()->UnLock();	
				}	
			return handle;			
			}
		}
	SetError(KDlOpenErrLoading);
	return NULL;		
	}