Beispiel #1
0
void ZealSettingsDialog::startTasks(qint8 tasks = 1)
{
    tasksRunning += tasks;
    if (tasksRunning == 0) {
        resetProgress();
    }

    displayProgress();
}
Beispiel #2
0
bool paren ( const char exp[], int lo, int hi ) { //���ʽ����ƥ���飬�ɼ����������
   Stack<char> S; //ʹ��ջ��¼�ѷ��ֵ���δƥ���������
   for ( int i = lo; i <= hi; i++ ) /* ��һ��鵱ǰ�ַ� */ /*DSA*/{
      switch ( exp[i] ) { //������ֱ�ӽ�ջ������������ջ��ʧ�䣬����ʽ�ز�ƥ��
         case '(': case '[': case '{': S.push ( exp[i] ); break;
         case ')': if ( ( S.empty() ) || ( '(' != S.pop() ) ) return false; break;
         case ']': if ( ( S.empty() ) || ( '[' != S.pop() ) ) return false; break;
         case '}': if ( ( S.empty() ) || ( '{' != S.pop() ) ) return false; break;
         default: break; //�������ַ�һ�ɺ���
      /*DSA*/} displayProgress ( exp, i, S );
   }
   return S.empty(); //�������ʽɨ�����ջ�����Բ����������ţ���ƥ�䣻����ջ�գ�ƥ��
}
Beispiel #3
0
void ProgressReporter::progress(const std::unique_ptr<TransferReport>& report) {
  const TransferStats& stats = report->getSummary();
  int64_t totalDiscoveredSize = report->getTotalFileSize();
  int progress = 0;
  if (totalDiscoveredSize > 0) {
    progress = stats.getEffectiveDataBytes() * 100 / totalDiscoveredSize;
  }
  if (isTty_) {
    displayProgress(progress, report->getThroughputMBps(),
                    report->getCurrentThroughputMBps());
  } else {
    logProgress(stats.getEffectiveDataBytes(), progress,
                report->getThroughputMBps(),
                report->getCurrentThroughputMBps());
  }
}
void placeQueens(int N) { //N皇后算法(迭代版):采用试探/回溯的策略,借助栈记录查找的结果
   Stack<Queen> solu; //存放(部分)解的栈
   Queen q(0, 0); //从原点位置出发
   do { //反复试探、回溯
      if (N <= solu.size() || N <= q.y) { //若已出界,则
         q = solu.pop(); q.y++; //回溯一行,并继续试探下一列
      } else { //否则,试探下一行
         while ((q.y < N) && (0 <= solu.find(q))) //通过与已有皇后的比对
            { q.y++; nCheck++; } //尝试找到可摆放下一皇后的列
         if (N > q.y) { //若存在可摆放的列,则
            solu.push(q); //摆上当前皇后,并
            if (N <= solu.size()) nSolu++; //若部分解已成为全局解,则通过全局变量nSolu计数
            q.x++; q.y = 0; //转入下一行,从第0列开始,试探下一皇后
         }
      }/*DSA*/if (Step == runMode) displayProgress(solu, N);
   } while ((0 < q.x) || (q.y < N)); //所有分支均已或穷举或剪枝之后,算法结束
}
Beispiel #5
0
/**
 * Records the success or failure or a particular service.
 * If no service name is specified, but a pid is, then all services provided
 * by the item are flagged.
 **/
