示例#1
0
//-----------------------------------------------------------------------------
bool HexMapTest::Update()
{
	int16 sprite1_pos_x,sprite1_pos_y;
	int16 sprite2_pos_x,sprite2_pos_y;
	if (mouse_mode == MOUSE_MODE_CHECKING)
		mouse_mode  = MOUSE_MODE_DOWN;

	// UI processing
	if (((s3ePointerGetState(S3E_POINTER_BUTTON_SELECT) & S3E_POINTER_STATE_PRESSED)) && mouse_mode == MOUSE_MODE_IDLE)
		mouse_mode = MOUSE_MODE_IDLE;
	if ((s3ePointerGetState(S3E_POINTER_BUTTON_SELECT) & S3E_POINTER_STATE_RELEASED))
		mouse_mode = MOUSE_MODE_CHECKING;

//	UpdateKey();

	IwGxSetViewMatrix(&s_viewMatrix);

    // Generate a ray pointing to the view plane from the camera
    CIwVec3 dir(s3ePointerGetX() - IwGxGetScreenWidth()/2, 
        s3ePointerGetY() - IwGxGetScreenHeight()/2, 
        IwGxGetPerspMul());
    
    // Rotate into camera space
    dir = s_viewMatrix.RotateVec(dir);

	// Update pointer system
	g_Input.Update();
	if (g_Input.finger1IsDown()) {
		if (g_Input.overThreshold()) {
			if (!g_Input.finger1Continuing()) {
				s_ModelMatrix_initial = s_ModelMatrix;
				CIwVec3 vectCenter = getWorldCoords(0, 0);
				zoom_initial = zoom;
				rotation_initial = rotation;
				screenTranslationX_initial = screenTranslationX;
				screenTranslationY_initial = screenTranslationY;
				if (!g_Input.isMultiTouch()) {
					if (g_Input.finger1MovedTo(sprite1_pos_x, sprite1_pos_y)) {
						if (sprite1_pos_x > int(IwGxGetScreenWidth()) - SCREEN_MARGIN) {
							zooming = true;
						}
						if (sprite1_pos_y > int(IwGxGetScreenHeight()) - SCREEN_MARGIN) {
							rotating = true;
						}
					}
				}
			}
			if (!g_Input.finger2IsDown() && g_Input.finger1MovedTo(sprite1_pos_x, sprite1_pos_y)) {
				if (g_Input.finger1Continuing()) {
					if (zooming) {
						if (sprite1_pos_x > int(IwGxGetScreenWidth()) - SCREEN_MARGIN) {
							int16 dsprite1_pos_x, dsprite1_pos_y;
							if (g_Input.finger1MovementDelta(dsprite1_pos_x, dsprite1_pos_y)) {
								float deltaZoom = 1.0f - 1.0f*(dsprite1_pos_y)/IwGxGetScreenHeight();
								SetZoom(deltaZoom, 8);
							}
						}
					} else if (rotating) {
						if (sprite1_pos_y > int(IwGxGetScreenHeight()) - SCREEN_MARGIN) {
							int16 dsprite1_pos_x, dsprite1_pos_y;
							if (g_Input.finger1MovementDelta(dsprite1_pos_x, dsprite1_pos_y)) {
								float deltaRotation = 360.0f*(dsprite1_pos_x)/IwGxGetScreenWidth();
								SetRotation(deltaRotation);
							}
						}
					} else {
						SetTranslation();
					}
				}
			} else {
				if (g_Input.finger1MovedTo(sprite1_pos_x, sprite1_pos_y)) {
					if (g_Input.finger2MovedTo(sprite2_pos_x, sprite2_pos_y)) {
						if (!g_Input.finger2Continuing()) {
							screenTranslationX_initial = screenTranslationX;
							screenTranslationY_initial = screenTranslationY;
							g_Input.resetInitial(0);
						} else {
							int16 sprite1_pos_x_initial,sprite1_pos_y_initial,sprite2_pos_x_initial,sprite2_pos_y_initial;
							g_Input.finger1Initial(sprite1_pos_x_initial,sprite1_pos_y_initial);
							g_Input.finger2Initial(sprite2_pos_x_initial,sprite2_pos_y_initial);
							int d12x=sprite1_pos_x-sprite2_pos_x;
							int d12y=sprite1_pos_y-sprite2_pos_y;
							int d12x_initial=sprite1_pos_x_initial-sprite2_pos_x_initial;
							int d12y_initial=sprite1_pos_y_initial-sprite2_pos_y_initial;
							int Delta_initial = d12x_initial*d12x_initial+d12y_initial*d12y_initial;
							int Delta = d12x*d12x+d12y*d12y;
							float newZoom = float(sqrt(1.0*Delta)/sqrt(Delta_initial));
							SetZoom(newZoom, 1);
							float oldRotation = float(atan2(float(d12y_initial), float(d12x_initial)));
							float newRotation = float(atan2(float(d12y), float(d12x)));
							SetRotation(180.0f*(oldRotation-newRotation)/PI);
							{
								char string[256];
								//sprintf(string, "`1`a  del %04d, %04d",d1x,d2x);
								//IwGxPrintString(2, 96, string);
								sprintf(string, "`1`a  zoo %5.2f, %5.2f, %5.2f",newZoom,oldRotation,newRotation);
								IwGxPrintString(2, 96, string);
							}
						}
					}
				}
			}
		}
	} else {
		zooming = false;
		rotating = false;
		//		s_ModelMatrix = CIwMat::g_Identity;
	}
	return true;
}
示例#2
0
void main()
{
   char x[512];
   char buffer[512];
   int size;

   while(1)
   {
      interrupt(33,0,"cxxxx][===blackdos===> \0",0,0);

      /* Takes command line input */
      SCANS(x);
      PRINTS("\r\n\0");

      if(strcmp(x,"boot\0") == 1)
      {
         BOOT;
      }
      else if(strcmp(x,"cls\0") == 1)
      {
         clr();
      }
      else if(strcmp(x,"help\0") == 1)
      {
         help();
      }
      else if(strcmp(x,"echo\0") == 1)
      {
         echo(x+5);
      }
      else if(strcmp(x,"type\0") == 1)
      {
         loadF(x+5,buffer,size);
      }
      else if(strcmp(x,"run\0") == 1)
      {
         runF(x+4);
      }
      else if(strcmp(x,"del\0") == 1)
      {
         delF(x+4);
      }
      else if(strcmp(x,"dir\0") == 1)
      {
         dir();
      }
      else if(strcmp(x,"tweet\0") == 1)
      {
         tweet(x+6);
      }
      else if(strcmp(x,"cp\0") == 1)
      {
         copy(x+3);
      }
      else
      {
         interrupt(33,0,"\r\nBad command or filename\r\n\0",0,0);
      }
      interrupt(33,0,"\r\n\0",0,0);
   }
   END;
}
示例#3
0
void RSSEditPopup::slotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    LOG(VB_GENERAL, LOG_DEBUG, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull ())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL = channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd", "image");
            if (nodes.size())
            {
                thumbnailURL = nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = QDateTime::currentDateTime();
        QString filename("");

        if (file.isEmpty())
            filename = file;

        QString link = m_urlEdit->GetText();

        if (!thumbnailURL.isEmpty() && filename.isEmpty())
        {
            QString fileprefix = GetConfDir();

            QDir dir(fileprefix);
            if (!dir.exists())
                    dir.mkdir(fileprefix);

            fileprefix += "/MythNetvision";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            fileprefix += "/sitecovers";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            QFileInfo fi(thumbnailURL);
            QString rawFilename = fi.fileName();

            filename = QString("%1/%2").arg(fileprefix).arg(rawFilename);

            bool exists = QFile::exists(filename);
            if (!exists)
                HttpComms::getHttpFile(filename, thumbnailURL, 20000, 1, 2);
        }
        if (insertInDB(new RSSSite(title, filename, VIDEO_PODCAST, description, link,
                author, download, QDateTime::currentDateTime())))
            emit saving();
    }
    Close();
}
示例#4
0
//
// Framework Functions
//
bool Setup()
{
	//
	// Create objects.
	//

	D3DXCreateTeapot(Device, &Objects[0], 0);
	D3DXCreateSphere(Device, 1.0f, 20, 20, &Objects[1], 0);
	D3DXCreateTorus(Device, 0.5f, 1.0f, 20, 20, &Objects[2], 0);
	D3DXCreateCylinder(Device, 0.5f, 0.5f, 2.0f, 20, 20, &Objects[3], 0);

	//
	// Build world matrices - position the objects in world space.
	//

	D3DXMatrixTranslation(&Worlds[0], 0.0f, 2.0f, 0.0f);
	D3DXMatrixTranslation(&Worlds[1], 0.0f, -2.0f, 0.0f);
	D3DXMatrixTranslation(&Worlds[2], -3.0f, 0.0f, 0.0f);
	D3DXMatrixTranslation(&Worlds[3], 3.0f, 0.0f, 0.0f);

	//
	// Setup the object's materials.
	//

	Mtrls[0] = d3d::RED_MTRL;
	Mtrls[1] = d3d::BLUE_MTRL;
	Mtrls[2] = d3d::GREEN_MTRL;
	Mtrls[3] = d3d::YELLOW_MTRL;

	//
	// Setup a directional light.
	//

	D3DXVECTOR3 dir(1.0f, -0.0f, 0.25f);
	D3DXCOLOR   c = d3d::WHITE;
	D3DLIGHT9 dirLight = d3d::InitDirectionalLight(&dir, &c);

	//
	// Set and Enable the light.
	//

	Device->SetLight(0, &dirLight);
	Device->LightEnable(0, true);

	//
	// Set lighting related render states.
	//

	Device->SetRenderState(D3DRS_NORMALIZENORMALS, true);
	Device->SetRenderState(D3DRS_SPECULARENABLE, false);

	//
	// Set the projection matrix.
	//

	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(
		&proj,
		D3DX_PI * 0.25f, // 45 - degree
		(float)Width / (float)Height,
		1.0f,
		1000.0f);
	Device->SetTransform(D3DTS_PROJECTION, &proj);

	return true;
}
示例#5
0
    Application(int &argc, char **argv)
        : QApplication(argc, argv)
    {
        QDir dir(applicationDirPath());
#ifdef Q_OS_MAC
        dir.cdUp();
        dir.cd("PlugIns");
        dir.cd("qt");
#else
        dir.cd("lib");
        dir.cd("qt5");
#endif
        addLibraryPath(dir.absolutePath());
        setOrganizationName("Meltytech");
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
        setOrganizationDomain("shotcut.org");
        setDesktopFileName("org.shotcut.Shotcut");
#else
        setOrganizationDomain("meltytech.com");
#endif
        setApplicationName("Shotcut");
        setApplicationVersion(SHOTCUT_VERSION);
        setAttribute(Qt::AA_UseHighDpiPixmaps);
        setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#if defined(Q_OS_MAC)
        setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

        // Process command line options.
        QCommandLineParser parser;
        parser.addHelpOption();
        parser.addVersionOption();
#ifndef Q_OS_WIN
        QCommandLineOption fullscreenOption("fullscreen",
            QCoreApplication::translate("main", "Fill the screen with the Shotcut window."));
        parser.addOption(fullscreenOption);
#endif
        QCommandLineOption noupgradeOption("noupgrade",
            QCoreApplication::translate("main", "Hide upgrade prompt and menu item."));
        parser.addOption(noupgradeOption);
        QCommandLineOption gpuOption("gpu",
            QCoreApplication::translate("main", "Use GPU processing."));
        parser.addOption(gpuOption);
        QCommandLineOption clearRecentOption("clear-recent",
            QCoreApplication::translate("main", "Clear Recent on Exit"));
        parser.addOption(clearRecentOption);
        QCommandLineOption appDataOption("appdata",
            QCoreApplication::translate("main", "The directory for app configuration and data."),
            QCoreApplication::translate("main", "directory"));
        parser.addOption(appDataOption);
        QCommandLineOption scaleOption("QT_SCALE_FACTOR",
            QCoreApplication::translate("main", "The scale factor for a high-DPI screen"),
            QCoreApplication::translate("main", "number"));
        parser.addOption(scaleOption);
        scaleOption = QCommandLineOption("QT_SCREEN_SCALE_FACTORS",
            QCoreApplication::translate("main", "A semicolon-separated list of scale factors for each screen"),
            QCoreApplication::translate("main", "list"));
        parser.addOption(scaleOption);
        parser.addPositionalArgument("[FILE]...",
            QCoreApplication::translate("main", "Zero or more files or folders to open"));
        parser.process(arguments());
#ifdef Q_OS_WIN
        isFullScreen = false;
#else
        isFullScreen = parser.isSet(fullscreenOption);
#endif
        setProperty("noupgrade", parser.isSet(noupgradeOption));
        setProperty("clearRecent", parser.isSet(clearRecentOption));
        if (!parser.value(appDataOption).isEmpty()) {
            appDirArg = parser.value(appDataOption);
            ShotcutSettings::setAppDataForSession(appDirArg);
        }
        if (parser.isSet(gpuOption))
            Settings.setPlayerGPU(true);
        if (!parser.positionalArguments().isEmpty())
            resourceArg = parser.positionalArguments();

        // Startup logging.
        dir = Settings.appDataLocation();
        if (!dir.exists()) dir.mkpath(dir.path());
        const QString logFileName = dir.filePath("shotcut-log.txt");
        QFile::remove(logFileName);
        FileAppender* fileAppender = new FileAppender(logFileName);
        fileAppender->setFormat("[%{type:-7}] <%{function}> %{message}\n");
        cuteLogger->registerAppender(fileAppender);
#ifndef NDEBUG
        // Only log to console in dev debug builds.
        ConsoleAppender* consoleAppender = new ConsoleAppender();
        consoleAppender->setFormat(fileAppender->format());
        cuteLogger->registerAppender(consoleAppender);

        mlt_log_set_level(MLT_LOG_VERBOSE);
#else
        mlt_log_set_level(MLT_LOG_INFO);
#endif
        mlt_log_set_callback(mlt_log_handler);
        cuteLogger->logToGlobalInstance("qml", true);

        // Log some basic info.
        LOG_INFO() << "Starting Shotcut version" << SHOTCUT_VERSION;
#if defined (Q_OS_WIN)
        LOG_INFO() << "Windows version" << QSysInfo::windowsVersion();
#elif defined(Q_OS_MAC)
        LOG_INFO() << "macOS version" << QSysInfo::macVersion();
#else
        LOG_INFO() << "Linux version";
#endif
        LOG_INFO() << "number of logical cores =" << QThread::idealThreadCount();
        LOG_INFO() << "locale =" << QLocale();
        LOG_INFO() << "install dir =" <<  applicationDirPath();
        LOG_INFO() << "device pixel ratio =" << devicePixelRatio();
        Settings.log();

#if defined(Q_OS_WIN)
        if (Settings.playerGPU()) {
            QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
        } else if (Settings.drawMethod() >= Qt::AA_UseDesktopOpenGL &&
                   Settings.drawMethod() <= Qt::AA_UseSoftwareOpenGL) {
            QCoreApplication::setAttribute(Qt::ApplicationAttribute(Settings.drawMethod()));
        }
#endif
        // Load translations
        QString locale = Settings.language();
        dir = applicationDirPath();
    #if defined(Q_OS_MAC)
        dir.cdUp();
        dir.cd("Resources");
        dir.cd("translations");
    #elif defined(Q_OS_WIN)
        dir.cd("share");
        dir.cd("translations");
    #else
        dir.cdUp();
        dir.cd("share");
        dir.cd("shotcut");
        dir.cd("translations");
    #endif
        if (locale.startsWith("pt_"))
            locale = "pt";
        else if (locale.startsWith("en_"))
            locale = "en";
        if (qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtTranslator);
        else if (qtTranslator.load("qt_" + locale, dir.absolutePath()))
            installTranslator(&qtTranslator);
        if (qtBaseTranslator.load("qtbase_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtBaseTranslator);
        else if (qtBaseTranslator.load("qtbase_" + locale, dir.absolutePath()))
            installTranslator(&qtBaseTranslator);
        if (shotcutTranslator.load("shotcut_" + Settings.language(), dir.absolutePath()))
            installTranslator(&shotcutTranslator);
    }
示例#6
0
int main(int argc, char *argv[])
{
	if (argc < 2) {
		std::cerr << "Need Resource Dir !" << std::endl;
		return 1;
	}

// 	if (argc < 3) {
// 		std::cerr << "Need Resource Dir & Extrude size !" << std::endl;
// 		return 1;
// 	}

	std::string dirpath = argv[1];
	wxArrayString files;
	DirTraverser traverser(files);

	wxDir dir(dirpath);
	dir.Traverse(traverser);

	std::map<std::string, ee::Rect> map_name2rect;

	double size = 1;
//	wxString(argv[2]).ToDouble(&size);
	try {
		for (size_t i = 0, n = files.size(); i < n; ++i)
		{
			wxFileName filename(files[i]);
			filename.Normalize();
			wxString filepath = filename.GetFullPath();
			
			if (ee::FileNameParser::isType(filepath, ee::FileNameParser::e_image))
			{
				coceditor::ExtrudeImg extrude(filepath.ToStdString());
				extrude.Trigger((int)size);
				map_name2rect.insert(std::make_pair(extrude.GetFileName(), extrude.GetRectTrimed()));
			}
		}

		for (size_t i = 0, n= files.size(); i < n; ++i)
		{
			wxFileName filename(files[i]);
			filename.Normalize();
			wxString filepath = filename.GetFullPath();

			if (ee::FileNameParser::isType(filepath, ee::FileNameParser::e_complex))
			{
				Json::Value value;
				Json::Reader reader;
				std::locale::global(std::locale(""));
				std::ifstream fin(filepath.fn_str());
				std::locale::global(std::locale("C"));
				reader.parse(fin, value);
				fin.close();

				bool dirty = false;

				int i = 0;
				Json::Value spriteValue = value["sprite"][i++];
				while (!spriteValue.isNull()) {

					std::string path = spriteValue["filepath"].asString();
					path = ee::FilenameTools::getFilenameWithExtension(path);
					std::map<std::string, ee::Rect>::iterator itr = map_name2rect.find(path);
					if (itr != map_name2rect.end()) {
						dirty = true;

						const float x = spriteValue["position"]["x"].asDouble(),
							y = spriteValue["position"]["y"].asDouble();
						value["sprite"][i-1]["position"]["x"] = x + itr->second.xCenter() * spriteValue["x scale"].asDouble();
						value["sprite"][i-1]["position"]["y"] = y + itr->second.yCenter() * spriteValue["y scale"].asDouble();
					}
					spriteValue = value["sprite"][i++];
				}

				if (dirty)
				{
					Json::StyledStreamWriter writer;
					std::locale::global(std::locale(""));
					std::ofstream fout(filepath.fn_str());
					std::locale::global(std::locale("C"));					
					writer.write(fout, value);
					fout.close();
				}
			}
		}
	} catch (ee::Exception& e) {
		std::cerr << e.what() << std::endl;
	}

	return 0;
}
示例#7
0
int readFile(string& filename)
{
  float stime[8][1024];
  float wave[8][1024];
  int nsample=0;
  string dir("data/");
  //filename=dir+filename;
  printf("Reading file:%s \n ",filename.c_str());
  ifstream file;
  file.open(filename.c_str());
  if(!file){
    printf("%s : cannot be opened.\n",filename.c_str());
    return 1;
  }else{
    printf("%s : opened successfully.\n",filename.c_str());
  }
  //anal.SetWaveTime(0,stime[0],wave[0]);
  //anal.SetWaveTime(1,stime[1],wave[1]);
  //anal.SetWaveTime((float**) stime,(float**) wave);
  string line;
  bool dflag=0,eflag=0;
  int nlines=0,ndat=0;
  int nmaxsample=NDIM;
  if(nsample>0) nmaxsample=nsample;
  nsample=0;
  while (getline(file,line)) {
       //if(nlines<10)printf("%s \n", line.c_str()); 
       //printf("%s \n", line.c_str()); 
       if(line.find("Event") != string::npos){
          printf("%s \n", line.c_str()); 
          eflag=1;
          continue;
       }
       if(line.find("t1[ns]") != string::npos){
          if(!eflag){
            printf("Error: unexpected line sequence.\n");
            return 1;
          }
          eflag=0;
          if(dflag){
            printf("close sample %i \n",ndat);
            if(ndat != NDIM){
             printf("ErrorL ndat= %i \n",ndat);
             return 1;
            }
    	    anal.Compare2Waves(0,1);
            ndat=0;
            nsample++;
            if(nsample>=nmaxsample){
             printf("Warning:  nsample=%i \n",nsample);
             return 0;
            }
          }
          printf("open sample \n");
          dflag=1;
          continue;
       }
       // take data
       vector<string> items;
       splitstring(line,items," ");
       int nitems=items.size();
       if((nitems != 4) && (nitems != 8)){
         printf("Expexted number of items in line != 4 : %i \n",nitems);
         return 1;
       }
       double t1,t2;
       //cout << atof(items[0].c_str()) << endl;
       t1=atof(items[0].c_str());
       wave[0][ndat]=atof(items[1].c_str());
       t2=atof(items[2].c_str());
       wave[1][ndat]=atof(items[3].c_str());
       stime[0][ndat]=t1;
       stime[1][ndat]=t2;
       //if(t1 != t2){
       //  printf("Warning: t1 != t2 %f %f \n",t1,t2);
       //}
       if(ndat >= NDIM){
         printf("Error: unexpected size of data %i \n",ndat);
         return 1;
       }
       nlines++;
       ndat++;
  }
  if(dflag){
    printf("close sample %i \n",ndat);
    if(ndat != NDIM){
       printf("ErrorL ndat= %i \n",ndat);
       return 1;
    }
    //anal.Compare2Waves(0,1);
    nsample++;
  }
  Float_t* tt1=stime[0];
  Float_t* tt2=stime[1];
  Float_t* w1=wave[0];
  Float_t* w2=wave[1];
  DrawWaves(tt1,tt2,w1,w2);
  printf("All samples read nsample: %i \n",nsample);
  return 0;

}
示例#8
0
void tcToolPanel::OnImportTable(wxCommandEvent& event)
{
    if (!tcDatabaseManager::Get()->IsOpen())
    {
        wxMessageBox("Database is not open", "Import Failed");
        return;
    }

    wxTextCtrl* dirTextCtrl = dirPicker->GetTextCtrl();

    wxString csvDir = dirPicker->GetPath();

    if (dirTextCtrl->IsModified())
    {
        csvDir = dirTextCtrl->GetValue();
    }

    bool inputValid = false;

    if (wxDir::Exists(csvDir))
    {
        wxDir dir(csvDir);
        if (dir.HasFiles("*.csv"))
        {
            inputValid = true;
        }
    }

    if (!inputValid)
    {
        wxString msg(wxString::Format("Input directory has no CSV files (%s)", csvDir.c_str()));
        wxMessageBox(msg, "Error", wxICON_ERROR);
        //SetStatusText(msg);
        return;
    }

	wxFileDialog dialog(this, "Choose table file", csvDir, "", "*.csv", wxFD_OPEN | wxFD_FILE_MUST_EXIST, wxDefaultPosition, wxDefaultSize, "filedlg");

	wxString fileToImport("");

    if (dialog.ShowModal() == wxID_OK)
    {    
		fileToImport = dialog.GetPath().c_str();
    }
	else
	{
		return;
	}

    textDisplay->Clear();

    sqlite3_connection& sqlConnection = tcDatabaseManager::Get()->GetConnection();

    tcDatabaseTranslator translator;
    bool success = translator.ImportTableFromCSV(sqlConnection, fileToImport);

    wxString msg;
    if (success)
    {
		msg.Printf("Imported CSV %s data from  \"%s\"  to database", fileToImport.c_str(), csvDir.c_str());
        if (translator.statusRows.size() > 0)
        {
            textDisplay->AppendText("IMPORT LOG:\n\n");
            for (size_t n=0; n<translator.statusRows.size(); n++)
            {
                textDisplay->AppendText(translator.statusRows[n]);
            }
        }
        
    }
    else
    {
        msg.Printf("ERROR importing CSV data from \"%s\"  to database", csvDir.c_str());
    }
    //SetStatusText(msg);

}
示例#9
0
文件: vplStroke.cpp 项目: msahlen/vpl
    // Make one closed path by adding the points of the inner path
    void Stroker::endStroke()
    {
        switch(endType_)
        {
            // Simplest case, just add the inner points
            case cButtEnd:
            {
                for(vplUint i = innerPoints_.getItemCount(); i > 0;i-=2)
                {
                    outerPoints_.add(innerPoints_[i - 2]);
                    outerPoints_.add(innerPoints_[i - 1]);
                }

                // Close the path
                outerPoints_.add(outerPoints_[0]);
                outerPoints_.add(outerPoints_[1]);
            }
                break;

            // End outer path with an arc, then add the inner points.
            // Finalize with a closing arc to the first point
            case cRoundEnd:
            {
                Winding winding = determineWinding(normal_,invert(normal_));

                generateArc(currentPoint_,normal_,invert(normal_),
                             winding,&outerPoints_);

                for(vplUint i = innerPoints_.getItemCount(); i > 0;i-=2)
                {
                    outerPoints_.add(innerPoints_[i - 2]);
                    outerPoints_.add(innerPoints_[i - 1]);
                }

                winding = determineWinding(invert(firstNormal_),firstNormal_);

                generateArc(firstPoint_,invert(firstNormal_),firstNormal_,
                            winding,&outerPoints_);

                // Close the path
                outerPoints_.add(outerPoints_[0]);
                outerPoints_.add(outerPoints_[1]);
            }
                break;

            // Add a rectangle with sides stroke width/2 x stroke width
            case cSquareEnd:
            {
                // Use the normals for calculation of the ends
                Vector dir(-normal_.y_,normal_.x_);
                Vector firstDir(-firstNormal_.y_,firstNormal_.x_);

                dir.normalize();
                firstDir.normalize();

                scale_.transform(dir);
                scale_.transform(firstDir);

                dir *= size_ / 2;
                firstDir *= size_ / 2;

                Vector v1 = currentPoint_ + normal_ + dir;
                Vector v2 = currentPoint_ - normal_ + dir;

                addPoint(&outerPoints_,v1);
                addPoint(&outerPoints_,v2);

                for(vplUint i = innerPoints_.getItemCount(); i > 0;i-=2)
                {
                    outerPoints_.add(innerPoints_[i - 2]);
                    outerPoints_.add(innerPoints_[i - 1]);
                }

                v1 = firstPoint_ - firstNormal_ - firstDir;
                v2 = firstPoint_ + firstNormal_ - firstDir;

                addPoint(&outerPoints_,v1);
                addPoint(&outerPoints_,v2);

                // Close the path
                outerPoints_.add(outerPoints_[0]);
                outerPoints_.add(outerPoints_[1]);
            }
                break;
        }

        innerPoints_.clear();
    }
示例#10
0
void tcToolPanel::OnExportTable(wxCommandEvent& event)
{
    if (!tcDatabaseManager::Get()->IsOpen())
    {
        wxMessageBox("Database is not open", "Export Failed");
        return;
    }

    sqlite3_connection& sqlConnection = tcDatabaseManager::Get()->GetConnection();

    tcDatabaseTranslator translator;

	wxArrayString tableList = translator.GetTableList(sqlConnection);

	wxSingleChoiceDialog dialog(this, "Choose table", "Select", tableList, (char**)NULL, wxCHOICEDLG_STYLE, wxDefaultPosition);
	int result = dialog.ShowModal();
	wxString tableName = "None";

	if (result == wxID_OK)
	{
		tableName = dialog.GetStringSelection();
	}
	else
	{
		textDisplay->AppendText("Export cancelled\n");
		return;
	}

    wxTextCtrl* dirTextCtrl = dirPicker->GetTextCtrl();
    wxString csvDir = dirPicker->GetPath();


    if (dirTextCtrl->IsModified())
    {
        csvDir = dirTextCtrl->GetValue();
    }

    if (wxDir::Exists(csvDir))
    {
        wxDir dir(csvDir);
		wxString exportFileName = tableName + ".csv";
		if (dir.HasFiles(exportFileName))
        {
            wxString msg(wxString::Format("Overwrite CSV file in output dir? (%s)", csvDir.c_str()));
            wxMessageDialog* confirm = new wxMessageDialog(NULL, msg, "Confirm Overwrite", wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION);
            if (confirm->ShowModal() != wxID_YES)
            {
                textDisplay->AppendText("Export cancelled\n");
                return;
            }
        }             
    }

	bool success = translator.ExportTableToCSV(sqlConnection, tableName, csvDir);

    wxString msg;
    if (success)
    {
		msg.Printf("Exported %s to  \"%s\"\n", tableName.c_str(), csvDir.c_str());
    }
    else
    {
        msg.Printf("ERROR exporting %s  to  \"%s\"\n", tableName.c_str(), csvDir.c_str());
    }
    textDisplay->AppendText(msg);

}
示例#11
0
void tcToolPanel::OnImport(wxCommandEvent& event)
{
    if (!tcDatabaseManager::Get()->IsOpen())
    {
        wxMessageBox("Database is not open", "Import Failed");
        return;
    }

    wxTextCtrl* dirTextCtrl = dirPicker->GetTextCtrl();

    wxString csvDir = dirPicker->GetPath();

    if (dirTextCtrl->IsModified())
    {
        csvDir = dirTextCtrl->GetValue();
    }

    bool inputValid = false;

    if (wxDir::Exists(csvDir))
    {
        wxDir dir(csvDir);
        if (dir.HasFiles("*.csv"))
        {
            inputValid = true;
        }
    }

    if (!inputValid)
    {
        wxString msg(wxString::Format("Input directory has no CSV files (%s)", csvDir.c_str()));
        wxMessageBox(msg, "Error", wxICON_ERROR);
        //SetStatusText(msg);
        return;
    }             

    textDisplay->Clear();

    sqlite3_connection& sqlConnection = tcDatabaseManager::Get()->GetConnection();

    tcDatabaseTranslator translator;
    bool success = translator.ImportDatabaseFromCSV(sqlConnection, csvDir);

    wxString msg;
    if (success)
    {
        msg.Printf("Imported CSV data from  \"%s\"  to database", csvDir.c_str());
        if (translator.statusRows.size() > 0)
        {
            textDisplay->AppendText("IMPORT LOG:\n\n");
            for (size_t n=0; n<translator.statusRows.size(); n++)
            {
                textDisplay->AppendText(translator.statusRows[n]);
            }
        }
        
    }
    else
    {
        msg.Printf("ERROR importing CSV data from \"%s\"  to database", csvDir.c_str());
    }
    //SetStatusText(msg);

}
示例#12
0
Common::Error AdvancedMetaEngine::createInstance(OSystem *syst, Engine **engine) const {
	assert(engine);

	const ADGameDescription *agdDesc = 0;
	Common::Language language = Common::UNK_LANG;
	Common::Platform platform = Common::kPlatformUnknown;
	Common::String extra;

	if (ConfMan.hasKey("language"))
		language = Common::parseLanguage(ConfMan.get("language"));
	if (ConfMan.hasKey("platform"))
		platform = Common::parsePlatform(ConfMan.get("platform"));
	if (_flags & kADFlagUseExtraAsHint) {
		if (ConfMan.hasKey("extra"))
			extra = ConfMan.get("extra");
	}

	Common::String gameid = ConfMan.get("gameid");

	Common::String path;
	if (ConfMan.hasKey("path")) {
		path = ConfMan.get("path");
	} else {
		path = ".";

		// This situation may happen only when game was
		// launched from a command line with wrong target and
		// no path was provided.
		//
		// A dummy entry will get created and will keep game path
		// We mark this entry, so it will not be added to the
		// config file.
		//
		// Fixes bug #1544799
		ConfMan.setBool("autoadded", true);

		warning("No path was provided. Assuming the data files are in the current directory");
	}
	Common::FSNode dir(path);
	Common::FSList files;
	if (!dir.isDirectory() || !dir.getChildren(files, Common::FSNode::kListAll, true)) {
		warning("Game data path does not exist or is not a directory (%s)", path.c_str());
		return Common::kNoGameDataFoundError;
	}

	if (files.empty())
		return Common::kNoGameDataFoundError;

	// Compose a hashmap of all files in fslist.
	FileMap allFiles;
	composeFileHashMap(allFiles, files, (_maxScanDepth == 0 ? 1 : _maxScanDepth));

	// Run the detector on this
	ADGameDescList matches = detectGame(files.begin()->getParent(), allFiles, language, platform, extra);

	if (cleanupPirated(matches))
		return Common::kNoGameDataFoundError;

	if (_singleid == NULL) {
		// Find the first match with correct gameid.
		for (uint i = 0; i < matches.size(); i++) {
			if (matches[i]->gameid == gameid) {
				agdDesc = matches[i];
				break;
			}
		}
	} else if (matches.size() > 0) {
		agdDesc = matches[0];
	}

	if (agdDesc == 0) {
		// Use fallback detector if there were no matches by other means
		agdDesc = fallbackDetect(allFiles, files);
		if (agdDesc != 0) {
			// Seems we found a fallback match. But first perform a basic
			// sanity check: the gameid must match.
			if (_singleid == NULL && agdDesc->gameid != gameid)
				agdDesc = 0;
		}
	}

	if (agdDesc == 0)
		return Common::kNoGameDataFoundError;

	// If the GUI options were updated, we catch this here and update them in the users config
	// file transparently.
	Common::String lang = getGameGUIOptionsDescriptionLanguage(agdDesc->language);
	if (agdDesc->flags & ADGF_ADDENGLISH)
		lang += " " + getGameGUIOptionsDescriptionLanguage(Common::EN_ANY);

	Common::updateGameGUIOptions(agdDesc->guioptions | _guioptions, lang);

	GameDescriptor gameDescriptor = toGameDescriptor(*agdDesc, _gameids);

	bool showTestingWarning = false;

#ifdef RELEASE_BUILD
	showTestingWarning = true;
#endif

	if (((gameDescriptor.getSupportLevel() == kUnstableGame
			|| (gameDescriptor.getSupportLevel() == kTestingGame
					&& showTestingWarning)))
			&& !Engine::warnUserAboutUnsupportedGame())
		return Common::kUserCanceled;

	debug(2, "Running %s", gameDescriptor.description().c_str());
	if (!createInstance(syst, engine, agdDesc))
		return Common::kNoGameDataFoundError;
	else
		return Common::kNoError;
}
bool DirectoryWork::hasDirectory(const QString path)
{
    QDir dir(path);
    return dir.exists();
}
示例#14
0
文件: main.cpp 项目: alessio/liteide
int main(int argc, char *argv[])
#endif
{
#ifndef LITEAPP_LIBRARY
    #if defined(_MSC_VER) && defined(_DEBUG)
        _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
    #endif
#endif
    QApplication::setGraphicsSystem("native");
    QApplication app(argc, argv);

#if QT_VERSION >= 0x050100
    app.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

    //QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
    QTranslator translator;
    QTranslator qtTranslator;

    QString resPath = LiteApp::getResoucePath();
    QString locale = QLocale::system().name();
    QString qss;
    QSettings global(resPath+"/liteapp/config/global.ini",QSettings::IniFormat);
    bool storeLocal = global.value(LITEIDE_STORELOCAL,false).toBool();
    if (storeLocal) {
        const QSettings settings(resPath+"/liteapp/config/liteide.ini", QSettings::IniFormat);
        locale = settings.value(LITEAPP_LANGUAGE,locale).toString();
        qss = settings.value(LITEAPP_QSS,"default.qss").toString();
    } else {
        const QSettings settings(QSettings::IniFormat,QSettings::UserScope,"liteide","liteide");
        locale = settings.value(LITEAPP_LANGUAGE,locale).toString();
        qss = settings.value(LITEAPP_QSS,"default.qss").toString();
    }

    if (!locale.isEmpty()) {
        const QString &liteideTrPath = resPath+"/translations";
        if (translator.load(QLatin1String("liteide_") + locale, liteideTrPath)) {
            const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
            const QString &qtTrFile = QLatin1String("qt_") + locale;
            // Binary installer puts Qt tr files into creatorTrPath            
            app.installTranslator(&translator);
            if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, liteideTrPath)) {
                app.installTranslator(&qtTranslator);
            }
            app.setProperty("liteide_locale", locale);
        }
    }
    if (!qss.isEmpty()) {
        QFile f(resPath+"/liteapp/qss/"+qss);
        if (f.open(QFile::ReadOnly)) {
            QString styleSheet = QLatin1String(f.readAll());
            app.setStyleSheet(styleSheet);
        }
    }

    QDir::addSearchPath("icon",resPath);
    QDir::addSearchPath("icon",resPath+"/liteapp");
    QDir::addSearchPath("icon",":/");
#if QT_VERSION >= 0x050000
    QString storage = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
    QString storage = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
    QDir dir(storage);
    dir.mkdir("liteide");

    QStringList argList;
    QStringList fileList;
    if (argc >= 2) {
        for (int i = 1; i < argc; i++) {
            QString arg = argv[i];
            if (arg.startsWith("-")) {
                argList.append(arg);
                continue;
            } else {
                fileList.append(arg);
            }
        }
    }

    IApplication *liteApp = LiteApp::NewApplication(true,0);

    if (fileList.size() == 1) {
        QString file = fileList.at(0);
        QFileInfo f(file);
        if (f.isFile()) {
            liteApp->fileManager()->addFolderList(f.path());
            liteApp->fileManager()->openEditor(file);
        } else if (f.isDir()) {
            liteApp->fileManager()->addFolderList(file);
        }
    } else {
        foreach(QString file, fileList) {
            QFileInfo f(file);
            if (f.isFile()) {
                liteApp->fileManager()->openEditor(file);
            } else if (f.isDir()) {
                liteApp->fileManager()->addFolderList(file);
            }
        }
    }
extern "C" bool CGT_DeleteFiles(
    CGT_CDiagMsg*pdm,
    const TCHAR* pszDir,
    const TCHAR* pszPattern,
    const TCHAR* pszExcFiles,
    bool         bSubDirs,
    const TCHAR* pszExcDirs
)
{
    bool            bOk;
    HANDLE          hd;
    HRESULT         hr;
    WIN32_FIND_DATA findFileData;    
    FC_CString      dir(MAX_PATH);
    FC_CString      file(MAX_PATH);


    if(pszDir && !FC_StringIsAbsPath(pszPattern))
        file.appendDir(pszDir);

    file.appendDir(pszPattern);

    dir.load(file).stripFilePart();


    //force absolute path:
    if(!FC_StringIsAbsPath(file))
    {
        CGT_IERR(pdm, _T("CGT_DeleteFiles called for relative path")); 
        return false;
    }


    //be carefull !
    //don't allow * pattern unless looks at least like gen dir:
    if(_tcschr(file, _T('*')) && !_tcsstr(file, _T("\\gen\\")))
    {
        CGT_IERR(pdm, _T("CGT_DeleteFiles called with '*' pattern but path contains no '\\gen\\'")); 
        return false;
    }

    //don't allow recursive unless looks at least like gen dir:
    if(bSubDirs && !_tcsstr(file, _T("\\gen\\")))
    {
        CGT_IERR(pdm, _T("CGT_DeleteFiles called with bSubDirs==true but path contains no '\\gen\\'")); 
        return false;
    }

    
    //dirty work:
    hd = FindFirstFile(file, &findFileData);
    if(hd == INVALID_HANDLE_VALUE)
    {
        hr = GetLastError();
        bOk = hr==ERROR_FILE_NOT_FOUND || hr==ERROR_PATH_NOT_FOUND; 
        if(!bOk)
            pdm->sysErr(GetLastError(), NULL, _T("FindFirstFile in folder:"), dir);
        return bOk;
    }
    
    if((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==0)
    {
        if(!pszExcFiles || !FC_StringMatchFilePattern(findFileData.cFileName, pszExcFiles))
        {
            file.load(dir).appendDir(findFileData.cFileName);
            if(!DeleteFile(file))
            {
                pdm->msg1(CG_E_FILE_DELETE, NULL, file);
                goto Error;
            }
        }
    }
    else if(bSubDirs && !IsDotDotDir(findFileData.cFileName))
    {
        if(!pszExcDirs || !FC_StringMatchFilePattern(findFileData.cFileName, pszExcDirs))
        {
            dir.appendDir(findFileData.cFileName);
            bOk = CGT_DeleteFiles(pdm, dir, FC_StringGetFilePart(pszPattern), 
                                  pszExcFiles, bSubDirs, pszExcDirs
                  );
            dir.stripFilePart();
            if(!bOk)
               goto Error;
        }
    }
    
    while(FindNextFile(hd , &findFileData))
    {
        if((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==0)
        {
            if(!pszExcFiles || !FC_StringMatchFilePattern(findFileData.cFileName, pszExcFiles))
            {
                file.load(dir).appendDir(findFileData.cFileName);
                if(!DeleteFile(file))
                {
                    pdm->msg1(CG_E_FILE_DELETE, NULL, file);
                    goto Error;
                }
            }
        }
        else if(bSubDirs && !IsDotDotDir(findFileData.cFileName))
        {
            if(!pszExcDirs || !FC_StringMatchFilePattern(findFileData.cFileName, pszExcDirs))
            {
                dir.appendDir(findFileData.cFileName);
                bOk = CGT_DeleteFiles(pdm, dir, FC_StringGetFilePart(pszPattern), 
                                  pszExcFiles, bSubDirs, pszExcDirs
                           );
                dir.stripFilePart();
                if(!bOk)
                   goto Error;
            }
        }
    }

    bOk = ERROR_NO_MORE_FILES == GetLastError();
    if(!FindClose(hd))
        bOk = false;

    if(!bOk)
        pdm->sysErr(GetLastError(), NULL, _T("delete files in folder:"), dir);

    return bOk;


Error: //must free find handle
    FindClose(hd);
    return false;
}
示例#16
0
mxProfile::mxProfile(wxWindow *parent):wxDialog(parent,wxID_ANY,_Z("Opciones del Lenguaje"),wxDefaultPosition,wxDefaultSize,wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER),old_config(LS_INIT) {
	
	text=NULL; // para que no procese el evento de seleccion al crear la lista
	
	old_config=config->lang;
	old_profile=config->profile;
	
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	
	wxBoxSizer *search_sizer = new wxBoxSizer(wxHORIZONTAL);
	search=new wxTextCtrl(this,wxID_FIND,"");
	search_sizer->Add(new wxStaticText(this,wxID_ANY,_Z("Buscar: ")),wxSizerFlags().Center());
	search_sizer->Add(search,wxSizerFlags().Proportion(1).Expand());
	
	sizer->Add(search_sizer,wxSizerFlags().Proportion(0).Expand().Border(wxALL,5));
	
	wxBoxSizer *button_sizer = new wxBoxSizer(wxHORIZONTAL);

	wxDir dir(config->profiles_dir);
	if ( dir.IsOpened() ) {
		wxString filename;
		wxString spec;
		bool cont = dir.GetFirst(&filename, spec , wxDIR_FILES);
		while ( cont ) {
			perfiles.Add(filename);
			cont = dir.GetNext(&filename);
		}
	}
	perfiles.Sort(comp_nocase);
	for(unsigned int i=0;i<perfiles.GetCount();i++) { 
		LangSettings l(LS_INIT); l.Load(DIR_PLUS_FILE(config->profiles_dir,perfiles[i]));
		descripciones.Add(l.descripcion.c_str());
	}
	
	list = new wxListCtrl(this,wxID_ANY,wxDefaultPosition,wxSize(200,200),wxLC_REPORT|wxLC_NO_HEADER|wxLC_SINGLE_SEL);
	list->InsertColumn(0,_Z("Perfil"));
	wxImageList *iml = new wxImageList(24,24,true);
	wxBitmap noimage(DIR_PLUS_FILE(DIR_PLUS_FILE(config->profiles_dir,"icons"),"null.png"),wxBITMAP_TYPE_PNG);
	for(unsigned int i=0;i<perfiles.GetCount();i++) {
		wxString ficon=DIR_PLUS_FILE(DIR_PLUS_FILE(config->profiles_dir,"icons"),perfiles[i]+".png");
		if (wxFileName::FileExists(ficon))
			iml->Add(wxBitmap(ficon,wxBITMAP_TYPE_PNG));
		else
			iml->Add(noimage);
	}
	iml->Add(wxBitmap(DIR_PLUS_FILE(DIR_PLUS_FILE(config->profiles_dir,"icons"),"personalizado.png"),wxBITMAP_TYPE_PNG));
	list->AssignImageList(iml,wxIMAGE_LIST_SMALL);
	
	Search();
	
	text = new wxTextCtrl(this,wxID_ANY,_T(""),wxDefaultPosition,wxDefaultSize,wxTE_MULTILINE|wxTE_READONLY);
	LoadProfile();
	
	wxButton *options_button = new mxBitmapButton (this, wxID_ABOUT, bitmaps->buttons.next, _Z("Personalizar..."));
	wxButton *ok_button = new mxBitmapButton (this, wxID_OK, bitmaps->buttons.ok, _Z("Aceptar"));
	wxButton *cancel_button = new mxBitmapButton (this, wxID_CANCEL, bitmaps->buttons.cancel, _Z("Cancelar"));
	button_sizer->Add(options_button,wxSizerFlags().Border(wxALL,5).Proportion(0).Expand());
	button_sizer->AddStretchSpacer(1);
	button_sizer->Add(cancel_button,wxSizerFlags().Border(wxALL,5).Proportion(0).Expand());
	button_sizer->Add(ok_button,wxSizerFlags().Border(wxALL,5).Proportion(0).Expand());
	
	sizer->Add(new wxStaticText(this,wxID_ANY,_Z(" Seleccione un perfil para configurar las reglas del lenguaje: ")),wxSizerFlags().Expand().Proportion(0).Border(wxTOP,5));
	sizer->Add(list,wxSizerFlags().Expand().Proportion(3).FixedMinSize());
	sizer->Add(new wxStaticText(this,wxID_ANY,_Z("")),wxSizerFlags().Expand().Proportion(0));
	sizer->Add(new wxStaticText(this,wxID_ANY,_Z(" Descripción del perfil seleccionado:")),wxSizerFlags().Expand().Proportion(0));
	sizer->Add(text,wxSizerFlags().Expand().Proportion(1).FixedMinSize());
	sizer->Add(new wxStaticText(this,wxID_ANY,""),wxSizerFlags().Expand().Proportion(0));
	sizer->Add(button_sizer,wxSizerFlags().Expand().Proportion(0));
	
	ok_button->SetDefault();
	SetEscapeId(wxID_CANCEL);
	
	SetSizerAndFit(sizer);
	
	this->Layout(); // para ajustar el tamaño de la columna de la lista
	list->SetColumnWidth(0,list->GetSize().GetWidth()-32);
	
	search->SetFocus();
	
	ShowModal();
}
示例#17
0
void SearchSet::addDirectory(const String &name, const String &directory, int priority, int depth, bool flat) {
	FSNode dir(directory);
	addDirectory(name, dir, priority, depth, flat);
}
示例#18
0
static WCHAR *GetGhostscriptPath()
{
    WCHAR *gsProducts[] = {
        L"AFPL Ghostscript",
        L"Aladdin Ghostscript",
        L"GPL Ghostscript",
        L"GNU Ghostscript",
    };

    // find all installed Ghostscript versions
    WStrVec versions;
    REGSAM access = KEY_READ | KEY_WOW64_32KEY;
TryAgain64Bit:
    for (int i = 0; i < dimof(gsProducts); i++) {
        HKEY hkey;
        ScopedMem<WCHAR> keyName(str::Join(L"Software\\", gsProducts[i]));
        if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, access, &hkey) != ERROR_SUCCESS)
            continue;
        WCHAR subkey[32];
        for (DWORD ix = 0; RegEnumKey(hkey, ix, subkey, dimof(subkey)) == ERROR_SUCCESS; ix++)
            versions.Append(str::Dup(subkey));
        RegCloseKey(hkey);
    }
    if ((access & KEY_WOW64_32KEY)) {
        // also look for 64-bit Ghostscript versions under 64-bit Windows
        access = KEY_READ | KEY_WOW64_64KEY;
#ifndef _WIN64
        // (unless this is 32-bit Windows)
        if (IsRunningInWow64())
#endif
        goto TryAgain64Bit;
    }
    versions.SortNatural();

    // return the path to the newest installation
    for (size_t ix = versions.Count(); ix > 0; ix--) {
        for (int i = 0; i < dimof(gsProducts); i++) {
            ScopedMem<WCHAR> keyName(str::Format(L"Software\\%s\\%s",
                                                 gsProducts[i], versions.At(ix - 1)));
            ScopedMem<WCHAR> GS_DLL(ReadRegStr(HKEY_LOCAL_MACHINE, keyName, L"GS_DLL"));
            if (!GS_DLL)
                continue;
            ScopedMem<WCHAR> dir(path::GetDir(GS_DLL));
            ScopedMem<WCHAR> exe(path::Join(dir, L"gswin32c.exe"));
            if (file::Exists(exe))
                return exe.StealData();
            exe.Set(path::Join(dir, L"gswin64c.exe"));
            if (file::Exists(exe))
                return exe.StealData();
        }
    }

    // if Ghostscript isn't found in the Registry, try finding it in the %PATH%
    DWORD size = GetEnvironmentVariable(L"PATH", NULL, 0);
    ScopedMem<WCHAR> envpath(AllocArray<WCHAR>(size));
    if (size > 0 && envpath) {
        GetEnvironmentVariable(L"PATH", envpath, size);
        WStrVec paths;
        paths.Split(envpath, L";", true);
        for (size_t ix = 0; ix < paths.Count(); ix++) {
            ScopedMem<WCHAR> exe(path::Join(paths.At(ix), L"gswin32c.exe"));
            if (file::Exists(exe))
                return exe.StealData();
            exe.Set(path::Join(paths.At(ix), L"gswin64c.exe"));
            if (file::Exists(exe))
                return exe.StealData();
        }
    }

    return NULL;
}
示例#19
0
/// \brief initiate the ultracopier event dispatcher and check if no other session is running
DebugEngine::DebugEngine()
{
	addDebugInformationCallNumber=0;
	//Load the first content
	debugHtmlContent+="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">";
	debugHtmlContent+="<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">";
	debugHtmlContent+="<head>";
	debugHtmlContent+="<meta name=\"Language\" content=\"en\" />";
	debugHtmlContent+="<meta http-equiv=\"content-language\" content=\"english\" />";
	debugHtmlContent+="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />";
	debugHtmlContent+="<style type=\"text/css\">";
	debugHtmlContent+="body{font-family:\"DejaVu Sans Mono\";font-size:9pt;}";
	debugHtmlContent+=".Information td{color:#7485df;}";
	debugHtmlContent+=".Critical td{color:#ff0c00;background-color:#FFFE8C;}";
	debugHtmlContent+=".Warning td{color:#efa200;}";
	debugHtmlContent+=".Notice td{color:#999;}";
	debugHtmlContent+=".time{font-weight:bold;}";
	debugHtmlContent+=".Note{font-weight:bold;font-size:1.5em}";
	debugHtmlContent+=".function{font-style:italic;text-decoration:underline}";
	debugHtmlContent+=".location{padding-right:15px;}";
	debugHtmlContent+="td {white-space:nowrap;}";
	debugHtmlContent+="</style>";
	debugHtmlContent+="<title>Ultracopier "+QString(ULTRACOPIER_VERSION)+" "+QString(ULTRACOPIER_PLATFORM_NAME)+", debug report</title>";
	debugHtmlContent+="</head>";
	debugHtmlContent+="<body>";
	debugHtmlContent+="<table>";
	//Load the start time at now
	startTime.start();
	//Load the log file end
	endOfLogFile="</table></body></html>";
	//check if other instance is running, then switch to memory backend
	if(tryConnect())
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_custom_Notice,"currentBackend: File because other session is runing");
		currentBackend=Memory;
		return;
	}
	//The lock and log file path is not defined
	bool fileNameIsLoaded=false;
	#ifdef ULTRACOPIER_VERSION_PORTABLE
		#ifdef ULTRACOPIER_VERSION_PORTABLEAPPS
			//Load the data folder path
			QDir dir(QCoreApplication::applicationDirPath());
			dir.cdUp();
			dir.cdUp();
			dir.cd("Data");
			logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
			lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
			fileNameIsLoaded=true;
		#else
			//Load the ultracopier path
			QDir dir(QCoreApplication::applicationDirPath());
			logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
			lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
			fileNameIsLoaded=true;
		#endif
	#else
		#ifdef Q_OS_WIN32
			#define EXTRA_HOME_PATH "\\ultracopier\\"
		#else
			#define EXTRA_HOME_PATH "/.config/Ultracopier/"
		#endif
		//Load the user path only if exists and writable
		QDir dir(QFSFileEngine::homePath()+EXTRA_HOME_PATH);
		bool errorFound=false;
		//If user's directory not exists create it
		if(!dir.exists())
		{
			//If failed not load the file
			if(!dir.mkpath(dir.absolutePath()))
			{
				errorFound=true;
				puts(qPrintable("Unable to make path: "+dir.absolutePath()+", disable file log"));
			}
		}
		//If no error found set the file name
		if(errorFound==false)
		{
			fileNameIsLoaded=true;
			logFile.setFileName(dir.absolutePath()+QDir::separator()+"log.html");
			lockFile.setFileName(dir.absolutePath()+QDir::separator()+"ultracopier.lock");
		}
		errorFound=false;
	#endif
	//If the file name is loaded
	if(fileNameIsLoaded)
	{
		//If the previous file is here, then crash previous, ask if the user want to save
		if(lockFile.exists() && logFile.exists())
		{
			//Try open the file as read only to propose save it as the user
			//Don't ask it if unable to write, because unable to remove, then alert at all start
			if(removeTheLockFile())
			{
				//Ask to the user
				QMessageBox::StandardButton reply = QMessageBox::question(NULL,"Save the previous report","Ultracopier seam have crashed, do you want save the previous report for report it to the forum?",QMessageBox::Yes|QMessageBox::No,QMessageBox::No);
				if(reply==QMessageBox::Yes)
					saveBugReport();
			}
			else
				puts(qPrintable(logFile.fileName()+" unable to open it as read"));
		}
		//Now try to create and open the log file and lock file
		if(!lockFile.open(QIODevice::WriteOnly|QIODevice::Truncate|QIODevice::Unbuffered))
		{
			currentBackend=Memory;
			puts(qPrintable(lockFile.fileName()+" unable to open it as write, log into file disabled"));
		}
		else
		{
			if(!logFile.open(QIODevice::ReadWrite|QIODevice::Truncate|QIODevice::Unbuffered))
			{
				currentBackend=Memory;
				puts(qPrintable(logFile.fileName()+" unable to open it as write, log into file disabled"));
				removeTheLockFile();
			}
			else
			{
				currentBackend=File;
				logFile.write(debugHtmlContent.toUtf8());
			}
		}
	}
	if(currentBackend==File)
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_custom_Notice,"currentBackend: File");
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_custom_Notice,"currentBackend: Memory");
}
int PixmapAnimation::GetFrameCount(const QString &emotion) {
    QString path = QString("image/system/emotion/%1/").arg(emotion);
    QDir dir(path);
    dir.setNameFilters(QStringList("*.png"));
    return dir.entryList(QDir::Files | QDir::NoDotAndDotDot).count();
}
示例#21
0
EngineError KadmosDialog::findClassifiers()
{
    findClassifierPath();

    KLocale *locale = KGlobal::locale();
    QStringList allCountries = locale->allLanguagesTwoAlpha ();
    for ( QStringList::Iterator it = allCountries.begin();
          it != allCountries.end(); ++it )
    {
        m_longCountry2short[locale->twoAlphaToCountryName(*it)] = *it;
    }
    m_longCountry2short[i18n("European Countries")] = "eu";
    m_longCountry2short[ CNTRY_CZ ] = "cz";
    m_longCountry2short[ CNTRY_GB ] = "us";

    QStringList lst;

    /* custom Path */
    if( ! m_customClassifierPath.isEmpty() )
    {
        QDir dir( m_customClassifierPath );

        QStringList lst1 = dir.entryList( "ttf*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }

        lst1 = dir.entryList( "hand*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }

        lst1 = dir.entryList( "norm*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }
    }
    else
    {
        /* standard location */
        KStandardDirs stdDir;
        kdDebug(28000) << "Starting to read resource" << endl;

        lst = stdDir.findAllResources( "data",
                                       "kooka/classifiers/*.rec",
                                       true,   /* recursive */
                                       true ); /* uniqu */
    }


    /* no go through lst and sort out hand-, ttf- and norm classifier */
    for ( QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
    {
        QFileInfo fi( *it);
        QString name = fi.fileName().lower();

        kdDebug(28000) << "Checking file " << *it << endl;

        if( name.startsWith( "ttf" ) )
        {
            QString lang = name.mid(3,2);
            if( allCountries.contains(lang) )
            {
                QString lngCountry = locale->twoAlphaToCountryName(lang);
                if( lngCountry.isEmpty() )
                    lngCountry = name;
                m_ttfClassifier << lngCountry;
                kdDebug(28000) << "ttf: Insert country " << lngCountry << endl;
            }
            else if( lang == "cz" )
            {
                m_ttfClassifier << CNTRY_CZ;
            }
            else if( lang == "us" )
            {
                m_ttfClassifier << CNTRY_GB;
            }
            else
            {
                m_ttfClassifier << name;
                kdDebug(28000) << "ttf: Unknown country" << endl;
            }
        }
        else if( name.startsWith( "hand" ) )
        {
            QString lang = name.mid(4,2);
            if( allCountries.contains(lang) )
            {
                QString lngCountry = locale->twoAlphaToCountryName(lang);
                if( lngCountry.isEmpty() )
                    lngCountry = name;
                m_handClassifier << lngCountry;
            }
            else if( lang == "cz" )
            {
                m_handClassifier << i18n( "Czech Republic, Slovakia");
            }
            else if( lang == "us" )
            {
                m_handClassifier << i18n( "Great Britain, USA" );
            }
            else
            {
                kdDebug(28000) << "Hand: Unknown country " << lang << endl;
                m_handClassifier << name;
            }
        }
        else if( name.startsWith( "norm" ))
        {
            m_haveNorm = true;
        }

        kdDebug(28000) << "Found classifier: " << *it << endl;
        m_classifierPath << *it;
    }

    if( m_handClassifier.count()+m_ttfClassifier.count()>0 )
    {
        /* There are classifiers */
        return ENG_OK;
    }
    else
    {
        /* Classifier are missing */
        return ENG_DATA_MISSING;
    }
}
示例#22
0
bool GameEngine::moveAI(Actor* monster) {
	//Death Curse damage
	if (monster->getSpell().getSpellType() == 5) {
		monster->doDMG(3);
		if (monster->getHP() <= 0)
			killMonster(monster->getLoc());
	}

	Point heroLoc = hero->getLoc();
	Point loc = monster->getLoc();
	int xDist = heroLoc.x() - loc.x();
	int yDist = heroLoc.y() - loc.y();
	int which = 0;

	Point dir(0, 0);

	//Choose direction
	if (xDist == 0 && yDist == 0)
		dir = Point(0, 0);
	else if (xDist == 0 && yDist != 0)
		dir = Point(0, yDist / abs(yDist));
	else if (xDist != 0 && yDist == 0)
		dir = Point(xDist / abs(xDist), 0);
	else if (xDist != 0 && yDist != 0)
		dir = Point(xDist / abs(xDist), yDist / abs(yDist));


	//Move monster based on whether it's close enough to the hero or not
	if (abs(xDist) + abs(yDist) < 5) {
		loc = loc + pickAIPoint(monster, dir, false);
		monster->gettingTired();
	}
	else
		loc = loc + pickAIPoint(monster, dir, true);

	//Don't move the monster if it's next to the hero, make it attack
	if (Point(abs(xDist), abs(yDist)) == Point(0, 1) || Point(abs(xDist), abs(yDist)) == Point(1, 0))
		return true; //Is going to attack hero
	else {
		//Update loc in map grid
		try {
			if (loc > Point(0, 0) && loc < Point(63, 63)) {
				if (moveableCell(map[loc.x()][loc.y()].getLoc())) {
					if (!monster->isTired()) {
						if (map[monster->getLoc().x()][monster->getLoc().y()].getSpell().getSpellType() != 4) { //If monster is in ice block, don't move
							//Move the monster
							map[monster->getLoc().x()][monster->getLoc().y()].setActor(NULL);
							monster->setLoc(loc);
							map[loc.x()][loc.y()].setActor(monster);
						}

						if (map[loc.x()][loc.y()].getSpell().getSpellType() == 1) { //Field of fire, damage monster if they're in the spell
							monster->doDMG(2);
							if (monster->getHP() <= 0)
								killMonster(monster->getLoc());
						}
						else if (map[loc.x()][loc.y()].getSpell().getSpellType() == 6) {
							monster->doDMG(10);
							log.registerEvent(monster->getActorDef().getDESC() + " triggered Fist of Katar!");
							if (monster->getHP() <= 0)
								killMonster(monster->getLoc());
							map[loc.x()][loc.y()].setSpell(Spell());
						}
					}
				}
			}
		}
		catch (int e) {
			OutputDebugString(to_string(e).c_str());
		}
		return false;
	}
}
示例#23
0
/**
* 
* @brief Open the log file for putting the voltage readings
* 
* @return bool true on success, false otherwise
*/
bool TestMgr::VoltageLogOpenFile(void) {
	int status = 0;
	std::string name;
	QDate cd = QDate::currentDate();
	QTime ct = QTime::currentTime();

	// Create the logs directory if it does not exist
	QDir dir("/opt/ES/VocPhase1Test/Logs");
	if (!dir.exists()) {
		if (!dir.mkpath("/op/ES/VocPhase1Test/Logs")) {
			// creation failed
			status = -1;
		}
	}

	// Attempt to open the file and write header
	if (status == 0) {

		m_VoltageLogEntryNumber = 0;
		char buf[1024];

		if (m_TestId.length() > 0) {
			// Name format is log_yyyy-mm-dd_hhmmss_testId
			sprintf(buf, "/opt/ES/VocPhase1Test/Logs/log_%4d-%02d-%02d_%02d%02d%02d_%s.csv",
					cd.year(), cd.month(), cd.day(),
					ct.hour(), ct.minute(), ct.second(),
					m_TestId.toLocal8Bit().constData());
		} else {
			// Name format is log_yyyy-mm-dd_hhmmss
			sprintf(buf, "/opt/ES/VocPhase1Test/Logs/log_%4d-%02d-%02d_%02d%02d%02d.csv",
					cd.year(), cd.month(), cd.day(), ct.hour(), ct.minute(), ct.second());
		}

		m_LogFileHandle = fopen(buf, "w");
		if (m_LogFileHandle) {

			printf("LOG FILE IS OPEN: %s\n", buf);

			sprintf(buf, "Run Date,%d/%d/%d %02d:%02d:%02d\n",
					cd.year(), cd.month(), cd.day(), ct.hour(), ct.minute(), ct.second());
			fprintf(m_LogFileHandle, buf, "%s");

			if (m_TestId.length() > 0) {
				sprintf(buf, "Test ID,%s\n", m_TestId.toLocal8Bit().constData());
				fprintf(m_LogFileHandle, buf, "%s");
			}

			if (m_TestNote.length() > 0) {
				sprintf(buf, "Test Note,%s\n", m_TestNote.toLocal8Bit().constData());
				fprintf(m_LogFileHandle, buf, "%s");
			}

			fprintf(m_LogFileHandle,
					"%s,%s,%s,%s,%s\n",
					"Entry", "Time(ms)", "Temp(C)", "VAC(volts)", "FREQ(HZ)");
		} else {
			std::cout << "ERROR:  Could not open file for logging: " << buf << std::endl;
			status = -1;
		}
	}
	return (status == 0) ? true : false;
}
void teenyWeenySearchNtot(){



  // data location in the tree ///////////////////////
  TString ndir("/lustre/ncg.ingrid.pt/cmslocal/samples/CMSSW_5_3_9_def/");
  TString hdir("/lustre/ncg.ingrid.pt/cmslocal/vischia/ttbarDileptonAnalysis/topMassAnalysis/tDilbh/");
  TString cutflow("myEventSelector/Selection/cutflow");
  TString tag("data"); 
  TString id("myEventSelector");
  vector<TString> base;
  vector<double> max;
  vector<int> fromZero;
  vector<double> compareWith;
//  base.push_back(    "ttbar_")       ;max.push_back(50); fromZero.push_back(1); compareWith.push_back(8228517.   );
//  base.push_back("stop_s_")       ;max.push_back(20); compareWith.push_back(0.);
//  base.push_back("stop_t_")       ;max.push_back(20); compareWith.push_back(0.);
//  base.push_back("stop_tW-DR_")   ;max.push_back(20); compareWith.push_back(0.);
//  base.push_back("stopbar_s_")    ;max.push_back(20); compareWith.push_back(0.);
//  base.push_back("stopbar_t_")    ;max.push_back(50); compareWith.push_back(0.);
//  base.push_back("stopbar_tW-DR_");max.push_back(20); compareWith.push_back(0.);
//  base.push_back("WJetsToLNu_")      ;max.push_back(400); fromZero.push_back(1);	compareWith.push_back(43636521.	 );
//  base.push_back("dy_from50_")       ;max.push_back(200); fromZero.push_back(1);	compareWith.push_back(6084984.	 );
//  base.push_back("dy_10_50_")	     ;max.push_back(100); fromZero.push_back(1);	compareWith.push_back(20751565.	 );
//  base.push_back("WW_")	             ;max.push_back(50); fromZero.push_back(1);	compareWith.push_back(9000414.	 );
//  base.push_back("WZ_")	             ;max.push_back(50); fromZero.push_back(1);	compareWith.push_back(9050268.	 );
//  base.push_back("ZZ_") 	     ;max.push_back(50); fromZero.push_back(1);	compareWith.push_back(9022326.	 );
//  base.push_back("qcd_EM_Pt30to80_"     );max.push_back(100); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("qcd_EM_Pt80to170_"    );max.push_back(100); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("qcd_30to80_BCtoE_"    );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("qcd_80to170_BCtoE_"   );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("PhotonJets_30to50_"   );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("PhotonJets_50to80_"   );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("PhotonJets_80to120_"  );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("PhotonJets_120to170_" );max.push_back(50); fromZero.push_back(1); compareWith.push_back(0.);
//  base.push_back("qcdmu15_20toinf_"     );max.push_back(100); fromZero.push_back(1); compareWith.push_back(0.);

  base.push_back("htb-pythia-m180_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(300000.	 );
  base.push_back("htb-pythia-m200_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(299999.	 );
  base.push_back("htb-pythia-m220_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(299999.	 );
  base.push_back("htb-pythia-m240_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(300000.	 );
  base.push_back("htb-pythia-m250_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(299668.	 );
  base.push_back("htb-pythia-m260_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(299686.	 );
  base.push_back("htb-pythia-m280_") ;max.push_back(30); fromZero.push_back(1);	compareWith.push_back(300000.	 );
  base.push_back("htb-pythia-m300_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  base.push_back("htb-pythia-m350_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  base.push_back("htb-pythia-m400_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  base.push_back("htb-pythia-m500_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  base.push_back("htb-pythia-m600_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  base.push_back("htb-pythia-m700_") ;max.push_back(30); fromZero.push_back(1); compareWith.push_back(300000.    );
  

  for(size_t i=0; i<base.size(); ++i){
    cout << "Base: " << base[i] << endl;
    TString dir( base[i].Contains("htb-pythia") ? hdir : ndir);
    double nevts(0);
    if(fromZero[i]){
      for(size_t k=0; k<max[i]; ++k){
	stringstream sidx;
	sidx<<k;
	string idx=sidx.str();

	TFile* f= new TFile(dir + base[i] + TString(idx) + TString(".root"));
	TH1D* h = (TH1D*) f->Get(cutflow);
	if(h) nevts+=h->GetBinContent(1);
	else cout << "Damaged file " << k << endl;
	f->Close();
      }
     
    }
    else{
      for(size_t k=1; k<=max[i]; ++k){
	stringstream sidx;
	sidx<<k;
	string idx=sidx.str();

	TFile* f= new TFile(dir + base[i] + TString(idx) + TString(".root"));
	TH1D* h = (TH1D*) f->Get(cutflow);
	if(h) nevts+=h->GetBinContent(1);
	else cout << "Damaged file " << i << endl;
	f->Close();
      }
    }

    stringstream sghi;
    sghi<<compareWith[i];
    string ghi=sghi.str();
	
    TString result( (nevts== compareWith[i]) ? "OK" : "BAD: code has "+ghi+"events"  );
    cout << setprecision(10) << "events total: " << nevts << ", which is " << result << endl;
  }


}
示例#25
0
bool DynamicsWorld::castRay(
	const btVector3 & origin,
	const btVector3 & direction,
	const btScalar length,
	const btCollisionObject * caster,
	COLLISION_CONTACT & contact) const
{
	btVector3 p = origin + direction * length;
	btVector3 n = -direction;
	btScalar d = length;
	int patch_id = -1;
	const BEZIER * b = 0;
	const TRACKSURFACE * s = TRACKSURFACE::None();
	const btCollisionObject * c = 0;

	MyRayResultCallback ray(origin, p, caster);
	rayTest(origin, p, ray);

	// track geometry collision
	bool geometryHit = ray.hasHit();
	if (geometryHit)
	{
		p = ray.m_hitPointWorld;
		n = ray.m_hitNormalWorld;
		d = ray.m_closestHitFraction * length;
		c = ray.m_collisionObject;
		if (c->isStaticObject())
		{
			TRACKSURFACE* tsc = static_cast<TRACKSURFACE*>(c->getUserPointer());
			const std::vector<TRACKSURFACE> & surfaces = track->GetSurfaces();
			if (tsc >= &surfaces[0] && tsc <= &surfaces[surfaces.size()-1])
			{
				s = tsc;
			}
#ifndef EXTBULLET
			else if (c->getCollisionShape()->isCompound())
			{
				TRACKSURFACE* tss = static_cast<TRACKSURFACE*>(ray.m_shape->getUserPointer());
				if (tss >= &surfaces[0] && tss <= &surfaces[surfaces.size()-1])
				{
					s = tss;
				}
			}
#endif
			//std::cerr << "static object without surface" << std::endl;
		}

		// track bezierpatch collision
		if (track)
		{
			MATHVECTOR<float, 3> org(ToMathVector<float>(origin));
			MATHVECTOR<float, 3> dir(ToMathVector<float>(direction));
			MATHVECTOR<float, 3> colpoint;
			MATHVECTOR<float, 3> colnormal;
			patch_id = contact.GetPatchId();
			if (track->CastRay(org, dir, length, patch_id, colpoint, b, colnormal))
			{
				p = ToBulletVector(colpoint);
				n = ToBulletVector(colnormal);
				d = (colpoint - org).Magnitude();
			}
		}

		contact = COLLISION_CONTACT(p, n, d, patch_id, b, s, c);
		return true;
	}

	// should only happen on vehicle rollover
	contact = COLLISION_CONTACT(p, n, d, patch_id, b, s, c);
	return false;
}
示例#26
0
//-----------------------------------------------------------------------
MainWindow::MainWindow()
	:	GraphicsSceneMainWindow( new GuidoGraphicsView() , new QGuidoItemContainerFactory() )
{
	//Dynamic plugin load.
	QDir dir(QApplication::applicationDirPath());
	dir.cdUp();
	dir.cd("Plugins");
	QCoreApplication::addLibraryPath( dir.absolutePath());

	mGraphicsView->setRenderHint( QPainter::Antialiasing , true );

	//Guido Engine initialization.
	QGuidoPainter::startGuidoEngine();
	
	mIsWorkspaceModeOn = false;
	GraphicsSceneMainWindow::init();

	mGuidoItemContainerFactory = (QGuidoItemContainerFactory*)mFactory;
	mExportState = None;
	mExportWindow = 0;
	
	mLanguageTextEdit->setLineWrapMode(QTextEdit::NoWrap);
	
#ifdef USES_GUIDO_AR
	mPlayingContainer = 0;

	//Add the QPaletteItem-s
	QPaletteItem * paletteItem;
	//Sum palette
	paletteItem = new QPaletteItem( PALETTE_GUIDO_ELEMENT , 100 , 0);
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiAfter.png" ) ,			COMBINATION_AFTER );
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiOverEnd.png" ) ,		COMBINATION_OVER_ALIGN_RIGHT );
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiOverStart.png" ) ,		COMBINATION_OVER_ALIGN_LEFT );
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiBefore.png" ) ,		COMBINATION_BEFORE );
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiUnderStart.png" ) ,	COMBINATION_UNDER_ALIGN_LEFT );
	paletteItem->addInteraction( buildPixmapItem(RSC_DIR + "combiUnderEnd.png" ) ,		COMBINATION_UNDER_ALIGN_RIGHT );
	mPalettes << paletteItem;
	//Selection palette
	paletteItem = new QPaletteItem( PALETTE_GUIDO_ELEMENT , 100 , 0);
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Tail") ,			COMBINATION_TAIL );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Voice Head") ,	COMBINATION_VOICE_HEAD );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Head") ,			COMBINATION_HEAD );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Voice tail") ,	COMBINATION_VOICE_TAIL );
	mPalettes << paletteItem;
	//Selection palette
	paletteItem = new QPaletteItem( PALETTE_GUIDO_ELEMENT , 100 , 0);
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Transpose") ,		COMBINATION_TRANSPOSE );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Stretch") ,		COMBINATION_DURATION );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Rythm") ,			COMBINATION_RYTHM );
	paletteItem->addInteraction( new QGraphicsSimpleTextItem("Note") ,			COMBINATION_PITCH );
	mPalettes << paletteItem;

	for ( int i = 0 ; i < mPalettes.size() ; i++ )
	{
		//Set each palette pen & brush
		mPalettes[i]->setBrush( HIGHLIGHTED_BRUSH );
		QPen palettePen( HIGHLIGHTED_PEN );
		palettePen.setWidth( palettePen.width() * 2 );
		mPalettes[i]->setPen( palettePen );
		mGraphicsScene->addItem( mPalettes[i] );
		
		//Desactivate each palette (its activation will be done according to the palette combobox selected item)
		mPalettes[i]->setPaletteEnabled( false );
		
		//Palette's positioning policy
		mPalettes[i]->setPositioningPolicy(QPaletteItem::CENTER_AND_RESIZE_POLICY);
	}
	
	QPaletteManager::instance()->setActivationDelay(500);
	connect( QPaletteManager::instance() , SIGNAL(interactionActivated(QGraphicsItem*,QGraphicsItem*,int,int,int)) , this , SLOT( combineItems(QGraphicsItem*,QGraphicsItem*,int,int,int) ) );
	changeActivePalette(0);
#endif

	adaptActions();
	
	mGuidoHighlighter = 0;
}
示例#27
0
int main(int argc, char **argv)
{
    QtSingleApplication app("quimup", argc, argv);
    bool b_multiple_instances = false;
    QString locale = "xx";
    QString message;
    int filecount = 0;
    // handle command line args
    for (int a = 1; a < argc; ++a)
    {
        QString msg = QString::fromUtf8(argv[a]);

        if ( msg == "-p" || msg == "-play")
        {
            message = "-play:" + message;
        }
        else
        if ( msg == "-i" || msg == "-instance")
        {
            b_multiple_instances = true;
        }
        else
        if ( msg == "-l"  || msg == "-locale" )
        {
            if (a < (argc-1) )
            {
                locale = argv[a+1];
                // possible stray '-l'
                if ( locale.startsWith("-") || locale.startsWith("file") )
                    locale = "xx";
                else
                    a++;
            }
        }
        else
        if (msg == "-h" || msg == "-help")
        {
            printf ("----\nQuimup version 1.4.0\n"); // VERSION //
            printf ("© 2008-2014 Johan Spee <*****@*****.**>\n");
            printf ("This program is licensed by the GPL and distributed in the hope that it will be useful, but without any warranty.\n");
            printf ("----\ncommand line parameters:\n");
            printf (" -h(elp)           show this information and exit\n");
            printf (" -i(nstance)       force a new instance of Quimup\n");
            printf (" -l(ocale) xx      use locale 'xx' (fr, po, en_GB, etc) or 'none' to force internal locale\n");
            printf (" -l(ocale) file    use locale from full path to quimup_xx.qm file\n");
            printf (" -p(lay) %%U        play files in %%U (or %%F) in new playlist\n");
            printf ("  %%U               append files in %%U (or %%F) to the playlist\n----\n");
            return 0;
        }
        else // if URL
        if ( msg.startsWith("file://"))
        {
            // we have a string in URL format, so convert special chars:
            msg = ( QUrl::fromEncoded ((const char*)msg.toUtf8()) ).toString();
            message.append(msg);
            filecount++;
        }
        else //  if plain path
        if (msg.startsWith("/") )
        {
            msg = "file://" + msg; // used as separator
            message.append(msg);
            filecount++;
        }
    }

    // send the args (and find out if a previous instance exists)
    if (!b_multiple_instances && app.sendMessage(message))
    {
        printf ("Quimup : already running (use '-i' to force a new instance)\n");
        return 0;
    }

    printf ("Quimup : starting new instance\n");

    //// Localization start >
    QTranslator trnsltr;
    //QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    bool b_locale_loaded = false;
    bool b_locale_default = true;
    if (locale == "xx") // no -l parameter was passed
        locale = QLocale::system().name();
    else
        b_locale_default = false;

    if (locale != "none")
    {
        if (!b_locale_default)
        {
            printf ("Locale : '%s': ", (const char*)locale.toUtf8());
            if ( locale.startsWith("/") && locale.endsWith(".qm")) // full path to a file
            {
                if ( trnsltr.load(locale) )
                {
                   printf ("OK\n");
                   b_locale_loaded = true;
                }
                else
                   printf ("failed! (using none)\n");
            }
            else // first try installation path, next default path
            {
                QDir dir(QApplication::applicationDirPath());

                if ( trnsltr.load(QString("quimup_") + locale, dir.absolutePath()) )
                {
                    printf ("OK (from %s)\n", (const char*)dir.absolutePath().toUtf8());
                    b_locale_loaded = true;
                }
                else
                {
                    if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
                    {
                        printf ("OK (from default location)\n");
                        b_locale_loaded = true;
                    }
                    else
                         printf ("failed! (using none)\n");
                }
            }

        }
        else // locale file in defaut system location
        {
            printf ("Locale : ");
            if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
            {
                printf ("using default (%s)\n", (const char*)locale.toUtf8());
                b_locale_loaded = true;
            }
            else
                printf ("using none\n");
        }
    }
    else
       printf ("Locale : using none (requested)\n");

    if (b_locale_loaded)
        app.installTranslator(&trnsltr);

    //// < end Localization

    qm_core *core = new qm_core();

    // handle files
    if (filecount > 0)
    {
        core->player->browser_window->plist_view->on_open_with_request(message);
    }

    QObject::connect(&app, SIGNAL(messageReceived(const QString&)), core, SLOT(on_message_from_2nd_instance(const QString&)));
    QObject::connect(&app, SIGNAL(aboutToQuit()), core, SLOT(on_system_quit()));

    return app.exec();
}
示例#28
0
Kfm::Kfm()
{
    pKfm = this;
    pHistory = new QStrList;
    
    kapp->setTopWidget( this );

    HTMLCache::load();
    
    pIconLoader = new KIconLoader();

    // We need this in KfmGui::KfmGui(), so moved it here. DF.
    QStrList* list = pIconLoader->getDirList();
    list->clear();
    QString tmp = kapp->kde_icondir().copy();
    list->append( tmp.data() );
    tmp = KApplication::localkdedir();
    tmp += "/share/icons";
    list->append( tmp.data() );

    KConfig *config = kapp->getConfig();
    QStrList dirList;
    config->setGroup("KDE Setup");
    config->readListEntry( "IconPath", dirList, ':' );

    for (const char *it=dirList.first(); it; it = dirList.next()) {
      QDir dir( it );

      if (dir.exists())
        list->append( it );
    }

    if ( KfmGui::rooticons )
    {
	kapp->enableSessionManagement( TRUE );
	kapp->setWmCommand( "" );
	
	connect( kapp, SIGNAL( saveYourself() ), this, SLOT( slotSave() ) );
	connect( kapp, SIGNAL( shutDown() ), this, SLOT( slotShutDown() ) );

        // Global configuration
	config->setGroup("KFM Misc Defaults");
        bAllowURLProps = config->readBoolEntry( "EnablePerURLProps", false );
        bTreeViewFollowMode = config->readBoolEntry( "TreeFollowsView", false);

	config->setGroup( "SM" );
	bool flag = config->hasKey( "URLs" );
	
	QStrList urlList;
	int n = config->readListEntry( "URLs", urlList );

	if ( !flag && KfmGui::rooticons == true )
	{
	    QString home = "file:";
	    home.detach();
	    home += QDir::homeDirPath().data();
	    KfmGui *m = new KfmGui( 0L, 0L, home.data() );
	    m->show();
	}

	if ( flag )
	{
	    int i;
	    for ( i = 1; i <= n; i++ )
	    {
		KfmGui *m = new KfmGui( 0L, 0L, urlList.at( i - 1 ) );
		m->readProperties(i);
		m->show();
	    }
	}
    }

    // Install HTTP Cookies
    {
        KConfig *config = kapp->getConfig();
        config->setGroup( "Browser Settings/HTTP" );
        
        bool cookiesEnabled = config->readBoolEntry( "Cookies", true );
        if ( cookiesEnabled)
        {
            cookiejar = new KCookieJar();
                            
            cookiejar->loadConfig( config );
                                    
            QString cookieFile = kapp->localkdedir().data();
            cookieFile += "/share/apps/kfm/cookies";
            cookiejar->loadCookies( cookieFile.data() );
        }
    }

    connect( &timer, SIGNAL( timeout() ), this, SLOT( slotTouch() ) );
    // Call every hour
    timer.start( 3600000 );
}
int main(int argc, char *argv[])
{
    timeSelector::addOptions();
    #include "addRegionOption.H"
    Foam::argList::addOption
    (
        "dir",
        "word",
        "Direction to remove in TKE. -dir x, or y, or z."
    );
    #include "setRootCase.H"
    #include "createTime.H"
    instantList timeDirs = timeSelector::select0(runTime, args);
    #include "createNamedMesh.H"
    
    if (args.optionFound("dir")==true)
    {
        word dir(args.optionRead<word>("dir"));
        
        forAll(timeDirs, timeI)
        {
            runTime.setTime(timeDirs[timeI], timeI);
            Info<< "Time = " << runTime.timeName() << endl;
            
            
            IOobject UPrime2MeanHeader
            (
                "UPrime2Mean",
                runTime.timeName(),
                mesh,
                IOobject::MUST_READ
            );
            
            volScalarField TKE2D
            (
                IOobject
                (
                    "TKE2D",
                    runTime.timeName(),
                    mesh,
                    IOobject::NO_READ,
                    IOobject::AUTO_WRITE
                ),
                mesh,
                dimensionedScalar
                (
                    "dimTKE2D",
                    pow(dimLength,2)/pow(dimTime,2),
                    0
                ),
                "zeroGradient"
            );
            
            if (UPrime2MeanHeader.headerOk())
            {
                Info<< "    Reading average field UPrime2Mean" << endl;
                volSymmTensorField UPrime2Mean(UPrime2MeanHeader, mesh);         
                
                if (dir=="x")
                {
                    Info << "    Calculating 2D turbulent kinetic energy TKE2D without the " 
                         << dir << "component." << endl;
                    TKE2D = 0.5 * (
//                               UPrime2Mean.component(0)
                              UPrime2Mean.component(3)
                            + UPrime2Mean.component(5)
                            );
                }
                else if (dir=="y")
                {
                    Info << "    Calculating 2D turbulent kinetic energy TKE2D without the " 
                         << dir << "component." << endl;
                    TKE2D = 0.5 * (
                              UPrime2Mean.component(0)
//                             + UPrime2Mean.component(3)
                            + UPrime2Mean.component(5)
                            );
                }
                else if (dir=="z")
                {
                    Info << "    Calculating 2D turbulent kinetic energy TKE2D without the " 
                         << dir << "component." << endl;
                    TKE2D = 0.5 * (
                              UPrime2Mean.component(0)
                            + UPrime2Mean.component(3)
//                             + UPrime2Mean.component(5)
                            );
                }
                else
                {
                    Info << "    dir must be x, y or z" << endl;
                }
            
            TKE2D.write();


            }
            else
            {
                Info << "No UPrime2Mean." << endl;
                return 1;
            }

        } 
示例#30
0
static void split_convex(const std::vector<DPoint>& in,
                         std::vector<DPoint>& out, std::vector<size_t>& cvx)
{
    // initialization
    std::vector<DPoint>::const_iterator p=in.begin(), pmax = in.end();
    bool is_closed = (in.front()==in.back());

    if(in.size()<4) {
        while(p!=pmax)
            out.push_back(*p++);
        cvx.push_back( out.size() );
        return;
    }

    int ni = 0;
    DPoint p1(*p++),p2(*p++),p3(*p++);
    out.push_back(p1);
    int d2 = dir(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);

    // MAIN LOOP : d1=angle(P1-P2-P3) and d2=angle(P2-P3-P4)

    bool ok = true;
    std::vector<DPoint>::const_iterator first=in.begin();

    while (ok) {
        int d1 = d2;
        DPoint p4=*p++;
        d2 = dir(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);

        if(d1*d2>0) { // convex part: store point and increment p
            out.push_back(p1=p2);
            p2 = p3;
            p3 = p4;
        }
        else if(d1*d2<0) { // split curve
            out.push_back(p2);
            DPoint m = .5*(p2+p3);
            out.push_back(m);
            cvx.push_back( out.size() );
            if(p==first)
                ok=false;
            if(first==in.begin())
                first=p;
            if(ok) {
                if(is_closed && !ni) {
                    out.clear();
                    cvx.clear();
                    cvx.push_back(0);
                }
                out.push_back(m);
                ni++;
                p1 = p2;
                p2 = p3;
                p3 = p4;
            }
        } else { // undefined sign: remove one point
            if(d1==0 || d2==0) {
                if(d1==0)
                    p2 = p3;
                p3 = p4;
                d2 = dir(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
            } else
                assert(false); // NaN in curve?
        }

        // test end of loop
        if(ok && p==pmax) {
            if (is_closed)
                p = in.begin()+1;
            else
                ok=false;
        }

        // stop for convex closed curves
        if(p==in.begin()+3 && ni==0)
            ok=false;
    }
    // END OF MAIN LOOP

    if (!is_closed) {
        out.push_back(p2);
        out.push_back(p3);
        cvx.push_back( out.size() );
    } else if(ni==0) { // convex closed curve */
        if (out.end() == out.begin()+1)
            out.push_back( out.front() );
        else
            out[0] = out.back();
        cvx.push_back( out.size() );
    }
}