Пример #1
0
cl_device_id mclGetBestDeviceID()
{
  cl_platform_id platform_id = mclGetPlatformID();

  // Info about devices
  cl_uint num_devices;
  logOclCall("clGetDeviceIDs (get number of devices)");
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices);
  cl_device_id* devices = calloc(sizeof(cl_device_id), num_devices);
  logOclCall("clGetDeviceIDs (get list of devices)");
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, num_devices, devices, NULL);

  if (mclLogLevel > 1) {
    logStream(stdout, "System has %d device(s):", num_devices);
    char buf1[MCL_MAX_STRING_LENGTH];
    char buf2[MCL_MAX_STRING_LENGTH];
    for(cl_uint i = 0; i < num_devices;i++) {
      logOclCall("clGetDeviceInfo, name of device %d", i);
      clGetDeviceInfo(devices[i], CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf1, NULL);
      logOclCall("clGetDeviceInfo, OpenCL version for device %d", i);
      clGetDeviceInfo(devices[i], CL_DEVICE_VERSION, MCL_MAX_STRING_LENGTH, buf2, NULL);
      logStream(stdout, "   Device %d: %s, which supports %s", i, buf1, buf2);
    }
  }

  if (num_devices < 1) {
    fprintf(stderr, "MCL - Exiting: No devices available\n");
    exit(1);
  }

  // Selecting the device
  cl_uint num_device = 0;
  cl_uint bestIndex = 0;
  for (cl_uint i = 0; i < num_devices; i++) {
    cl_uint maxComputeUnits, maxClockFrequency;
    logOclCall("clGetDeviceInfo, max compute unites device %d", i);
    clGetDeviceInfo(devices[i], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &maxComputeUnits, NULL);
    logOclCall("clGetDeviceInfo, max clock frequency %d", i);
    clGetDeviceInfo(devices[i], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(cl_uint), &maxClockFrequency, NULL);
    cl_uint index = maxComputeUnits * maxClockFrequency;
    if (index > bestIndex) {
      bestIndex = index;
      num_device = i;
    }
  }

  cl_device_id device_id = devices[num_device];
  if (mclLogLevel > 0) {
    char buf[MCL_MAX_STRING_LENGTH];
    logOclCall("clGetDeviceInfo, name of selected device (%d)", device_id);
    clGetDeviceInfo(device_id, CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf, NULL);
    logStream(stdout,"Selected device %d: %s", num_device, buf);
    if (mclLogLevel > 2) {
      mclPrintDeviceInfo(device_id);
    }
  }
  return device_id;
}
Пример #2
0
mclContext mclInitialize(unsigned int log_level) {
  mclLogLevel = log_level;
  mclContext context;
  if (mclLogLevel > 1) {
    logStream(stdout, "Obtaining best device.");
  }
  context.device_id = mclGetBestDeviceID();
  if (mclLogLevel > 1) {
    logStream(stdout, "Creating context.");
  }
  context.context = mclCreateContext(&context.device_id);
  context.command_queue = mclCreateCommandQueue(context.context,context.device_id);
  return context;
}
Пример #3
0
int Rts2SchedBag::constructSchedules (int num)
{
	struct ln_lnlat_posn *observer = rts2core::Configuration::instance ()->getObserver ();

	ticketSet->load (tarSet);
	if (ticketSet->size () == 0)
	{
		logStream (MESSAGE_ERROR) << "There aren't any scheduling tickets in database (tickets table)" << sendLog;
		return -1;
	}

	for (int i = 0; i < num; i++)
	{
		Rts2Schedule *sched = new Rts2Schedule (JDstart, JDend, minObsDuration, observer);
		if (sched->constructSchedule (ticketSet))
			return -1;
		push_back (sched);
	}

	popSize = size ();

	mutationNum = popSize / 2;

	reserve (popSize * 2);

	return 0;
}
Пример #4
0
		int checkSbigHw (PAR_ERROR ret)
		{
			if (ret == CE_NO_ERROR)
				return 0;
			logStream (MESSAGE_ERROR) << "Sbig::checkSbigHw ret: " << ret << sendLog;
			return -1;
		}