static void statusMessage (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
    if (anIPCMessage && aStartupContext && aStartupContext->aStatusDict)
      {
        CFMutableDictionaryRef anItem       = itemFromIPCMessage(aStartupContext, anIPCMessage);
        CFStringRef            aServiceName = CFDictionaryGetValue(anIPCMessage, kIPCServiceNameKey);
        CFBooleanRef	       aStatus      = CFDictionaryGetValue(anIPCMessage, kIPCStatusKey);
        
        if (anItem && aStatus && 
            CFGetTypeID(aStatus) == CFBooleanGetTypeID() &&
            (!aServiceName || CFGetTypeID(aServiceName) == CFStringGetTypeID()))
          {
            StartupItemSetStatus(aStartupContext->aStatusDict, anItem, aServiceName, CFBooleanGetValue(aStatus), TRUE);
            displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
          }
      }
}
Beispiel #6
0
void MainWindow::on_startButton_clicked()
{
    QMessageBox msgBox;
    QMessageBox msgBox1;

    //initalize the StartThread with filpath
    StartThread *start_thread = new StartThread(MainWindow::filePath);
    simple_client *sc = new simple_client();

    if(ui->fileLabel->text() != "NA"){
        msgBox.setText("Are you sure you want to start downloading?");
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setDefaultButton(QMessageBox::Yes);
        int ret = msgBox.exec();
        switch(ret){
        case (QMessageBox::Yes):
            tv->torProgress = "Downloading";
            displayProgress(tv);

            //connect signal
            //            connect(sc,SIGNAL(displayProgress(torVariable)),this,SLOT(displayProgress(torVariable));
            connect(start_thread,SIGNAL(threadResult(int)),this,SLOT(displayResultFromSC(int)));
            //connect(start_thread, SIGNAL(finished()), start_thread, SLOT(deleteLater()));

            start_thread->start();

            //display processing message
            msgBox1.setText("Your request is being processed");
            msgBox1.exec();

            break;

        case(QMessageBox::No):
            break;
        }


    }
Beispiel #7
0
// creates a total download progress for multiple QNetworkReplies
void ZealSettingsDialog::on_downloadProgress(quint64 recv, quint64 total){
    if(recv > 10240) { // don't show progress for non-docset pages (like Google Drive first request)
        QNetworkReply *reply = (QNetworkReply*) sender();
        // Try to get the item associated to the request
        QVariant itemId = reply->property("listItem");
        QListWidgetItem *item = ui->docsetsList->item(itemId.toInt());
        QPair<qint32, qint32> *previousProgress = progress[reply];
        if (previousProgress == nullptr) {
            previousProgress = new QPair<qint32, qint32>(0, 0);
            progress[reply] = previousProgress;
        }

        if( item != NULL ){
            item->setData( ProgressItemDelegate::ProgressMaxRole, total );
            item->setData( ProgressItemDelegate::ProgressRole, recv );
        }
        currentDownload += recv - previousProgress->first;
        totalDownload += total - previousProgress->second;
        previousProgress->first = recv;
        previousProgress->second = total;
        displayProgress();
    }
}
Beispiel #8
0
/**
 * Loads the SystemStarter display bundle at the specified path.
 * A no-op if SystemStarter is not starting in graphical mode.
 **/
static void loadDisplayBundle (StartupContext aStartupContext, CFDictionaryRef anIPCMessage)
{
    if (!gVerboseFlag && anIPCMessage && aStartupContext)
      {
        CFStringRef aBundlePath = CFDictionaryGetValue(anIPCMessage, kIPCDisplayBundlePathKey);        
        if (aBundlePath && CFGetTypeID(aBundlePath) == CFStringGetTypeID())
          {
            extern void LoadDisplayPlugIn(CFStringRef);

            if (aStartupContext->aDisplayContext)
                freeDisplayContext(aStartupContext->aDisplayContext);
            LoadDisplayPlugIn(aBundlePath);
            aStartupContext->aDisplayContext = initDisplayContext();
            
              {
                CFStringRef aLocalizedString = LocalizedString(aStartupContext->aResourcesBundlePath, kWelcomeToMacintoshKey);
                if (aLocalizedString)
                  {
                    displayStatus(aStartupContext->aDisplayContext, aLocalizedString);
                    displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
                    CFRelease(aLocalizedString);
                  }
              }
            
            if (gSafeBootFlag)
              {
                CFStringRef aLocalizedString = LocalizedString(aStartupContext->aResourcesBundlePath, kSafeBootKey);
                if (aLocalizedString)
                  {
                    (void) displaySafeBootMsg(aStartupContext->aDisplayContext, aLocalizedString);
                    CFRelease(aLocalizedString);
                  }
              }
          }
      }
}
Beispiel #9
0
void TransferServer::deserializeAction(MemoryBuffer & msg, unsigned action)
{
    SocketEndpoint ep;
    ep.deserialize(msg);
    if (!ep.isLocal())
    {
        StringBuffer host, expected;
        queryHostIP().getIpText(host);
        ep.getIpText(expected);
        throwError2(DFTERR_WrongComputer, expected.str(), host.str());
    }

    srcFormat.deserialize(msg);
    tgtFormat.deserialize(msg);
    msg.read(calcInputCRC);
    msg.read(calcOutputCRC);
    deserialize(partition, msg);
    msg.read(numParallelSlaves);
    msg.read(updateFrequency);
    msg.read(replicate);
    msg.read(mirror);
    msg.read(isSafeMode);

    srand((unsigned)get_cycles_now());
    int adjust = (rand() * rand() * rand()) % updateFrequency - (updateFrequency/2);
    lastTick = msTick() + adjust;

    StringBuffer localFilename;
    if (action == FTactionpull)
    {
        partition.item(0).outputName.getPath(localFilename);
        LOG(MCdebugProgress, unknownJob, "Process Pull Command: %s", localFilename.str());
    }
    else
    {
        partition.item(0).inputName.getPath(localFilename);
        LOG(MCdebugProgress, unknownJob, "Process Push Command: %s", localFilename.str());
    }
    LOG(MCdebugProgress, unknownJob, "Num Parallel Slaves=%d Adjust=%d/%d", numParallelSlaves, adjust, updateFrequency);
    LOG(MCdebugProgress, unknownJob, "replicate(%d) mirror(%d) safe(%d) incrc(%d) outcrc(%d)", replicate, mirror, isSafeMode, calcInputCRC, calcOutputCRC);

    displayPartition(partition);

    unsigned numProgress;
    msg.read(numProgress);
    for (unsigned i = 0; i < numProgress; i++)
    {
        OutputProgress & next = *new OutputProgress;
        next.deserializeCore(msg);
        progress.append(next);
    }
    if (msg.remaining())
        msg.read(throttleNicSpeed);
    if (msg.remaining())
        msg.read(compressedInput).read(compressOutput);
    if (msg.remaining())
        msg.read(copyCompressed);
    if (msg.remaining())
        msg.read(transferBufferSize);
    if (msg.remaining()) 
        msg.read(encryptKey).read(decryptKey);
    if (msg.remaining())
    {
        srcFormat.deserializeExtra(msg, 1);
        tgtFormat.deserializeExtra(msg, 1);
    }

    ForEachItemIn(i1, progress)
        progress.item(i1).deserializeExtra(msg, 1);

    LOG(MCdebugProgress, unknownJob, "throttle(%d), transferBufferSize(%d)", throttleNicSpeed, transferBufferSize);
    PROGLOG("compressedInput(%d), compressedOutput(%d), copyCompressed(%d)", compressedInput?1:0, compressOutput?1:0, copyCompressed?1:0);
    PROGLOG("encrypt(%d), decrypt(%d)", encryptKey.isEmpty()?0:1, decryptKey.isEmpty()?0:1);

    //---Finished deserializing ---
    displayProgress(progress);

    totalLengthRead = 0;
    totalLengthToRead = 0;
    ForEachItemIn(idx, partition)
        totalLengthToRead += partition.item(idx).inputLength;
}
AccountSettings::AccountSettings(QWidget *parent, Qt::WindowFlags flags)
    : QDialog(parent, flags),
      preExisting(false),
      deleteBatchSize(0),
      deleteProgress(0)
{
    setWindowTitle(tr("Accounts"));
    QVBoxLayout *vb = new QVBoxLayout(this);
    vb->setContentsMargins(0, 0, 0, 0);

    accountModel = new QMailAccountListModel(this);
    accountModel->setKey(QMailAccountKey::status(QMailAccount::UserEditable, QMailDataComparator::Includes));
    accountModel->setSortKey(QMailAccountSortKey::id(Qt::AscendingOrder));
    connect(accountModel,SIGNAL(rowsInserted(QModelIndex,int,int)),this,SLOT(updateActions()));
    connect(accountModel,SIGNAL(rowsRemoved(QModelIndex,int,int)),this,SLOT(updateActions()));

    accountView = new QListView(this);
    accountView->setContextMenuPolicy(Qt::ActionsContextMenu);
    accountView->setModel(accountModel);

    if (accountModel->rowCount())
        accountView->setCurrentIndex(accountModel->index(0, 0));
    else //no accounts so automatically add
        QTimer::singleShot(0,this,SLOT(addAccount()));

    addAccountAction = new QAction( Qtmail::icon("add"), tr("New"), this );
    connect(addAccountAction, SIGNAL(triggered()), this, SLOT(addAccount()));

    editAccountAction = new QAction(Qtmail::icon("settings"),tr("Edit"), this);
    connect(editAccountAction,SIGNAL(triggered()),this,SLOT(editCurrentAccount()));
    accountView->addAction(editAccountAction);

    resetAccountAction = new QAction( Qtmail::icon("reset"), tr("Reset"), this );
    connect(resetAccountAction, SIGNAL(triggered()), this, SLOT(resetAccount()));
    accountView->addAction(resetAccountAction);

    removeAccountAction = new QAction( Qtmail::icon("remove"), tr("Remove"), this );
    connect(removeAccountAction, SIGNAL(triggered()), this, SLOT(removeAccount()));
    accountView->addAction(removeAccountAction);

    QToolBar *buttonBar = new QToolBar(this);
    buttonBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    buttonBar->addAction(addAccountAction);
    buttonBar->addSeparator();
    buttonBar->addAction(editAccountAction);
    buttonBar->addAction(resetAccountAction);
    buttonBar->addAction(removeAccountAction);

    vb->addWidget(buttonBar);
    vb->addWidget(accountView);

    statusDisplay = new StatusBar(this);
    statusDisplay->setDetailsButtonVisible(false);
    statusDisplay->setVisible(false);


    vb->addWidget(statusDisplay);

    connect(accountView, SIGNAL(activated(QModelIndex)),
            this, SLOT(editCurrentAccount()));

    retrievalAction = new QMailRetrievalAction(this);
    connect(retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(activityChanged(QMailServiceAction::Activity)));
    connect(retrievalAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(displayProgress(uint, uint)));

    transmitAction = new QMailTransmitAction(this);
    connect(transmitAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(activityChanged(QMailServiceAction::Activity)));
    connect(transmitAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(displayProgress(uint, uint)));
}
Beispiel #11
0
/**
  * This is the watcher thread main stuff. It iterates on watching its 'known' directories and
  * notifying the associated filter with the directories/files changes.
  */
void Watcher::run() {
    QTime                       passStart;
    int                         numEntries = 0;
    const QList<PathSegment *>  *pathsP = NULL;

    // do nothing if no root url set
    if (m_url.isEmpty())
        return;

    m_stop = false;
    m_numWatchedFiles = 0;

    // we'll start by scanning this one
    m_files.addPath(m_url, true);
    do {
        passStart.restart();

#ifdef _VERBOSE_WATCHER
        qDebug() << "(File)Watcher does a pass at " << passStart;
#endif
        // now, don't let the filter play concurrently
        if (!tryAcquireWatchSemaphore())
            goto nextPass;

        // check for new or modified files/directories
        pathsP = m_files.getPaths(true);
        numEntries = pathsP->count();
        for (int i = 0; !m_stop && i < numEntries; i++) {
            QString filepath = pathsP->at(i)->getPath();

            // show progress
            displayActivity(tr("Scanning directory %1").arg(filepath));
            displayProgress(0, numEntries - 1, i);

            watchDirectory(filepath);
        }

        // add the new files and directories to the watch lists
#ifdef _VERBOSE_PATH
        m_files.dump("dumping watched files before merging");
        m_newFiles.dump("dumping new files before merging");
#endif

        m_files.merge(&m_newFiles);
        m_newFiles.deleteAll();

#ifdef _VERBOSE_PATH
        m_files.dump("dumping watched files after merging");
        m_newFiles.dump("dumping new files after merging");
#endif

        // now check if any of the watched files have disappeared

        // check removed directories
        for (QList<PathSegment *>::const_iterator i = m_files.getPaths(true)->begin(); i != m_files.getPaths(true)->end(); i++) {
            QString filepath = (*i)->getPath();
            QFileInfoExt entryInfo(filepath);
            if (!entryInfo.exists()) {
                // we DO NOT need to check the content and signal for everything...
                // because the content will be checked later on...
#ifdef _VERBOSE_WATCHER
                qDebug() << "Detected deleted directory " << filepath;
#endif
                directoryDeleted(filepath);
                m_removedFiles.addPath(filepath, true);
            }
        }

        // check removed files
        for (QList<PathSegment *>::const_iterator i = m_files.getPaths()->begin(); !m_stop && i != m_files.getPaths()->end(); i++) {
            QString filepath = (*i)->getPath();
            QFileInfoExt entryInfo(filepath);
            if (!entryInfo.exists()) {
#ifdef _VERBOSE_WATCHER
                qDebug() << "Detected deleted file " << filepath;
#endif
//              fileDeleted(filepath);
                fileDeleted(entryInfo.absoluteFilePath());
                m_removedFiles.addPath(filepath);
                --m_numWatchedFiles;
            }
        }

        // and remove

        // directories
        for (QList<PathSegment *>::const_iterator i = m_removedFiles.getPaths(true)->begin(); i != m_removedFiles.getPaths(true)->end(); i++)
            m_files.deletePath((*i)->getPath(), true);

        // files
        for (QList<PathSegment *>::const_iterator i = m_removedFiles.getPaths()->begin(); !m_stop && i != m_removedFiles.getPaths()->end(); i++)
            m_files.deletePath((*i)->getPath());

        m_removedFiles.deleteAll();

        // keep last pass time
        m_lastPass = QDateTime::currentDateTime();

        // now, the filter can play
        releaseWatchSemaphore();

nextPass:
#ifdef _VERBOSE_WATCHER
        qDebug() << "(File)Watcher ends pass at " << m_lastPass << " (duration: " << passStart.elapsed() << " ms)";
#endif
        QString duration;
        duration.sprintf("%d", passStart.elapsed());
        displayActivity(tr("Scanning pass completed in (%1) milliseconds. Now sleeping.").arg(duration));
        displayProgress(1, 100, 100);

        // a little break
        if (!m_stop)
            msleep(WATCH_PASS_INTERVAL);
    } while (!m_stop);

#ifdef _VERBOSE_WATCHER
    qDebug() << "(File)Watcher now EXITING!";
#endif
}
Beispiel #12
0
/**
  * Watches the given directory. Detects the new directories but delegates their initial inspection
  * to the getSubDirectories method. The latter will recursively list all of their sub directories.
  */
void Watcher::watchDirectory(QString directory) {
    if (m_stop)
        return;

    // now watch all contained files
    QDirExt rootDir(directory);

    // get the directory entries
    QStringList entries = rootDir.entryList();

#ifdef _VERBOSE_WATCHER
    qDebug() << "Watching into " << directory;
#endif

    // has the directory been removed?
    // if so, just return, the removal signal will be sent later on.
    QFileInfoExt entryInfo(directory);
    if (!entryInfo.exists())
        return;

    // has the directory changed since last pass?
    if (entryInfo.lastModified() >= m_lastPass) {
#ifdef _VERBOSE_WATCHER
        qDebug() << "Detected modified directory " << directory;
#endif
        // signal
        directoryModified(directory);
    }

    // walk through the list
    int numNewDirs = 0;
    for (QList<QString>::iterator i = entries.begin(); !m_stop && numNewDirs < NEW_DIRS_PER_PASS && i != entries.end(); i++) {
        QString entryPath = directory;
        entryPath.append(QDirExt::separator(directory));
        entryPath.append(*i);
        QFileInfoExt entryInfo(entryPath);

        if (entryInfo.isHidden())
            continue; // we don't care about these ones.

        if (!entryInfo.isDir()) {
            // a regular file found

            // is it new?
            if (!m_files.findPath(entryPath) && m_numWatchedFiles < MAX_WATCHED_FILES) {
                m_newFiles.addPath(entryPath);
                ++m_numWatchedFiles;

#ifdef _VERBOSE_PATH
            m_newFiles.dump("file added, dumping new files");
#endif

#ifdef _VERBOSE_WATCHER
            qDebug() << "Detected new file " << entryPath;
#endif
                // signal new file
                fileAdded(entryInfo.absoluteFilePath());
            } else if (entryInfo.lastModified() >= m_lastPass) {
#ifdef _VERBOSE_WATCHER
                qDebug() << "Detected modified file " << entryPath;
#endif
                // signal modified file
                fileModified(entryInfo.absoluteFilePath());
            }
        } else {
            // if the directory is not in the list, and doing a recursive watch, browse it.
            if (m_recursive && !m_files.findPath(entryPath)) {
                // go through new dir's content
                displayProgress(0, 0, 0); // back and forth moving progress
                getNewSubDirectories(entryPath);
#ifdef _VERBOSE_PATH
                m_newFiles.dump("new directory browsed, dumping new files");
#endif
                ++numNewDirs;
            }
        }
    }
}
Beispiel #13
0
/**
 * A CFMachPort invalidation callback that records the termination of
 * a startup item task.  Stops the current run loop to give system_starter
 * another go at running items.
 **/
static void startupItemTerminated (CFMachPortRef aMachPort, void *anInfo)
{
    TerminationContext aTerminationContext = (TerminationContext) anInfo;
    
    if (aMachPort)
      {
        mach_port_deallocate(mach_task_self(), CFMachPortGetPort(aMachPort));
      }
    
    if (aTerminationContext && aTerminationContext->anItem)
      {
        pid_t	 		aPID 		= 0;
        pid_t	 		rPID 		= 0;
        int			aStatus		= 0;
        CFMutableDictionaryRef	anItem          = aTerminationContext->anItem;
        StartupContext		aStartupContext = aTerminationContext->aStartupContext;

        /* Get the exit status */
        if (anItem)
          {
            aPID = StartupItemGetPID(anItem);
            if (aPID > 0)
                rPID = waitpid(aPID, &aStatus, WNOHANG);
          }
          
        if (aStartupContext)
          {
            --aStartupContext->aRunningCount;

            /* Record the item's status */
            if (aStartupContext->aStatusDict)
              {
                StartupItemExit(aStartupContext->aStatusDict, anItem, (WIFEXITED(aStatus) && WEXITSTATUS(aStatus) == 0));
                if (aStatus)
                  {
                    warning(CFSTR("%@ (%d) did not complete successfully.\n"), CFDictionaryGetValue(anItem, CFSTR("Description")), aPID);
                  }
                else
                  {
                    if (gDebugFlag) debug(CFSTR("Finished %@ (%d)\n"), CFDictionaryGetValue(anItem, CFSTR("Description")), aPID);
                  }
                displayProgress(aStartupContext->aDisplayContext, ((float)CFDictionaryGetCount(aStartupContext->aStatusDict)/((float)aStartupContext->aServicesCount + 1.0)));
              }

            /* If the item failed to start, then add it to the failed list */
            if (WEXITSTATUS(aStatus) || WTERMSIG(aStatus) || WCOREDUMP(aStatus))
              {
                CFDictionarySetValue(anItem, kErrorKey, kErrorReturnNonZero);
                AddItemToFailedList(aStartupContext, anItem);
              }

            /* Remove the item from the waiting list regardless if it was successful or it failed. */
            RemoveItemFromWaitingList(aStartupContext, anItem);
          }
      }
      
    if (aTerminationContext) free(aTerminationContext);

    
    /* Stop the current run loop so the system_starter engine will cycle and try to start any newly eligible items */
    CFRunLoopStop(CFRunLoopGetCurrent());
}