void HelpForm::on_pushButton_clicked()
{
//    QProcess::startDetached(QString("qrc:/help/help-%1.").arg(ui->cbLang->currentText()) );
    QString fileName = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + QString("/help-%1.pdf").arg(ui->cbLang->currentText());
    QString sourceFileName = QString(":/help/help-%1.pdf").arg(ui->cbLang->currentText());
    int sourceFileSize = 0;
    if(true){
        QFileInfo fi(sourceFileName);
        sourceFileSize = fi.size();
    }

    QFileInfo fi(fileName);
    if(!fi.exists() || fi.size() < 1000 || fi.size() != sourceFileSize){
        QSaveFile sfile(fileName);

        QFile file(sourceFileName);

        if(sfile.open(QSaveFile::WriteOnly|QSaveFile::Unbuffered)){
            file.open(QFile::ReadOnly);
            sfile.write(file.readAll());
            sfile.commit();
            file.close();
        }
    }
    if(fileName.startsWith("/"))
        fileName = fileName.mid(1);
    fileName.prepend("file:///");

    QDesktopServices::openUrl(QUrl(fileName ));
}
Exemple #2
0
mesh::mesh(std::string vfile_name, std::string sfile_name, std::string efile_name)
{
    std::ifstream vfile(vfile_name.c_str()), sfile(sfile_name.c_str()), efile(efile_name.c_str());

    vfile >> nv;
    sfile >> ns;
    efile >> ne;

    v = new vertex[nv];
    s = new side[ns];
    e = new element[ne];

    read_vertices(vfile);
    read_sides(sfile);
    read_elems(efile);

    vfile.close();
    sfile.close();
    efile.close();

    compute_geom_props();
    init_boundary_vertices();
    init_boundary_sides();

    ncolors = edge_coloring::do_edge_coloring(*this, false);
    nbcolors = edge_coloring::do_edge_coloring(*this, true);

    init_color_sides();
    init_b_color_sides();
}
Exemple #3
0
void IndicatorDataView::initView(const QString& indicator)
{
  if(!mPainter->mIndicator) return;

  mIndicator = indicator;

  // Delete old entries

  // Insert new entries
  QStringList var;
  //mPainter->mData->getVariableNames(var);
  QSet<QString> varList;
  mPainter->mIndicator->getVariableNames(&varList);
  var = varList.values();
  //qDebug() << "IndicatorDataView::initView()" << var << varList.size();

  // Sort the variable list, but place the bardata as block in front
  var.removeAt(var.indexOf("OPEN"));
  var.removeAt(var.indexOf("HIGH"));
  var.removeAt(var.indexOf("LOW"));
  var.removeAt(var.indexOf("CLOSE"));
  var.removeAt(var.indexOf("VOLUME"));
  var.removeAt(var.indexOf("OPINT"));
  var.sort();
  var.prepend("OPINT");
  var.prepend("VOLUME");
  var.prepend("CLOSE");
  var.prepend("LOW");
  var.prepend("HIGH");
  var.prepend("OPEN");
  var.prepend("Date"); // Should not be a variable but is also interesting

  // And now insert entries
  int row = 0;
  QString name;
  QCheckBox* cb;

  mFilterView.setColumnCount(1);
  mFilterView.setRowCount(var.size());

  // Restore saved settings, if some
  QString filterPath;
  filterPath = mRcFile->getPath("FiluHome");
  filterPath.append("IndicatorFilterSettings/");
  SettingsFile sfile(filterPath + mIndicator);

  foreach(name, var)
  {
    cb = new QCheckBox(name);
    if(sfile.getBL(name))
    {
      cb->setCheckState(Qt::Checked);
    }
    else
    {
      cb->setCheckState(Qt::Unchecked);
    }
    connect(cb, SIGNAL(stateChanged(int)), this, SLOT(filterChanged(int)));
    mFilterView.setCellWidget(row++, 0, cb);
  }
Exemple #4
0
void IndiWidgetSimple::readSettings()
{
  // FIXME: Hardcoded settings
  mSheet->useFont(QFont("DejaVu Sans", 9, 50, 0));
  mSheet->useScaleColor(QColor(Qt::white));
  mSheet->useGridColor(QColor(Qt::gray));
  mSheet->useSheetColor(QColor(Qt::black));
  mSheet->setPalette(QPalette(QColor(Qt::black)));
  mSheet->setDateRange(QDate(1900,1,1), QDate::currentDate());

  // Individual settings
  SettingsFile sfile(mFullIndiSetsPath + mSetName);
  mSheet->setDensity(sfile.getDB("Density", 10));
  mSheet->showYScale(sfile.getBL("ShowYScale"));

  sfile.beginGroup(mName);
  mUsedIndiFile = sfile.getST("Indicator", "Default");
  mSheet->useIndicator(mUsedIndiFile);
  mSheet->showGrid(sfile.getBL("ShowGrid"));
  mSheet->showGrid(sfile.getBL("ShowGrid"));
  mSheet->showXScale(sfile.getBL("ShowXScale"));
  mSheet->mPainter->mScaleToScreen = sfile.getIT("ScaleToScreen", 10);

  watchIndicator();
}
Exemple #5
0
void CsoundSoundController::openExerciseFile()
{
    QStringList templateList;
    templateList.append(QStringLiteral("assets:/share/template.csd"));
    templateList.append(QStringLiteral("assets:/share/template_rhythm.csd"));

    foreach (const QString &templateString, templateList) {
        QFile sfile(templateString);
        if (!sfile.open(QIODevice::ReadOnly | QIODevice::Text))
            return;

        QTextStream in(&sfile);
        QString lineData;
        QString tempBeginLine;
        QString tempEndLine;

        while (!in.atEnd()) {
            lineData = in.readLine();
            tempBeginLine = tempBeginLine + lineData + "\n";
            if (lineData.contains("<CsScore>")) {
                m_begLine.append(tempBeginLine);
                break;
            }
        }

        while (!in.atEnd()) {
            lineData = in.readLine();
            tempEndLine += lineData + "\n";
        }
        m_endLine.append(tempEndLine);
    }
Exemple #6
0
void IndiWidgetGroup::saveSetup()
{
  if(mSetName.isEmpty()) return;

  SettingsFile sfile(mFullIndiSetsPath + mSetName);
  sfile.setValue("GroupSplitter", mSplitter->saveState());
  sfile.setValue("IndicatorCount", mSplitter->count());
}
Exemple #7
0
void Playlist::save()
{
    QString fName = m_Settings->appPath();
    fName += QString::number(m_Hash);

    QSettings sfile(fName, QSettings::IniFormat);

    // Playlist data: library id/name, etc.
    sfile.beginGroup("Playlist");

    switch(m_listType) {
        case PlaylistWidget::Search:
            sfile.setValue("strSearch", m_sSearch);
            sfile.setValue("offset", m_Parser->offset());
            sfile.setValue("more", m_Parser->more());
        break;
        case PlaylistWidget::AudioLib:
            sfile.setValue("libraryId", m_LibraryId);
            sfile.setValue("libraryName", m_LibraryName);
        break;
        case PlaylistWidget::Suggestions:
            sfile.setValue("offset", m_Parser->offset());
            sfile.setValue("more", m_Parser->more());
        break;
        case PlaylistWidget::DbSearch:
            sfile.setValue("strSearch", m_sSearch);
        break;
    }

    sfile.setValue("last_track", m_tList.indexOf(m_LastTrack));
    sfile.endGroup();

    // Tracks data
    sfile.beginWriteArray("Tracks");
    for(int i = 0; i < m_tList.size(); i++) {
        sfile.setArrayIndex(i);

        Track *t = m_tList.at(i);

        sfile.setValue("artist", t->artist());
        sfile.setValue("title", t->title());
        sfile.setValue("album", t->album());
        sfile.setValue("url", t->url());
        sfile.setValue("duration", t->duration());
        sfile.setValue("lenght", t->lenght());
        sfile.setValue("aid", t->aid());
        sfile.setValue("oid", t->oid());
        sfile.setValue("hash", t->hash());
        sfile.setValue("delHash", t->delHash());
        sfile.setValue("bitrate", t->rawBitrate());
        sfile.setValue("metaArtist", t->metaArtist());
        sfile.setValue("metaTitle", t->metaTitle());
        sfile.setValue("metaAlbum", t->metaAlbum());
        sfile.setValue("meta", t->metaLoaded());
    }
    sfile.endArray();
}
/* Algorithm
 *  if the filename is from a different directory other then '.'
 *    remove all of the preceding directories until only the file remains.
 *  open a file with that given name as a output stream
 *  write the given data to the file
 *  close the file
 *
 *  @param filename : name of the file to write to
 *  @param data     : the data to write to the file
*/
void FileUtils::putFile(const char *filename, const char *data)
{
  std::string sfile (filename);
  unsigned int local = sfile.find_last_of("/\\");
  sfile = sfile.substr(local + 1);
  std::ofstream file (sfile);
  file.write(data, strlen(data));
  file.close();
}
Exemple #9
0
void MainWindow::sendResults()
{
    if (rbtnNetwork->isChecked()) {
        QByteArray results;
        QDataStream out(&results, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_2);
        out << (quint64)0;
        // ---------------------------------------------------------------------
        for (int i = 0; i < LQListWidget->count(); ++i) {
            out << QString("[Q_NAME]\n");
            out << current_test_questions.value(LQListWidget->item(i))->name();
            out << QString("\n[Q_ANSWERED]\n");
            if (current_db_multiple_ans_support) {
                out << QString("%1\n").arg(current_test_questions.value(LQListWidget->item(i))->answered());
            } else {
                out << QString("%1\n").arg(Question::convertToOldAnsNumber(current_test_questions.value(LQListWidget->item(i))->answered()));
            }
        }
        // ---------------------------------------------------------------------
        out.device()->seek(0);
        out << (quint64)(results.size() - sizeof(quint64));
        tcpSocket->write(results);
    }
    
    QString save_file_name; // yyyy.MM.dd-hh:mm
    QString datetime = current_test_date; datetime.replace(13, 1, '.');
    if (useDefaultOutputCheckBox->isChecked()) {
        save_file_name = QString("%1/%2-%3-%4.itcl").arg(QDir::homePath()).arg(current_db_name).arg(datetime).arg(nameLineEdit->text());
    } else {
        save_file_name = savePathLineEdit->text();
    }
    if (save_file_name.isNull() || save_file_name.isEmpty())
        return;
    QFile file(save_file_name);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::critical(this, tr("Save answer log"), tr("Cannot write file %1:\n%2.").arg(save_file_name).arg(file.errorString()));
        return;
    }
    QTextStream sfile(&file);
    sfile.setCodec("UTF-8");
    sfile << "[TEST_NAME]\n" << current_db_name << endl;
    sfile << "[TEST_TIMESTAMP]\n" << current_test_date << endl;
    sfile << "[TIME_FINISHED]\n" << current_test_time_finished << endl;
    sfile << "[CLIENT_NAME]\n" << nameLineEdit->text() << endl;
    for (int i = 0; i < LQListWidget->count(); ++i) {
        sfile << "[Q_NAME]\n";
        sfile << current_test_questions.value(LQListWidget->item(i))->name();
        sfile << "\n[Q_ANSWERED]\n";
        if (current_db_multiple_ans_support) {
            sfile << current_test_questions.value(LQListWidget->item(i))->answered();
        } else {
            sfile << Question::convertToOldAnsNumber(current_test_questions.value(LQListWidget->item(i))->answered());
        }
        sfile << endl;
    }
}
Exemple #10
0
void IndiWidgetSimple::useIndicator(const QString& file)
{
  mUsedIndiFile = file;
  mSheet->useIndicator(mUsedIndiFile);
  watchIndicator();

  SettingsFile sfile(mFullIndiSetsPath + mSetName);
  sfile.beginGroup(mName);
  sfile.set("Indicator", mUsedIndiFile);
}
void s(QString str, int pos)
{
    QFile sfile("settings");
    sfile.open(QIODevice::ReadWrite);
    QString s = sfile.readAll();
    QStringList sl = s.split("\n");
    sl[pos-1] = str;
    sfile.resize(0);
    QString o = sl.join("\n");
    QByteArray qba = o.toUtf8();
    sfile.write(qba); sfile.close();
}
Exemple #12
0
void PlistsGroup::loadLists()
{
    QString fName = m_Settings->appPath();
    fName += "playlists";

    QSettings sfile(fName, QSettings::IniFormat);

    sfile.beginGroup("Options");
    int lastIndex = sfile.value("last_list").toInt();
    sfile.endGroup();

    int size = sfile.beginReadArray("Lists");
    if(size > 0) {
        for(int i = 0; i < size; i++) {
            sfile.setArrayIndex(i);

            int type = sfile.value("type").toInt();

            PlaylistWidget::ListTypes eType;
            switch(type) {
            case 1:
                eType = PlaylistWidget::Search;
            break;
            case 2:
                eType = PlaylistWidget::AudioLib;
            break;
            case 3:
                eType = PlaylistWidget::LocalList;
            break;
            case 4:
                eType = PlaylistWidget::Suggestions;
            break;
            case 5:
                eType = PlaylistWidget::DbSearch;
            break;
            }

            QString title = sfile.value("title").toString();
            bool isTitleCustom = sfile.value("title_custom").toBool();
            quint64 hash = sfile.value("hash").toULongLong();
            bool isLast = i == lastIndex ? true : false;

            createList(eType, title, hash, false, isLast);
            m_playLists.last()->setTitleCustom(isTitleCustom);
        }
    } else {
        createList(PlaylistWidget::Search, tr("Search"));
    }
    sfile.endArray();

    // Activate last played list tab
    m_widget->setActiveTab(lastIndex);
}
//! load conf. file for info this version
void aboutTrollEdit::loadVersionInfo()
{
    QFile sfile(":/files/aboutThisVersion");
    if(sfile.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream in(&sfile);
        QString text= in.readAll();
        sfile.close();
        ui->textEdit_5->setPlainText(text);
    }


} //! END of aboutTrollEDit
Exemple #14
0
bool Option::IsFileExcluded(const std::string &file,
                            const std::set<std::string> &patterns) {
  String sfile(file.c_str(), file.size(), CopyString);
  for (auto const& pattern : patterns) {
    Variant matches;
    Variant ret = preg_match(String(pattern.c_str(), pattern.size(),
                                    CopyString), sfile, &matches);
    if (ret.toInt64() > 0) {
      return true;
    }
  }
  return false;
}
void s(int c)
{
   QFile sfile("settings");
   sfile.open(QIODevice::ReadWrite);
   QString s = sfile.readAll();
   QStringList sl = s.split("\n");
   if(c==0) {QString fs; fs.append("/home/"); fs.append(un); fs.append("/x11vncpassword"); sl[3]=fs;}
   else if(c==1) {QString fs; fs.append("/home/"); fs.append(un); fs.append("/.config/x11vncpassword"); sl[3]=fs;}
   sfile.resize(0);
   QString o = sl.join("\n");
   QByteArray qba = o.toUtf8();
   sfile.write(qba);
   sfile.close();
}
Exemple #16
0
void IndiWidgetSimple::saveSettings()
{
  SettingsFile sfile(mFullIndiSetsPath + mSetName);
  if("1" == mName)
  {
    sfile.set("Density", mSheet->mPainter->mDensity);
    sfile.set("ShowYScale", mSheet->mPainter->mShowYScale);
  }

  sfile.beginGroup(mName);
  sfile.set("ShowGrid", mSheet->mPainter->mShowGrid);
  sfile.set("ShowXScale", mSheet->mPainter->mShowXScale);
  sfile.set("ScaleToScreen", mSheet->mPainter->mScaleToScreen);
}
Exemple #17
0
bool
Player::loadData()
{
    char buff[256];

    std::string filename = get_config_dir_name();

    filename+="/";
    filename+=name;
    filename+=".sav";

    std::ifstream sfile(filename.c_str());

    if(!sfile) return false;

    int version;
    int numcourses;

    std::string notused;

    sfile >> buff >> buff >> version;
    sfile >> notused; //character
    sfile >> notused; //difficulty
    sfile >> notused; //num difficulties
    sfile >> numcourses;

    for (int i=0; i<numcourses ; i++) {
        double time;
        int _herring;
        int _score;
        sfile.get();
        sfile.getline(buff,256);
        sfile >> time >> _herring >> _score;
        PlayerCourseData& data = courses[buff];
        data.time=time;
        data.herring=_herring;
        data.score=_score;
    }

    int numevents;

    sfile >> numevents;
    for(int i=0; i<numevents; i++) {
        sfile.get();
        sfile.getline(buff,256);
        events[buff].loadData(sfile);
    }

    return true;
}
Exemple #18
0
void Settings::createSettingsFile()
{
    if (!fileExists(Settings::getSettingsPath()))
    {
        qCritical() << "Settings file" << Settings::getSettingsPath() <<"does not exist. Creating it now...";
        QFile sfile(Settings::getSettingsPath());
        if(!sfile.open(QIODevice::WriteOnly))
        {
            qDebug() << "Unable to create" << Settings::getSettingsPath() << "Check folder permissions.";
            return;
        }

        QTextStream header(&sfile);
        header << "##############################################################"
                 << "\n#    SEGS configuration file."
                 << "\n#"
                 << "\n#    listen_addr values below should contain the IP the"
                 << "\n#      clients will connect to."
                 << "\n#"
                 << "\n#    location_addr values below should contain the IP the"
                 << "\n#      clients will receive data from."
                 << "\n#"
                 << "\n#    Both values are set to 127.0.0.1 by default but should"
                 << "\n#      be set to your local IP address on the network"
                 << "\n#      for example: 10.0.0.2"
                 << "\n#"
                 << "\n#    Default ports are listed below:"
                 << "\n#      AccountDatabase db_port:		5432"
                 << "\n#      CharacterDatabase db_port:	5432"
                 << "\n#      AuthServer location_addr:		2106"
                 << "\n#      GameServer listen_addr:		7002"
                 << "\n#      GameServer location_addr:     7002"
                 << "\n#      MapServer listen_addr:		7003"
                 << "\n#      MapServer location_addr:		7003"
                 << "\n#"
                 << "\n##############################################################";

        sfile.close();

        setDefaultSettings();

        return;
    }
    else
    {
        qDebug() << "Settings file already exists at" << Settings::getSettingsPath();
        return;
    }
}
Exemple #19
0
bool Note::save()
{
    if (fileName.isEmpty())
            return Note::saveAs();

    QFile sfile(fn);
    if(sfile.open(QFile::WriteOnly | QFile::Text))
    {
        QTextStream out(&sfile);
        out << textEdit->toPlainText();
        sfile.flush();
        sfile.close();
    }

    textEdit->document()->setModified(false);
    return true;

}
Exemple #20
0
void PlistsGroup::savePlaylists()
{
    QString fName = m_Settings->appPath();
    fName += "playlists";

    QSettings sfile(fName, QSettings::IniFormat);
    sfile.clear();

    sfile.beginGroup("Options");
    sfile.setValue("last_list", m_playLists.indexOf(m_LastList));
    sfile.endGroup();

    sfile.beginWriteArray("Lists");
    for(int i = 0; i < m_playLists.size(); i++) {
        sfile.setArrayIndex(i);

        //PlaylistWidget::ListTypes type = m_playLists.at(i)->type();
        int iType = 0;
        switch(m_playLists.at(i)->type()) {
        case PlaylistWidget::Search:
            iType = 1;
        break;
        case PlaylistWidget::AudioLib:
            iType = 2;
        break;
        case PlaylistWidget::LocalList:
            iType = 3;
        break;
        case PlaylistWidget::Suggestions:
            iType = 4;
        break;
        case PlaylistWidget::DbSearch:
            iType = 5;
        break;
        }

        sfile.setValue("type", iType);
        sfile.setValue("title", m_playLists.at(i)->listTitle());
        sfile.setValue("title_custom", m_playLists.at(i)->isTitleCustom());
        sfile.setValue("hash", QString::number(m_playLists.at(i)->hash()));
    }
    sfile.endArray();
}
int Budget::save(std::string file) {
	std::ofstream sfile(file.c_str());
	sfile << "#BUDGETAPP|Johannes Linden|"; // A sign of the file to know what file type it is
	sfile << "'          '";
	// Save events
	for (std::list<Event>::iterator it = events.begin(); it != events.end(); ++it){
		sfile << it->id();  // sign so we know what type the structure is
		sfile << *it;
	}
	// Save repeated events
	for (std::list<REvent>::iterator it = revents.begin(); it != revents.end(); ++it){
		sfile << it->id();
		sfile << *it;
	}
	sfile << "GROUPS";
	// Save groups
	unsigned int eventsSize = events.size();
	for (std::list<GroupEvent >::iterator grpIt = groups.begin(); grpIt != groups.end(); ++grpIt) {
		sfile << grpIt->name() << '\0';
		for (GroupEvent::iterator eventIt = grpIt->begin(); eventIt != grpIt->end(); ++eventIt) {
			int index = 0;
			for (std::list<Event>::iterator kt = events.begin(); kt != events.end(); ++kt, index++) {
				if(*eventIt == &(*kt)) {
					sfile << ' ' << index;
					index = -1;
					// break;
				}
			}
			if(index != -1) {
				// int index = 0;
				for (std::list<REvent>::iterator kt = revents.begin(); kt != revents.end(); ++kt, index++) {
					if(*eventIt == &(*kt)) {
						sfile << ' ' << index;
						// break;
					}
				}
			}
		}sfile << ":";
	}
	sfile << "'          '";
}
Exemple #22
0
void IndiWidgetGroup::loadSetup(const QString& setup)
{
  if(setup.isEmpty() or setup == mSetName) return;

  saveSetup();
  mSetName = setup;

  int rowCount;
  SettingsFile sfile(mFullIndiSetsPath + mSetName);
  rowCount = sfile.getIT("IndicatorCount", 1);

  for(int i = 0; (i < mSplitter->count()) and (i < rowCount); ++i)
  {
    static_cast<IndicatorWidget*>(mSplitter->widget(i))->loadSetup(mSetName, i);
  }

  while(mSplitter->count() < rowCount) addWindow();
  while(mSplitter->count() > rowCount) removeWindow();

  mSplitter->restoreState(sfile.getBA("GroupSplitter"));
}
Exemple #23
0
bool
Player::saveData()
{
    std::string filename=get_config_dir_name();

    filename+="/";
    filename+=name;
    filename+=".sav";

    std::ofstream sfile(filename.c_str());

    sfile << "PPRacer SAVE " << 1 << std::endl;
    sfile << "tux" << std::endl;
    sfile << "easy" << std::endl;
    sfile << 1 << std::endl;
    sfile << courses.size() << std::endl;

    {
        std::map<std::string,PlayerCourseData>::iterator it;
        for(it=courses.begin(); it!=courses.end(); it++) {
            sfile << (*it).first << std::endl;
            sfile << (*it).second.time << std::endl;
            sfile << (*it).second.herring << std::endl;
            sfile << (*it).second.score << std::endl;
        }
    }


    sfile << events.size() << std::endl;

    if(events.size()>0) {
        std::map<std::string,PlayerEventData>::iterator it;
        for (it=events.begin(); it!=events.end(); it++) {
            sfile << (*it).first << std::endl;
            (*it).second.saveData(sfile);
        }
    }

    return true;
}
Exemple #24
0
// Saves the players options...
void Ultra1::App::PlayerOptions::Save( )
{
  	std::string home;
#ifdef WIN32
	home = getenv("USERPROFILE");
#else
	home = getenv("HOME");
#endif
	std::fstream ffile((home + "/.ultrabear1/config/screen.dat").c_str( ), std::ios::out );
  if(!ffile.is_open( )) throw Sim::Exception("Save", "Could not write to screen file");
	if( fullscreen )
		ffile << 1 << std::endl;
	else
		ffile << 0 << std::endl;
	ffile.close( );

	std::fstream sfile((home + "/.ultrabear1/config/sound.dat").c_str( ), std::ios::out );
  if(!sfile.is_open( )) throw Sim::Exception("Save", "Could not write to sound file");
	if( sound )
		sfile << 1 << std::endl;
	else
		sfile << 0 << std::endl;
	if( music )
		sfile << 1 << std::endl;
	else
		sfile << 0 << std::endl;
	sfile.close( );

	std::fstream kfile((home + "/.ultrabear1/config/keys.dat").c_str( ), std::ios::out );
  if(!kfile.is_open( )) throw Sim::Exception("Save", "Could not write to keys file");
	kfile << left << std::endl;
	kfile << right << std::endl;
	kfile << up << std::endl;
	kfile << down << std::endl;
	kfile << jump << std::endl;
	kfile << 0 << std::endl;
	kfile << pause << std::endl;
	kfile.close( );

}
Exemple #25
0
/**
 * \brief Compute directory size
 * 
 * \param path Directory path
 * \param recursive If true, recursively compute size of subfolders
 * \return Directory size in bytes
 */
uint64_t Directory::dirSize(std::string path, bool force, bool recursive, bool writestats)
{
	std::string entry_path, entry_name;
	struct dirent *entry;
	struct stat st;
	uint64_t size{0};
	
	MSG_DEBUG(msg_module, "scanning %s", path.c_str());     
	
	std::string statsfile(path + "/stats.txt");
	if (!force && stat(statsfile.c_str(), &st)) {
		/* stats.txt not exists - force scan*/
		force = true;
	}
	
	if (!force) {
		MSG_DEBUG(msg_module, "reading %s", statsfile.c_str());
		std::ifstream sfile(statsfile, std::ios::in);
		sfile >> size;
		sfile.close();
		return size;
	}
Exemple #26
0
bool AnimatedSprite::loadTrackFile(const std::string& file, const std::string& name, std::shared_ptr<Library> &lib)
{
	std::ifstream sfile(file.c_str());
	if (!sfile.is_open()) {
		Guy::printLog("Error loading %s anim file", file.c_str());
		return false;
	}

	Json::Value root;
	Json::Reader reader;
	if (!reader.parse(sfile, root) ) {
		Guy::printLog("Failed to parse %s anim file, reason: %s", file.c_str(), reader.getFormatedErrorMessages().c_str());
		return false;
	}

	Track track;
	track.frameCount = root.get("frameCount", "UTF-8" ).asUInt();
	const Json::Value keyframes = root["keyFrames"];
	for ( int index = 0; index < keyframes.size(); ++index )
	{
		Keyframe key;
		const Json::Value keyframe = keyframes[index];
		const Json::Value data = keyframe["data"];
		key.frame = keyframe.get("frame", "UTF-8").asUInt();
		key.filename = data.get("fileName", "UTF-8").asString();
		Guy::TextureManager::instance().getTexture(key.filename);

		const Json::Value offset = data["offset"];
		key.origin.x = -offset.get("x", "UTF-8").asDouble();
		key.origin.y = -offset.get("y", "UTF-8").asDouble();

		{
			const Json::Value rect = data["rect"];
			const Json::Value bottomRight = rect["bottomRight"];
			const Json::Value topLeft     = rect["topLeft"];

			key.rect.update(math::vec2i(bottomRight.get("x", "UTF-8").asInt(), bottomRight.get("y", "UTF-8").asInt()));
			key.rect.update(math::vec2i(    topLeft.get("x", "UTF-8").asInt(),     topLeft.get("y", "UTF-8").asInt()));
		}

		{
			const Json::Value custom = data["customProperties"];
			Json::Value::Members members = custom.getMemberNames();
			for(std::size_t i; i < members.size(); ++i) {
				if (members[i] == std::string("velx"))
				{
					key.acceleration.x = custom.get("velx", "UTF-8").asDouble();
					key.useAsVelocity = true;
				}
				else if (members[i] == std::string("vely"))
				{
					key.acceleration.y = custom.get("vely", "UTF-8").asDouble();
					key.useAsVelocity = true;
				}
				else if (members[i] == std::string("accx"))
				{
					key.acceleration.x = custom.get("accx", "UTF-8").asDouble();
					key.useAsVelocity = false;
				}
				else if (members[i] == std::string("accy"))
				{
					key.acceleration.y = custom.get("accy", "UTF-8").asDouble();
					key.useAsVelocity = false;
				}
				else if (members[i] == std::string("frix"))
				{
					key.friction.x = custom.get("frix", "UTF-8").asDouble();
				}
				else if (members[i] == std::string("friy"))
				{
					key.friction.y = custom.get("friy", "UTF-8").asDouble();
				}
				else if (members[i] == std::string("maxx"))
				{
					key.maxVel.x = custom.get("maxx", "UTF-8").asDouble();
				}
				else if (members[i] == std::string("maxy"))
				{
					key.maxVel.y = custom.get("maxy", "UTF-8").asDouble();
				}
			}
		}

		const Json::Value hitBoxes = data["hitBoxes"];
		for ( int index = 0; index < hitBoxes.size(); ++index )
		{
			const Json::Value hitBox = hitBoxes[index];
			const Json::Value rect = hitBox["rect"];
			const Json::Value bottomRight = rect["bottomRight"];
			const Json::Value topLeft     = rect["topLeft"];

			math::bbox3i box;
			box.update(math::vec3i(bottomRight.get("x", "UTF-8").asInt(), bottomRight.get("y", "UTF-8").asInt(), -100));
			box.update(math::vec3i(    topLeft.get("x", "UTF-8").asInt(),     topLeft.get("y", "UTF-8").asInt(),  100));

			if (hitBox.get("group", "UTF-8").asString() == std::string("body")) {
				key.body.push_back(box);
			}
			if (hitBox.get("group", "UTF-8").asString() == std::string("damage")) {
				key.damage.push_back(box);
			}
		}

		track.keyframes.push_back(key);
	}

	lib->trackNames.insert(std::make_pair(name, lib->tracks.size()));
	lib->tracks.push_back(track);

	return true;
}
Exemple #27
0
void Trasporta(Int_t s,Int_t Rhum, TRandom *GeneratoreEsterno=0,Int_t Noise_Medio = 20) {

	TStopwatch tempo;

	tempo.Start(kTRUE);

	cout<<endl<<"Sto trasportando attraverso i rivelatori: attendere... "<<endl;
	TRandom *smear;
	if(GeneratoreEsterno == 0){
		smear = new TRandom3();
		cout<<"Generatore Interno";
	}else{
		smear = GeneratoreEsterno;
		cout<<"Generatore Esterno";
	}
	
	cout<<" FirstRNDM: "<<smear->Rndm()<<endl;
	
	//////////////////////////////////////////////////////
	//Creo un nuovo file e
	//Definisco Struct per salvare i nuovi dati x y z 
	//////////////////////////////////////////////////////

	//Definisco il nuovo albero per salvare i punti di hit	
	TFile sfile("trasporto_tree.root","RECREATE");
  
	TTree *trasporto = new TTree("Ttrasporto","TTree con 3 branches");
	 //Punti sul layer
	TTree *Rel_Lay1 = new TTree("Layer1","TTree con 1 branch");
	TTree *Rel_Lay2 = new TTree("Layer2","TTree con 1 branch");
	 //rumore
	TTree *Noise = new TTree("Rumore","TTree con 1 branch");

	typedef struct {
		Double_t X,Y,Z;
		Int_t Flag;		
	} HIT; 
	static HIT beam;  	
	static HIT lay1;  
	static HIT lay2;

	typedef struct {
		Int_t event;
		Int_t tipo;
		Int_t Noiselay1;
		Int_t Noiselay2;
	} infoRumore;
	static infoRumore InfoR;


	//Dichiaro i rami dei tree
	trasporto->Branch("BeamPipe",&beam.X,"X/D:Y:Z:Flag/I");  
	trasporto->Branch("Layer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	trasporto->Branch("Layer2",&lay2.X,"X/D:Y:Z:Flag/I");  

	Rel_Lay1->Branch("RealLayer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	Rel_Lay2->Branch("RealLayer2",&lay2.X,"X/D:Y:Z:Flag/I"); 
	
	Noise->Branch("Rumore",&InfoR,"event/I:tipo:Noiselay1:Noiselay2"); 
	Double_t temp_phi = 0;
	Int_t Nnoise=0;	

  ////////////////////////////////
  //Acquisizione Vertici
  ///////////////////////////////
  TClonesArray *dir = new TClonesArray("Direction",100);	
  typedef struct {
    Double_t X,Y,Z;
    Int_t N;
  }SINGLE_EVENT;
  static SINGLE_EVENT event;    //struct con molteplicita' e vertice di un singolo evento
	
  TFile hfile("event_tree.root");


  TTree *Born = (TTree*)hfile.Get("T");       
  TBranch *b1=Born->GetBranch("Event"); 
  TBranch *b2=Born->GetBranch("Direzioni");  //acquisisco i due branches


  b1->SetAddress(&event.X); //passo l'indirizzo del primo oggetto della struct e assegno tutto a b1
  b2->SetAddress(&dir); // lo stesso per il vettore 




  /////////////////////////
  //Geometria del rivelatore
  /////////////////////////
  Double_t R1=3;	//raggio 3 cm beam pipe
  Double_t R2=4;	//raggio 4 cm primo layer
  Double_t R3=7;	//raggio 7 cm secondo layer

  Double_t limit = 8.; //lunghezza layer su z-> z in [-8,8]

  //Variabili Varie
	Double_t Xo=0.;Double_t Yo=0.;Double_t Zo=0.;
  	Double_t X1=0.;Double_t Y1=0.;Double_t Z1=0.;
	Double_t X2=0.;Double_t Y2=0.;Double_t Z2=0.;

	Int_t N=0; //molteplicita'

	Int_t yes = 0;
	Int_t no = 0;	       
	
	for(Int_t e=0; e < Born->GetEntries(); e++){
	
		Born->GetEvent(e);
		Xo=event.X;
		Yo=event.Y;
		Zo=event.Z;		
		N=event.N;	    
		
		for(Int_t i=0; i<N; i++){
			
			//Cast dell'elemenento i di TClones a Direction
			Direction *angolacci=(Direction*)dir->At(i);
			angolacci->SetRNDGenerator(smear);//uso lo stesso generatore anche nella classe
			
			//primo hit beam pipe
			angolacci->GeneraHit(Xo,Yo,Zo,R1);//genero il punto di impatto sul beam pipe		
			
			beam.X=angolacci->GetNewX(); //recupero le coordinate del punto d'impatto sul BP
			beam.Y=angolacci->GetNewY();					
			beam.Z=angolacci->GetNewZ();
			beam.Flag=1;
		

			///////////////////////////////////////////////////
			/////////////scattering sul beam pipe//////////////
			///////////////////////////////////////////////////
			if(s==1){
				//dipende dal tipo di materiale
				angolacci->Scattering(0.08,35.28);
			}
					
				
			//secondo hit layer 1			
			angolacci->GeneraHit(beam.X,beam.Y,beam.Z,R2);

			X1 = angolacci->GetNewX();	
			Y1 = angolacci->GetNewY();
			Z1 = angolacci->GetNewZ();
			
			lay1.X=X1;
			lay1.Y=Y1;							
			lay1.Z=Z1;	
			
			//verifico che la particella colpisca il layer
			if(TMath::Abs(Z1) < limit){

				lay1.Flag = e;
				Rel_Lay1->Fill();					       
				
				///////////////////////////////////////////////
				/////////////scattering sul layer//////////////	
				///////////////////////////////////////////////
				if(s==1){
					angolacci->Scattering(0.02,9.37);
				}				
							
				yes++;
				
			}else no++;	      
				

		      //terzo hit layer 2			
		      angolacci->GeneraHit(X1,Y1,Z1,R3);

		      X2 = angolacci->GetNewX();	
		      Y2 = angolacci->GetNewY();
		      Z2 = angolacci->GetNewZ();
		      lay2.X=X2;
		      lay2.Y=Y2;							
		      lay2.Z=Z2;
			

		      //verifico che la particella colpisca il layer
		      if(TMath::Abs(Z2) < limit){

			lay2.Flag = e;	
			Rel_Lay2->Fill();			
	
			yes++;

		      }else{
			no++;	
		      }

			angolacci->RemoveGenerator();
			trasporto->Fill(); //riempie tutto con quello che ho definito sopra

		      // Debug
		      /*printf("Evento %d : part %d \n",e,i+1);
			printf("x beam= %f ; y beam= %f; z beam= %f \n",beam.X,beam.Y,beam.Z);

			if(lay1.Flag){
			printf("x lay1= %f ; y lay1= %f; z lay1= %f \n",lay1.X,lay1.Y,lay1.Z);
			}else{
			printf("Non urta sul layer 1 \n");
			}


			if(lay2.Flag){
			printf("x lay2= %f ; y lay2= %f; z lay2= %f \n",lay2.X,lay2.Y,lay2.Z);
			}else{
			printf("Non urta sul layer 2 \n");
			}*/
		}

		////////////////////////////////////////////////////////////////////////////
		//////////////////////////RUMORE////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////
		InfoR.event = e;
		InfoR.tipo = Rhum;
		if(Rhum != 0){
		//genero rumore lay 1
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}
		
		
			InfoR.Noiselay1 = Nnoise;
		
			for(Int_t y =0; y < Nnoise; y++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());
				lay1.X = R2*TMath::Cos(temp_phi);
				lay1.Y = R2*TMath::Sin(temp_phi);							
				lay1.Z = smear->Uniform(-limit,limit);
	
				lay1.Flag=e;

				Rel_Lay1->Fill();		
		
			}

		      //genero rumore lay 2					
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}

			InfoR.Noiselay2 = Nnoise;

			for(Int_t w =0; w < Nnoise; w++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());

				lay2.X = R3*TMath::Cos(temp_phi);
				lay2.Y = R3*TMath::Sin(temp_phi);							
				lay2.Z = smear->Uniform(-limit,limit);
	
				lay2.Flag=e;

				Rel_Lay2->Fill();	
			}
		}else{
			InfoR.Noiselay1 = 0;
			InfoR.Noiselay2 = 0;
		}
	
	//fill per il rumore
	Noise->Fill();
	}


	sfile.Write(); 
 
	sfile.Close();
	//ho il file con tutti gli eventi

  

 	tempo.Stop();
  
	cout<<endl<<endl<<endl<<"//////////////////////////////////////"<<endl<<endl;
	cout<<"Completato!"<<endl<<endl;
	cout<<"Il trasporto è durato "<<endl;
	tempo.Print();
	cout<<endl<<endl;
	cout<<"PARAMETRI TRASPORTO: "<<endl;
	cout<<"\t"<<"Scattering:     "<<s;
	if(s==1)cout<<"  Scattering attivo"<<endl;
	if(s==0)cout<<"  Scattering non attivo"<<endl;
	cout<<"\t"<<"Rumore:         ";
	if(Rhum==1)cout<<"  Rumore gaussiano  "<<endl;
	if(Rhum==0)cout<<"  Nessun rumore"<<endl;
	if((Rhum!=0) & (Rhum!=1))cout<<"  Rumore con molteplicita' fissa "<<Rhum<<endl;
  	cout<<endl<<"//////////////////////////////////////"<<endl;

}
Exemple #28
0
int main(int argc,char *args[]){
  int n = 8;
  if(argc!=n){
    gotestUsage(args[0]);
    exit(1);
  }

  int rands = 0;
  rands = atoi(args[1]);
  if(rands!=0)
    srand(rands);
  else{
    rands = time(0);
    srand(rands);
    cout << "ny seed: " << rands << endl;
  }

  //1. load the example file
  NEATsettings * set = new NEATsettings();
  ifstream ifs(args[2],ios::in);
  ifs>>set;
  ifs.close(); 

  //2. generate the pop
  TransferFunctions * tfs = new TransferFunctions(set);
  Population * pop = makePopulation(args[3],set,tfs);
  
  //3. then the selector
  Selector * sel = makeSelector(args[4]);
  Coevolution * coevo = NULL;
  FitnessEvaluator * fe = makeFitnessEvaluator(args[5],coevo);

  int g = atoi(args[6]);
  int iter = atoi(args[7]);
  Evaluator * ev = new Evaluator(fe); 
  LocalReproducer * rep = new LocalReproducer();

  //files  
  int pid = getpid();
  //files  
  stringstream ssCurrentFile; ssCurrentFile << "results/" << getPureTimeString() << "-" << pid << "/" ;
  mkdir(ssCurrentFile.str().c_str(),0777);
  stringstream sCurrentGraphFile; sCurrentGraphFile << ssCurrentFile << "graph";
  stringstream sCurrentGenomeFile; sCurrentGenomeFile << ssCurrentFile << "curgenome";
  string sSettingsFile = ssCurrentFile.str() + "settings";
  stringstream sCurrentXMLGenomeFile; sCurrentXMLGenomeFile << ssCurrentFile << "curgenome";
  string sFinalGenomeFile = ssCurrentFile.str() + "finalgenome";
  string finalgraphfile = ssCurrentFile.str() + "finalgraph";
  stringstream specgraphfile; specgraphfile << ssCurrentFile << "specgraph";

  ofstream sfile(sSettingsFile.c_str());
  sfile << set;
  sfile.close();

  icb->fe = fe;

  NEATRunner * run = new NEATRunner(g,iter);

  int nodes = 0;

  run->pop = pop; run->sel = sel; 
  run->sCurrentGenomeFile.str(sCurrentGenomeFile.str());
  run->sCurrentGraphFile.str(sCurrentGraphFile.str());
  run->sCurrentXMLGenomeFile.str(sCurrentXMLGenomeFile.str()); 
  run->sFinalGenomeFile = sFinalGenomeFile; run->finalgraphfile = finalgraphfile;
  run->rep = rep; run->coevo = coevo; run->nodes = nodes; run->icb = icb; run->set = set; run->tfs = tfs;
  run->ev = ev;
  run->signalhandler = signalhandler;
  run->basefile = ssCurrentFile.str();
  run->pid = getpid();
  run->sgf.str(specgraphfile.str());
  icb->run = run;

  addToAllSignals(signalhandler);

  run->runLoop();

  delete pop;
  delete ev;
  delete fe;
  delete sel;
  delete rep;
  delete set;
  delete tfs;

  return 0;
}
Exemple #29
0
void Playlist::load()
{
    m_bLoadingState = true;
    int lastIndex = 0;

    setModelHeaders();

    QString fName = m_Settings->appPath();
    fName += QString::number(m_Hash);

    if(QFile::exists(fName)) {
        QSettings sfile(fName, QSettings::IniFormat);

        // Playlist data: library id/name, etc.
        sfile.beginGroup("Playlist");

        switch(m_listType) {
            case PlaylistWidget::Search:
                m_sSearch = sfile.value("strSearch").toString();

                m_Parser->setSearchStr(m_sSearch);
                m_Parser->setOffset(sfile.value("offset").toInt());
                m_Parser->setMore(sfile.value("more").toBool());
                m_Parser->setReqType(0);

                m_listWidget->setSearchStr(m_sSearch);
            break;
            case PlaylistWidget::AudioLib:
            setLibId(sfile.value("libraryId").toString(), "0");
                m_LibraryName = sfile.value("libraryName").toString();
                m_listWidget->setLibraryName(m_LibraryName);

                m_Parser->setReqType(1);
            break;
            case PlaylistWidget::Suggestions:
                m_Parser->setOffset(sfile.value("offset").toInt());
                m_Parser->setMore(sfile.value("more").toBool());
                m_Parser->setReqType(2);
            break;
            case PlaylistWidget::DbSearch:
                m_sSearch = sfile.value("strSearch").toString();

                m_listWidget->setSearchStr(m_sSearch);
            break;
        }
        lastIndex = sfile.value("last_track").toInt();

        sfile.endGroup();

        // Tracks data
        int size = sfile.beginReadArray("Tracks");
        for(int i = 0; i < size; i++) {
            sfile.setArrayIndex(i);

            Track *t = new Track(this);

            t->setArtist(sfile.value("artist").toString());
            t->setTitle(sfile.value("title").toString());
            t->setAlbum(sfile.value("album").toString());
            t->setUrl(sfile.value("url").toString());
            t->setDuration(sfile.value("duration").toString());
            t->setLenght(sfile.value("lenght").toInt());
            t->setAid(sfile.value("aid").toString());
            t->setOid(sfile.value("oid").toString());
            t->setHash(sfile.value("hash").toString());
            t->setDelHash(sfile.value("delHash").toString());
            t->setBitrate(sfile.value("bitrate").toInt());
            t->setMetaArtist(sfile.value("metaArtist").toString());
            t->setMetaTitle(sfile.value("metaTitle").toString());
            t->setMetaAlbum(sfile.value("metaAlbum").toString());
            t->setMetaLoaded(sfile.value("meta").toBool());

            addTrack(t);
            connect(t, SIGNAL(removeMe()), SLOT(onTrackSelfRemove()));

        }

        //fixme
        if(lastIndex < 0)
            lastIndex = 0;

        if(!m_tList.isEmpty()) {
            if(m_tList.size() > 0 && m_tList.size() >= lastIndex)
                m_LastTrack = m_tList.at(lastIndex);
            else
                m_LastTrack = m_tList.first();
        } else {
            m_LastTrack = 0;
        }

            sfile.endArray();
    }

    m_bLoadingState = false;

    m_listWidget->setActiveIndex(m_ProxyModel->index(lastIndex, 0));

}
int Budget::load(std::string file) {
	std::ifstream sfile(file.c_str());
	load(&sfile);
}