double SelfMadeTimer::printOverallEclipsedTime()
{
	std::ofstream logStream(timeStatisticFileName);
	if (!logStream.good())
	{
		std::cerr<<"IO error while open log file"<<std::endl;
		return -1;
	}

	std::cout<<"Summary of "<<projectName.c_str()<<"'s consumed time in order:\n";
	logStream<<"Summary of "<<projectName.c_str()<<"'s consumed time in order:\n";
	double seconds=0.0;
	if (periods.size()!=taskNames.size())
	{
		std::cout<<"You may forget to name some tasks... Here are all tasks regardless of name"<<std::endl;
		logStream<<"You may forget to name some tasks... Here are all tasks regardless of name"<<std::endl;
	}
	for (std::vector<clock_t>::iterator pos=periods.begin();pos!=periods.end();pos++)
	{
		seconds+=printEclipsedTimeAtIndex(pos-periods.begin(),logStream);
	}
	std::cout<<"Overall consumed time is "<<seconds<<" seconds"<<std::endl;
	std::cout<<"Averaged consumed time is "<<seconds/periods.size()<<" seconds"<<std::endl;
	std::cout<<"End of "<<projectName.c_str()<<"\n\n"<<std::endl;
	logStream<<"Overall consumed time is "<<seconds<<" seconds"<<std::endl;
	logStream<<"Averaged consumed time is "<<seconds/periods.size()<<" seconds"<<std::endl;
	logStream<<"End of "<<projectName.c_str()<<"\n\n"<<std::endl;
	logStream.close();
	return seconds;
}
Пример #6
0
 void SBPLPlannerStatsEntry::
 logInfo(char const * prefix) const
 {
   ostringstream os;
   logStream(os, "ompl::SBPLPlannerStatistics", prefix);
   ROS_INFO("%s", os.str().c_str());
 }
