当前位置: 首页>>代码示例>>C++>>正文


C++ QTime类代码示例

本文整理汇总了C++中QTime的典型用法代码示例。如果您正苦于以下问题:C++ QTime类的具体用法?C++ QTime怎么用?C++ QTime使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: handleRequest

void QgsServer::handleRequest( QgsServerRequest &request, QgsServerResponse &response )
{
  QgsMessageLog::MessageLevel logLevel = QgsServerLogger::instance()->logLevel();
  QTime time; //used for measuring request time if loglevel < 1
  QgsProject::instance()->removeAllMapLayers();

  qApp->processEvents();

  if ( logLevel == QgsMessageLog::INFO )
  {
    time.start();
  }

  // Pass the filters to the requestHandler, this is needed for the following reasons:
  // Allow server request to call sendResponse plugin hook if enabled
  QgsFilterResponseDecorator responseDecorator( sServerInterface->filters(), response );

  //Request handler
  QgsRequestHandler requestHandler( request, response );

  try
  {
    // TODO: split parse input into plain parse and processing from specific services
    requestHandler.parseInput();
  }
  catch ( QgsMapServiceException &e )
  {
    QgsMessageLog::logMessage( "Parse input exception: " + e.message(), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
    requestHandler.setServiceException( e );
  }

  // Set the request handler into the interface for plugins to manipulate it
  sServerInterface->setRequestHandler( &requestHandler );

  // Call  requestReady() method (if enabled)
  responseDecorator.start();

  // Plugins may have set exceptions
  if ( !requestHandler.exceptionRaised() )
  {
    try
    {
      QMap<QString, QString> parameterMap = request.parameters();
      printRequestParameters( parameterMap, logLevel );

      //Config file path
      QString configFilePath = configPath( *sConfigFilePath, parameterMap );

      // load the project if needed and not empty
      const QgsProject *project = mConfigCache->project( configFilePath );
      if ( ! project )
      {
        throw QgsServerException( QStringLiteral( "Project file error" ) );
      }

      sServerInterface->setConfigFilePath( configFilePath );

      //Service parameter
      QString serviceString = parameterMap.value( QStringLiteral( "SERVICE" ) );

      if ( serviceString.isEmpty() )
      {
        // SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo
        QString requestString = parameterMap.value( QStringLiteral( "REQUEST" ) );
        if ( requestString == QLatin1String( "GetMap" ) || requestString == QLatin1String( "GetFeatureInfo" ) )
        {
          serviceString = QStringLiteral( "WMS" );
        }
      }

      QString versionString = parameterMap.value( QStringLiteral( "VERSION" ) );

      //possibility for client to suggest a download filename
      QString outputFileName = parameterMap.value( QStringLiteral( "FILE_NAME" ) );
      if ( !outputFileName.isEmpty() )
      {
        requestHandler.setResponseHeader( QStringLiteral( "Content-Disposition" ), "attachment; filename=\"" + outputFileName + "\"" );
      }

      // Lookup for service
      QgsService *service = sServiceRegistry.getService( serviceString, versionString );
      if ( service )
      {
        service->executeRequest( request, responseDecorator, project );
      }
      else
      {
        throw QgsOgcServiceException( QStringLiteral( "Service configuration error" ),
                                      QStringLiteral( "Service unknown or unsupported" ) ) ;
      }
    }
    catch ( QgsServerException &ex )
    {
      responseDecorator.write( ex );
    }
    catch ( QgsException &ex )
    {
      // Internal server error
      response.sendError( 500, ex.what() );
    }
//.........这里部分代码省略.........
开发者ID:ndavid,项目名称:QGIS,代码行数:101,代码来源:qgsserver.cpp

示例2: doAnalysis

// This is called from the AnalyserQueue thread
bool AnalyserQueue::doAnalysis(TrackPointer tio, SoundSourceProxy* pSoundSource) {
    int totalSamples = pSoundSource->length();
    //qDebug() << tio->getFilename() << " has " << totalSamples << " samples.";
    int processedSamples = 0;

    QTime progressUpdateInhibitTimer;
    progressUpdateInhibitTimer.start(); // Inhibit Updates for 60 milliseconds

    int read = 0;
    bool dieflag = false;
    bool cancelled = false;
    int progress; // progress in 0 ... 100

    do {
        ScopedTimer t("AnalyserQueue::doAnalysis block");
        read = pSoundSource->read(kAnalysisBlockSize, m_pSamplesPCM);

        // To compare apples to apples, let's only look at blocks that are the
        // full block size.
        if (read != kAnalysisBlockSize) {
            t.cancel();
        }

        // Safety net in case something later barfs on 0 sample input
        if (read == 0) {
            t.cancel();
            break;
        }

        // If we get more samples than length, ask the analysers to process
        // up to the number we promised, then stop reading - AD
        if (read + processedSamples > totalSamples) {
            qDebug() << "While processing track of length " << totalSamples << " actually got "
                     << read + processedSamples << " samples, truncating analysis at expected length";
            read = totalSamples - processedSamples;
            dieflag = true;
        }

        // Normalize the samples from [SHRT_MIN, SHRT_MAX] to [-1.0, 1.0].
        // TODO(rryan): Change the SoundSource API to do this for us.
        for (int i = 0; i < read; ++i) {
            m_pSamples[i] = static_cast<CSAMPLE>(m_pSamplesPCM[i]) / SHRT_MAX;
        }

        QListIterator<Analyser*> it(m_aq);

        while (it.hasNext()) {
            Analyser* an =  it.next();
            //qDebug() << typeid(*an).name() << ".process()";
            an->process(m_pSamples, read);
            //qDebug() << "Done " << typeid(*an).name() << ".process()";
        }

        // emit progress updates
        // During the doAnalysis function it goes only to 100% - FINALIZE_PERCENT
        // because the finalise functions will take also some time
        processedSamples += read;
        //fp div here prevents insane signed overflow
        progress = (int)(((float)processedSamples)/totalSamples *
                         (1000 - FINALIZE_PERCENT));

        if (m_progressInfo.track_progress != progress) {
            if (progressUpdateInhibitTimer.elapsed() > 60) {
                // Inhibit Updates for 60 milliseconds
                emitUpdateProgress(tio, progress);
                progressUpdateInhibitTimer.start();
            }
        }

        // Since this is a background analysis queue, we should co-operatively
        // yield every now and then to try and reduce CPU contention. The
        // analyser queue is CPU intensive so we want to get out of the way of
        // the audio callback thread.
        //QThread::yieldCurrentThread();
        //QThread::usleep(10);

        //has something new entered the queue?
        if (deref(m_aiCheckPriorities)) {
            m_aiCheckPriorities = false;
            if (isLoadedTrackWaiting(tio)) {
                qDebug() << "Interrupting analysis to give preference to a loaded track.";
                dieflag = true;
                cancelled = true;
            }
        }

        if (m_exit) {
            dieflag = true;
            cancelled = true;
        }

        // Ignore blocks in which we decided to bail for stats purposes.
        if (dieflag || cancelled) {
            t.cancel();
        }
    } while(read == kAnalysisBlockSize && !dieflag);

    return !cancelled; //don't return !dieflag or we might reanalyze over and over
}
开发者ID:YoungLeeNENU,项目名称:mixxx,代码行数:100,代码来源:analyserqueue.cpp

示例3: g0

// This requires all the Grids be of the same size and all the orbitals to be
// of the same spin.  Returns true only if something was calculated.
bool MolecularOrbitals::computeOrbitalGrids(Data::GridDataList& grids)
{
   if (grids.isEmpty()) return false;;

   // Check that the grids are all of the same size and Spin
   Data::GridData* g0(grids[0]);
   QList<int> orbitals;
   Data::GridDataList::iterator iter;

   for (iter = grids.begin(); iter != grids.end(); ++iter) {
qDebug() << "Computing grid" << (*iter)->surfaceType().toString() ;
(*iter)->size().dump();
       if ( ((*iter)->size() != g0->size()) ) {
          QLOG_ERROR() << "Different sized grids found in molecular orbitals calculator";
          return false;
       }
       if ( ((*iter)->surfaceType().kind() != Data::SurfaceType::AlphaOrbital) &&
            ((*iter)->surfaceType().kind() != Data::SurfaceType::BetaOrbital) ) {
          QLOG_ERROR() << "Incorrect grid type found in molecular orbitals calculator";
          QLOG_ERROR() << (*iter)->surfaceType().toString(); 
          return false;
       }
       orbitals.append((*iter)->surfaceType().index()-1);
   }

   QTime time;
   time.start();

   Matrix const* coefficients;
   if (g0->surfaceType().kind() == Data::SurfaceType::AlphaOrbital) {
      QLOG_TRACE() << "Setting MO coefficient data to Alpha";
      coefficients = &(m_molecularOrbitals.alphaCoefficients());
   }else {
      QLOG_TRACE() << "Setting MO coefficient data to Beta";
      coefficients = &(m_molecularOrbitals.betaCoefficients());
   }
   
   unsigned nOrb(orbitals.size());
   unsigned nx, ny, nz;
   g0->getNumberOfPoints(nx, ny, nz);
   Vec delta(g0->delta());
   Vec origin(g0->origin());

   QProgressDialog progressDialog("Calculating orbital grid data", "Cancel", 0, 
       nx, QApplication::activeWindow());
   int progress(0);

   progressDialog.setValue(progress);
   progressDialog.setWindowModality(Qt::WindowModal);
   progressDialog.show();

   double  x, y, z;
   double* values;
   double* tmp = new double[nOrb];
   unsigned i, j, k;

   Data::ShellList const& shells(m_molecularOrbitals.shellList());
   Data::ShellList::const_iterator shell;

   for (i = 0, x = origin.x;  i < nx;  ++i, x += delta.x) {
       for (j = 0, y = origin.y;  j < ny;  ++j, y += delta.y) {
           for (k = 0, z = origin.z;  k < nz;  ++k, z += delta.z) {
   
               Vec gridPoint(x,y,z);

               for (unsigned orb = 0; orb < nOrb; ++orb) tmp[orb] = 0.0;
               unsigned count(0);

               //-----------------------------------------------------
               for (shell = shells.begin(); shell != shells.end(); ++shell) {
                   if ( (values = (*shell)->evaluate(gridPoint)) ) {
                      for (unsigned s = 0; s < (*shell)->nBasis(); ++s) {
                          for (unsigned orb = 0; orb < nOrb; ++orb) {
                              tmp[orb] += (*coefficients)(orbitals[orb], count) * values[s];
                          }
                          ++count;
                      }
                   }else {
                      count += (*shell)->nBasis();
                   }
               }

               for (unsigned orb = 0; orb < nOrb; ++orb) {
                   (*grids.at(orb))(i, j, k) = tmp[orb];
               }
               //-----------------------------------------------------
           }
       }

       ++progress;
       progressDialog.setValue(progress);
       if (progressDialog.wasCanceled()) return false;
   }

   delete [] tmp;

   double t = time.elapsed() / 1000.0;
   QLOG_INFO() << "Time to compute orbital grid data:" << t << "seconds";
//.........这里部分代码省略.........
开发者ID:epifanovsky,项目名称:IQmol,代码行数:101,代码来源:MolecularOrbitalsLayer.C

示例4: qWarning

bool GribV2::loadFile(QString fileName) {

    FILE * fptr=NULL;
    int msg=0;

    this->fileName=fileName;

    QTime tLoad;
    int m_sec_readCgrib=0;
    int m_sec_ginfo=0;
    int m_sec_g2_getfld=0;
    int m_sec_grecConst=0;
    int m_sec_endLoop=0;

    qWarning() << "GV2 loading " << fileName;

    g2int lskip=0,lgrib=0,iseek=0;
    unsigned char *cgrib; // msg buffer
    g2int ierr,listsec0[3],listsec1[13],numfields,numlocal;


    std::string fname = qPrintable(fileName);
    if(fileName == "") return false;

    gribfield  *gfld=NULL;

    ok=false;

    fptr=fopen(fname.c_str(),"rb");
    if(!fptr) {
        qWarning() << "Can't open Grib2 file (in loadFile): " << fileName;
        return false;
    }

    fseek(fptr,0,SEEK_END);
    fileSize=ftell(fptr);
    rewind(fptr);

    /* clean data structure + iso lines */
    clean_all_vectors();
    Util::cleanListPointers(listIsobars);
    Util::cleanListPointers(listIsotherms0);

    for(;;) {

        msg++;

        seekgb(fptr,iseek,32000,&lskip,&lgrib);
        if (lgrib == 0) break;    // end loop at EOF or problem

        cgrib=(unsigned char *)malloc(lgrib);

        fseek(fptr,lskip,SEEK_SET);
        tLoad.start();
        fread(cgrib,sizeof(unsigned char),lgrib,fptr);
        m_sec_readCgrib+=tLoad.elapsed();
        //qWarning() << "Size of cgrib: " << lgrib << ", skip=" << lskip;
        //qWarning() << "Bytes read from file: " << bRead;
        //qWarning() << "EOF=" << feof(fptr) << ", ferror=" << ferror(fptr);
        //qWarning() << "File pos=" << ftell(fptr);
        //qWarning() << "End of grib=" << cgrib[lgrib-4] << cgrib[lgrib-3] << cgrib[lgrib-2] << cgrib[lgrib-1];

        iseek=lskip+lgrib;

        tLoad.start();
        ierr=g2_info(cgrib,listsec0,listsec1,&numfields,&numlocal);
        m_sec_ginfo+=tLoad.elapsed();
        if(ierr) {
            qWarning() << "msg " << msg << ": g2_info error num=" << ierr;
            fclose(fptr);
            return false;
        }



        // accepting only GRIB2 with discipline=0 => Meteorological product (table 0.0)
        if(listsec0[1]!=2 || (listsec0[0]!=0 && listsec0[0]!=10)) {
            qWarning() << "msg " << msg << ": wrong version " << listsec0[1] << ", or discipline: " << listsec0[0];
            continue;
        }

        if(listsec1[4]!=1) {
            qWarning() << "msg " << msg << ": wrong reference time type: " << listsec1[4];
            continue;
        }

        /* loop on th fields => 1 field = 1 GribRecord */
        //qWarning() << "nb fields=" << numfields << ", nb locals=" << numlocal;

        for(int i=0;i<numfields;++i) {
            tLoad.start();
            ierr=g2_getfld(cgrib,i+1,GRB2_UNPACK,GRB2_EXPAND,&gfld);
            m_sec_g2_getfld+=tLoad.elapsed();
            if(ierr) {
                qWarning() << "msg=" << msg << "- field=" << i << ": g2_getfld error num=" << ierr;
                continue;
            }
            tLoad.start();
            GribV2Record * record = new GribV2Record(gfld,msg,i);
            m_sec_grecConst+=tLoad.elapsed();
//.........这里部分代码省略.........
开发者ID:nohal,项目名称:qtVlm,代码行数:101,代码来源:GribV2.cpp

示例5: y

int DataCurve::tableRow(int point)
{
    if (!d_table)
        return -1;

    if (d_type == Graph::Pie) {
        double y_val = y(point);
        int ycol = d_table->colIndex(title().text());
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            if (d_table->cell(i, ycol) == y_val)
                return i;
        }
    }

    int xcol = d_table->colIndex(d_x_column);
    int ycol = d_table->colIndex(title().text());

    if (xcol < 0 || ycol < 0)
        return -1;

    int xColType = d_table->columnType(xcol);
    if (xColType == Table::Date) {
        QString format = d_table->columnFormat(xcol);
        QDateTime date0 = QDateTime::fromString (d_table->text(d_start_row, xcol), format);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            QDateTime d = QDateTime::fromString (d_table->text(i, xcol), format);
            if (d.isValid()) {
                if (d_type == Graph::HorizontalBars && date0.secsTo(d) == y(point) && d_table->cell(i, ycol) == x(point))
                    return i;
                else if (date0.secsTo(d) == x(point) && d_table->cell(i, ycol) == y(point))
                    return i;
            }
        }
    } else if (xColType == Table::Time) {
        QString format = d_table->columnFormat(xcol);
        QTime t0 = QTime::fromString (d_table->text(d_start_row, xcol), format);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            QTime t = QTime::fromString (d_table->text(i, xcol), format);
            if (t.isValid()) {
                if (d_type == Graph::HorizontalBars && t0.msecsTo(t) == y(point) && d_table->cell(i, ycol) == x(point))
                    return i;
                if (t0.msecsTo(t) == x(point) && d_table->cell(i, ycol) == y(point))
                    return i;
            }
        }
    } else if (xColType == Table::Text) {
        double y_val = y(point);
        for (int i = d_start_row; i <= d_end_row; i++ ) {
            if (d_table->cell(i, ycol) == y_val)
                return i;
        }
    }

    double x_val = x(point);
    double y_val = y(point);
    for (int i = d_start_row; i <= d_end_row; i++ ) {
        if (d_table->cell(i, xcol) == x_val && d_table->cell(i, ycol) == y_val)
            return i;
    }

    return point;
}
开发者ID:kuzavas,项目名称:qtiplot,代码行数:62,代码来源:PlotCurve.cpp

示例6: fopen

bNEVwr::bNEVwr(char file_name[], int num_channels, char typeGrid[], char comment[])
{
    NEV = fopen(file_name, "wb");
    char headerName[8] = {'N','E','U','R','A','L','E','V'};
    fwrite(headerName, 1, sizeof(headerName), NEV);

    unsigned short fileSpec[] = {0x0201,0};
    fwrite(fileSpec,sizeof(fileSpec),1,NEV);

    //64*16bits+8bytes header = 136

    unsigned int packetSize = 136;
    unsigned int timeResolution = 40000;
    unsigned int Fs = 40000;
    unsigned int headerSize = 400 + num_channels*32; // 336 + 32 (extended) + 32 (extended)
    unsigned int bytes[] = {headerSize,packetSize,timeResolution,Fs};
    fwrite(bytes,sizeof(bytes),1,NEV);

    QDate theDate = QDate::currentDate();
    short year = theDate.year();
    short month = theDate.month();
    short day = theDate.day();
    short dayOfWeek = theDate.dayOfWeek();

    QTime theTime = QTime::currentTime();
    short hour = theTime.hour();
    short minute = theTime.minute();
    short second = theTime.second();
    short msec = theTime.msec();

    //GetSystemTime(&time);
    //fwrite(&time,sizeof(time),1,NEV);

    //short systemTime[2] = {1111111,999999};
    //fwrite(fakeSYSTEMTIME,sizeof(fakeSYSTEMTIME),1,NEV);

    short timeToWrite[8] = {year,month,day,dayOfWeek,hour,minute,second,msec};
    fwrite(timeToWrite,sizeof(timeToWrite),1,NEV);

    char appName[32] = "BIC NEV Writer v1.0";
    fwrite(appName,sizeof(char),32,NEV);

    // Must be NULL terminated
    char *commentWrite = (char*)malloc(256);
    strcpy(commentWrite,comment);
    fwrite(commentWrite,sizeof(char),256,NEV);


    fwrite(numHead,sizeof(numHead),1,NEV);

    ////////////////////////////////////////////////

    char arrayName[8] = {'A','R','R','A','Y','N','M','E'};
    fwrite(arrayName, 1, sizeof(arrayName), NEV);

    char *gridWrite = (char*)malloc(24);
    strcpy(gridWrite,typeGrid);
    fwrite(gridWrite,sizeof(char),24,NEV);

    ////////////////////////////////////////////////

    char NSASName[8] = {'N','S','A','S','E','X','E','V'};
    fwrite(NSASName, 1, sizeof(NSASName), NEV);

    // No periodic generation - random
    unsigned short tempShort[1]= {0};
    fwrite(tempShort,sizeof(tempShort),1,NEV);

    // Digital Input Changes should not be ignored...
    unsigned char tempChar[1]= {1};
    fwrite(tempChar,sizeof(tempChar),1,NEV);

    //Analog Channel 1
    tempChar[0] = 2;
    fwrite(tempChar,sizeof(tempChar),1,NEV);
    tempShort[0] = 2500;
    fwrite(tempShort,sizeof(tempShort),1,NEV);

    //Analog Channel 2
    tempChar[0] = 2;
    fwrite(tempChar,sizeof(tempChar),1,NEV);
    tempShort[0] = 2500;
    fwrite(tempShort,sizeof(tempShort),1,NEV);

    //Analog Channel 3
    tempChar[0] = 2;
    fwrite(tempChar,sizeof(tempChar),1,NEV);
    tempShort[0] = 2500;
    fwrite(tempShort,sizeof(tempShort),1,NEV);

    //Analog Channel 4
    tempChar[0] = 2;
    fwrite(tempChar,sizeof(tempChar),1,NEV);
    tempShort[0] = 2500;
    fwrite(tempShort,sizeof(tempShort),1,NEV);

    //Analog Channel 5
    tempChar[0] = 2;
    fwrite(tempChar,sizeof(tempChar),1,NEV);
    tempShort[0] = 2500;
//.........这里部分代码省略.........
开发者ID:daborton,项目名称:RTVT,代码行数:101,代码来源:bNEVwr.cpp

示例7: painter


//.........这里部分代码省略.........
        double factor = (m_dMaxValue_init-m_dMinValue_init)/(m_pRTSA->getMaxValue()-m_pRTSA->getMinValue());
        // Draw text
        painter.setPen(QPen(Qt::darkCyan, 1, Qt::SolidLine));
        painter.drawText(iStartX+8, iEndY, tr("Zoom %1x").arg(factor, 0, 'f', 2));

    }

    //*************************************************************************************************************
    //=============================================================================================================
    // Draw coordinates at mouse position
    //=============================================================================================================

    if(m_bPosition && m_pRTSA->getSamplingRate())
    {
        int iPosX = mapFromGlobal(QCursor::pos()).x();

        int iPosY = mapFromGlobal(QCursor::pos()).y();

        if(iPosX > usPosX && iPosX  < (usPosX + usWidth) && iPosY > usPosY && iPosY < usPosY + usHeight )
        {
            //Vertical Measuring
            painter.setPen(QPen(Qt::gray, 1, Qt::DashLine));

            QPoint start(usPosX, iPosY);//iStartY-5);//paint measure line vertical direction
            QPoint end(usPosX + usWidth, iPosY);//iStartY+5);

            painter.drawLine(start, end);

            start.setX(iPosX); start.setY(usPosY);//iStartY - 5);
            end.setX(iPosX); end.setY(usPosY + usHeight);//iStartY + 5);
            painter.drawLine(start, end);

            // Compute time between MouseStartPosition and MouseEndPosition
            QTime t = m_pTimeCurrentDisplay->addMSecs((int)(1000*(iPosX-usPosX)/(float)m_pRTSA->getSamplingRate()));
            float fAbsMag = m_pRTSA->getMinValue()+(usHeight-(iPosY-usPosY))*(dMinMaxDifference/usHeight);

            // Draw text
            painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine));

            painter.drawText(iPosX+8, iPosY-22, tr("%1").arg(t.toString("hh:mm:ss.zzz")));// ToDo Precision should be part of preferences
            painter.drawText(iPosX+8, iPosY-8, tr("%1%2").arg(fAbsMag, 0, 'e', 3).arg(m_pRTSA->getUnit()));
        }
    }

    //*************************************************************************************************************
    //=============================================================================================================
    // Draw the measurement tools of the curve
    //=============================================================================================================

    if(m_bMeasurement && m_pRTSA->getSamplingRate())
    {
        int iEndX   = m_qPointMouseEndPosition.x();
        int iStartX = m_qPointMouseStartPosition.x();

        int iEndY   = m_qPointMouseEndPosition.y();
        int iStartY = m_qPointMouseStartPosition.y();


        // Compute pixel difference
        double iPixelDifferenceX = abs(iStartX - iEndX);
        double iPixelDifferenceY = abs(iStartY - iEndY);

        if(iPixelDifferenceX < 5 && iPixelDifferenceY < 5)
            return;

        //Vertical Measuring
开发者ID:Lx37,项目名称:mne-cpp,代码行数:67,代码来源:newrealtimesamplearraywidget.cpp

示例8: ResultsRS


//.........这里部分代码省略.........
    const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo ();

    // check for more input errors now that we have fits header
    input.left = clamp( input.left, 0, hdr.naxis1-1);
    input.right = clamp( input.right, 0, hdr.naxis1-1);
    input.top = clamp( input.top, 0, hdr.naxis2-1);
    input.bottom = clamp( input.bottom, 0, hdr.naxis2-1);
    if( input.left > input.right) std::swap( input.left, input.right);
    if( input.top > input.bottom) std::swap( input.top, input.bottom);


    // prepare results (partial)
    m_currRes.input = input; // save reference to (fixed) input
    m_currRes.width = m_currRes.input.right - m_currRes.input.left + 1;
    m_currRes.height = m_currRes.input.bottom - m_currRes.input.top + 1;
    m_currRes.totalPixels = m_currRes.width * m_currRes.height;
    m_currRes.depth = hdr.totalFrames;
    m_currRes.currentFrame = m_currRes.input.currentFrame;
    throwIfInterrupt();

    int frame = m_currRes.input.currentFrame;

    // get the frame results for the current frame, unless we can retrieve this already
    // from the last time
    m_currRes.frames.resize( hdr.totalFrames);
    if( cacheValid && frame < m_currRes.nFramesComputed) {

    } else {
        m_currRes.frames[ frame] = computeFrame( input, frame);
    }
    ResultsRS::FrameRes & cfr = m_currRes.frames[ frame];

    // copy out the relevant bits
    m_currRes.nanPixels = cfr.nanPixels;
    m_currRes.min = cfr.min;
    m_currRes.max = cfr.max;
    m_currRes.average = cfr.average;
    m_currRes.sum = cfr.sum;
    m_currRes.rms = cfr.rms;
    m_currRes.bkgLevel = cfr.bkgLevel;
    m_currRes.sumMinusBkg = cfr.sumMinusBkg;
    m_currRes.maxMinusBkg = cfr.maxMinusBkg;
    m_currRes.maxPos = cfr.maxPos;

    { // total flux
        double bmin = 0.0, bmaj = 0.0;
        bool ok = true;
        if( ok) bmin = hdr.bmin.toDouble( & ok);
        if( ok) bmaj = hdr.bmaj.toDouble( & ok);
        if( ok) {
            m_currRes.beamArea = bmin * bmaj * 1.13309003545679845240692073642916670254
                    / (hdr.cdelt1 * hdr.cdelt2);
            m_currRes.beamArea = fabs( m_currRes.beamArea);
            m_currRes.totalFluxDensity = m_currRes.sum / m_currRes.beamArea;
            m_currRes.aboveBackground = m_currRes.sumMinusBkg / m_currRes.beamArea;
        } else {
            m_currRes.totalFluxDensity = std::numeric_limits<double>::quiet_NaN();
            m_currRes.aboveBackground = std::numeric_limits<double>::quiet_NaN();
            m_currRes.beamArea = std::numeric_limits<double>::quiet_NaN();
        }
    }

    // if the results are already complete, we are done
    if( m_currRes.nFramesComputed == hdr.totalFrames) {
        m_currRes.status_ = ResultsRS::Complete;
        emit done (m_currRes);
        return;
    }

    // otherwise we'll have to compute the remaining frames, but in any case,
    // report a partial result right now with the current frame
    m_currRes.status_ = ResultsRS::Partial;
    emit progress( m_currRes);

    // initialize timer for reporting progress
    QTime progressTimer;
    progressTimer.restart ();

    // now extract all the other frames
    int startFrame = m_currRes.nFramesComputed;
    for( int i = startFrame ; i < hdr.totalFrames ; i ++ ) {
        throwIfInterrupt();
        if( i == frame) continue; // skip the current frame, we already did that one
        // compute the frame
        m_currRes.frames[i] = computeFrame( input, i);
        m_currRes.nFramesComputed = i + 1;
        // report progress every second or so, but not for the last frame...
        if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) {
            progressTimer.restart ();
            throwIfInterrupt ();
            emit progress( m_currRes);
        }
    }

    // we are done
    m_currRes.status_ = ResultsRS::Complete;
    m_currRes.nFramesComputed = m_currRes.depth;
    throwIfInterrupt ();
    emit done (m_currRes);
}
开发者ID:pfederl,项目名称:CARTAvis,代码行数:101,代码来源:RegionStatsService.cpp

示例9: kDebug

void Project::load(const QString &newProjectPath)
{
    QTime a;a.start();

    ThreadWeaver::Weaver::instance()->dequeue();
    kDebug()<<"loading"<<newProjectPath<<"Finishing jobs...";

    if (!m_path.isEmpty())
    {
        TM::CloseDBJob* closeDBJob=new TM::CloseDBJob(projectID(),this);
        connect(closeDBJob,SIGNAL(done(ThreadWeaver::Job*)),closeDBJob,SLOT(deleteLater()));
    }
    ThreadWeaver::Weaver::instance()->finish();//more safety

    kDebug()<<"5...";

    setSharedConfig(KSharedConfig::openConfig(newProjectPath, KConfig::NoGlobals));
    kDebug()<<"4...";
    readConfig();
    m_path=newProjectPath;
    m_desirablePath.clear();

    //cache:
    m_projectDir=KUrl(m_path).directory();

    kDebug()<<"3...";
    m_localConfig->setSharedConfig(KSharedConfig::openConfig(projectID()+".local", KConfig::NoGlobals,"appdata"));
    m_localConfig->readConfig();

    if (langCode().isEmpty())
        setLangCode(KGlobal::locale()->language());
    kDebug()<<"2...";

    //KConfig config;
    //delete m_localConfig; m_localConfig=new KConfigGroup(&config,"Project-"+path());

    populateDirModel();

    kDebug()<<"1...";

    //put 'em into thread?
    //QTimer::singleShot(0,this,SLOT(populateGlossary()));
    populateGlossary();//we cant postpone it becase project load can be called from define new term function

    if (newProjectPath.isEmpty())
        return;

    //NOTE do we need to explicitly call it when project id changes?
    TM::DBFilesModel::instance()->openDB(projectID());

    if (QaModel::isInstantiated())
    {
        QaModel::instance()->saveRules();
        QaModel::instance()->loadRules(qaPath());
    }

    kDebug()<<"until emitting signal"<<a.elapsed();

    emit loaded();
    kDebug()<<"loaded!"<<a.elapsed();
}
开发者ID:ShermanHuang,项目名称:kdesdk,代码行数:61,代码来源:project.cpp

示例10: qDebug


//.........这里部分代码省略.........
    fprintf(stderr, "pass-out: %i\n", gPassOutSuit);
    rMove = 0;
  } else gPassOutSuit = -1;

  // build desk
  int turn = 0;
  if (lMove) {
    desk[turn++] = CARD(lMove->face(), lMove->suit()-1);
    if (rMove) desk[turn++] = CARD(rMove->face(), rMove->suit()-1);
  } else if (rMove) {
    desk[turn++] = CARD(rMove->face(), rMove->suit()-1);
  }

  // build hands
  for (int f = 0; f < 3; f++) {
    xHands[f].suitCount[0] = xHands[f].suitCount[1] = xHands[f].suitCount[2] = xHands[f].suitCount[3] = 0;
    xHands[f].suitStart[0] = xHands[f].suitStart[1] = xHands[f].suitStart[2] = xHands[f].suitStart[3] = 11;
    xHands[f].tricks = plst[f]->tricksTaken();
    int st;
    for (int z = 0; z < 10; z++) {
      if (hands[f][z]) {
        xHands[f].faces[z] = FACE(hands[f][z]);
        st = xHands[f].suits[z] = SUIT(hands[f][z]);
        if (xHands[f].suitCount[st]++ == 0) xHands[f].suitStart[st] = z;
      } else xHands[f].faces[z] = 0;
    }
  }

  // build desk
  for (int f = 0; f < turn; f++) {
    xDeskFaces[f] = FACE(desk[f]);
    xDeskSuits[f] = SUIT(desk[f]);
  }

  int a, b, c, move;
  int me = this->number()-1;
  xCardsLeft = crdLeft;
  gTrumpSuit = trumpSuit;
  gIterations = 0;

  printf("%shand 0:", this->number()==0?"*":" ");
  printHand(&(xHands[0]));
  printf("%shand 1:", this->number()==1?"*":" ");
  printHand(&(xHands[1]));
  printf("%shand 2:", this->number()==2?"*":" ");
  printHand(&(xHands[2]));
  printDesk(turn);

  // оптимизации
