コード例 #1
0
BrowserMessageArea::BrowserMessageArea( QWidget *parent )
    : QFrame( parent )
    , m_busy( false )
{
    setObjectName( "BrowserMessageArea" );

    setLayout( new QVBoxLayout( this ) );

    m_progressBar = new CompoundProgressBar( this );
    connect( m_progressBar, SIGNAL(allDone()), this, SLOT(hideProgress()) );
    layout()->addWidget( m_progressBar );
    m_progressBar->hide();

    m_messageLabel = new QLabel( this );
    m_messageLabel->setAlignment( Qt::AlignCenter );
    m_messageLabel->setWordWrap( true );
    layout()->addWidget( m_messageLabel );
    m_messageLabel->hide();

    m_shortMessageTimer = new QTimer( this );
    m_shortMessageTimer->setSingleShot( true );
    connect( m_shortMessageTimer, SIGNAL(timeout()), SLOT(nextShortMessage()) );

    //register to carry MessageType across threads
    qRegisterMetaType<Amarok::Logger::MessageType>( "MessageType" );
    connect( this, SIGNAL(signalLongMessage( const QString &, MessageType )),
             this, SLOT(slotLongMessage( const QString &, MessageType )),
             Qt::QueuedConnection );
}
コード例 #2
0
void edaSeqWorkflow::search(edaPopulation &pop) {
	checkError();

	// pack problem
	edaBuffer pro_buf;
	problem->pack(pro_buf);

	// initialize worker
	worker = new edaSeqWorker();
	unsigned int lastSearch = eda::FLAG;

	// If all job is done, quit
	while (!allDone()) {
		// Find nodes that ready to run
		vector<unsigned int> readyNodes = findReadyTask();
		vector<unsigned int>::iterator intIter;

		for (intIter = readyNodes.begin(); intIter != readyNodes.end();
				intIter++) {
			edaSearch *sa = taskDAG[*intIter];
			sa->ProcID = 0;
			lastSearch = *intIter;
			edaPopulation *Pop = chooseSolution(*intIter, pop);
			// pack the search algorithm
			edaBuffer sa_buf;
			sa->pack(sa_buf);

			// pack the problem and solution
			edaBuffer pro_buf, pop_buf_in, pop_buf_out;
			problem->pack(pro_buf);
			Pop->pack(pop_buf_in);
			// Invoke wrapper's search method
			worker->set(sa_buf);
			worker->search(pro_buf, pop_buf_in, pop_buf_out);
			fflush (stdout);
			// Unpack and save the solution
			easerObject(taskPop[*intIter]);
			taskPop[*intIter] = (edaPopulation*) unpack(pop_buf_out);

			// Reconfigure the problem for the solution
			taskPop[*intIter]->reconfig(problem);

			taskStatus[*intIter] = STATUS_FINISHED;

			checkLoopStatus(*intIter);
			// Destroy objects
			easerObject(Pop);
		}
	}

	// Return the solution
	unsigned int bestResultTaskID = detectBestResultTaskID();
	if (lastSearch != eda::FLAG && bestResultTaskID != eda::FLAG) {
		//Return the best result among results
		pop = *(taskPop[bestResultTaskID]);
	}
}
コード例 #3
0
E6Irc::E6Irc (QWidget *parent, bool isPhone)
  :QDeclarativeView (parent),
   isProbablyPhone (isPhone),
   channelGroup (0),
   control (0)
{
  channelGroup = new IrcQmlChannelGroup (this, this);
  control = new IrcQmlControl (this, this, channelGroup);
  connect (engine(), SIGNAL (quit()), this, SLOT(allDone()));
}
コード例 #4
0
ファイル: statusBar.cpp プロジェクト: mytbk/fqterm
void StatusBar::hideMainProgressBar() {
  if (allDone() && popupProgressMessage_->isHidden()) {
    pruneProgressBars();

    resetMainText();

    mainProgressBar_->setValue(0);
    progressBox()->close();
  }
}
コード例 #5
0
ファイル: ftpclient.cpp プロジェクト: maxselym/Magistral
void ftpClient::ftpCommandFinished(int commandId, bool error)
{
    if (ftp->currentCommand() == QFtp::ConnectToHost) {
        if (error) {
            qDebug()<<"FTP";
            qDebug()<<tr("Unable to connect to the FTP server "
                      "at %1. Please check that the host "
                      "name is correct.").arg(ftpServer);
            connectOrDisconnect();
            return;
        }
        qDebug()<<tr("Logged onto %1.").arg(ftpServer);
        return;
    }
//![6]

//![7]
    if (ftp->currentCommand() == QFtp::Login)
        ftp->list();
//![7]

//![8]
    if (ftp->currentCommand() == QFtp::Get) {
        if (error) {
           qDebug()<<tr("Canceled download of %1.").arg(file->fileName());
            file->close();
            file->remove();
        } else {
            qDebug()<<tr("Downloaded %1 to current directory.").arg(file->fileName());
            file->close();
            if(!f_list.isEmpty())
                downloadFile(); //Если есть еще файлы, то качаем
            else
            {
                delete file;
                qDebug()<<"end!!!"; /// А тут высылаем сигнал о выходе

                emit allDone(0,QProcess::NormalExit);
            }

        }

//![8]
//![9]
    } else if (ftp->currentCommand() == QFtp::List) {
//        if (isDirectory.isEmpty()) {
//            qDebug()<<tr("File scan ended!");
            downloadFile(); //начинаем скачку файлов
 //       }
    }
    //![9]
}
コード例 #6
0
ファイル: psqltocsv.cpp プロジェクト: maxselym/Magistral
void PsqlToCsv::writeAll()
{
    QSqlDatabase* database = db->GetDB();
    QSqlQuery* query = new QSqlQuery(*database);
    if(query->exec("SELECT * FROM stn_list"))
    {
        while(query->next())
        {
            if(writeStation(query->value(0).toInt()))
            {
                qDebug()<< "Station "<<query->value(0).toInt()<< "written!";
            }
        }
    } else
    {
        qDebug()<< query->lastError();
    }
    delete query;
    emit allDone(0,QProcess::NormalExit);
}
コード例 #7
0
ファイル: statusBar.cpp プロジェクト: mytbk/fqterm
/*
  void
  StatusBar::endProgressOperation()
  {
  QObject *owner = (QObject*)sender(); //HACK deconsting it
  KIO::Job *job = dynamic_cast<KIO::Job*>( owner );

  //FIXME doesn't seem to work for KIO::DeleteJob, it has its own error handler and returns no error too
  // if you try to delete http urls for instance <- KDE SUCKS!

  if( job && job->error() )
  longMessage( job->errorString(), Error );

  endProgressOperation( owner );
  }
*/
void StatusBar::endProgressOperation(QObject *owner) {
  //the owner of this progress operation has been deleted
  //we need to stop listening for progress from it
  //NOTE we don't delete it yet, as this upsets some
  //things, we just call setDone().

  if (!progressMap_.contains(owner)) {
    return ;
  }

  progressMap_[owner]->setDone();

  if (allDone() && popupProgressMessage_->isHidden()) {
    cancelButton()->setEnabled(false);
    //SingleShotPool::startTimer( 2000, this, SLOT(hideMainProgressBar()) );
    hideMainProgressBar();
  }

  updateTotalProgress();
}
コード例 #8
0
ファイル: WorkerThread.cpp プロジェクト: maciag/prover
void WorkerThread::run() {

	while (truthTree.decomposeStep()) {
		stopLock.lock();
		if (stop)
			return;
		stopLock.unlock();
		//emit stepDone(QString::fromStdString(truthTree.toFormattedString()));
	}
	truthTree.eliminateNodes();
	
	stopLock.lock();
	if (stop)
		return;
	stopLock.unlock();
	//emit stepDone(QString::fromStdString(truthTree.toFormattedString()));

	emit allDone(QString::fromStdString(truthTree.toFormattedString()), truthTree.getResult());

}
コード例 #9
0
ファイル: mainwindow.cpp プロジェクト: gt945/gov
void MainWindow::downloadVPN()
{
    Website *last = NULL;
    emit abortFetch();
    for( int i = 0; i < vpnList.count(); ++i )
    {
        if (vpnList[i]->out == false) {
               //qDebug() << vpnList[i]->timescore;
            Website *w = new Website;
            QString filename = QString("%1/%2").arg(this->ui->filePath->text(), vpnList[i]->getFilename());
            w->fetchLater(vpnList[i]->getDownloadURL(), filename);
            if (last) {
                connect(w, SIGNAL(finished()), last, SLOT(startFetch()));
            } else {
                connect(w, SIGNAL(finished()), this, SLOT(allDone()));
            }
            last = w;
            connect(this, SIGNAL(abortFetch()), w, SLOT(abortFetch()));
        }
    }

    last->startFetch();
}
コード例 #10
0
ファイル: statusBar.cpp プロジェクト: mytbk/fqterm
void StatusBar::resetMainText() {
  /*
    if( sender() )
    debug() << sender()->name() << endl;

    // don't reset if we are showing a shortMessage
    if( SingleShotPool::isActive( this, SLOT(resetMainText()) ) )
    return;
  */
  m_mainTextLabel->setPalette(QPalette());

  if (allDone()) {
    m_mainTextLabel->setText(mainText_);
  }

  else {
    //m_mainTextLabel->setPaletteBackgroundColor( m_mainTextLabel->paletteBackgroundColor().dark( 110 ) );
    m_mainTextLabel->setPalette(QToolTip::palette());

    ProgressBar *bar = 0;
    uint count = 0;

    for (ProgressMap::ConstIterator it = progressMap_.begin();
        it != progressMap_.end(); ++it ) {
      if (!(*it)->isFinished_) {
        bar =  *it;
        count++;
      }
    }

    if (count == 1) {
      m_mainTextLabel->setText(bar->description() + "...");
    } else {
      m_mainTextLabel->setText(tr("Multiple background-tasks running"));
    }
  }
}
コード例 #11
0
ファイル: statusBar.cpp プロジェクト: mytbk/fqterm
ProgressBar &StatusBar::newProgressOperation(QObject *owner) {
  if (progressMap_.contains(owner)) {
    return  *progressMap_[owner];
  }

  if (allDone()) {
    // if we're allDone then we need to remove the old progressBars before
    // we start anything new or the total progress will not be accurate
    pruneProgressBars();
  } else {
    (progressBox()->findChild < QWidget * > ("showAllProgressDetails"))->show();
  }

  QWidget *hbox = new QWidget(popupProgressMessage_);
  QHBoxLayout *hlayout = new QHBoxLayout(hbox);
  QLabel *label = new QLabel(hbox);
  hlayout->addWidget(label);
  ProgressBar *pBar = new ProgressBar(hbox, label);
  hlayout->addWidget(pBar);
  hbox->show();
  popupProgressMessage_->addWidget(hbox);
  progressMap_.insert(owner, pBar);


  FQ_VERIFY(connect(owner, SIGNAL(destroyed(QObject*)), SLOT(endProgressOperation(QObject*))));

  // so we can show the correct progress information
  // after the ProgressBar is setup
  //SingleShotPool::startTimer( 0, this, SLOT(updateProgressAppearance()) );
  updateProgressAppearance();

  progressBox()->show();
  cancelButton()->setEnabled(true);

  return  *progressMap_[owner];
}
コード例 #12
0
// fftcalc class is designed to treat with fft calculations
FFTCalc::FFTCalc(QObject *parent)
  :QObject(parent){

  // fftcalc is done in other thread
  // so it cannot overload the main thread
  processor.moveToThread(&processorThread);

  // qRegisterMetaType is used to register QVector<double> as the typename for QVector<double>
  // it is necessary for signal/slots events treatment.
  qRegisterMetaType< QVector<double> >("QVector<double>");

  // when the spectrum is calculated, setSpectrum function will comunicate
  // such spectrum to Qt as an emitted signal
  connect(&processor, SIGNAL(calculatedSpectrum(QVector<double>)), SLOT(setSpectrum(QVector<double>)));

  // when the processor finishes the calculation, the busy condition is changed.
  connect(&processor, SIGNAL(allDone()),SLOT(freeCalc()));

  // start the processor thread with low priority
  processorThread.start(QThread::LowestPriority);

  // initially, the processor is not occupied
  isBusy = false;
}
void QHttpNetworkConnectionChannel::_q_receiveReply()
{
    Q_ASSERT(socket);

    qint64 bytes = 0;
    QAbstractSocket::SocketState socketState = socket->state();

    // connection might be closed to signal the end of data
    if (socketState == QAbstractSocket::UnconnectedState) {
        if (!socket->bytesAvailable()) {
            if (reply && reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                reply->d_func()->state = QHttpNetworkReplyPrivate::AllDoneState;
                this->state = QHttpNetworkConnectionChannel::IdleState;
                allDone();
            } else {
                // try to reconnect/resend before sending an error.
                if (reconnectAttempts-- > 0) {
                    closeAndResendCurrentRequest();
                } else if (reply) {
                    reply->d_func()->errorString = connection->d_func()->errorDetail(QNetworkReply::RemoteHostClosedError, socket);
                    emit reply->finishedWithError(QNetworkReply::RemoteHostClosedError, reply->d_func()->errorString);
                    QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
                }
            }
        }
    }

    // read loop for the response
    while (socket->bytesAvailable()) {
        QHttpNetworkReplyPrivate::ReplyState state = reply ? reply->d_func()->state : QHttpNetworkReplyPrivate::AllDoneState;
        switch (state) {
        case QHttpNetworkReplyPrivate::NothingDoneState:
        case QHttpNetworkReplyPrivate::ReadingStatusState: {
            eatWhitespace();
            qint64 statusBytes = reply->d_func()->readStatus(socket);
            if (statusBytes == -1 && reconnectAttempts <= 0) {
                // too many errors reading/receiving/parsing the status, close the socket and emit error
                close();
                reply->d_func()->errorString = connection->d_func()->errorDetail(QNetworkReply::ProtocolFailure, socket);
                emit reply->finishedWithError(QNetworkReply::ProtocolFailure, reply->d_func()->errorString);
                QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
                break;
            } else if (statusBytes == -1) {
                reconnectAttempts--;
                reply->d_func()->clear();
                closeAndResendCurrentRequest();
                break;
            }
            bytes += statusBytes;
            lastStatus = reply->d_func()->statusCode;
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingHeaderState: {
            QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
            bytes += replyPrivate->readHeader(socket);
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                if (replyPrivate->isGzipped() && replyPrivate->autoDecompress) {
                    // remove the Content-Length from header
                    replyPrivate->removeAutoDecompressHeader();
                } else {
                    replyPrivate->autoDecompress = false;
                }
                if (replyPrivate->statusCode == 100) {
                    replyPrivate->state = QHttpNetworkReplyPrivate::ReadingStatusState;
                    break; // ignore
                }
                if (replyPrivate->shouldEmitSignals())
                    emit reply->headerChanged();
                if (!replyPrivate->expectContent()) {
                    replyPrivate->state = QHttpNetworkReplyPrivate::AllDoneState;
                    this->state = QHttpNetworkConnectionChannel::IdleState;
                    allDone();
                    return;
                }
            }
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingDataState: {
           QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
           if (replyPrivate->downstreamLimited && !replyPrivate->responseData.isEmpty() && replyPrivate->shouldEmitSignals()) {
               // We already have some HTTP body data. We don't read more from the socket until
               // this is fetched by QHttpNetworkAccessHttpBackend. If we would read more,
               // we could not limit our read buffer usage.
               // We only do this when shouldEmitSignals==true because our HTTP parsing
               // always needs to parse the 401/407 replies. Therefore they don't really obey
               // to the read buffer maximum size, but we don't care since they should be small.
               return;
           }

            if (!replyPrivate->isChunked() && !replyPrivate->autoDecompress
                && replyPrivate->bodyLength > 0) {
                // bulk files like images should fulfill these properties and
                // we can therefore save on memory copying
                bytes = replyPrivate->readBodyFast(socket, &replyPrivate->responseData);
                replyPrivate->totalProgress += bytes;
                if (replyPrivate->shouldEmitSignals()) {
                    QPointer<QHttpNetworkReply> replyPointer = reply;
                    emit reply->readyRead();
                    // make sure that the reply is valid
                    if (replyPointer.isNull())
                        return;
                    emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                    // make sure that the reply is valid
                    if (replyPointer.isNull())
                        return;
                }
            }
            else
            {
                // use the traditional slower reading (for compressed encoding, chunked encoding,
                // no content-length etc)
                QByteDataBuffer byteDatas;
                bytes = replyPrivate->readBody(socket, &byteDatas);
                if (bytes) {
                    if (replyPrivate->autoDecompress)
                        replyPrivate->appendCompressedReplyData(byteDatas);
                    else
                        replyPrivate->appendUncompressedReplyData(byteDatas);

                    if (!replyPrivate->autoDecompress) {
                        replyPrivate->totalProgress += bytes;
                        if (replyPrivate->shouldEmitSignals()) {
                            QPointer<QHttpNetworkReply> replyPointer = reply;
                            // important: At the point of this readyRead(), the byteDatas list must be empty,
                            // else implicit sharing will trigger memcpy when the user is reading data!
                            emit reply->readyRead();
                            // make sure that the reply is valid
                            if (replyPointer.isNull())
                                return;
                            emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                            // make sure that the reply is valid
                           if (replyPointer.isNull())
                                return;
                        }
                    }
#ifndef QT_NO_COMPRESS
                    else if (!expand(false)) { // expand a chunk if possible
                        return; // ### expand failed
                    }
#endif
                }
            }
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState)
                break;
            // everything done, fall through
            }
      case QHttpNetworkReplyPrivate::AllDoneState:
            this->state = QHttpNetworkConnectionChannel::IdleState;
            allDone();
            break;
        default:
            break;
        }
    }
}
コード例 #14
0
/* main program starts here */
void bootloader(void)
{
#ifdef ADABOOT
  char firstcharzero=0;
#endif
  uint8_t ch,ch2;
  uint16_t w;

  error_count = 0;
  initSerial();


  /* forever loop */
  for (;;) 
    {
    bitTgl(UsbLed);

      if (error_count >= MAX_ERROR_COUNT)  // Probably normal serial traffic is causing this.
        {
          releaseChipAccess();
          return;
          //initSerial();
          //error_count = 0;
        }

      /* get character from UART */
      //bitSet(BluLed);
      ch = bootldrgetch();
      if (ch ==0)
        {
        releaseChipAccess();
        return;
        }
      //bitClr(BluLed);
      //blinkLed(GrnLedId,100*mSec,1);
      /* A bunch of if...else if... gives smaller code than switch...case ! */

#if  0 //def ADABOOT
      // Hello is anyone home ?   lady ada hack -  BBR
      if(ch=='0') {
        firstcharzero = 1; // we got an appropriate bootloader instruction
        nothing_response();
      } 
	
      else if (firstcharzero == 0) {
        // the first character we got is not '0', lets bail!
        // autoreset via watchdog (sneaky!)
        // return();
      }	
#else

      /* Hello is anyone home ? */ 
      if(ch=='0') 
        {
          nothing_response();
	}
#endif

      /* Request programmer ID */
      /* Not using PROGMEM string due to boot block in m128 being beyond 64kB boundry  */
      /* Would need to selectively manipulate RAMPZ, and it's only 9 characters anyway so who cares.  */
      else if(ch=='1') {
        if (bootldrgetch() == ' ') {
          putNch(pgmrId,9);
        } else {
          ++error_count;
        }
      }


      /* AVR ISP/STK500 board commands  DON'T CARE so default nothing_response */
      else if(ch=='@') {
        ch2 = bootldrgetch();
        if (ch2>0x85) bootldrgetch();
        nothing_response();
      }


      /* AVR ISP/STK500 board requests */
      /* Cmnd_STK_GET_PARAMETER 0x41 */
      else if(ch=='A') {
        ch2 = bootldrgetch();
        if(ch2==0x80) byte_response(HW_VER);		// Hardware version
        else if(ch2==0x81) byte_response(SW_MAJOR);	// Software major version
        else if(ch2==0x82) byte_response(SW_MINOR);	// Software minor version
        else if(ch2==0x98) byte_response(0x03);		// Unknown but seems to be required by avr studio 3.56
        else byte_response(0x00);				// Covers various unnecessary responses we don't care about
      }


      /* Cmnd_STK_SET_DEVICE 0x42
      Device Parameters  DON'T CARE, DEVICE IS FIXED  */
      else if(ch=='B') {
        getNch(20);
        nothing_response();
      }


      /* Cmnd_SET_DEVICE_EXT 0x45 */
      else if(ch=='E') {
        getNch(5);
        nothing_response();
      }

      /* P: Enter programming mode  */
      else if(ch=='P')
        {
        if (!initChipAccess(&devId[1]))
          {
          failed_response();
          }
        else nothing_response();
        }
        
      /* R: Erase device, don't care as we will erase one page at a time anyway.  */
      else if(ch=='R')
        {
        eraseDevice();
        nothing_response();
        }


      /* Leave programming mode  */
      else if(ch=='Q') 
        {
        nothing_response();
        delay(5*mSec);
        releaseChipAccess();        
        allDone();
        return;
#ifdef WATCHDOG_MODS
        assert(0);
#endif
        }


      /* Set address, little endian. EEPROM in bytes, FLASH in words  */
      /* Perhaps extra address bytes may be added in future to support > 128kB FLASH.  */
      /* This might explain why little endian was used here, big endian used everywhere else.  */
      else if(ch=='U') {
        address.word = myget2LE();
        //address.byte[0] = bootldrgetch();
        //address.byte[1] = bootldrgetch();
        nothing_response();
      }


      /* Universal SPI programming command. Used for fuses and lock bits.  */
      else if(ch=='V') {
        unsigned char spicmdbuf[4];
        bootldrgetNch(spicmdbuf,4);
                
        if (0) { // spicmdbuf[0] == 0x30) {
          if (spicmdbuf[2] == 0) {
            byte_response(SIG1);
          } else if (spicmdbuf[2] == 1) {
            byte_response(SIG2); 
          } else {
            byte_response(SIG3);
          } 
        } 
        // Call my erase device embedded routine if the erase device SPI cmd comes in
        else if ((spicmdbuf[0] == 0xac) && (spicmdbuf[1] == 0x80))
        {
        eraseDevice();
        byte_response(0);
        }
        // Don't let them program the fuse bits into a non-working clock
        // This SPI on this chip can't go slow enough to work with very slow AVR clocks (<=1mhz)
        else if ((spicmdbuf[0] == 0xAC) && (spicmdbuf[1] == 0xA0) && (((spicmdbuf[3]&0x80) == 0) || ((spicmdbuf[3]&0x0f) == 3)))
        {
              failed_response();
        }       
        else
        {
          byte_response(issueSpiCmd(spicmdbuf));
        }
      }


      /* Write memory, length is big endian and is in bytes  */
      else if(ch=='d') {
        length.word = myget2BE();
        //length.byte[1] = bootldrgetch();
        //length.byte[0] = bootldrgetch();
        flags.eeprom = 0;
        if (bootldrgetch() == 'E') flags.eeprom = 1;
        for (w=0;w<length.word;w++) 
          {
            buff[w] = bootldrgetch();	                        // Store data in buffer, can't keep up with serial data stream whilst programming pages
          }
        if (bootldrgetch() == ' ') 
          {
            if (flags.eeprom) {		                //Write to EEPROM one byte at a time
              address.word <<= 1;
              for(w=0;w<length.word;w++) {
                eeprom_write_byte((void *)address.word,buff[w]);
                address.word++;
              }			
            }
            else {					        //Write to FLASH one page at a time
              if (address.byte[1]>127) address_high = 0x01;	//Only possible with m128, m256 will need 3rd address byte. FIXME
              else address_high = 0x00;

              address.word = address.word << 1;	        //address * 2 -> byte location
              /* if ((length.byte[0] & 0x01) == 0x01) length.word++;	//Even up an odd number of bytes */
              //if ((length.byte[0] & 0x01)) length.word++;	//Even up an odd number of bytes
              if (length.word&1) length.word++; // Even up an odd number of bytes
              flash_write((void*)address.word, length.word, address_high, buff);
            }
            putNch(endStmt,2);
            //myputch(0x14);
            //myputch(0x10);
          } else {
          ++error_count;
        }		
      }


      /* Read memory block mode, length is big endian.  */
      else if(ch=='t') 
        {
        length.word = myget2BE();
        //length.byte[1] = bootldrgetch();
        //length.byte[0] = bootldrgetch();
#if defined(__AVR_ATmega128__)  || defined(__AVR_ATmega1280__)
        if (address.word>0x7FFF) flags.rampz = 1;		// No go with m256, FIXME
        else flags.rampz = 0;
#endif
        address.word = address.word << 1;	        // address * 2 -> byte location
        if (bootldrgetch() == 'E') flags.eeprom = 1;
        else flags.eeprom = 0;
        if (bootldrgetch() == ' ') 
          {		                // Command terminator
          myputch(0x14);
          if (1)
            {		        // Can handle odd and even lengths okay
            if (flags.eeprom) 
              { // Byte access EEPROM read
              for (w=0;w < length.word;w++,address.word++)
                {
                myputch(eeprom_read_byte((void *)address.word));
                }
              }
            else 
              {
              int bpos = 0;
              
              for (w=0;w < length.word;w++,address.word++,bpos++)
                {
                if (!flags.rampz) buff[bpos] = pgm_read_byte_near((void*)address.word);
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__)
                else buff[bpos] = pgm_read_byte_far(address.word + 0x10000);
                // Hmmmm, yuck  FIXME when m256 arrvies
#endif
                if (bpos == 63)
                  {
                  putNch(buff,64);
                  bpos = -1;
                  }
                }
              if (bpos > 0)
                {
                  putNch(buff,bpos);
                }
              }
            }
          myputch(0x10);
          }
        }


      /* Get device signature bytes  */
      else if(ch=='u') {
        if (bootldrgetch() == ' ') {
          bitSet(UsbLed);
          putNch(devId,5);
        } else {
          ++error_count;
        }
      }


      /* Read oscillator calibration byte */
      else if(ch=='v') {
        byte_response(0x00);
      }


#ifdef MONITOR
      /* here come the extended monitor commands by Erik Lins */
      /* check for three times exclamation mark pressed */
      else if(ch=='!') monitor();
#endif
      else   /* Garbled 1st character */
        {
          //printf("garbled character %d %c\n",ch,ch);
          ++error_count;
        }

    } /* end of forever loop */

}
コード例 #15
0
void BufferProcessor::run(){
  // spectrum amplitude
  qreal amplitude;
  qreal SpectrumAnalyserMultiplier = 0.15e-3;

  // tells when all chunks has been processed
  if(pass == chunks){
    emit allDone();
    return;
  }

  // we does not calc spectra when array is too small
  if(array.size() < SPECSIZE){
    return;
  }

  // prepare complex frame for fft calculations
  for(uint i=0; i<SPECSIZE; i++){
    complexFrame[i] = Complex(window[i]*array[i+pass*SPECSIZE],0);
  }

  // do the magic
  fft(complexFrame);

  // some scaling/windowing is needed for displaying the fourier spectrum somewhere
  for(uint i=0; i<SPECSIZE/2;i++){
    amplitude = SpectrumAnalyserMultiplier*std::abs(complexFrame[i]);
    amplitude = qMax(qreal(0.0), amplitude);
    amplitude = qMin(qreal(1.0), amplitude);
    complexFrame[i] = amplitude;
  }

  // audio spectrum is usually compressed for better displaying
  if(compressed){
    for (int i = 0; i <SPECSIZE/2; i ++){
      /* sum up values in freq array between logscale[i] and logscale[i + 1],
         including fractional parts */
      int a = ceilf (logscale[i]);
      int b = floorf (logscale[i+1]);
      float sum = 0;

      if (b < a)
        sum += complexFrame[b].real()*(logscale[i+1]-logscale[i]);
      else{
        if (a > 0)
          sum += complexFrame[a-1].real()*(a-logscale[i]);
        for (; a < b; a++)
          sum += complexFrame[a].real();
        if (b < SPECSIZE/2)
          sum += complexFrame[b].real()*(logscale[i+1] - b);
      }

      /* fudge factor to make the graph have the same overall height as a
         12-band one no matter how many bands there are */
      sum *= (float) SPECSIZE/24;

      /* convert to dB */
      float val = 20*log10f (sum);

      /* scale (-DB_RANGE, 0.0) to (0.0, 1.0) */
      val = 1 + val / 40;
      spectrum[i] = CLAMP (val, 0, 1);
    }
  }
  else{
    // if not compressed, just copy the real part clamped between 0 and 1
    for(int i=0; i<SPECSIZE/2; i++){
      spectrum[i] = CLAMP(complexFrame[i].real()*100,0,1);
    }
  }
  // emit the spectrum
  emit calculatedSpectrum(spectrum);

  // count the pass
  pass++;
}
コード例 #16
0
ファイル: statusBar.cpp プロジェクト: mytbk/fqterm
void StatusBar::showMainProgressBar() {
  if (!allDone()) {
    progressBox()->show();
  }
}
コード例 #17
0
ファイル: ftpclient.cpp プロジェクト: maxselym/Magistral
void ftpClient::cancelDownload()
{
    emit allDone(1,QProcess::CrashExit);
}
コード例 #18
0
void QHttpNetworkConnectionChannel::_q_receiveReply()
{
    Q_ASSERT(socket);

    if (!reply) {
        // heh, how should that happen!
        qWarning() << "QHttpNetworkConnectionChannel::_q_receiveReply() called without QHttpNetworkReply,"
                << socket->bytesAvailable() << "bytes on socket.";
        close();
        return;
    }

    // only run when the QHttpNetworkConnection is not currently being destructed, e.g.
    // this function is called from _q_disconnected which is called because
    // of ~QHttpNetworkConnectionPrivate
    if (!qobject_cast<QHttpNetworkConnection*>(connection)) {
        return;
    }

    QAbstractSocket::SocketState socketState = socket->state();

    // connection might be closed to signal the end of data
    if (socketState == QAbstractSocket::UnconnectedState) {
        if (socket->bytesAvailable() <= 0) {
            if (reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                // finish this reply. this case happens when the server did not send a content length
                reply->d_func()->state = QHttpNetworkReplyPrivate::AllDoneState;
                allDone();
                return;
            } else {
                handleUnexpectedEOF();
                return;
            }
        } else {
            // socket not connected but still bytes for reading.. just continue in this function
        }
    }

    // read loop for the response
    qint64 bytes = 0;
    qint64 lastBytes = bytes;
    do {
        lastBytes = bytes;

        QHttpNetworkReplyPrivate::ReplyState state = reply->d_func()->state;
        switch (state) {
        case QHttpNetworkReplyPrivate::NothingDoneState: {
            state = reply->d_func()->state = QHttpNetworkReplyPrivate::ReadingStatusState;
            // fallthrough
        }
        case QHttpNetworkReplyPrivate::ReadingStatusState: {
            qint64 statusBytes = reply->d_func()->readStatus(socket);
            if (statusBytes == -1) {
                // connection broke while reading status. also handled if later _q_disconnected is called
                handleUnexpectedEOF();
                return;
            }
            bytes += statusBytes;
            lastStatus = reply->d_func()->statusCode;
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingHeaderState: {
            QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
            qint64 headerBytes = replyPrivate->readHeader(socket);
            if (headerBytes == -1) {
                // connection broke while reading headers. also handled if later _q_disconnected is called
                handleUnexpectedEOF();
                return;
            }
            bytes += headerBytes;
            // If headers were parsed successfully now it is the ReadingDataState
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                if (replyPrivate->isCompressed() && replyPrivate->autoDecompress) {
                    // remove the Content-Length from header
                    replyPrivate->removeAutoDecompressHeader();
                } else {
                    replyPrivate->autoDecompress = false;
                }
                if (replyPrivate->statusCode == 100) {
                    replyPrivate->clearHttpLayerInformation();
                    replyPrivate->state = QHttpNetworkReplyPrivate::ReadingStatusState;
                    break; // ignore
                }
                if (replyPrivate->shouldEmitSignals())
                    emit reply->headerChanged();
                // After headerChanged had been emitted
                // we can suddenly have a replyPrivate->userProvidedDownloadBuffer
                // this is handled in the ReadingDataState however

                if (!replyPrivate->expectContent()) {
                    replyPrivate->state = QHttpNetworkReplyPrivate::AllDoneState;
                    allDone();
                    break;
                }
            }
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingDataState: {
           QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
           if (socket->state() == QAbstractSocket::ConnectedState &&
               replyPrivate->downstreamLimited && !replyPrivate->responseData.isEmpty() && replyPrivate->shouldEmitSignals()) {
               // (only do the following when still connected, not when we have already been disconnected and there is still data)
               // We already have some HTTP body data. We don't read more from the socket until
               // this is fetched by QHttpNetworkAccessHttpBackend. If we would read more,
               // we could not limit our read buffer usage.
               // We only do this when shouldEmitSignals==true because our HTTP parsing
               // always needs to parse the 401/407 replies. Therefore they don't really obey
               // to the read buffer maximum size, but we don't care since they should be small.
               return;
           }

           if (replyPrivate->userProvidedDownloadBuffer) {
               // the user provided a direct buffer where we should put all our data in.
               // this only works when we can tell the user the content length and he/she can allocate
               // the buffer in that size.
               // note that this call will read only from the still buffered data
               qint64 haveRead = replyPrivate->readBodyVeryFast(socket, replyPrivate->userProvidedDownloadBuffer + replyPrivate->totalProgress);
               if (haveRead > 0) {
                   bytes += haveRead;
                   replyPrivate->totalProgress += haveRead;
                   // the user will get notified of it via progress signal
                   emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
               } else if (haveRead == 0) {
                   // Happens since this called in a loop. Currently no bytes available.
               } else if (haveRead < 0) {
                   connection->d_func()->emitReplyError(socket, reply, QNetworkReply::RemoteHostClosedError);
                   break;
               }
           } else if (!replyPrivate->isChunked() && !replyPrivate->autoDecompress
                 && replyPrivate->bodyLength > 0) {
                 // bulk files like images should fulfill these properties and
                 // we can therefore save on memory copying
                qint64 haveRead = replyPrivate->readBodyFast(socket, &replyPrivate->responseData);
                bytes += haveRead;
                replyPrivate->totalProgress += haveRead;
                if (replyPrivate->shouldEmitSignals()) {
                    emit reply->readyRead();
                    emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                }
            }
            else
            {
                // use the traditional slower reading (for compressed encoding, chunked encoding,
                // no content-length etc)
                qint64 haveRead = replyPrivate->readBody(socket, &replyPrivate->responseData);
                if (haveRead > 0) {
                    bytes += haveRead;
                    replyPrivate->totalProgress += haveRead;
                    if (replyPrivate->shouldEmitSignals()) {
                        emit reply->readyRead();
                        emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                    }
                } else if (haveRead == -1) {
                    // Some error occured
                    connection->d_func()->emitReplyError(socket, reply, QNetworkReply::ProtocolFailure);
                    break;
                }
            }
            // still in ReadingDataState? This function will be called again by the socket's readyRead
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState)
                break;

            // everything done, fall through
            }
      case QHttpNetworkReplyPrivate::AllDoneState:
            allDone();
            break;
        default:
            break;
        }
    } while (bytes != lastBytes && reply);
}
コード例 #19
0
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
void arduinoThread::update(){
    ard.update();
    
    switch (curState) {
        case JOG:
            sleepDoneMotors();
            if (allDone()) curState = IDLE;
            break;
        // arm has raised and is ready to take a photo
        case SHOOT_FACE:
            sleepDoneMotors();
            if (allDone()) curState = IDLE;
            break;
        // photo taken, arm is going to the limit switches: home
        case FACE_PHOTO:
            goHome();
            break;
        case HOMING: 
            break;
        // X, Z, and Y have hit limits
        case HOME:
            // start X, Y, and I
            ard.sendDigital(X_SLEEP_PIN, ARD_HIGH);
            ard.sendDigital(Y_SLEEP_PIN, ARD_HIGH);
            ard.sendDigital(INK_SLEEP_PIN, ARD_HIGH);
            // sleep Z
            ard.sendDigital(Z_SLEEP_PIN, ARD_LOW);
            ofSleepMillis(10);
            journeyOn(true);
            curState = PREPRINT;
            point_count = 1;
            break;
        // this is when arm moves from home to first point
        case PREPRINT:
            if (journeysDone()) {
                curState = PRINTING;
            }
            break;
        // print has started from first point
        case PRINTING:
            if (journeysDone()) {
                journeyOn(false);
            }
            break;
        // print is finished and arm is raising up
        case DONE:
            break;
        case ERROR:
            x_steps = y_steps = z_steps = i_steps = x_inc = y_inc = z_inc = i_inc = 0;
            ard.sendDigital(X_SLEEP_PIN, ARD_LOW);
            ard.sendDigital(Y_SLEEP_PIN, ARD_LOW);
            ard.sendDigital(Z_SLEEP_PIN, ARD_LOW);
            ard.sendDigital(INK_SLEEP_PIN, ARD_LOW);
            break;
        case RESET:
            if (journeysDone()){
                curState = IDLE;
                ard.sendDigital(X_SLEEP_PIN, ARD_LOW);
                ard.sendDigital(Y_SLEEP_PIN, ARD_LOW);
                ard.sendDigital(Z_SLEEP_PIN, ARD_LOW);
                x_inc = y_inc = z_inc = x_steps = y_steps = z_steps = 0;
            }
        default:
            break;
    }
}
コード例 #20
0
bool edaMpiWrapperControl::search( edaSolutionList &list )
{ 
  // variables
  int i, j, p, l;
  int command;
  int nidles;
  int idles[nprocs_];
  MPI_Status mpiStat;

  // initialize status variables
  runningJobCount = 0;
  for( i=1; i<nprocs_; i++ ){
    workers_[i].stat_ = EDA_MPI_PROCESSOR_IDLE;
    workers_[i].taskID_ = -1;
  }

  // start the search
  while (!allDone()) {
    vector<int> readyTasks = findReadyTask();
    vector<int>::iterator readyIter;

    // find idle processors
    nidles = 0;
    for( i=1; i<nprocs_; i++ )
      if ( workers_[i].stat_ == EDA_MPI_PROCESSOR_IDLE )
        idles[nidles++] = i;

    // Create the search objects for all ready nodes
    p = 0;
    for (readyIter = readyTasks.begin(); readyIter != readyTasks.end(); readyIter++)
    {
      // task ID on DAG
      int taskID = *readyIter;

      // send computing request to first idle processor
      if ( p < nidles ){
        // send command
        command = EDA_MPI_START_SEARCH;
        MPI_Send( &command, 1, MPI_INT, idles[p], 0, MPI_COMM_WORLD );
       
        // pack search and its parameters
        edaBuffer sa_buf;
        edaSearch *sa = taskDAG[taskID];
        sa->ProcID = idles[p];
        sa->doSerialize( sa_buf, true );

        
        // send buffer for search method
        l = sa_buf.getActualSize();
        MPI_Send( &l, 1, MPI_INT, idles[p],
                  0, MPI_COMM_WORLD );
        MPI_Send( sa_buf.getBuffer(), sa_buf.getActualSize(), 
                  MPI_CHAR, idles[p], 0, MPI_COMM_WORLD );

        // pack solution
        edaBuffer sol_buf;
        edaSolutionList *mysol = NULL;
        mysol = chooseSolution( taskID, list );
        mysol->doSerialize( sol_buf, true );
        
        // send buffer for solution to worker
        l = sol_buf.getActualSize();
        MPI_Send( &l, 1, MPI_INT, idles[p],
                  0, MPI_COMM_WORLD );
        MPI_Send( sol_buf.getBuffer(), l, MPI_CHAR, idles[p],
                  0, MPI_COMM_WORLD );

        // set status of worker to computing
        workers_[idles[p]].stat_ = EDA_MPI_PROCESSOR_COMPUTING;
        workers_[idles[p]].taskID_ = taskID;
        taskStatus[taskID] = STATUS_RUNNING;
        runningJobCount ++;
        p ++;
      } else {
        // no processor idle, then break the loop
        break;
      }
    }
    
    int pollingResult = POLLING_NOCHANGE;
    int nodeFinished;

    // Polling for job finished
    while (true)
    {
      if ( runningJobCount == 0 ){
        // Nothing to poll
        pollingResult = POLLING_NOCHANGE;
        break;
      }

      // poll for any return
      pollingResult = polling( nodeFinished );
      if ( pollingResult == POLLING_FINISHED ){
        break;
      } else if ( pollingResult == POLLING_ERROR ){
        break;
      } else { // NOCHANGE
      }

    }

    // Job finished
    if ( pollingResult == POLLING_FINISHED )
    {
//      printDebug(3, "Job finished: " << workers_[nodeFinished].taskID_);
      taskStatus[workers_[nodeFinished].taskID_] = STATUS_FINISHED;
      runningJobCount--;

      // Get the solution
      edaBuffer result_buf;

      // receive the result status
      MPI_Recv( &l, 1, MPI_INT, nodeFinished, 0, MPI_COMM_WORLD, &mpiStat );
      if ( l == EDA_MPI_SEARCH_FINISHED ) {

        // receive the result into a buffer of characters
        MPI_Recv( &j, 1, MPI_INT, nodeFinished, 0, MPI_COMM_WORLD, &mpiStat );
        char *buf = new char[j];
        MPI_Recv( buf, j, MPI_CHAR, nodeFinished, 0, MPI_COMM_WORLD, &mpiStat );
        result_buf.setBuffer( j, buf );

        edaSolutionList *result = (edaSolutionList*)classGenerateFromBuffer(result_buf);
        taskSolutionList[workers_[nodeFinished].taskID_] = result;
        searchOrder.push_back( workers_[nodeFinished].taskID_ );

        workers_[nodeFinished].stat_ = EDA_MPI_PROCESSOR_IDLE;
      }
      
      checkLoopStatus(workers_[nodeFinished].taskID_);
    }

    // Job error
    if ( pollingResult == POLLING_ERROR )
    {
//      printDebug(3, "Job error while running: " << workers_[nodeFinished].taskID_);
      taskStatus[workers_[nodeFinished].taskID_] = STATUS_ERROR;
      runningJobCount--;
      searchOrder.remove( workers_[nodeFinished].taskID_ );
    }
  }

  if (searchOrder.empty())
  {
    return false;
  }
  
  // TODO: Should return the best result among results
//  printDebug(4, "Last search block is: " << searchOrder.back());
  list = *(taskSolutionList[searchOrder.back()]);

  return true;
}
コード例 #21
0
void QHttpNetworkConnectionChannel::_q_receiveReply()
{
    Q_ASSERT(socket);

    if (!reply) {
        // heh, how should that happen!
        qWarning() << "QHttpNetworkConnectionChannel::_q_receiveReply() called without QHttpNetworkReply,"
                << socket->bytesAvailable() << "bytes on socket.";
        close();
        return;
    }

    // only run when the QHttpNetworkConnection is not currently being destructed, e.g.
    // this function is called from _q_disconnected which is called because
    // of ~QHttpNetworkConnectionPrivate
    if (!qobject_cast<QHttpNetworkConnection*>(connection)) {
        return;
    }

    qint64 bytes = 0;
    QAbstractSocket::SocketState socketState = socket->state();

    // connection might be closed to signal the end of data
    if (socketState == QAbstractSocket::UnconnectedState) {
        if (socket->bytesAvailable() <= 0) {
            if (reply->d_func()->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                // finish this reply. this case happens when the server did not send a content length
                reply->d_func()->state = QHttpNetworkReplyPrivate::AllDoneState;
                allDone();
                return;
            } else {
                handleUnexpectedEOF();
                return;
            }
        } else {
            // socket not connected but still bytes for reading.. just continue in this function
        }
    }

    // read loop for the response
    while (socket->bytesAvailable()) {
        QHttpNetworkReplyPrivate::ReplyState state = reply->d_func()->state;
        switch (state) {
        case QHttpNetworkReplyPrivate::NothingDoneState: {
            // only eat whitespace on the first call
            eatWhitespace();
            state = reply->d_func()->state = QHttpNetworkReplyPrivate::ReadingStatusState;
            // fallthrough
        }
        case QHttpNetworkReplyPrivate::ReadingStatusState: {
            qint64 statusBytes = reply->d_func()->readStatus(socket);
            if (statusBytes == -1) {
                // connection broke while reading status. also handled if later _q_disconnected is called
                handleUnexpectedEOF();
                return;
            }
            bytes += statusBytes;
            lastStatus = reply->d_func()->statusCode;
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingHeaderState: {
            QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
            qint64 headerBytes = replyPrivate->readHeader(socket);
            if (headerBytes == -1) {
                // connection broke while reading headers. also handled if later _q_disconnected is called
                handleUnexpectedEOF();
                return;
            }
            bytes += headerBytes;
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState) {
                if (replyPrivate->isGzipped() && replyPrivate->autoDecompress) {
                    // remove the Content-Length from header
                    replyPrivate->removeAutoDecompressHeader();
                } else {
                    replyPrivate->autoDecompress = false;
                }
                if (replyPrivate->statusCode == 100) {
                    replyPrivate->clearHttpLayerInformation();
                    replyPrivate->state = QHttpNetworkReplyPrivate::ReadingStatusState;
                    break; // ignore
                }
                if (replyPrivate->shouldEmitSignals())
                    emit reply->headerChanged();
                if (!replyPrivate->expectContent()) {
                    replyPrivate->state = QHttpNetworkReplyPrivate::AllDoneState;
                    allDone();
                    break;
                }
            }
            break;
        }
        case QHttpNetworkReplyPrivate::ReadingDataState: {
           QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
           if (replyPrivate->downstreamLimited && !replyPrivate->responseData.isEmpty() && replyPrivate->shouldEmitSignals()) {
               // We already have some HTTP body data. We don't read more from the socket until
               // this is fetched by QHttpNetworkAccessHttpBackend. If we would read more,
               // we could not limit our read buffer usage.
               // We only do this when shouldEmitSignals==true because our HTTP parsing
               // always needs to parse the 401/407 replies. Therefore they don't really obey
               // to the read buffer maximum size, but we don't care since they should be small.
               return;
           }

            if (!replyPrivate->isChunked() && !replyPrivate->autoDecompress
                && replyPrivate->bodyLength > 0) {
                // bulk files like images should fulfill these properties and
                // we can therefore save on memory copying
                bytes = replyPrivate->readBodyFast(socket, &replyPrivate->responseData);
                replyPrivate->totalProgress += bytes;
                if (replyPrivate->shouldEmitSignals()) {
                    QPointer<QHttpNetworkReply> replyPointer = reply;
                    emit reply->readyRead();
                    // make sure that the reply is valid
                    if (replyPointer.isNull())
                        return;
                    emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                    // make sure that the reply is valid
                    if (replyPointer.isNull())
                        return;
                }
            }
            else
            {
                // use the traditional slower reading (for compressed encoding, chunked encoding,
                // no content-length etc)
                QByteDataBuffer byteDatas;
                bytes = replyPrivate->readBody(socket, &byteDatas);
                if (bytes) {
                    if (replyPrivate->autoDecompress)
                        replyPrivate->appendCompressedReplyData(byteDatas);
                    else
                        replyPrivate->appendUncompressedReplyData(byteDatas);

                    if (!replyPrivate->autoDecompress) {
                        replyPrivate->totalProgress += bytes;
                        if (replyPrivate->shouldEmitSignals()) {
                            QPointer<QHttpNetworkReply> replyPointer = reply;
                            // important: At the point of this readyRead(), the byteDatas list must be empty,
                            // else implicit sharing will trigger memcpy when the user is reading data!
                            emit reply->readyRead();
                            // make sure that the reply is valid
                            if (replyPointer.isNull())
                                return;
                            emit reply->dataReadProgress(replyPrivate->totalProgress, replyPrivate->bodyLength);
                            // make sure that the reply is valid
                           if (replyPointer.isNull())
                                return;
                        }
                    }
#ifndef QT_NO_COMPRESS
                    else if (!expand(false)) { // expand a chunk if possible
                        return; // ### expand failed
                    }
#endif
                }
            }
            // still in ReadingDataState? This function will be called again by the socket's readyRead
            if (replyPrivate->state == QHttpNetworkReplyPrivate::ReadingDataState)
                break;

            // everything done, fall through
            }
      case QHttpNetworkReplyPrivate::AllDoneState:
            allDone();
            break;
        default:
            break;
        }
    }
}
コード例 #22
0
ファイル: boggle.c プロジェクト: dsj36/FB-Engineering-Puzzles
int doBoards(const node* dictionary, const boggleBoard* boards,
             int boardCount, int rank, int size, int* pStart, int timing)
{
    assert(size > 1);

    /* Use tag 0 for completion messages, 1 for steal requests, and 2 for work given */
    int i, j, total, boardSize, target, completed, someoneWants, who, remaining, work;
    int gotWork, donorFinished;
    point pt;
    queue* queue = qinit();
    int done[size-1];
    int want[size-1];
    int notDone[size-1];
    MPI_Request doneRequests[size-1];
    MPI_Request wantRequests[size-1];
    MPI_Request workRequest;

    /* We don't want everyone choosing the same increments randomly, so add the rank to the seed */
    struct mt19937p state;
    sgenrand(10302011UL + rank, &state);

    /* Index the requests such that current thread is -1 (i.e. not present), and all */
    /* the other threads follow round robin, wrapping around at 'size'. We're not    */
    /* explicitly interested in the contents of 'done' or 'want', only the signals.  */
    for (i = 1; i < size; ++i) {
        want[i-1] = done[i-1] = 0;
        target = (rank + i) % size;

        MPI_Irecv(done + i - 1, 1, MPI_INT, target, 0, MPI_COMM_WORLD, doneRequests + i - 1);
        MPI_Irecv(want + i - 1, 1, MPI_INT, target, 1, MPI_COMM_WORLD, wantRequests + i - 1);
    }

    completed = 0;
    total = 0;
    boardSize = boards[0].n;

    /* Maintain a local work queue with assigned board indices */
    for (i = pStart[rank]; i < pStart[rank+1]; ++i)
        qpush(queue, i);

    /* Do assigned work and listen for requests for extra work */
    while (!qempty(queue)) {
        i = qpop(queue);

        /* Try to find someone who's asking for work */
        MPI_Testany(size-1, wantRequests, &who, &someoneWants, MPI_STATUS_IGNORE);
        who = (rank + 1 + who) % size;

        if (someoneWants) {
            /* printf("Who let thread %d steal my (thread %d) work (#%d)?!\n", who, rank, i); */
            MPI_Send(&i, 1, MPI_INT, who, 2, MPI_COMM_WORLD);

            /* Reopen asynchronous receive to thread */
            MPI_Irecv(want + i - 1, 1, MPI_INT, who, 1, MPI_COMM_WORLD,
                      wantRequests - 1 + (size + who - rank) % size);
        }
        else {
            for (j = 0; j < boardSize * boardSize; ++j) {
                pt.x = j / boardSize;
                pt.y = j % boardSize;
                total += exploreOne(dictionary, boards + i, pt, timing);
            }
        }
    }

    /* Broadcast that we are done (MPI_Scatter is a little annoying) */
    completed = 1;
    for (i = 1; i < size; ++i)
        MPI_Send(&completed, 1, MPI_INT, (rank + i) % size, 0, MPI_COMM_WORLD);

    /* Loop while everyone isn't done */
    while(!allDone(doneRequests, size)) {
        remaining = 0;

        /* Find all of the workers that have not completed */
        for (i = 0; i < size - 1; ++i) {
            MPI_Test(doneRequests + i, &donorFinished, MPI_STATUS_IGNORE);

            if (!donorFinished)
                notDone[remaining++] = i;
        }

        if (remaining > 0) {
            i = notDone[genrand(&state) % remaining];
            target = (rank + i + 1) % size;

            /* Pick one of the guys at random and send him a request */
            MPI_Send(&target, 1, MPI_INT, target, 1, MPI_COMM_WORLD);
            MPI_Irecv(&work, 1, MPI_INT, target, 2, MPI_COMM_WORLD, &workRequest);

            gotWork = donorFinished = 0;

            /* Check if he wrote back or if he finished in the meantime */
            while (!gotWork && !donorFinished) {
                MPI_Test(&workRequest, &gotWork, MPI_STATUS_IGNORE);
                MPI_Test(doneRequests + i, &donorFinished, MPI_STATUS_IGNORE);

                if (gotWork) {
                    for (j = 0; j < boardSize * boardSize; ++j) {
                        pt.x = j / boardSize;
                        pt.y = j % boardSize;
                        total += exploreOne(dictionary, boards + work, pt, timing);
                    }
                }
            }
        }
    }

    qdest(queue);

    return total;
}