Пример #7
0
TEST(Stream, append)
{
    const std::wstring LOG_FILE_NAME(L"StreamTest.log");
    removeFile(LOG_FILE_NAME);
    auto output(std::make_unique<LogOutput>(LOG_FILE_NAME));
    auto prefix(std::make_unique<NothingPrefix>());
    unsigned char uc[] = "uc";
    void* pointer = reinterpret_cast<void*>(12345678U);
    LogStream logStream(std::move(output), std::move(prefix));
    logStream << bkzFlush;
    logStream << 1;
    logStream << 2U;
    logStream << 1L;
    logStream << 2LU;
    logStream << 4.4f;
    logStream << 3.3;
    logStream << "HELLO";
    logStream << uc;
    logStream << std::string("string");
    logStream << std::wstring(L"wstring");
    logStream << pointer;

    logStream << bkzEndl;

    const std::wstring actual = stringFromFile(LOG_FILE_NAME);
    EXPECT_EQ(L"12124.403.300HELLOucstringwstring12345678\n", actual);
}
Пример #8
0
void BatchJob::ShowLog()
{

    QDialog dlg(MIMainWindow::instance());
    dlg.setWindowTitle(logFile);
    dlg.setModal(true);
    dlg.setSizeGripEnabled(true);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    dlg.setLayout(mainLayout);

    QTextBrowser *browse = new QTextBrowser(&dlg);
    mainLayout->addWidget(browse);

    QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, &dlg);
    mainLayout->addWidget(bb);
    dlg.connect(bb, SIGNAL(accepted()), &dlg, SLOT(accept()));

    QFile logFileObj(logFile);
    if ( !logFileObj.open(QFile::ReadOnly | QFile::Text) )
    {
        browse->setPlainText(QObject::tr("ERROR: Log file %1 not found!")
                             .arg(logFile));
    }
    else
    {
        QTextStream logStream(&logFileObj);
        browse->setPlainText(logStream.readAll());
    }

    dlg.exec();
}
Пример #9
0
int Rts2SchedBag::constructSchedulesFromObsSet (int num, struct ln_date *obsNight)
{
  	Rts2Night night = Rts2Night (obsNight, rts2core::Configuration::instance ()->getObserver ());

	rts2db::ObservationSet obsSet = rts2db::ObservationSet ();
	obsSet.loadTime (night.getFrom (), night.getTo ());

	if (obsSet.size () == 0)
	{
		logStream (MESSAGE_ERROR) << "Empty observation set" << sendLog;
		return -1;
	}

	JDstart = night.getJDFrom ();
	JDend = night.getJDTo ();

	if (isnan (JDstart) || isnan (JDend))
	{
	  	logStream (MESSAGE_ERROR) << "Null start or end dates" << sendLog;
		return -1;
	}

	struct ln_lnlat_posn *observer = rts2core::Configuration::instance ()->getObserver ();

	ticketSet->constructFromObsSet (tarSet, obsSet);
	if (ticketSet->size () == 0)
	{
		logStream (MESSAGE_ERROR) << "There aren't any scheduling tickets constructed from observations." << sendLog;
		return -1;
	}

	for (int i = 0; i < num; i++)
	{
		Rts2Schedule *sched = new Rts2Schedule (JDstart, JDend, minObsDuration, observer);
		if (sched->constructSchedule (ticketSet))
			return -1;
		push_back (sched);
	}

	popSize = size ();

	mutationNum = popSize / 2;

	reserve (popSize * 2);

	return 0;
}
Пример #10
0
int
Rts2DevMirrorFram::mirror_command (char cmd, int arg, char *ret_cmd,
int *ret_arg)
{
	char command_buffer[3];
	int ret;
	size_t readed;
	char tc[27];
	time_t t;
	command_buffer[0] = cmd;
	*((int *) &command_buffer[1]) = arg;
	logStream (MESSAGE_DEBUG) << "cmd " << cmd << " arg " << arg << sendLog;

	ret = write (mirror_fd, command_buffer, 3);
	if (ret != 3)
	{
		t = time (NULL);
		ctime_r (&t, tc);
		fprintf (mirr_log, "%s:write %i\n", tc, ret);
		fflush (mirr_log);
		return -1;
	}
	readed = 0;
	while (readed != 3)
	{
		ret = read (mirror_fd, &command_buffer[readed], 3);
		if (ret <= 0)
		{
			t = time (NULL);
			ctime_r (&t, tc);
			fprintf (mirr_log, "%s:read %i\n", tc, ret);
			fflush (mirr_log);
			return -1;
		}
		readed += ret;
	}
	logStream (MESSAGE_DEBUG) << "ret_cmd: " << command_buffer[0]
		<< " ret_arg: " << command_buffer[1] << sendLog;
	if (ret_cmd)
		*ret_cmd = command_buffer[0];
	if (ret_arg)
		*ret_arg = *((int *) &command_buffer[1]);
	flock (mirror_fd, LOCK_UN);
	return 0;
}
Пример #11
0
void Logger::WriteLine(const QString &message)
{
    if (_logFile.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream logStream(&_logFile);
        logStream << message << "\n";
        _logFile.close();
    }
}
Пример #12
0
void logOclCall(const char* fmt, ...)
{
  if (mclLogLevel > 0) {
    va_list args;
    va_start(args,fmt);
    logStream(stdout,fmt,args);
    va_end(args);
  }
}
Пример #13
0
cl_device_id mclGetGpuDeviceID()
{
  cl_platform_id platform_id = mclGetPlatformID();

  // Info about devices
  cl_uint num_devices;
  logOclCall("clGetDeviceIDs (get number of devices)");
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices);
  cl_device_id* devices = calloc(sizeof(cl_device_id), num_devices);
  logOclCall("clGetDeviceIDs (get list of devices)");
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, devices, NULL);

  if (mclLogLevel > 1) {
    logStream(stdout, "System has %d GPU device(s):", num_devices);
    char buf1[MCL_MAX_STRING_LENGTH];
    char buf2[MCL_MAX_STRING_LENGTH];
    for(cl_uint i = 0; i < num_devices;i++) {
      logOclCall("clGetDeviceInfo, name of device %d", i);
      clGetDeviceInfo(devices[i], CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf1, NULL);
      logOclCall("clGetDeviceInfo, OpenCL version for device %d", i);
      clGetDeviceInfo(devices[i], CL_DEVICE_VERSION, MCL_MAX_STRING_LENGTH, buf2, NULL);
      logStream(stdout, "   Device %d: %s, which supports %s", i, buf1, buf2);
    }
  }

  if (num_devices < 1) {
    fprintf(stderr, "MCL - Exiting: No GPU devices available\n");
    exit(1);
  }

  // Selecting the device
  cl_uint num_device = num_devices - 1;
  cl_device_id device_id = devices[num_device];
  if (mclLogLevel > 0) {
    char buf[MCL_MAX_STRING_LENGTH];
    logOclCall("clGetDeviceInfo, name of device %d", device_id);
    clGetDeviceInfo(device_id, CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf, NULL);
    logStream(stdout,"Selected device %d: %s", num_device, buf);
    if (mclLogLevel > 2) {
      mclPrintDeviceInfo(device_id);
    }
  }
  return device_id;
}
Пример #14
0
Logger::Logger(string &adhash_home) {
	time_t rawtime;
	time(&rawtime);
	long myId;
	myId = MPI::COMM_WORLD.Get_rank();
    logFile = adhash_home+"/logs/log" + toString(myId) + ".txt";
	ofstream logStream(logFile.c_str());
	logStream << "Logging activity at " << ctime(&rawtime) << endl;
	logStream << "Process id: " << getpid() << endl << endl;
}
Пример #15
0
void ReaderManipulatorWidget::writeToOutput(const QString &text)
{
    ui->teOutput->append(text);

    if(m_useLogFile && m_logFile->isOpen()){
        QTextStream logStream(m_logFile);
        logStream << text << QString("\r");
        logStream.flush();
    }
}
Пример #16
0
void Logger::writeToLog(string record, bool to_screen){
#ifdef enable_logging
    ofstream logStream(logFile.c_str(), ios::app);
    logStream << record << endl;
    logStream.flush();
    logStream.close();
#endif
    if(to_screen){
        printf("%s\n", record.c_str());
        //cout.flush();
    }
}
Пример #17
0
cl_platform_id mclGetPlatformID()
{
  /* Get the platform information */
  cl_uint num_platforms;
  logOclCall("clGetPlatformIDs (get number of platforms)");
  clGetPlatformIDs(0, NULL, &num_platforms);             // get number of platforms
  cl_platform_id* platforms = calloc(sizeof(cl_platform_id), num_platforms);
  logOclCall("clGetPlatformIDs (list of platforms, n = %d)", num_platforms);
  clGetPlatformIDs(num_platforms, platforms, NULL);     // populate platform table
  if (mclLogLevel > 1) {
    logStream(stdout,"System has %d platform(s):", num_platforms);
    for(cl_uint i = 0; i < num_platforms;i++) {
      char buf[MCL_MAX_STRING_LENGTH];
      logOclCall("clGetPlatformInfo (get platform name for device %d)", i);
      clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, MCL_MAX_STRING_LENGTH, buf, NULL);
      logStream(stdout,"  Platform: %s", buf);
    }
  }
  if (num_platforms == 0) {
    fprintf(stderr, "MCL - Exiting: No OpenCL Platform available\n");
    exit(1);
  }
  return platforms[0];
}
Пример #18
0
void ControlWindows::Save()
{
  
  
  QString nameFile=QFileDialog::getSaveFileName(this,"Save File","./");
  QTextStream logStream(stdout);
  QFile fileLog;
  fileLog.setFileName(nameFile);
  fileLog.open(QIODevice::WriteOnly | QIODevice::Append);
  logStream.setDevice(&fileLog);
  logStream << m_cache << flush;
  fileLog.close();
  m_cache.clear();

  
}
Пример #19
0
 void writeLog(QString strLog)
 {
     QFile logFile("/mnt/log.txt");
     QDateTime timestamp = QDateTime::currentDateTime();
     logFile.open(QIODevice::Append);
     if (logFile.isOpen())
     {
         QTextStream logStream(&logFile);
         logStream << timestamp.toString() << " " << strLog << '\n';
         logFile.close();
     }
     else
     {
         qDebug() << timestamp.toString() << " " << strLog;
     }
 }