/*
  if (turn > 0) {
    // можем вообще взять?
    if (hands[me].suitCount(
  }
*/

  stTime = QTime::currentTime();
  stTime.start();
  abcPrune(turn, me, -666, 666, 666, &a, &b, &c, &move);

  qDebug() <<
    "face:" << FACE(hands[me][move]) <<
    "suit:" << SUIT(hands[me][move])+1 <<
    "move:" << move <<
    "turn:" << turn <<
    "moves:" << crdLeft <<
    "trump:" << trumpSuit <<
    "iters:" << gIterations <<
    "";

/*
  for (int h = 0; h < 3; h++) {
    fprintf(stderr, (h == me)?"*":" ");
    fprintf(stderr, "hand %i:", h);
    for (int f = 0; f < 10; f++) {
      if (hands[h][f]) {
        fprintf(stderr, " %2i.%i(%3i)", FACE(hands[h][f]), SUIT(hands[h][f]), hands[h][f]);
      } else {
        fprintf(stderr, " %2i.%i(%3i)", 0, 0, hands[h][f]);
      }
    }
    fprintf(stderr, "\n");
  }
  fprintf(stderr, "desk:");
  for (int f = 0; f < turn; f++) {
    fprintf(stderr, " %2i.%i(%3i)", FACE(desk[f]), SUIT(desk[f]), desk[f]);
  }
  fprintf(stderr, "\n");
*/
  Q_ASSERT(move >= 0);

  Card *moveCard = getCard(FACE(hands[me][move]), SUIT(hands[me][move])+1);

  qDebug() << "move:" << moveCard->toString();

  mCards.remove(moveCard);
  mCardsOut.insert(moveCard);

  return moveCard;
}
开发者ID:infsega,项目名称:bbpref,代码行数:101,代码来源:aialphabeta.cpp