Пример #20
0
  void SBPLPlannerStatsEntry::
  logFile(char const * filename, char const * title, char const * prefix) const
  {
    FILE * ff(fopen(filename, "a"));
    if (0 == ff) {
      ROS_WARN("SBPLPlannerStatsEntry::logFile(): fopen(%s): %s",
	       filename, strerror(errno));
      return;
    }
    ostringstream os;
    logStream(os, title, prefix);
    fprintf(ff, "%s", os.str().c_str());
    if (0 != fclose(ff))
      ROS_WARN("SBPLPlannerStatsEntry::logFile(): fclose() on %s: %s",
	       filename, strerror(errno));
  }
Пример #21
0
void NoGUI::tick()
{
    if(!isValid()) {
        for(QVariant &variant : m_statistics) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }

        for(QVariant &variant : m_models) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }

        for(QVariant &variant : m_datas) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }
        if(!isValid()) {
            qDebug() << "Error, NoGUI or children not ready...";
            exit(1);
        }
    }
    if(!m_timer.isValid()) m_timer.start();
    if(m_monteCarlo) m_monteCarlo->tick(m_timestep);

    if( m_monteCarlo && (m_timestep % m_printEvery) == 0) {
        double timeLeft = m_timer.elapsed() / ( double(m_timestep+1)) * (m_timesteps-m_timestep) / 1000.; // seconds
        QTextStream logStream(&m_log);
        qDebug() << "MC step " << m_timestep << "/" << m_timesteps << ". χ^2: " << QString::number( m_monteCarlo->chiSquared(), 'f', 10 ) << ", T=" << m_monteCarlo->temperature() << " with acceptance ratio " << m_monteCarlo->acceptanceRatio() << " (" << m_monteCarlo->accepted() << " / " << m_monteCarlo->steps() << ") and random walk fraction " << m_geometry->randomWalkFraction() << ". Estimated time left: " << timeLeft << " seconds.";
        logStream << "MC step " << m_timestep << "/" << m_timesteps << ". χ^2: " << QString::number( m_monteCarlo->chiSquared(), 'f', 10 ) << ", T=" << m_monteCarlo->temperature() << " with acceptance ratio " << m_monteCarlo->acceptanceRatio() << " (" << m_monteCarlo->accepted() << " / " << m_monteCarlo->steps() << ") and random walk fraction " << m_geometry->randomWalkFraction() << ". Estimated time left: " << timeLeft << " seconds.\n";
        if(m_visualize) {
            for(QVariant &variant : m_statistics) {
                Statistic *statistic = variant.value<Statistic*>();
                statistic->compute(m_geometry, m_timestep);
                if(m_visualize) {
                    statistic->updateQML();
                }
            }
        }
    }

    m_timestep++;

    if(m_timestep >= m_timesteps) {
        setFinished(true);
    }
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
ModuleService::unload(module_ptr_type _pModule)
{
    // Get the logger stream
    Zen::Utility::log_stream& logStream(
        I_PluginManager::getSingleton().getApplication()->getLogStream()
    );

    // Guard this method
    boost::shared_ptr<Threading::CriticalSection> pGuard(
        new Threading::CriticalSection(m_pModuleGuard) );

    // Use _pModule to get the module info
    module_info_ptr_type pModuleInfo = m_modules[_pModule];

    // Decrement the reference
    // If the count is zero, get the handle and unload the library
    if( pModuleInfo->decrementReferences() == 0 )
    {
        std::string moduleName = pModuleInfo->getName();

        // Remove module from the index
        module_name_index_iterator_type moduleIndexIterator = m_moduleIndex.find(moduleName);
        m_moduleIndex.erase(moduleIndexIterator);

        // Physically unload module
        I_ModuleInfo::module_handle_type hModule = pModuleInfo->getHandle();

#ifdef _WIN32
        if( !FreeLibrary(hModule) )
#else
        if( dlclose(hModule) )
#endif // _WIN32
        {
            logStream << "DEBUG: Error unloading module " << moduleName << " Error " << Zen::Utility::GetLastError() << std::endl;

            // TODO Throw an exception with the error
            return;
        }

        // Remove module from the cache
        modules_iterator_type moduleIterator = m_modules.find(_pModule);
        m_modules.erase(moduleIterator);

    }
}
Пример #23
0
void Console::logToFile(const LogMessage& message) {
#if defined __APPLE__
    NSLogWrapper(message.string());
#else
    IO::FileManager fileManager;
    const String logDirectory = fileManager.logDirectory();
    if (logDirectory.empty())
        return;
    if (!fileManager.exists(logDirectory))
        fileManager.makeDirectory(logDirectory);
    const String logFilePath = fileManager.appendPath(logDirectory, "TrenchBroom.log");
    std::fstream logStream(logFilePath.c_str(), std::ios::out | std::ios::app);
    if (logStream.is_open()) {
        wxDateTime now = wxDateTime::Now();
        logStream << wxGetProcessId() << " " << now.FormatISOCombined(' ') << ": " << message.string() << std::endl;
    }
#endif
}
Пример #24
0
void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
    Q_UNUSED(context);

    QString logMessage;
    QString threadId = QString::number((long long)QThread::currentThreadId(), 16);
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");

    switch (type)
    {
        case QtDebugMsg:
            logMessage = QString("[%1] [%2] [D] %3").arg(timestamp).arg(threadId).arg(message);
            break;
        case QtWarningMsg:
            logMessage = QString("[%1] [%2] [W] %3").arg(timestamp).arg(threadId).arg(message);
            break;
        case QtCriticalMsg:
            logMessage = QString("[%1] [%2] [C] %3").arg(timestamp).arg(threadId).arg(message);
            break;
        case QtFatalMsg:
            logMessage = QString("[%1] [%2] [F] %3").arg(timestamp).arg(threadId).arg(message);
    }

    fprintf(stderr, "%s\n", qPrintable(logMessage));

    QString path = QString("%1/.CasparCG/Client/Logs").arg(QDir::homePath());

    QDir directory(path);
    if (!directory.exists())
        directory.mkpath(".");

    QFile logFile(QString("%1/Client_%2.log").arg(path).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd")));
    logFile.open(QIODevice::WriteOnly | QIODevice::Append);

    QTextStream logStream(&logFile);
    logStream << logMessage << endl;

    logFile.close();

    if (type == QtFatalMsg)
       abort();
}
Пример #25
0
void ApplicationLog::write(QString message) {
    QString datetimeString = QDateTime::currentDateTime().toString(LOG_MESSAGE_DATETIME_PATTERN);
    QString formattedMessage = QString("%1 %2").arg(datetimeString, message);
    this -> logMutex -> lock();
    // если новая дата
    if (this -> currentDate != QDate::currentDate()) {
        writeToStdout(QString("The current log file will be closed and a new file opened for the new date."));
        this -> logFile -> close();
        if (!this -> createLogFile()) {
            return;
        }
    }
    QTextStream stdoutStream(stdout);
    QTextStream logStream(logFile);
    stdoutStream << formattedMessage << endl;
    logStream << formattedMessage << endl;
    stdoutStream.flush();
    logStream.flush();
    logMutex -> unlock();
}
Пример #26
0
    void writeLog(QString strLog)
    {
        QFile logFile(QDir::homePath() + "/" + "osmc_installer_log.txt");
        QDateTime timestamp = QDateTime::currentDateTime();
        logFile.open(QIODevice::Append);
        if (logFile.isOpen())
        {
#ifdef Q_OS_LINUX
            // Set the owner and group the same as the home path
            QFileInfo info(QDir::homePath());
            fchown(logFile.handle(),info.ownerId(),info.groupId());
#endif
            QTextStream logStream(&logFile);
            logStream << timestamp.toString() << " " << strLog << '\n';
            logFile.close();
        }
        else
        {
            qDebug() << timestamp.toString() << " " << strLog;
        }
    }