示例11: done

void Worker::doWorkOld (InputParametersRS input)
{
    ResultsRS r;
    // for null input emit null output
    if( input.isNull) {
        r.status_ = ResultsRS::NullInput;
        emit done(r);
        return;
    }

    // initialize the parser if it's not already initialized
    if( ! m_parser)
        m_parser = new FitsParser();

    // if the parser is working on a different filename, reopen it
    if( currentFitsLocation_.uniqueId () != input.fitsLocation.uniqueId ()) {
        bool res = m_parser->loadFile ( input.fitsLocation);
        if( ! res)
            throw std::runtime_error("Could not open file");
        else
            currentFitsLocation_ = input.fitsLocation;
    }

    // get a reference to the fits header
    const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo ();

    // check for more input errors now that we have fits header
    input.left = clamp( input.left, 0, hdr.naxis1-1);
    input.right = clamp( input.right, 0, hdr.naxis1-1);
    input.top = clamp( input.top, 0, hdr.naxis2-1);
    input.bottom = clamp( input.bottom, 0, hdr.naxis2-1);
    if( input.left > input.right) std::swap( input.left, input.right);
    if( input.top > input.bottom) std::swap( input.top, input.bottom);

    // prepare results (partial)
    r.input = input; // save reference to (fixed) input
    r.width = r.input.right - r.input.left + 1;
    r.height = r.input.bottom - r.input.top + 1;
    r.totalPixels = r.width * r.height;
    r.status_ = ResultsRS::Partial;
    r.depth = hdr.totalFrames;
    r.currentFrame = r.input.currentFrame;
    throwIfInterrupt();
//    emit progress (r);

    int frame = r.input.currentFrame;

    // get the frame results for the current frame
    r.frames.resize( hdr.totalFrames);
    r.frames[ frame] = computeFrame( input, frame);
    ResultsRS::FrameRes & cfr = r.frames[ frame];
//    cfr = computeForFrame( input, frame);

    // copy out the relevant bits
    r.nanPixels = cfr.nanPixels;
    r.min = cfr.min;
    r.max = cfr.max;
    r.average = cfr.average;
    r.sum = cfr.sum;
    r.rms = cfr.rms;
    r.bkgLevel = cfr.bkgLevel;
    r.sumMinusBkg = cfr.sumMinusBkg;
    r.maxMinusBkg = cfr.maxMinusBkg;
    r.maxPos = cfr.maxPos;

    emit progress( r);

    // initialize timer for reporting progress
    QTime progressTimer;
    progressTimer.restart ();

    // now extract all the other frames
    for( int i = 0 ; i < hdr.totalFrames ; i ++ ) {
        throwIfInterrupt();
        if( i == frame) continue; // skip the current frame, we already did that one
        // compute the frame
        r.frames[i] = computeFrame( input, i);
        r.nFramesComputed = i + 1;
        // report progress every second or so, but not for the last frame...
        if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) {
            progressTimer.restart ();
            throwIfInterrupt ();
            emit progress( r);
        }
    }

    // we are done
    r.status_ = ResultsRS::Complete;
    r.nFramesComputed = r.depth;
    throwIfInterrupt ();
    emit done (r);
}
开发者ID:pfederl,项目名称:CARTAvis,代码行数:92,代码来源:RegionStatsService.cpp