Пример #27
0
Файл: main.cpp Проект: OSLL/sca
void logToFile(QtMsgType type, const char *msg)
{
    QFile file(LOG_PATH);
    if (!file.open(QFile::ReadWrite | QFile::Text | QFile::Append))
    {
        abort();
        return;
    }
    QTextStream logStream(&file);
    QString str(LOG_PATTERN);
    switch (type)
    {
    case QtDebugMsg:
        str = str.arg("Debug");
        break;
    case QtWarningMsg:
        str = str.arg("Warning");
        break;
    case QtCriticalMsg:
        str = str.arg("Critical");
        break;
    case QtFatalMsg:
        str = str.arg("Fatal").arg(msg);
        abort();
    default:
        file.close();
        return;
    }
    str = str.arg(msg);
    logStream << str;
#ifdef WIN32
    OutputDebugString(reinterpret_cast<const wchar_t *>(str.utf16()));
#endif
#ifdef __linux__
    std::cerr << str.toStdString() << std::endl;
#endif
    file.close();
}
Пример #28
0
FocusCameraClient *FocusClient::initFocCamera (FocusCameraClient * cam)
{
	std::vector < char *>::iterator cam_iter;
	cam->setSaveImage (autoSave || focExe);
	if (defCenter)
	{
		cam->center (imageWidth, imageHeight);
	}
	else if (xOffset >= 0 || yOffset >= 0 || imageWidth >= 0 || imageHeight >= 0)
	{
		cam->queCommand (new rts2core::CommandBox (cam, xOffset, yOffset, imageWidth, imageHeight));
	}
	if (!std::isnan (defExposure))
	{
		cam->queCommand (new rts2core::CommandChangeValue (cam->getMaster (), "exposure", '=', defExposure));

	}
	if (darks)
	{
		cam->queCommand (new rts2core::CommandChangeValue (cam->getMaster (), "SHUTTER", '=', 1));
	}
	if (defBin >= 0)
	{
		cam->queCommand (new rts2core::CommandChangeValue (cam->getMaster (), "binning", '=', defBin));
	}
	// post exposure event..if name agree
	for (cam_iter = cameraNames.begin (); cam_iter != cameraNames.end (); cam_iter++)
	{
		if (!strcmp (*cam_iter, cam->getName ()))
		{
			logStream (MESSAGE_DEBUG) << "exposing on " << cam->getName () << sendLog;
			cam->queCommand (new rts2core::CommandExposure (this, cam, bop >= 0 ? bop : 0));
		}
	}
	return cam;
}
Пример #29
0
void ChatWindow::logText(const QString& text)
{
    if(log())
    {
        // "cd" into log path or create path, if it's not there
        cdIntoLogPath();

        if(logfile.open(QIODevice::WriteOnly | QIODevice::Append))
        {
            // wrap the file into a stream
            QTextStream logStream(&logfile);
            // write log in utf8 to help i18n
            logStream.setCodec(QTextCodec::codecForName("UTF-8"));
            logStream.setAutoDetectUnicode(true);

            if(firstLog)
            {
                QString intro(i18n("\n*** Logfile started\n*** on %1\n\n", QDateTime::currentDateTime().toString()));
                logStream << intro;
                firstLog=false;
            }

            QDateTime dateTime = QDateTime::currentDateTime();
            QString logLine(QString("[%1] [%2] %3\n").arg(QLocale().toString(dateTime.date(), QLocale::LongFormat)).
                arg(QLocale().toString(dateTime.time(), QLocale::LongFormat)).arg(text));
            logStream << logLine;

            // detach stream from file
            logStream.setDevice(0);

            // close file
            logfile.close();
        }
        else qWarning() << "open(QIODevice::Append) for " << logfile.fileName() << " failed!";
    }
}
Пример #30
0
/**
 * This benchmark runs a series of huge strokes on a canvas with a
 * particular configuration of the swapper/pooler and history
 * management. After the test is done you can visualize the results
 * with the GNU Octave. Please use kis_low_memory_show_report.m file
 * for that.
 */
void KisLowMemoryBenchmark::benchmarkWideArea(const QString presetFileName,
                                              const QRectF &rect, qreal vstep,
                                              int numCycles,
                                              bool createTransaction,
                                              int hardLimitMiB,
                                              int softLimitMiB,
                                              int poolLimitMiB,
                                              int index)
{
    KisPaintOpPresetSP preset = new KisPaintOpPreset(QString(FILES_DATA_DIR) + QDir::separator() + presetFileName);
    LOAD_PRESET_OR_RETURN(preset, presetFileName);


    /**
     * Initialize image and painter
     */
    const KoColorSpace *colorSpace = KoColorSpaceRegistry::instance()->rgb8();
    KisImageSP image = new KisImage(0, HUGE_IMAGE_SIZE, HUGE_IMAGE_SIZE, colorSpace, "stroke sample image", true);
    KisLayerSP layer = new KisPaintLayer(image, "temporary for stroke sample", OPACITY_OPAQUE_U8, colorSpace);
    KisLayerSP layerExtra = new KisPaintLayer(image, "temporary for threading", OPACITY_OPAQUE_U8, colorSpace);

    image->addNode(layer, image->root());
    image->addNode(layerExtra, image->root());

    KisPainter *painter = new KisPainter(layer->paintDevice());

    painter->setPaintColor(KoColor(Qt::black, colorSpace));
    painter->setPaintOpPreset(preset, layer, image);

    /**
     * A simple adapter that will store all the transactions for us
     */
    KisSurrogateUndoAdapter undoAdapter;

    /**
     * Reset configuration to the desired settings
     */
    KisImageConfig config;
    qreal oldHardLimit = config.memoryHardLimitPercent();
    qreal oldSoftLimit = config.memorySoftLimitPercent();
    qreal oldPoolLimit = config.memoryPoolLimitPercent();
    const qreal _MiB = 100.0 / KisImageConfig::totalRAM();

    config.setMemoryHardLimitPercent(hardLimitMiB * _MiB);
    config.setMemorySoftLimitPercent(softLimitMiB * _MiB);
    config.setMemoryPoolLimitPercent(poolLimitMiB * _MiB);

    KisTileDataStore::instance()->testingRereadConfig();

    /**
     * Create an empty the log file
     */
    QString fileName;
    fileName = QString("log_%1_%2_%3_%4_%5.txt")
        .arg(createTransaction)
        .arg(hardLimitMiB)
        .arg(softLimitMiB)
        .arg(poolLimitMiB)
        .arg(index);

    QFile logFile(fileName);
    logFile.open(QFile::WriteOnly | QFile::Truncate);
    QTextStream logStream(&logFile);
    logStream.setFieldWidth(10);
    logStream.setFieldAlignment(QTextStream::AlignRight);

    /**
     * Start painting on the image
     */

    QTime cycleTime;
    QTime lineTime;
    cycleTime.start();
    lineTime.start();

    qreal rectBottom = rect.y() + rect.height();

    for (int i = 0; i < numCycles; i++) {
        cycleTime.restart();

        QLineF line(rect.topLeft(), rect.topLeft() + QPointF(rect.width(), 0));
        if (createTransaction) {
            painter->beginTransaction();
        }

        KisDistanceInformation currentDistance;

        while(line.y1() < rectBottom) {
            lineTime.restart();

            KisPaintInformation pi1(line.p1(), 0.0);
            KisPaintInformation pi2(line.p2(), 1.0);
            painter->paintLine(pi1, pi2, &currentDistance);
            painter->device()->setDirty(painter->takeDirtyRegion());

            logStream << "L 1" << i << lineTime.elapsed()
                      << KisTileDataStore::instance()->numTilesInMemory() * 16
                      << KisTileDataStore::instance()->numTiles() * 16
                      << createTransaction << endl;

            line.translate(0, vstep);
        }

        painter->device()->setDirty(painter->takeDirtyRegion());

        if (createTransaction) {
            painter->endTransaction(&undoAdapter);
        }

        // comment/uncomment to emulate user waiting after the stroke
        QTest::qSleep(1000);

        logStream << "C 2" << i << cycleTime.elapsed()
                  << KisTileDataStore::instance()->numTilesInMemory() * 16
                  << KisTileDataStore::instance()->numTiles() * 16
                  << createTransaction
                  << config.memoryHardLimitPercent() / _MiB
                  << config.memorySoftLimitPercent() / _MiB
                  << config.memoryPoolLimitPercent() / _MiB  << endl;
    }

    config.setMemoryHardLimitPercent(oldHardLimit * _MiB);
    config.setMemorySoftLimitPercent(oldSoftLimit * _MiB);
    config.setMemoryPoolLimitPercent(oldPoolLimit * _MiB);

    delete painter;
}