示例12: setSearch

  /*
   * BIG MACHINE
   */
  std::list<LabelPosition*>* Pal::labeller( int nbLayers, char **layersName, double *layersFactor, double scale, double bbox[4], PalStat **stats, bool displayAll )
  {
#ifdef _DEBUG_
    std::cout << "LABELLER (selection)" << std::endl;
#endif

    Problem *prob;

    SearchMethod old_searchMethod = searchMethod;

    if ( displayAll )
    {
      setSearch( POPMUSIC_TABU );
    }

#ifdef _VERBOSE_
    clock_t start = clock();
    double create_time;
    std::cout << std::endl << "bbox: " << bbox[0] << " " << bbox[1] << " " << bbox[2] << " " << bbox[3] << std::endl;
#endif

#ifdef _EXPORT_MAP_
    // TODO this is not secure
    std::ofstream svgmap( "pal-map.svg" );

    svgmap << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" << std::endl
    << "<svg" << std::endl
    << "xmlns:dc=\"http://purl.org/dc/elements/1.1/\"" << std::endl
    << "xmlns:cc=\"http://creativecommons.org/ns#\"" << std::endl
    << "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" << std::endl
    << "xmlns:svg=\"http://www.w3.org/2000/svg\"" << std::endl
    << "xmlns=\"http://www.w3.org/2000/svg\"" << std::endl
    << "xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"" << std::endl
    << "xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"" << std::endl
    << "width=\"" << convert2pt( bbox[2] - bbox[0], scale, dpi )  << "\"" << std::endl
    << "height=\"" << convert2pt( bbox[3] - bbox[1], scale, dpi )  << "\">" << std::endl; // TODO xmax ymax
#endif

    QTime t;
    t.start();

    // First, extract the problem
    // TODO which is the minimum scale? (> 0, >= 0, >= 1, >1 )
    if ( scale < 1 || ( prob = extract( nbLayers, layersName, layersFactor, bbox[0], bbox[1], bbox[2], bbox[3], scale,
#ifdef _EXPORT_MAP_
                                        & svgmap
#else
                                        NULL
#endif
                                      ) ) == NULL )
    {

#ifdef _VERBOSE_
      if ( scale < 1 )
        std::cout << "Scale is 1:" << scale << std::endl;
      else
        std::cout << "empty problem... finishing" << std::endl;
#endif

#ifdef _EXPORT_MAP_
      svgmap << "</svg>" << std::endl;
      svgmap.close();
#endif

      // nothing to be done => return an empty result set
      if ( stats )
        ( *stats ) = new PalStat();
      return new std::list<LabelPosition*>();
    }

    std::cout << "PAL EXTRACT: " << t.elapsed() / 1000.0 << " s" << std::endl;
    t.restart();

    // reduce number of candidates
    // (remove candidates which surely won't be used)
    prob->reduce();

#ifdef _VERBOSE_
    std::cerr << prob->nblp << "\t"
              << prob->nbOverlap;
#endif


    prob->displayAll = displayAll;

#ifdef _VERBOSE_
    create_time = double( clock() - start ) / double( CLOCKS_PER_SEC );

    std::cout << std::endl << "Problem : " << prob->nblp << " candidates for " << prob->nbft << " features makes " << prob->nbOverlap << " overlaps" << std::endl;
    std::cout << std::endl << "Times:"  << std::endl << "    to create problem:  " << create_time << std::endl;
#endif

    // search a solution
    if ( searchMethod == FALP )
      prob->init_sol_falp();
    else if ( searchMethod == CHAIN )
      prob->chain_search();
//.........这里部分代码省略.........
开发者ID:Ariki,项目名称:QGIS,代码行数:101,代码来源:pal.cpp

示例13: main


//.........这里部分代码省略.........
        }

        if (dataSets.count() > 20 && function == "sum")
        {
            gbtLog(QObject::tr("You cannot classify more than 20 datasets using sum as function"));
            mydb.close();
            con.closeConnection();
            return 1;
        }

        QStringList letters;
        letters.append("A");
        letters.append("B");
        letters.append("C");
        letters.append("D");
        letters.append("E");
        letters.append("F");
        letters.append("G");
        letters.append("H");
        letters.append("I");
        letters.append("J");
        letters.append("K");
        letters.append("L");
        letters.append("M");
        letters.append("N");
        letters.append("O");
        letters.append("P");
        letters.append("Q");
        letters.append("R");
        letters.append("S");
        letters.append("T");


        QTime procTime;
        procTime.start();

        QString sqlSelect;
        QSqlQuery qry(mydb);

        sqlSelect = "SELECT T" + letters[0] + ".geokey,";
        sqlSelect = sqlSelect + "T" + letters[0] + ".xpos,";
        sqlSelect = sqlSelect + "T" + letters[0] + ".ypos,";
        sqlSelect = sqlSelect + "(";
        int pos;
        for (pos = 0; pos <= dataSets.count()-1;pos++)
        {
            if (function == "sum")
                sqlSelect = sqlSelect + "T" + letters[pos] + ".classCode + ";
            else
                sqlSelect = sqlSelect + "T" + letters[pos] + ".classCode * ";
        }
        sqlSelect = sqlSelect.left(sqlSelect.length()-3) + ") as comCode";

        QString sqlFrom;
        sqlFrom = " FROM ";
        for (pos = 0; pos <= dataSets.count()-1;pos++)
        {
            sqlFrom = sqlFrom + dataSets[pos] + " T" + letters[pos] + ",";
        }
        sqlFrom = sqlFrom.left(sqlFrom.length()-1);


        QString extentWhere;
        if (!extent.isEmpty())
            extentWhere =  getWhereClauseFromExtent(extent,mydb,dataSets[0]);
开发者ID:qlands,项目名称:GOBLET,代码行数:66,代码来源:main.cpp

示例14: main


//.........这里部分代码省略.........
  cout << "Radius:    " << radius << " m  (if circling)" << endl;
  cout << "Direction: " << direction.toLatin1().data() << " Turn" << endl;
  cout << "Climbrate: " << climb << " m/s" << endl;
  cout << "Time:      " << Time << " sec" << endl;
  cout << "Pause:     " << Pause << " ms" << endl;
  cout << "Device:    " << device.toLatin1().data() << endl;

  for( int i = 0; i < 10; i++ )
    {
      QString key = QString("sentence%1: ").arg(i);

      if( ! sentences[i].isEmpty() )
        {
          key += sentences[i];

          cout << key.toLatin1().data() << endl;
        }
    }

  cout << endl;

  glider myGl( lat, lon, speed, heading, wind, winddirTrue, altitude, climb );
  myGl.setFd( fifo );
  myGl.setCircle( radius, direction );

  // @AP: This is used for the GSA output simulation
  uint gsa = 0;
  QStringList satIds;
  satIds << "14" << "32" << "17" << "20" << "11" << "23" << "28" << "25" << "35";
  QString pdop = "1.7";
  QString hdop = "1.1";
  QString vdop = "1.2";

  QTime start = QTime::currentTime();

  if( Pause < 100 )
    {
      // Minimum is set to 100ms
      Pause = 100;
    }

  int nextTimeReporting = 0;

  while( start.elapsed() < Time*1000 )
    {
      gsa++;

      if( nextTimeReporting < start.elapsed() )
        {
          nextTimeReporting = start.elapsed() + 1000;
          cout << "Seconds remaining: " << Time - start.elapsed()/1000 << endl;
        }

      usleep( Pause * 1000 );

      if( mode == "str" )
        myGl.Straight();
      if( mode == "cir" )
        myGl.Circle();
      if( mode == "pos" )
        myGl.FixedPos();
      if( mode == "gpos" )
        myGl.FixedPosGround();

      // GSA output simulation
      if( ! (gsa % 40) )
开发者ID:Exadios,项目名称:Cumulus,代码行数:67,代码来源:main.cpp

示例15: findBreakInrange

long long PrePostRollFlagger::findBreakInrange(long long startFrame,
                                               long long stopFrame,
                                               long long totalFrames,
                                               long long &framesProcessed,
                                             QTime &flagTime, bool findLast)
{
    float flagFPS;
    int requiredBuffer = 30;
    long long currentFrameNumber;
    int prevpercent = -1;

    if(startFrame > 0)
        startFrame--;
    else
        startFrame = 0;

    player->DiscardVideoFrame(player->GetRawVideoFrame(0));

    long long tmpStartFrame = startFrame;
    VideoFrame* f = player->GetRawVideoFrame(tmpStartFrame);
    float aspect = player->GetVideoAspect();
    currentFrameNumber = f->frameNumber;
    LOG(VB_COMMFLAG, LOG_INFO, QString("Starting with frame %1")
            .arg(currentFrameNumber));
    player->DiscardVideoFrame(f);

    long long foundFrame = 0;

    while (!player->GetEof())
    {
        struct timeval startTime;
        if (stillRecording)
            gettimeofday(&startTime, NULL);

        VideoFrame* currentFrame = player->GetRawVideoFrame();
        currentFrameNumber = currentFrame->frameNumber;

        if(currentFrameNumber % 1000 == 0)
        {
            LOG(VB_COMMFLAG, LOG_INFO, QString("Processing frame %1")
                    .arg(currentFrameNumber));
        }

        if(currentFrameNumber > stopFrame || (!findLast && foundFrame))
        {
            player->DiscardVideoFrame(currentFrame);
            break;
        }

        double newAspect = currentFrame->aspect;
        if (newAspect != aspect)
        {
            SetVideoParams(aspect);
            aspect = newAspect;
        }

        if (((currentFrameNumber % 500) == 0) ||
            (((currentFrameNumber % 100) == 0) &&
             (stillRecording)))
        {
            emit breathe();
            if (m_bStop)
            {
                player->DiscardVideoFrame(currentFrame);
                return false;
            }
        }

        while (m_bPaused)
        {
            emit breathe();
            sleep(1);
        }

        // sleep a little so we don't use all cpu even if we're niced
        if (!fullSpeed && !stillRecording)
            usleep(10000);

        if (((currentFrameNumber % 500) == 0) ||
            ((showProgress || stillRecording) &&
             ((currentFrameNumber % 100) == 0)))
        {
            float elapsed = flagTime.elapsed() / 1000.0;

            if (elapsed)
                flagFPS = framesProcessed / elapsed;
            else
                flagFPS = 0.0;

            int percentage;
            if (stopFrame)
                percentage = framesProcessed * 100 / totalFrames;
            else
                percentage = 0;

            if (percentage > 100)
                percentage = 100;

            if (showProgress)
            {
//.........这里部分代码省略.........
开发者ID:Olti,项目名称:mythtv,代码行数:101,代码来源:PrePostRollFlagger.cpp


注:本文中的QTime类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。