void DiscoInfoWindow::updateWindow() { IDiscoInfo dinfo = FDiscovery->discoInfo(FStreamJid,FContactJid,FNode); int row = 0; ui.twtIdentity->clearContents(); foreach(const IDiscoIdentity &identity, dinfo.identity) { ui.twtIdentity->setRowCount(row+1); ui.twtIdentity->setItem(row,0,new QTableWidgetItem(identity.category)); ui.twtIdentity->setItem(row,1,new QTableWidgetItem(identity.type)); ui.twtIdentity->setItem(row,2,new QTableWidgetItem(identity.name)); row++; } ui.twtIdentity->verticalHeader()->resizeSections(QHeaderView::ResizeToContents); qSort(dinfo.features); ui.lwtFearures->clear(); foreach(const QString &featureVar, dinfo.features) { IDiscoFeature dfeature = FDiscovery->discoFeature(featureVar); dfeature.var = featureVar; QListWidgetItem *listItem = new QListWidgetItem; listItem->setIcon(dfeature.icon); listItem->setText(dfeature.name.isEmpty() ? dfeature.var : dfeature.name); if (FDiscovery->hasFeatureHandler(featureVar)) { QFont font = ui.lwtFearures->font(); font.setBold(true); listItem->setData(Qt::FontRole,font); } listItem->setData(Qt::UserRole,dfeature.var); listItem->setData(Qt::UserRole+1,dfeature.description); ui.lwtFearures->addItem(listItem); } onCurrentFeatureChanged(ui.lwtFearures->currentItem(), NULL); if (FDataForms) { if (FFormMenu) { FFormMenu->deleteLater(); FFormMenu = NULL; } if (!dinfo.extensions.isEmpty()) { FFormMenu = new Menu(ui.pbtExtensions); for (int index=0; index<dinfo.extensions.count(); index++) { IDataForm form = FDataForms->localizeForm(dinfo.extensions.at(index)); Action *action = new Action(FFormMenu); action->setData(ADR_FORM_INDEX,index); action->setText(!form.title.isEmpty() ? form.title : FDataForms->fieldValue("FORM_TYPE",form.fields).toString()); connect(action,SIGNAL(triggered(bool)),SLOT(onShowExtensionForm(bool))); FFormMenu->addAction(action); } } ui.pbtExtensions->setMenu(FFormMenu); ui.pbtExtensions->setEnabled(FFormMenu!=NULL); } if (!dinfo.error.isNull()) { ui.lblError->setText(tr("Error: %1").arg(dinfo.error.errorMessage())); ui.twtIdentity->setEnabled(false); ui.lwtFearures->setEnabled(false); ui.lblError->setVisible(true); } else { ui.twtIdentity->setEnabled(true); ui.lwtFearures->setEnabled(true); ui.lblError->setVisible(false); } ui.twtIdentity->horizontalHeader()->setResizeMode(0,QHeaderView::ResizeToContents); ui.twtIdentity->horizontalHeader()->setResizeMode(1,QHeaderView::ResizeToContents); ui.twtIdentity->horizontalHeader()->setResizeMode(2,QHeaderView::Stretch); ui.pbtUpdate->setEnabled(true); }
/*! Redraw the liquid in thermometer pipe. \param painter Painter \param pipeRect Bounding rectangle of the pipe without borders */ void QwtThermo::drawLiquid( QPainter *painter, const QRect &pipeRect ) const { painter->save(); painter->setClipRect( pipeRect, Qt::IntersectClip ); painter->setPen( Qt::NoPen ); const QwtScaleMap scaleMap = scaleDraw()->scaleMap(); QRect liquidRect = fillRect( pipeRect ); if ( d_data->colorMap != NULL ) { const QwtInterval interval = scaleDiv().interval().normalized(); // Because the positions of the ticks are rounded // we calculate the colors for the rounded tick values QVector<double> values = qwtTickList( scaleDraw()->scaleDiv() ); if ( scaleMap.isInverting() ) qSort( values.begin(), values.end(), qGreater<double>() ); else qSort( values.begin(), values.end(), qLess<double>() ); int from; if ( !values.isEmpty() ) { from = qRound( scaleMap.transform( values[0] ) ); qwtDrawLine( painter, from, d_data->colorMap->color( interval, values[0] ), pipeRect, liquidRect, d_data->orientation ); } for ( int i = 1; i < values.size(); i++ ) { const int to = qRound( scaleMap.transform( values[i] ) ); for ( int pos = from + 1; pos < to; pos++ ) { const double v = scaleMap.invTransform( pos ); qwtDrawLine( painter, pos, d_data->colorMap->color( interval, v ), pipeRect, liquidRect, d_data->orientation ); } qwtDrawLine( painter, to, d_data->colorMap->color( interval, values[i] ), pipeRect, liquidRect, d_data->orientation ); from = to; } } else { if ( !liquidRect.isEmpty() && d_data->alarmEnabled ) { const QRect r = alarmRect( liquidRect ); if ( !r.isEmpty() ) { painter->fillRect( r, palette().brush( QPalette::Highlight ) ); liquidRect = QRegion( liquidRect ).subtracted( r ).boundingRect(); } } painter->fillRect( liquidRect, palette().brush( QPalette::ButtonText ) ); } painter->restore(); }
/* This is the main workhorse of the QGridLayout. It portions out available space to the chain's children. The calculation is done in fixed point: "fixed" variables are scaled by a factor of 256. If the layout runs "backwards" (i.e. RightToLeft or Up) the layout is computed mirror-reversed, and it's the caller's responsibility do reverse the values before use. chain contains input and output parameters describing the geometry. count is the count of items in the chain; pos and space give the interval (relative to parentWidget topLeft). */ void qGeomCalc(QVector<QLayoutStruct> &chain, int start, int count, int pos, int space, int spacer) { int cHint = 0; int cMin = 0; int cMax = 0; int sumStretch = 0; int sumSpacing = 0; bool wannaGrow = false; // anyone who really wants to grow? // bool canShrink = false; // anyone who could be persuaded to shrink? bool allEmptyNonstretch = true; int pendingSpacing = -1; int spacerCount = 0; int i; for (i = start; i < start + count; i++) { QLayoutStruct *data = &chain[i]; data->done = false; cHint += data->smartSizeHint(); cMin += data->minimumSize; cMax += data->maximumSize; sumStretch += data->stretch; if (!data->empty) { /* Using pendingSpacing, we ensure that the spacing for the last (non-empty) item is ignored. */ if (pendingSpacing >= 0) { sumSpacing += pendingSpacing; ++spacerCount; } pendingSpacing = data->effectiveSpacer(spacer); } wannaGrow = wannaGrow || data->expansive || data->stretch > 0; allEmptyNonstretch = allEmptyNonstretch && !wannaGrow && data->empty; } int extraspace = 0; if (space < cMin + sumSpacing) { /* Less space than minimumSize; take from the biggest first */ int minSize = cMin + sumSpacing; // shrink the spacers proportionally if (spacer >= 0) { spacer = minSize > 0 ? spacer * space / minSize : 0; sumSpacing = spacer * spacerCount; } QList<int> list; for (i = start; i < start + count; i++) list << chain.at(i).minimumSize; qSort(list); int space_left = space - sumSpacing; int sum = 0; int idx = 0; int space_used=0; int current = 0; while (idx < count && space_used < space_left) { current = list.at(idx); space_used = sum + current * (count - idx); sum += current; ++idx; } --idx; int deficit = space_used - space_left; int items = count - idx; /* * If we truncate all items to "current", we would get "deficit" too many pixels. Therefore, we have to remove * deficit/items from each item bigger than maxval. The actual value to remove is deficitPerItem + remainder/items * "rest" is the accumulated error from using integer arithmetic. */ int deficitPerItem = deficit/items; int remainder = deficit % items; int maxval = current - deficitPerItem; int rest = 0; for (i = start; i < start + count; i++) { int maxv = maxval; rest += remainder; if (rest >= items) { maxv--; rest-=items; } QLayoutStruct *data = &chain[i]; data->size = qMin(data->minimumSize, maxv); data->done = true; } } else if (space < cHint + sumSpacing) { /* Less space than smartSizeHint(), but more than minimumSize. Currently take space equally from each, as in Qt 2.x. Commented-out lines will give more space to stretchier items. */ int n = count; int space_left = space - sumSpacing; int overdraft = cHint - space_left; // first give to the fixed ones: for (i = start; i < start + count; i++) { QLayoutStruct *data = &chain[i]; if (!data->done && data->minimumSize >= data->smartSizeHint()) { data->size = data->smartSizeHint(); data->done = true; space_left -= data->smartSizeHint(); // sumStretch -= data->stretch; n--; } } bool finished = n == 0; while (!finished) { finished = true; Fixed64 fp_over = toFixed(overdraft); Fixed64 fp_w = 0; for (i = start; i < start+count; i++) { QLayoutStruct *data = &chain[i]; if (data->done) continue; // if (sumStretch <= 0) fp_w += fp_over / n; // else // fp_w += (fp_over * data->stretch) / sumStretch; int w = fRound(fp_w); data->size = data->smartSizeHint() - w; fp_w -= toFixed(w); // give the difference to the next if (data->size < data->minimumSize) { data->done = true; data->size = data->minimumSize; finished = false; overdraft -= data->smartSizeHint() - data->minimumSize; // sumStretch -= data->stretch; n--; break; } } } } else { // extra space int n = count; int space_left = space - sumSpacing; // first give to the fixed ones, and handle non-expansiveness for (i = start; i < start + count; i++) { QLayoutStruct *data = &chain[i]; if (!data->done && (data->maximumSize <= data->smartSizeHint() || (wannaGrow && !data->expansive && data->stretch == 0) || (!allEmptyNonstretch && data->empty && !data->expansive && data->stretch == 0))) { data->size = data->smartSizeHint(); data->done = true; space_left -= data->size; sumStretch -= data->stretch; n--; } } extraspace = space_left; /* Do a trial distribution and calculate how much it is off. If there are more deficit pixels than surplus pixels, give the minimum size items what they need, and repeat. Otherwise give to the maximum size items, and repeat. Paul Olav Tvete has a wonderful mathematical proof of the correctness of this principle, but unfortunately this comment is too small to contain it. */ int surplus, deficit; do { surplus = deficit = 0; Fixed64 fp_space = toFixed(space_left); Fixed64 fp_w = 0; for (i = start; i < start + count; i++) { QLayoutStruct *data = &chain[i]; if (data->done) continue; extraspace = 0; if (sumStretch <= 0) fp_w += fp_space / n; else fp_w += (fp_space * data->stretch) / sumStretch; int w = fRound(fp_w); data->size = w; fp_w -= toFixed(w); // give the difference to the next if (w < data->smartSizeHint()) { deficit += data->smartSizeHint() - w; } else if (w > data->maximumSize) { surplus += w - data->maximumSize; } } if (deficit > 0 && surplus <= deficit) { // give to the ones that have too little for (i = start; i < start+count; i++) { QLayoutStruct *data = &chain[i]; if (!data->done && data->size < data->smartSizeHint()) { data->size = data->smartSizeHint(); data->done = true; space_left -= data->smartSizeHint(); sumStretch -= data->stretch; n--; } } } if (surplus > 0 && surplus >= deficit) { // take from the ones that have too much for (i = start; i < start + count; i++) { QLayoutStruct *data = &chain[i]; if (!data->done && data->size > data->maximumSize) { data->size = data->maximumSize; data->done = true; space_left -= data->maximumSize; sumStretch -= data->stretch; n--; } } } } while (n > 0 && surplus != deficit); if (n == 0) extraspace = space_left; } /* As a last resort, we distribute the unwanted space equally among the spacers (counting the start and end of the chain). We could, but don't, attempt a sub-pixel allocation of the extra space. */ int extra = extraspace / (spacerCount + 2); int p = pos + extra; for (i = start; i < start+count; i++) { QLayoutStruct *data = &chain[i]; data->pos = p; p += data->size; if (!data->empty) p += data->effectiveSpacer(spacer) + extra; } #ifdef QLAYOUT_EXTRA_DEBUG qDebug() << "qGeomCalc" << "start" << start << "count" << count << "pos" << pos << "space" << space << "spacer" << spacer; for (i = start; i < start + count; ++i) { qDebug() << i << ':' << chain[i].minimumSize << chain[i].smartSizeHint() << chain[i].maximumSize << "stretch" << chain[i].stretch << "empty" << chain[i].empty << "expansive" << chain[i].expansive << "spacing" << chain[i].spacing; qDebug() << "result pos" << chain[i].pos << "size" << chain[i].size; } #endif }
void MessagingHelper::handleNestedFiltersFromMessageFilter(QMessageFilter &filter) { QMessageStore* store = QMessageStore::instance(); QMessageFilterPrivate* pMFFilter = QMessageFilterPrivate::implementation(filter); if (pMFFilter->_filterList.count() > 0) { int filterListCount = pMFFilter->_filterList.count(); for (int i=0; i < filterListCount; i++) { for (int j=0; j < pMFFilter->_filterList[i].count(); j++) { QMessageFilterPrivate* pMFFilter2 = QMessageFilterPrivate::implementation(pMFFilter->_filterList[i][j]); if (pMFFilter2->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = store->queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (accountIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < accountIds.count(); x++) { if (x == 0) { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < accountIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < accountIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_accountFilter; pMFFilter2->_accountFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else if (pMFFilter2->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = store->queryFolders(*pMFFilter2->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue)); if (folderIds.count() > 0) { pMFFilter->_filterList[i].removeAt(j); if (cmp == QMessageDataComparator::Includes) { for (int x = 0; x < folderIds.count(); x++) { if (x == 0) { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[i]); } pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } else { if (x+1 < folderIds.count()) { pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]); pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan); } else { pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal)); qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan); } } } } else { // Excludes for (int x = 0; x < folderIds.count(); x++) { pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::NotEqual)); } qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { delete pMFFilter2->_folderFilter; pMFFilter2->_folderFilter = 0; pMFFilter2->_field = QMessageFilterPrivate::Id; qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan); } } else { break; } } } } else { if (pMFFilter->_field == QMessageFilterPrivate::ParentAccountIdFilter) { QMessageAccountIdList accountIds = store->queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (accountIds.count() > 0) { for (int i=0; i < accountIds.count(); i++) { if (i == 0) { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentAccountId; pMFFilter->_value = accountIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_accountFilter; pMFFilter->_accountFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } else if (pMFFilter->_field == QMessageFilterPrivate::ParentFolderIdFilter) { QMessageFolderIdList folderIds = store->queryFolders(*pMFFilter->_folderFilter, QMessageFolderSortOrder(), 0, 0); QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue)); if (folderIds.count() > 0) { for (int i=0; i < folderIds.count(); i++) { if (i == 0) { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::ParentFolderId; pMFFilter->_value = folderIds[0].toString(); pMFFilter->_comparatorType = QMessageFilterPrivate::Equality; if (cmp == QMessageDataComparator::Includes) { pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal); } else { // Excludes pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual); } } else { if (cmp == QMessageDataComparator::Includes) { filter |= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::Equal); } else { // Excludes filter &= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::NotEqual); } } } } else { delete pMFFilter->_folderFilter; pMFFilter->_folderFilter = 0; pMFFilter->_field = QMessageFilterPrivate::Id; } } } }
ReportList::ReportList(BoxType type, bool sortByScore, QWidget *parent) : QMainWindow(parent) { this->sort = sortByScore; printAction = new QAction("&Print...", this); QMenu* fileMenu = menuBar()->addMenu("&File"); fileMenu->addAction(printAction); connect(printAction, SIGNAL(triggered()), this, SLOT(print())); QWidget* central = new QWidget(); this->setCentralWidget(central); QHBoxLayout* mainLayout = new QHBoxLayout(); central->setLayout(mainLayout); this->reports = new QStackedWidget(); int size = 0; if(type == employee) { employeeData = DataInterface::getEmployees(); if(sortByScore) { this->setWindowTitle("Employee View - Sorted By Average Score"); qSort(employeeData.begin(), employeeData.end()); } else { this->setWindowTitle("Employee View"); } size = employeeData.size(); for(int i = 0; i < size; i++) { EmployeeReportBox* box = new EmployeeReportBox(employeeData.at(i), i, size); reports->addWidget(box); } } else if(type == employer) { this->setWindowTitle("Employer View"); employerData = DataInterface::getEmployers(); size = employerData.size(); for(int i = 0; i < size; i++) { EmployerReportBox* box = new EmployerReportBox(employerData.at(i), i, size); reports->addWidget(box); } } else { QMessageBox::information(this, "Failed To Read Data", "Failed to read the data from the file."); return; } QScrollBar *scrollBar = new QScrollBar(Qt::Vertical); scrollBar->setRange(0, size - 1); scrollBar->setValue(0); scrollBar->setFocusPolicy(Qt::WheelFocus); connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(moveToBox(int))); this->setFixedHeight(370); reports->setCurrentIndex(0); mainLayout->addWidget(reports); mainLayout->addWidget(scrollBar); }
bool OsmAnd::MapRenderer::prePrepareFrame() { if(!_isRenderingInitialized) return false; // If we have current configuration invalidated, we need to update it // and invalidate frame if(_currentConfigurationInvalidatedMask) { { QReadLocker scopedLocker(&_configurationLock); _currentConfiguration = _requestedConfiguration; } bool ok = updateCurrentConfiguration(); if(ok) _currentConfigurationInvalidatedMask = 0; invalidateFrame(); // If configuration is still invalidated, abort processing if(_currentConfigurationInvalidatedMask) return false; } // If we have current state invalidated, we need to update it // and invalidate frame if(_currentStateInvalidated) { { QReadLocker scopedLocker(&_stateLock); _currentState = _requestedState; } bool ok = updateCurrentState(); if(ok) _currentStateInvalidated = false; invalidateFrame(); // If state is still invalidated, abort processing if(_currentStateInvalidated) return false; } // If we have invalidated resources, purge them if(_invalidatedRasterLayerResourcesMask) { QReadLocker scopedLocker(&_invalidatedRasterLayerResourcesMaskLock); for(int layerId = 0; layerId < RasterMapLayersCount; layerId++) { if((_invalidatedRasterLayerResourcesMask & (1 << layerId)) == 0) continue; validateRasterLayerResources(static_cast<RasterMapLayerId>(layerId)); _invalidatedRasterLayerResourcesMask &= ~(1 << layerId); } } if(_invalidatedElevationDataResources) { validateElevationDataResources(); _invalidatedElevationDataResources = false; } // Sort visible tiles by distance from target qSort(_visibleTiles.begin(), _visibleTiles.end(), [this](const TileId& l, const TileId& r) -> bool { const auto lx = l.x - _targetTileId.x; const auto ly = l.y - _targetTileId.y; const auto rx = r.x - _targetTileId.x; const auto ry = r.y - _targetTileId.y; return (lx*lx + ly*ly) > (rx*rx + ry*ry); }); // Get set of tiles that are unique: visible tiles may contain same tiles, but wrapped _uniqueTiles.clear(); for(auto itTileId = _visibleTiles.begin(); itTileId != _visibleTiles.end(); ++itTileId) { const auto& tileId = *itTileId; _uniqueTiles.insert(Utilities::normalizeTileId(tileId, _currentState.zoomBase)); } //TODO: Keep cache fresh and throw away outdated tiles return true; }
bool Parser::process(int parsingMode) { m_parsingMode = parsingMode; ngrt4n::clearCoreData(*m_cdata); m_dotContent.clear(); QDomDocument xmlDoc; QDomElement xmlRoot; QFile file(m_descriptionFile); if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { m_lastErrorMsg = QObject::tr("Unable to open the file %1").arg(m_descriptionFile); Q_EMIT errorOccurred(m_lastErrorMsg); file.close(); return false; } if (!xmlDoc.setContent(&file)) { file.close(); m_lastErrorMsg = QObject::tr("Error while parsing the file %1").arg(m_descriptionFile); Q_EMIT errorOccurred(m_lastErrorMsg); return false; } file.close(); // The content of the file is already in memory xmlRoot = xmlDoc.documentElement(); m_cdata->monitor = xmlRoot.attribute("monitor").toInt(); m_cdata->format_version = xmlRoot.attribute("compat").toDouble(); QDomNodeList services = xmlRoot.elementsByTagName("Service"); NodeT node; qint32 serviceCount = services.length(); for (qint32 srv = 0; srv < serviceCount; ++srv) { QDomElement service = services.item(srv).toElement(); node.parent.clear(); node.monitored = false; node.id = service.attribute("id").trimmed(); node.type = service.attribute("type").toInt(); node.sev = node.sev_prop = ngrt4n::Unknown; node.sev_crule = service.attribute("statusCalcRule").toInt(); node.sev_prule = service.attribute("statusPropRule").toInt(); node.icon = service.firstChildElement("Icon").text().trimmed(); node.name = service.firstChildElement("Name").text().trimmed(); node.description = service.firstChildElement("Description").text().trimmed(); node.alarm_msg = service.firstChildElement("AlarmMsg").text().trimmed(); node.notification_msg = service.firstChildElement("NotificationMsg").text().trimmed(); node.child_nodes = service.firstChildElement("SubServices").text().trimmed(); node.weight = (m_cdata->format_version >= 3.1) ? service.attribute("weight").toDouble() : ngrt4n::WEIGHT_UNIT; if (node.sev_crule == CalcRules::WeightedAverageWithThresholds) { QString thdata = service.firstChildElement("Thresholds").text().trimmed(); node.thresholdLimits = ThresholdHelper::dataToList(thdata); qSort(node.thresholdLimits.begin(), node.thresholdLimits.end(), ThresholdLessthanFnt()); } node.check.status = -1; if (node.icon.isEmpty()) node.icon = ngrt4n::DEFAULT_ICON; switch(node.type) { case NodeType::BusinessService: insertBusinessServiceNode(node); break; case NodeType::ITService: insertITServiceNode(node); break; case NodeType::ExternalService: insertExternalServiceNode(node); break; default: break; } } updateNodeHierachy(); saveCoordinatesFile(); if (m_parsingMode == ParsingModeDashboard) return parseDotResult(); return true; }
void NemoCalendarAgendaModel::doRefresh(bool reset) { mKCal::ExtendedCalendar::Ptr calendar = NemoCalendarDb::calendar(); QDate endDate = mEndDate.isValid()?mEndDate:mStartDate; mKCal::ExtendedCalendar::ExpandedIncidenceList newEvents = calendar->rawExpandedEvents(mStartDate, endDate, false, false, KDateTime::Spec(KDateTime::LocalZone)); // Filter out excluded notebooks for (int ii = 0; ii < newEvents.count(); ++ii) { if (!NemoCalendarEventCache::instance()->mNotebooks.contains(NemoCalendarDb::calendar()->notebook(newEvents.at(ii).second))) { newEvents.remove(ii); --ii; } } qSort(newEvents.begin(), newEvents.end(), eventsLessThan); int oldEventCount = mEvents.count(); if (reset) { beginResetModel(); qDeleteAll(mEvents); mEvents.clear(); } QList<NemoCalendarEventOccurrence *> events = mEvents; int newEventsCounter = 0; int eventsCounter = 0; int mEventsIndex = 0; while (newEventsCounter < newEvents.count() || eventsCounter < events.count()) { // Remove old events int removeCount = 0; while ((eventsCounter + removeCount) < events.count() && (newEventsCounter >= newEvents.count() || eventsLessThan(events.at(eventsCounter + removeCount)->expandedEvent(), newEvents.at(newEventsCounter)))) removeCount++; if (removeCount) { Q_ASSERT(false == reset); beginRemoveRows(QModelIndex(), mEventsIndex, mEventsIndex + removeCount - 1); mEvents.erase(mEvents.begin() + mEventsIndex, mEvents.begin() + mEventsIndex + removeCount); endRemoveRows(); for (int ii = eventsCounter; ii < eventsCounter + removeCount; ++ii) delete events.at(ii); eventsCounter += removeCount; } // Skip matching events while (eventsCounter < events.count() && newEventsCounter < newEvents.count() && eventsEqual(newEvents.at(newEventsCounter), events.at(eventsCounter)->expandedEvent())) { Q_ASSERT(false == reset); eventsCounter++; newEventsCounter++; mEventsIndex++; } // Insert new events int insertCount = 0; while ((newEventsCounter + insertCount) < newEvents.count() && (eventsCounter >= events.count() || eventsLessThan(newEvents.at(newEventsCounter + insertCount), events.at(eventsCounter)->expandedEvent()))) insertCount++; if (insertCount) { if (!reset) beginInsertRows(QModelIndex(), mEventsIndex, mEventsIndex + insertCount - 1); for (int ii = 0; ii < insertCount; ++ii) { NemoCalendarEventOccurrence *event = new NemoCalendarEventOccurrence(newEvents.at(newEventsCounter + ii)); mEvents.insert(mEventsIndex++, event); } newEventsCounter += insertCount; if (!reset) endInsertRows(); } } if (reset) endResetModel(); if (oldEventCount != mEvents.count()) emit countChanged(); }
void HelpDialog::updateHelpText(void) const { QString htmlText = "<html><head><title>"; htmlText += q_("Stellarium Help").toHtmlEscaped(); htmlText += "</title></head><body>\n"; // WARNING! Section titles are re-used below! htmlText += "<p align=\"center\"><a href=\"#keys\">" + q_("Keys").toHtmlEscaped() + "</a> • <a href=\"#links\">" + q_("Further Reading").toHtmlEscaped() + "</a></p>\n"; htmlText += "<h2 id='keys'>" + q_("Keys").toHtmlEscaped() + "</h2>\n"; htmlText += "<table cellpadding=\"10%\">\n"; // Describe keys for those keys which do not have actions. // navigate htmlText += "<tr><td>" + q_("Pan view around the sky").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Arrow keys & left mouse drag").toHtmlEscaped() + "</b></td></tr>\n"; // zoom in/out htmlText += "<tr><td rowspan='2'>" + q_("Zoom in/out").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Page Up/Down").toHtmlEscaped() + "</b></td></tr>\n"; htmlText += "<tr><td><b>" + q_("Ctrl+Up/Down").toHtmlEscaped() + "</b></td></tr>\n"; // time dragging/scrolling htmlText += "<tr><td>" + q_("Time dragging").toHtmlEscaped() + "</td><td><b>" + q_("Ctrl & left mouse drag").toHtmlEscaped() + "</b></td></tr>"; htmlText += "<tr><td>" + q_("Time scrolling: minutes").toHtmlEscaped() + "</td><td><b>" + q_("Ctrl & mouse wheel").toHtmlEscaped() + "</b></td></tr>"; htmlText += "<tr><td>" + q_("Time scrolling: hours").toHtmlEscaped() + "</td><td><b>" + q_("Ctrl+Shift & mouse wheel").toHtmlEscaped() + "</b></td></tr>"; htmlText += "<tr><td>" + q_("Time scrolling: days").toHtmlEscaped() + "</td><td><b>" + q_("Ctrl+Alt & mouse wheel").toHtmlEscaped() + "</b></td></tr>"; htmlText += "<tr><td>" + q_("Time scrolling: years").toHtmlEscaped() + "</td><td><b>" + q_("Ctrl+Alt+Shift & mouse wheel").toHtmlEscaped() + "</b></td></tr>"; // select object htmlText += "<tr><td>" + q_("Select object").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Left click").toHtmlEscaped() + "</b></td></tr>\n"; // clear selection htmlText += "<tr><td>"; htmlText += q_("Clear selection").toHtmlEscaped() + "</td>"; #ifdef Q_OS_MAC htmlText += "<td><b>" + q_("Ctrl & left click").toHtmlEscaped() + "</b></td></tr>\n"; #else htmlText += "<td><b>" + q_("Right click").toHtmlEscaped() + "</b></td></tr>\n"; #endif // add custom marker htmlText += "<tr><td>" + q_("Add custom marker").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Shift & left click").toHtmlEscaped() + "</b></td></tr>\n"; // delete one custom marker htmlText += "<tr><td>" + q_("Delete marker closest to mouse cursor").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Shift & right click").toHtmlEscaped() + "</b></td></tr>\n"; // delete all custom markers htmlText += "<tr><td>" + q_("Delete all custom markers").toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + q_("Shift & Alt & right click").toHtmlEscaped() + "</b></td></tr>\n"; htmlText += "</table>\n<p>" + q_("Below are listed only the actions with assigned keys. Further actions may be available via the \"%1\" button.") .arg(ui->editShortcutsButton->text()).toHtmlEscaped() + "</p><table cellpadding=\"10%\">\n"; // Append all StelAction shortcuts. StelActionMgr* actionMgr = StelApp::getInstance().getStelActionManager(); typedef QPair<QString, QString> KeyDescription; for (auto group : actionMgr->getGroupList()) { QList<KeyDescription> descriptions; for (auto* action : actionMgr->getActionList(group)) { if (action->getShortcut().isEmpty()) continue; QString text = action->getText(); QString key = action->getShortcut().toString(QKeySequence::NativeText); descriptions.append(KeyDescription(text, key)); } qSort(descriptions); htmlText += "<tr></tr><tr><td><b><u>" + q_(group) + ":</u></b></td></tr>\n"; for (const auto& desc : descriptions) { htmlText += "<tr><td>" + desc.first.toHtmlEscaped() + "</td>"; htmlText += "<td><b>" + desc.second.toHtmlEscaped() + "</b></td></tr>\n"; } } htmlText += "<tr></tr><tr><td><b><u>" + q_("Text User Interface (TUI)") + ":</u></b></td></tr>\n"; htmlText += "<tr><td>" + q_("Activate TUI") + "</td>"; htmlText += "<td><b>Alt+T</b></td></tr>\n"; htmlText += "</table>"; // Regexp to replace {text} with an HTML link. QRegExp a_rx = QRegExp("[{]([^{]*)[}]"); // WARNING! Section titles are re-used above! htmlText += "<h2 id=\"links\">" + q_("Further Reading").toHtmlEscaped() + "</h2>\n"; htmlText += q_("The following links are external web links, and will launch your web browser:\n").toHtmlEscaped(); htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{Frequently Asked Questions} about Stellarium. Answers too.").toHtmlEscaped().replace(a_rx, "<a href=\"https://github.com/Stellarium/stellarium/wiki/FAQ\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{The Stellarium Wiki} - general information.").toHtmlEscaped().replace(a_rx, "<a href=\"https://github.com/Stellarium/stellarium/wiki\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{The landscapes} - user-contributed landscapes for Stellarium.").toHtmlEscaped().replace(a_rx, "<a href=\"https://stellarium.org/landscapes.html\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{The scripts} - user-contributed and official scripts for Stellarium.").toHtmlEscaped().replace(a_rx, "<a href=\"https://stellarium.org/scripts.html\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{Bug reporting and feature request system} - if something doesn't work properly or is missing and is not listed in the tracker, you can open bug reports here.").toHtmlEscaped().replace(a_rx, "<a href=\"https://github.com/Stellarium/stellarium/issues\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{Google Groups} - discuss Stellarium with other users.").toHtmlEscaped().replace(a_rx, "<a href=\"https://groups.google.com/forum/#!forum/stellarium\">\\1</a>"); htmlText += "</p>\n"; htmlText += "<p>"; // TRANSLATORS: The text between braces is the text of an HTML link. htmlText += q_("{Open Collective} - donations to the Stellarium development team.").toHtmlEscaped().replace(a_rx, "<a href=\"https://opencollective.com/stellarium\">\\1</a>"); htmlText += "</p>\n"; htmlText += "</body></html>\n"; ui->helpBrowser->clear(); StelGui* gui = dynamic_cast<StelGui*>(StelApp::getInstance().getGui()); Q_ASSERT(gui); ui->helpBrowser->document()->setDefaultStyleSheet(QString(gui->getStelStyle().htmlStyleSheet)); ui->helpBrowser->insertHtml(htmlText); ui->helpBrowser->scrollToAnchor("top"); }
void AbstractPort::updatePacketListSequential() { long sec = 0; long nsec = 0; qDebug("In %s", __FUNCTION__); // First sort the streams by ordinalValue qSort(streamList_.begin(), streamList_.end(), StreamBase::StreamLessThan); clearPacketList(); for (int i = 0; i < streamList_.size(); i++) { if (streamList_[i]->isEnabled()) { int len = 0; ulong n, x, y; ulong burstSize; double ibg = 0; quint64 ibg1 = 0, ibg2 = 0; quint64 nb1 = 0, nb2 = 0; double ipg = 0; quint64 ipg1 = 0, ipg2 = 0; quint64 npx1 = 0, npx2 = 0; quint64 npy1 = 0, npy2 = 0; quint64 loopDelay; ulong frameVariableCount = streamList_[i]->frameVariableCount(); // We derive n, x, y such that // n * x + y = total number of packets to be sent switch (streamList_[i]->sendUnit()) { case OstProto::StreamControl::e_su_bursts: burstSize = streamList_[i]->burstSize(); x = AbstractProtocol::lcm(frameVariableCount, burstSize); n = ulong(burstSize * streamList_[i]->numBursts()) / x; y = ulong(burstSize * streamList_[i]->numBursts()) % x; if (streamList_[i]->burstRate() > 0) { ibg = 1e9/double(streamList_[i]->burstRate()); ibg1 = quint64(ceil(ibg)); ibg2 = quint64(floor(ibg)); nb1 = quint64((ibg - double(ibg2)) * double(x)); nb2 = x - nb1; } loopDelay = ibg2; break; case OstProto::StreamControl::e_su_packets: x = frameVariableCount; n = 2; while (x < minPacketSetSize_) x = frameVariableCount*n++; n = streamList_[i]->numPackets() / x; y = streamList_[i]->numPackets() % x; burstSize = x + y; if (streamList_[i]->packetRate() > 0) { ipg = 1e9/double(streamList_[i]->packetRate()); ipg1 = quint64(ceil(ipg)); ipg2 = quint64(floor(ipg)); npx1 = quint64((ipg - double(ipg2)) * double(x)); npx2 = x - npx1; npy1 = quint64((ipg - double(ipg2)) * double(y)); npy2 = y - npy1; } loopDelay = ipg2; break; default: qWarning("Unhandled stream control unit %d", streamList_[i]->sendUnit()); continue; } qDebug("\nframeVariableCount = %lu", frameVariableCount); qDebug("n = %lu, x = %lu, y = %lu, burstSize = %lu", n, x, y, burstSize); qDebug("ibg = %g", ibg); qDebug("ibg1 = %" PRIu64, ibg1); qDebug("nb1 = %" PRIu64, nb1); qDebug("ibg2 = %" PRIu64, ibg2); qDebug("nb2 = %" PRIu64 "\n", nb2); qDebug("ipg = %g", ipg); qDebug("ipg1 = %" PRIu64, ipg1); qDebug("npx1 = %" PRIu64, npx1); qDebug("npy1 = %" PRIu64, npy1); qDebug("ipg2 = %" PRIu64, ipg2); qDebug("npx2 = %" PRIu64, npx2); qDebug("npy2 = %" PRIu64 "\n", npy2); if (n > 1) loopNextPacketSet(x, n, 0, loopDelay); else if (n == 0) x = 0; for (uint j = 0; j < (x+y); j++) { if (j == 0 || frameVariableCount > 1) { len = streamList_[i]->frameValue( pktBuf_, sizeof(pktBuf_), j); } if (len <= 0) continue; qDebug("q(%d, %d) sec = %lu nsec = %lu", i, j, sec, nsec); appendToPacketList(sec, nsec, pktBuf_, len); if ((j > 0) && (((j+1) % burstSize) == 0)) { nsec += (j < nb1) ? ibg1 : ibg2; while (nsec >= long(1e9)) { sec++; nsec -= long(1e9); } } else { if (j < x) nsec += (j < npx1) ? ipg1 : ipg2; else nsec += ((j-x) < npy1) ? ipg1 : ipg2; while (nsec >= long(1e9)) { sec++; nsec -= long(1e9); } } } switch(streamList_[i]->nextWhat()) { case ::OstProto::StreamControl::e_nw_stop: goto _stop_no_more_pkts; case ::OstProto::StreamControl::e_nw_goto_id: /*! \todo (MED): define and use streamList_[i].d.control().goto_stream_id(); */ /*! \todo (MED): assumes goto Id is less than current!!!! To support goto to any id, do if goto_id > curr_id then i = goto_id; goto restart; else returnToQIdx = 0; */ setPacketListLoopMode(true, 0, streamList_[i]->sendUnit() == StreamBase::e_su_bursts ? ibg1 : ipg1); goto _stop_no_more_pkts; case ::OstProto::StreamControl::e_nw_goto_next: break; default: qFatal("---------- %s: Unhandled case (%d) -----------", __FUNCTION__, streamList_[i]->nextWhat() ); break; } } // if (stream is enabled) } // for (numStreams) _stop_no_more_pkts: isSendQueueDirty_ = false; }
void AbstractPort::updatePacketListInterleaved() { int numStreams = 0; quint64 minGap = ULLONG_MAX; quint64 duration = quint64(1e9); QList<quint64> ibg1, ibg2; QList<quint64> nb1, nb2; QList<quint64> ipg1, ipg2; QList<quint64> np1, np2; QList<ulong> schedSec, schedNsec; QList<ulong> pktCount, burstCount; QList<ulong> burstSize; QList<bool> isVariable; QList<QByteArray> pktBuf; QList<ulong> pktLen; qDebug("In %s", __FUNCTION__); // First sort the streams by ordinalValue qSort(streamList_.begin(), streamList_.end(), StreamBase::StreamLessThan); clearPacketList(); for (int i = 0; i < streamList_.size(); i++) { if (!streamList_[i]->isEnabled()) continue; double numBursts = 0; double numPackets = 0; quint64 _burstSize = 0; double ibg = 0; quint64 _ibg1 = 0, _ibg2 = 0; quint64 _nb1 = 0, _nb2 = 0; double ipg = 0; quint64 _ipg1 = 0, _ipg2 = 0; quint64 _np1 = 0, _np2 = 0; switch (streamList_[i]->sendUnit()) { case OstProto::StreamControl::e_su_bursts: numBursts = streamList_[i]->burstRate(); if (streamList_[i]->burstRate() > 0) { ibg = 1e9/double(streamList_[i]->burstRate()); _ibg1 = quint64(ceil(ibg)); _ibg2 = quint64(floor(ibg)); _nb1 = quint64((ibg - double(_ibg2)) * double(numBursts)); _nb2 = quint64(numBursts) - _nb1; _burstSize = streamList_[i]->burstSize(); } break; case OstProto::StreamControl::e_su_packets: numPackets = streamList_[i]->packetRate(); if (streamList_[i]->packetRate() > 0) { ipg = 1e9/double(streamList_[i]->packetRate()); _ipg1 = llrint(ceil(ipg)); _ipg2 = quint64(floor(ipg)); _np1 = quint64((ipg - double(_ipg2)) * double(numPackets)); _np2 = quint64(numPackets) - _np1; _burstSize = 1; } break; default: qWarning("Unhandled stream control unit %d", streamList_[i]->sendUnit()); continue; } qDebug("numBursts = %g, numPackets = %g\n", numBursts, numPackets); qDebug("ibg = %g", ibg); qDebug("ibg1 = %" PRIu64, _ibg1); qDebug("nb1 = %" PRIu64, _nb1); qDebug("ibg2 = %" PRIu64, _ibg2); qDebug("nb2 = %" PRIu64 "\n", _nb2); qDebug("ipg = %g", ipg); qDebug("ipg1 = %" PRIu64, _ipg1); qDebug("np1 = %" PRIu64, _np1); qDebug("ipg2 = %" PRIu64, _ipg2); qDebug("np2 = %" PRIu64 "\n", _np2); if (_ibg2 && (_ibg2 < minGap)) minGap = _ibg2; if (_ibg1 && (_ibg1 > duration)) duration = _ibg1; ibg1.append(_ibg1); ibg2.append(_ibg2); nb1.append(_nb1); nb2.append(_nb1); burstSize.append(_burstSize); if (_ipg2 && (_ipg2 < minGap)) minGap = _ipg2; if (_np1) { if (_ipg1 && (_ipg1 > duration)) duration = _ipg1; } else { if (_ipg2 && (_ipg2 > duration)) duration = _ipg2; } ipg1.append(_ipg1); ipg2.append(_ipg2); np1.append(_np1); np2.append(_np1); schedSec.append(0); schedNsec.append(0); pktCount.append(0); burstCount.append(0); if (streamList_[i]->isFrameVariable()) { isVariable.append(true); pktBuf.append(QByteArray()); pktLen.append(0); } else { isVariable.append(false); pktBuf.append(QByteArray()); pktBuf.last().resize(kMaxPktSize); pktLen.append(streamList_[i]->frameValue( (uchar*)pktBuf.last().data(), pktBuf.last().size(), 0)); } numStreams++; } // for i qDebug("minGap = %" PRIu64, minGap); qDebug("duration = %" PRIu64, duration); uchar* buf; int len; quint64 durSec = duration/ulong(1e9); quint64 durNsec = duration % ulong(1e9); quint64 sec = 0; quint64 nsec = 0; quint64 lastPktTxSec = 0; quint64 lastPktTxNsec = 0; do { for (int i = 0; i < numStreams; i++) { // If a packet is not scheduled yet, look at the next stream if ((schedSec.at(i) > sec) || (schedNsec.at(i) > nsec)) continue; for (uint j = 0; j < burstSize[i]; j++) { if (isVariable.at(i)) { buf = pktBuf_; len = streamList_[i]->frameValue(pktBuf_, sizeof(pktBuf_), pktCount[i]); } else { buf = (uchar*) pktBuf.at(i).data(); len = pktLen.at(i); } if (len <= 0) continue; qDebug("q(%d) sec = %" PRIu64 " nsec = %" PRIu64, i, sec, nsec); appendToPacketList(sec, nsec, buf, len); lastPktTxSec = sec; lastPktTxNsec = nsec; pktCount[i]++; schedNsec[i] += (pktCount.at(i) < np1.at(i)) ? ipg1.at(i) : ipg2.at(i); while (schedNsec.at(i) >= 1e9) { schedSec[i]++; schedNsec[i] -= long(1e9); } } burstCount[i]++; schedNsec[i] += (burstCount.at(i) < nb1.at(i)) ? ibg1.at(i) : ibg2.at(i); while (schedNsec.at(i) >= 1e9) { schedSec[i]++; schedNsec[i] -= long(1e9); } } nsec += minGap; while (nsec >= 1e9) { sec++; nsec -= long(1e9); } } while ((sec < durSec) || (nsec < durNsec)); qint64 delaySec = durSec - lastPktTxSec; qint64 delayNsec = durNsec - lastPktTxNsec; while (delayNsec < 0) { delayNsec += long(1e9); delaySec--; } qDebug("loop Delay = %" PRId64 "/%" PRId64, delaySec, delayNsec); setPacketListLoopMode(true, delaySec, delayNsec); isSendQueueDirty_ = false; }
/** * \return List of same vectors as given, ordered from left to right, top to bottom. */ QList<RVector> RVector::getSortedLeftRightTopBottom(const QList<RVector>& list) { QList<RVector> ret = list; qSort(ret.begin(), ret.end(), RVector::RVectorLeftRightTopBottomSort::lessThan); return ret; }
/** * \return List of same vectors as given, ordered by shortes distance to given vector v. */ QList<RVector> RVector::getSortedByDistance(const QList<RVector>& list, const RVector& v) { RVectorDistanceSort::v = v; QList<RVector> ret = list; qSort(ret.begin(), ret.end(), RVector::RVectorDistanceSort::lessThan); return ret; }
void KexiFileWidget::updateFilters() { if (d->filtersUpdated) return; d->filtersUpdated = true; d->lastFileName.clear(); // m_lastUrl = KUrl(); clearFilter(); QString filter; KMimeType::Ptr mime; QStringList allfilters; const bool normalOpeningMode = d->mode & Opening && !(d->mode & Custom); const bool normalSavingMode = d->mode & SavingFileBasedDB && !(d->mode & Custom); if (normalOpeningMode || normalSavingMode) { mime = KMimeType::mimeType(KexiDB::defaultFileBasedDriverMimeType()); if (mime && !d->excludedMimeTypes.contains(mime->name().toLower())) { filter += KexiUtils::fileDialogFilterString(mime); allfilters += mime->patterns(); } } if (normalOpeningMode || d->mode & SavingServerBasedDB) { mime = KMimeType::mimeType("application/x-kexiproject-shortcut"); if (mime && !d->excludedMimeTypes.contains(mime->name().toLower())) { filter += KexiUtils::fileDialogFilterString(mime); allfilters += mime->patterns(); } } if (normalOpeningMode || d->mode & SavingServerBasedDB) { mime = KMimeType::mimeType("application/x-kexi-connectiondata"); if (mime && !d->excludedMimeTypes.contains(mime->name().toLower())) { filter += KexiUtils::fileDialogFilterString(mime); allfilters += mime->patterns(); } } //! @todo hardcoded for MSA: if (normalOpeningMode) { mime = KMimeType::mimeType("application/vnd.ms-access"); if (mime && !d->excludedMimeTypes.contains(mime->name().toLower())) { filter += KexiUtils::fileDialogFilterString(mime); allfilters += mime->patterns(); } } foreach(const QString& mimeName, d->additionalMimeTypes) { if (mimeName == "all/allfiles") continue; if (d->excludedMimeTypes.contains(mimeName.toLower())) continue; filter += KexiUtils::fileDialogFilterString(mimeName); mime = KMimeType::mimeType(mimeName); allfilters += mime->patterns(); } if (!d->excludedMimeTypes.contains("all/allfiles")) filter += KexiUtils::fileDialogFilterString("all/allfiles"); // mime = KMimeType::mimeType("all/allfiles"); // if (mime) { // filter += QString(mime->patterns().isEmpty() ? "*" : mime->patterns().join(" ")) // + "|" + mime->comment()+ " (*)\n"; // } //remove duplicates made because upper- and lower-case extenstions are used: QStringList allfiltersUnique = allfilters.toSet().toList(); qSort(allfiltersUnique); if (allfiltersUnique.count() > 1) {//prepend "all supoported files" entry filter.prepend(allfilters.join(" ") + "|" + i18n("All Supported Files (%1)", allfiltersUnique.join(", ")) + "\n"); } if (filter.right(1) == "\n") filter.truncate(filter.length() - 1); setFilter(filter); if (d->mode & Opening) { KFileWidget::setMode(KFile::ExistingOnly | KFile::LocalOnly | KFile::File); setOperationMode(KFileWidget::Opening); } else { KFileWidget::setMode(KFile::LocalOnly | KFile::File); setOperationMode(KFileWidget::Saving); } }
bool KArchiveDirectory::copyTo(const QString &dest, bool recursiveCopy) const { QDir root; QList<const KArchiveFile *> fileList; QMap<qint64, QString> fileToDir; // placeholders for iterated items QStack<const KArchiveDirectory *> dirStack; QStack<QString> dirNameStack; dirStack.push(this); // init stack at current directory dirNameStack.push(dest); // ... with given path do { const KArchiveDirectory *curDir = dirStack.pop(); const QString curDirName = dirNameStack.pop(); if (!root.mkpath(curDirName)) { return false; } const QStringList dirEntries = curDir->entries(); for (QStringList::const_iterator it = dirEntries.begin(); it != dirEntries.end(); ++it) { const KArchiveEntry *curEntry = curDir->entry(*it); if (!curEntry->symLinkTarget().isEmpty()) { QString linkName = curDirName + QLatin1Char('/') + curEntry->name(); // To create a valid link on Windows, linkName must have a .lnk file extension. #ifdef Q_OS_WIN if (!linkName.endsWith(QStringLiteral(".lnk"))) { linkName += QStringLiteral(".lnk"); } #endif QFile symLinkTarget(curEntry->symLinkTarget()); if (!symLinkTarget.link(linkName)) { //qDebug() << "symlink(" << curEntry->symLinkTarget() << ',' << linkName << ") failed:" << strerror(errno); } } else { if (curEntry->isFile()) { const KArchiveFile *curFile = dynamic_cast<const KArchiveFile *>(curEntry); if (curFile) { fileList.append(curFile); fileToDir.insert(curFile->position(), curDirName); } } if (curEntry->isDirectory() && recursiveCopy) { const KArchiveDirectory *ad = dynamic_cast<const KArchiveDirectory *>(curEntry); if (ad) { dirStack.push(ad); dirNameStack.push(curDirName + QLatin1Char('/') + curEntry->name()); } } } } } while (!dirStack.isEmpty()); qSort(fileList.begin(), fileList.end(), sortByPosition); // sort on d->pos, so we have a linear access for (QList<const KArchiveFile *>::const_iterator it = fileList.constBegin(), end = fileList.constEnd(); it != end; ++it) { const KArchiveFile *f = *it; qint64 pos = f->position(); if (!f->copyTo(fileToDir[pos])) { return false; } } return true; }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); QTextCodec *big5 = QTextCodec::codecForName("Big5-hkscs"); #if 0 QFile f("/home/lars/dev/qt-4.0/util/unicode/data/big5-eten.txt"); f.open(QFile::ReadOnly); while (!f.atEnd()) { QByteArray line = f.readLine(); if (line.startsWith("#")) continue; line.replace("0x", ""); line.replace("U+", ""); line.replace("\t", " "); line = line.simplified(); QList<QByteArray> split = line.split(' '); bool ok; int b5 = split.at(0).toInt(&ok, 16); Q_ASSERT(ok); int uc = split.at(1).toInt(&ok, 16); Q_ASSERT(ok); if (b5 < 0x100) continue; #else QFile f(":/BIG5"); f.open(QFile::ReadOnly); while (!f.atEnd()) { QByteArray line = f.readLine(); if (line.startsWith("CHARMAP")) break; } QSet<uint> b5_ok; QSet<uint> uc_ok; QList<Map> b5_to_uc_map; QList<Map> uc_to_b5_map; while (!f.atEnd()) { QByteArray line = f.readLine(); if (line.startsWith("%")) continue; if (line.startsWith("END CHARMAP")) break; line.replace("/x", ""); line.replace("<U", ""); line.replace(">", ""); line.replace("\t", " "); line = line.simplified(); QList<QByteArray> split = line.split(' '); bool ok; int b5 = split.at(1).toInt(&ok, 16); Q_ASSERT(ok); int uc = split.at(0).toInt(&ok, 16); Q_ASSERT(ok); if (b5 < 0x100 || uc > 0xffff) continue; #endif // qDebug() << hex << "testing: '" << b5 << "' - '" << uc << "'"; QByteArray ba; ba += (char)(uchar)(b5 >> 8); ba += (char)(uchar)(b5 & 0xff); QString s = big5->toUnicode(ba); Q_ASSERT(s.length() == 1); QString s2; s2 = QChar(uc); ba = big5->fromUnicode(s2); Q_ASSERT(ba.length() <= 2); int round; if (ba.length() == 1) round = (int)(uchar)ba[0]; else round = ((int)(uchar)ba[0] << 8) + (int)(uchar)ba[1]; if (b5 != round) uc_to_b5_map += Map(uc, b5); else b5_ok.insert(b5); if (s[0].unicode() != uc) b5_to_uc_map += Map(uc, b5); else uc_ok.insert(uc); }; QList<QByteArray> list; foreach(Map m, b5_to_uc_map) { if (!uc_ok.contains(m.b5)) list += QByteArray(" { 0x" + QByteArray::number(m.b5, 16) + ", 0x" + QByteArray::number(m.uc, 16) + " }\n");; } QByteArray ba; qSort(list); foreach(QByteArray a, list) ba += a; qDebug() << "struct B5Map b5_to_uc_map = {\n" << ba + "\n};"; list = QList<QByteArray>(); foreach(Map m, uc_to_b5_map) if (!b5_ok.contains(m.uc)) list += QByteArray(" { 0x" + QByteArray::number(m.uc, 16) + ", 0x" + QByteArray::number(m.b5, 16) + " }\n");; ba = QByteArray(); qSort(list); foreach(QByteArray a, list) ba += a; qDebug() << "struct B5Map uc_to_b5_map = {\n" << ba + "\n};"; }
void QueryDB::execMainQuery( QueryResult& q_result ) { QString query ; QString logical_global ; if ( this->global_and ) logical_global = " AND " ; else logical_global = " OR " ; bool prevq = false ; query.append( " ( " ) ; if ( p_chiave ) { QString logical_at = " OR " ; QString logical = this->logical_titolo ; query.append( " ( " ) ; if ( parole_chiave.size() > 0 ) { query.append( "( " ) ; for ( QStringList::iterator it = parole_chiave.begin() ; it < parole_chiave.end() ; it++ ) { QString first_word , word , last_word ; first_word.append( *it ) ; first_word.append( " %" ) ; word.append("%") ; word.append(*it) ; word.append("%") ; last_word.append("% ") ; last_word.append(*it) ; query.append(" ( titolo like \"") ; query.append( first_word ) ; query.append( "\" or " ) ; query.append("titolo like \"") ; query.append( word ) ; query.append( "\" or " ) ; query.append("titolo like \"") ; query.append( last_word ) ; query.append( "\" ) " ) ; if ( it+1 != parole_chiave.end() ) query.append( logical ) ; } query.append( " ) " ) ; } else { query.append( "( titolo like null )" ) ; } query.append( logical_at ) ; if ( parole_chiave_abstract.size() > 0 ) { query.append( "( " ) ; for ( QStringList::iterator it = parole_chiave_abstract.begin() ; it < parole_chiave_abstract.end() ; it++ ) { QString first_word , word , last_word ; first_word.append( *it ) ; first_word.append( " %" ) ; word.append("%") ; word.append(*it) ; word.append("%") ; last_word.append("% ") ; last_word.append(*it) ; query.append(" ( abstract like \"") ; query.append( first_word ) ; query.append( "\" or " ) ; query.append("abstract like \"") ; query.append( word ) ; query.append( "\" or " ) ; query.append("abstract like \"") ; query.append( last_word ) ; query.append( "\" ) " ) ; if ( it+1 != parole_chiave_abstract.end() ) query.append( logical ) ; } query.append( " )" ) ; } else { query.append( "( abstract like null )" ) ; } query.append( " )" ) ; prevq = true ; } //list<string> lista_rubriche = this->getRubriche() ; if ( rubriche && lista_rubriche.size() > 0 ) { if ( prevq ) { query.append( logical_global ) ; prevq = false ; } query.append( " ( idrubrica in ( " ) ; query.append( " select id from rubriche where " ) ; for ( QStringList::iterator it = lista_rubriche.begin() ; it < lista_rubriche.end() ; it++ ) { query.append( " ( idrubrica in ( " ) ; query.append( " select id from rubriche where rubrica like \"" ); query.append( *it ) ; query.append( "\" ) ) " ) ; if ( it < lista_rubriche.end() - 1 ) { query.append( " OR " ) ; } } query.append( " ) ) " ) ; prevq = true ; } if ( categorie && lista_categorie.size() > 0 ) { if ( prevq ) { query.append( logical_global ) ; prevq = false ; } query.append( " ( articoli.id in ( " ) ; query.append( " select idarticolo from articoli_categorie where " ) ; for ( QStringList::iterator it = lista_categorie.begin() ; it < lista_categorie.end() ; it++ ) { query.append( " ( idcategoria in ( " ) ; query.append( " select id from categorie where categoria like \"" ); query.append( *it ) ; query.append( "\" ) ) " ) ; if ( it < lista_categorie.end() - 1 ) { query.append( " OR " ) ; } } query.append( " ) ) " ) ; prevq = true ; } if ( autori_l && lista_autori.size() > 0 ) { if ( prevq ) { query.append( logical_global ) ; prevq = false ; } query.append( " ( articoli.id in ( " ) ; query.append( " select idarticolo from articoli_autori where " ) ; for ( QStringList::iterator it = lista_autori.begin() ; it < lista_autori.end() ; it++ ) { query.append( " ( idautore in ( " ) ; query.append( " select id from autori where Autore like \"" ) ; query.append( *it ) ; query.append( "\" ) ) " ) ; if ( it < lista_autori.end() - 1 ) { query.append( " OR " ) ; } } query.append( " ) ) " ) ; prevq = true ; } if ( anno && lista_anni.size() > 0 ) { if ( prevq ) { query.append( logical_global ) ; prevq = false ; } typedef QPair<int,int> yearsInterval ; QList<yearsInterval> years ; int a1 , a2 ; qSort( lista_anni.begin() , lista_anni.end() , StrIntLessThan ) ; for ( QStringList::iterator it = lista_anni.begin() ; it < lista_anni.end() ; it++ ) { qDebug() << *it ; a1 = (*it).toInt() ; if ( it+1 < lista_anni.end() ) a2 = (*(it+1)).toInt() ; else a2 = a1 ; if ( ( a2 - a1 ) == 1 ) { int a3 = a1 ; int a4 ; QStringList::iterator it_b ; for ( it_b = it + 1 ; it_b < lista_anni.end() ; it_b++ ) { a4 = (*it_b).toInt() ; if ( a4 - a3 == 1 ) a3 = a4 ; else break ; } yearsInterval y_int ; y_int.first = a1 ; y_int.second = a3 ; years.append( y_int ); it = it_b-1 ; qDebug() << "Intervallo: " << a1 << " " << a3 ; } else { yearsInterval y_int ; y_int.first = a1 ; y_int.second = a1 ; years.append( y_int ); qDebug() << "Intervallo: " << a1 << " " << a1 ; } } query.append( " ( articoli.idrivista in ( " ) ; query.append( " select id from riviste where " ) ; for ( QList<yearsInterval>::iterator it = years.begin() ; it < years.end() ; it++ ) { query.append( " ( " ) ; query.append( " anno >= " ) ; query.append( QString::number( it->first ) ) ; query.append( " and anno <= " ) ; query.append( QString::number( it->second ) ) ; query.append( " ) " ) ; if ( it < years.end() - 1 ) { query.append( " or " ) ; } } query.append( " ) ) " ) ; prevq = true ; } if ( testo ) { if ( prevq ) { query.append( logical_global ) ; prevq = false ; } buildQuerySegTestoEsteso( query ) ; prevq = true ; } query.append( " ) " ) ; if ( fvorites_only ) { Bookmark bk ; QueryResult query_r ; bk.getFavorites( query_r ); if ( !query_r.empty() ) { query.append( " and articoli.id in ( " ) ; for( QueryResult::iterator itr = query_r.begin() ; itr < query_r.end() ; itr++ ) { query += query_r.getField( "IdEntry" , itr ) ; if ( itr < query_r.end() - 1 ) query += " , " ; } query.append( " ) " ) ; } } query.append( " ORDER BY idrivista" ) ; //query.prepend( "SELECT titolo,idRivista,id FROM articoli WHERE " ) ; query.prepend( "SELECT titolo,numero,articoli.id FROM articoli, riviste WHERE articoli.idrivista = riviste.id and " ) ; qDebug() << query ; q_result.clear() ; this->execQuery( this->dbPath , query , q_result ) ; //q_result.printResult() ; }
void LocalScene::populateTopRatedArtist(int YPos) { int artistRow = 0; int Column = 0; item_count = (parentView()->width()/160 > 2) ? parentView()->width()/160 : 2; int char_entry = 0; CategorieGraphicItem *category = new CategorieGraphicItem(qobject_cast<QGraphicsView*> (parentView())->viewport()); category->m_name = QString(tr("Top rated artists")); category->setPos(0 ,YPos); addItem(category); //! get artists List from LocalTrackModel QList<MEDIA::ArtistPtr> artists; for (int i=0 ; i < m_localTrackModel->rootItem()->childCount(); i++ ) { artists << MEDIA::ArtistPtr::staticCast(m_localTrackModel->rootItem()->child(i)); } //! sort qSort(artists.begin(), artists.end(), MEDIA::compareArtistItemRating); //! loop over artist MediaItem foreach(MEDIA::ArtistPtr artist, artists) { if(artist->rating == 0.0 || char_entry == MAX_CHART_ENTRY) break; if( !m_localTrackModel->isMediaMatch(artist) ) continue; ArtistGraphicItem_v3 *artist_item = new ArtistGraphicItem_v3(); artist_item->media = artist; artist_item->setPos(4+160*Column, YPos + 35 + artistRow*190); addItem(artist_item); char_entry++; /* ALBUM COVER LOOP */ artist_item->albums_covers.clear(); for(int j = artist->childCount()-1 ; j >= 0; j--) { if(!m_localTrackModel->isMediaMatch(artist->child(j)) ) continue; MEDIA::AlbumPtr album = MEDIA::AlbumPtr::staticCast(artist->child(j)); artist_item->albums_covers.prepend(album); /* WARNING limite de l'affichage à 6 cover max */ if(artist_item->albums_covers.size() >=6) break; } if(Column < (item_count-1)) { Column++; } else { Column = 0; artistRow++; } } //! si liste vide --> message if(char_entry==0) { InfoGraphicItem *info = new InfoGraphicItem(qobject_cast<QGraphicsView*> (parentView())->viewport()); info->_text = tr("No entry found"); info->setPos( 0 , YPos + 50); addItem(info); } }
double QgsComposerHtml::findNearbyPageBreak( double yPos ) { if ( !mWebPage || !mRenderedPage || !mUseSmartBreaks ) { return yPos; } //convert yPos to pixels int idealPos = yPos * htmlUnitsToMM(); //if ideal break pos is past end of page, there's nothing we need to do if ( idealPos >= mRenderedPage->height() ) { return yPos; } int maxSearchDistance = mMaxBreakDistance * htmlUnitsToMM(); //loop through all lines just before ideal break location, up to max distance //of maxSearchDistance int changes = 0; QRgb currentColor; bool currentPixelTransparent = false; bool previousPixelTransparent = false; QRgb pixelColor; QList< QPair<int, int> > candidates; int minRow = qMax( idealPos - maxSearchDistance, 0 ); for ( int candidateRow = idealPos; candidateRow >= minRow; --candidateRow ) { changes = 0; currentColor = qRgba( 0, 0, 0, 0 ); //check all pixels in this line for ( int col = 0; col < mRenderedPage->width(); ++col ) { //count how many times the pixels change color in this row //eventually, we select a row to break at with the minimum number of color changes //since this is likely a line break, or gap between table cells, etc //but very unlikely to be midway through a text line or picture pixelColor = mRenderedPage->pixel( col, candidateRow ); currentPixelTransparent = qAlpha( pixelColor ) == 0; if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) ) { //color has changed currentColor = pixelColor; changes++; } previousPixelTransparent = currentPixelTransparent; } candidates.append( qMakePair( candidateRow, changes ) ); } //sort candidate rows by number of changes ascending, row number descending qSort( candidates.begin(), candidates.end(), candidateSort ); //first candidate is now the largest row with smallest number of changes //ok, now take the mid point of the best candidate position //we do this so that the spacing between text lines is likely to be split in half //otherwise the html will be broken immediately above a line of text, which //looks a little messy int maxCandidateRow = candidates[0].first; int minCandidateRow = maxCandidateRow + 1; int minCandidateChanges = candidates[0].second; QList< QPair<int, int> >::iterator it; for ( it = candidates.begin(); it != candidates.end(); ++it ) { if (( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 ) { //no longer in a consecutive block of rows of minimum pixel color changes //so return the row mid-way through the block //first converting back to mm return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) / htmlUnitsToMM(); } minCandidateRow = ( *it ).first; } //above loop didn't work for some reason //return first candidate converted to mm return candidates[0].first / htmlUnitsToMM(); }
void LinePlotterWindow::plotSpectrLine(HyperCube *pCube, uint x1, uint x2, uint y1, uint y2, uint z1, uint z2) { m_customPlot->clearGraphs(); // только 1 график на виджете uint k = 1; int length = round (qSqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1)) / k); if (length == 0 || length == 1) { qDebug()<<"выберите точки, расположенные дальше друг от друга"; throw(GenericExc("Точки должны быть расположены дальше друг от друга")); return; } int* cordXarr = new int[length]; int* cordYarr = new int[length]; int* cordZarr = new int[length]; for (int i = 0; i<length; ++i) { cordXarr[i] = x1 + (double)((int)x2-(int)x1)/(length-1) * i; cordYarr[i] = y1 + (double)((int)y2-(int)y1)/(length-1) * i; cordZarr[i] = z1 +(double)((int)z2-(int)z1)/(length-1) * i; } QVector<double> plotXArr(length), plotYArr(length); quint16 Chnls = pCube->GetCountofChannels(); for (int i = 0; i<length; ++i) { qint16* pSpectrValues = new qint16[Chnls]; try{ pCube->GetSpectrumPoint(cordXarr[i], cordYarr[i],pSpectrValues); }catch(...) { qDebug()<<"не берет GetSpectrumPoint"; } plotYArr[i] = pSpectrValues[cordZarr[i]]; // эти три строчки можно заменить GetSpectrum1Point, если реализовать ее в гиперкубе plotXArr[i] = i; delete pSpectrValues; } delete cordXarr; delete cordYarr; delete cordZarr; QVector<double> sortedYArr; sortedYArr = plotYArr; qSort(sortedYArr); double minY = 70000, maxY = -10000; if (sortedYArr.first() < minY ) minY = sortedYArr.first(); if (sortedYArr.last() > maxY ) maxY = sortedYArr.last(); m_customPlot->setInteraction(QCP::iRangeDrag , true); m_customPlot->setInteraction(QCP::iRangeZoom , true); m_customPlot->addGraph(); m_customPlot->graph()->setPen(QPen(Qt::black)); m_customPlot->graph()->setData(plotXArr,plotYArr); m_customPlot->xAxis->setRange(plotXArr.first(),plotXArr.last()); m_customPlot->yAxis->setRange(minY,maxY); m_customPlot->legend->setVisible(true); m_customPlot->graph()->setName("Начало(X=" + QString::number(x1) +", Y="+ QString::number(y1) +", Z="+ QString::number(z1) + ")" +" Конец(X=" + QString::number(x2) +", Y="+ QString::number(y2) +", Z="+ QString::number(z2) + ")"); m_customPlot->xAxis->setLabel("Интервалы разбиения прямой"); m_customPlot->yAxis->setLabel("Яркость"); m_customPlot->replot(); }
void FileAnalyzer::run() { m_bSuccess.fetchAndStoreOrdered(0); m_tasksCounterNext = 0; m_tasksCounterDone = 0; m_completedCounter = 0; m_completedFiles.clear(); m_completedTaskIds.clear(); m_runningTaskIds.clear(); m_filesAccepted = 0; m_filesRejected = 0; m_filesDenied = 0; m_filesDummyCDDA = 0; m_filesCueSheet = 0; m_timer->invalidate(); //Sort files MUtils::natural_string_sort(m_inputFiles, true); //Handle playlist files first! handlePlaylistFiles(); const unsigned int nFiles = m_inputFiles.count(); if(nFiles < 1) { qWarning("File list is empty, nothing to do!"); return; } //Update progress emit progressMaxChanged(nFiles); emit progressValChanged(0); //Create the thread pool if (m_pool.isNull()) { m_pool.reset(new QThreadPool()); } //Update thread count const int idealThreadCount = QThread::idealThreadCount(); if(idealThreadCount > 0) { m_pool->setMaxThreadCount(qBound(2, ((idealThreadCount * 3) / 2), 12)); } //Start first N threads QTimer::singleShot(0, this, SLOT(initializeTasks())); //Start event processing this->exec(); //Wait for pending tasks to complete m_pool->waitForDone(); //Was opertaion aborted? if(MUTILS_BOOLIFY(m_bAborted)) { qWarning("Operation cancelled by user!"); return; } //Update progress emit progressValChanged(nFiles); //Emit pending files (this should not be required though!) if(!m_completedFiles.isEmpty()) { qWarning("FileAnalyzer: Pending file information found after last thread terminated!"); QList<unsigned int> keys = m_completedFiles.keys(); qSort(keys); while(!keys.isEmpty()) { emit fileAnalyzed(m_completedFiles.take(keys.takeFirst())); } } qDebug("All files added.\n"); m_bSuccess.fetchAndStoreOrdered(1); QThread::msleep(333); }
void SetList::sortByKey() { qSort(begin(), end(), CompareFunctor()); }
void PostedListWidget::applyRanking() { /* uses current settings to sort posts, then add to layout */ std::cerr << "PostedListWidget::applyRanking()"; std::cerr << std::endl; shallowClearPosts(); /* sort */ switch(mSortMethod) { default: case RsPosted::HotRankType: std::cerr << "PostedListWidget::applyRanking() HOT"; std::cerr << std::endl; qSort(mPostItems.begin(), mPostItems.end(), CmpPIHot); break; case RsPosted::NewRankType: std::cerr << "PostedListWidget::applyRanking() NEW"; std::cerr << std::endl; qSort(mPostItems.begin(), mPostItems.end(), CmpPINew); break; case RsPosted::TopRankType: std::cerr << "PostedListWidget::applyRanking() TOP"; std::cerr << std::endl; qSort(mPostItems.begin(), mPostItems.end(), CmpPITop); break; } mLastSortMethod = mSortMethod; std::cerr << "PostedListWidget::applyRanking() Sorted mPostList"; std::cerr << std::endl; /* go through list (skipping out-of-date items) to get */ QLayout *alayout = ui->scrollAreaWidgetContents->layout(); int counter = 0; time_t min_ts = 0; foreach (PostedItem *item, mPostItems) { std::cerr << "PostedListWidget::applyRanking() Item: " << item; std::cerr << std::endl; if (item->getPost().mMeta.mPublishTs < min_ts) { std::cerr << "\t Skipping OLD"; std::cerr << std::endl; item->hide(); continue; } if (counter >= mPostIndex + mPostShow) { std::cerr << "\t END - Counter too high"; std::cerr << std::endl; item->hide(); } else if (counter >= mPostIndex) { std::cerr << "\t Adding to Layout"; std::cerr << std::endl; /* add it in! */ alayout->addWidget(item); item->show(); } else { std::cerr << "\t Skipping to Low"; std::cerr << std::endl; item->hide(); } ++counter; }
//! Set the color map to be used. void medImageMaskAnnotationData::setColorMap( const ColorMapType & colorMap ) { m_colorMap = colorMap; qSort( m_colorMap ); }
QString ToolTipFiller::filterActionTipContents(const FilterAction& action) { if (action.isNull()) { return QString(); } QString str; DToolTipStyleSheet cnt(ApplicationSettings::instance()->getToolTipsFont()); QString tip = cnt.tipHeader; tip += cnt.headBeg + i18n("Filter") + cnt.headEnd; // Displayable name tip += cnt.cellBeg + i18n("Name:") + cnt.cellMid + DImgFilterManager::instance()->i18nDisplayableName(action) + cnt.cellEnd; // Category QString reproducible("---"); switch (action.category()) { case FilterAction::ReproducibleFilter: reproducible = i18nc("Image filter reproducible: Yes", "Yes"); break; case FilterAction::ComplexFilter: reproducible = i18nc("Image filter reproducible: Partially", "Partially"); break; case FilterAction::DocumentedHistory: reproducible = i18nc("Image filter reproducible: No", "No"); break; default: break; }; tip += cnt.cellBeg + i18n("Reproducible:") + cnt.cellMid + reproducible + cnt.cellEnd; // Description str = action.description(); if (str.isEmpty()) { str = QString("---"); } tip += cnt.cellSpecBeg + i18nc("Image filter description", "Description:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; // Identifier + version tip += cnt.cellBeg + i18n("Identifier:") + cnt.cellMid + action.identifier() + " (v" + QString::number(action.version()) + ") " + cnt.cellEnd; if (action.hasParameters()) { tip += cnt.headBeg + i18n("Technical Parameters") + cnt.headEnd; const QHash<QString, QVariant>& params = action.parameters(); QList<QString> keys = params.keys(); qSort(keys); foreach(const QString& key, keys) { QHash<QString, QVariant>::const_iterator it; for (it = params.find(key); it != params.end() && it.key() == key; ++it) { if (it.key().isEmpty() || !it.value().isValid()) { continue; } if (it.key().startsWith(QLatin1String("curveData"))) { str = i18n("<i>Binary Data</i>"); } else { str = it.value().toString(); } if (str.length() > cnt.maxStringLength) { str = cnt.elidedText(str, Qt::ElideRight); } QString key = it.key(); QChar first = key.at(0); if (first.isLower()) { key.replace(0, 1, first.toUpper()); } tip += cnt.cellBeg + key + cnt.cellMid + str + cnt.cellEnd; } }
void OsmAnd::ObfPoiSectionReader_P::readAmenities( const ObfReader_P& reader, const std::shared_ptr<const ObfPoiSectionInfo>& section, QSet<uint32_t>* desiredCategories, QList< std::shared_ptr<const Amenity> >* amenitiesOut, const ZoomLevel zoom, uint32_t zoomDepth, const AreaI* bbox31, std::function<bool (std::shared_ptr<const Amenity>)> visitor, const IQueryController* const controller) { const auto cis = reader.getCodedInputStream().get(); QList< std::shared_ptr<Tile> > tiles; for(;;) { const auto tag = cis->ReadTag(); switch(gpb::internal::WireFormatLite::GetTagFieldNumber(tag)) { case 0: if (!ObfReaderUtilities::reachedDataEnd(cis)) return; return; case OBF::OsmAndPoiIndex::kBoxesFieldNumber: { const auto length = ObfReaderUtilities::readBigEndianInt(cis); const auto offset = cis->CurrentPosition(); const auto oldLimit = cis->PushLimit(length); readTile(reader, section, tiles, nullptr, desiredCategories, zoom, zoomDepth, bbox31, controller, nullptr); ObfReaderUtilities::ensureAllDataWasRead(cis); cis->PopLimit(oldLimit); if (controller && controller->isAborted()) return; } break; case OBF::OsmAndPoiIndex::kPoiDataFieldNumber: { // Sort tiles byte data offset, to all cache-friendly with I/O system qSort(tiles.begin(), tiles.end(), [](const std::shared_ptr<Tile>& l, const std::shared_ptr<Tile>& r) -> bool { return l->_hash < r->_hash; }); for(const auto& tile : constOf(tiles)) { cis->Seek(section->_offset + tile->_offset); const auto length = ObfReaderUtilities::readBigEndianInt(cis); const auto offset = cis->CurrentPosition(); const auto oldLimit = cis->PushLimit(length); readAmenitiesFromTile(reader, section, tile.get(), desiredCategories, amenitiesOut, zoom, zoomDepth, bbox31, visitor, controller, nullptr); ObfReaderUtilities::ensureAllDataWasRead(cis); cis->PopLimit(oldLimit); if (controller && controller->isAborted()) return; } cis->Skip(cis->BytesUntilLimit()); } return; default: ObfReaderUtilities::skipUnknownField(cis, tag); break; } } }
void UpdateChecker::resultReceiver(QString data) { QDomDocument xml; qDebug() << data; xml.setContent(data); QDomElement productxml = xml.firstChildElement("product"); if (productxml.isNull()) { QMessageBox::critical(NULL, tr("Error"), tr("Could not check for updates. Wrong server response.")); inProgress = false; return; } QDomElement urlxml = productxml.firstChildElement("url"); QString url = urlxml.text(); QDomNodeList versionsx = xml.elementsByTagName("version"); if (versionsx.length()==0) { QMessageBox::critical(NULL, tr("Error"), tr("Could not check for updates. No versions found.")); inProgress = false; return; } QString platform; #ifdef Q_OS_WIN platform = "WIN"; #endif #ifdef Q_OS_MAC platform = "MAC"; #endif if (platform.isEmpty()) platform = "UNIX"; QStringList versions; QMap<QString, QUrl> urls; for(unsigned int i=0; i<versionsx.length(); i++) { QDomNode version = versionsx.at(i); QDomNode platformx = version.attributes().namedItem("platform"); if (platformx.isNull()) continue; QString vpl = platformx.nodeValue(); if ((vpl != platform) && (vpl != "ALL")) continue; QString ver = version.attributes().namedItem("id").nodeValue(); versions.append(ver); QDomElement xurl = version.toElement().firstChildElement("url"); urls[ver] = QUrl(xurl.text()); } if (!versions.size()) { if (!workSilent) QMessageBox::information(NULL, tr("No updates available"), tr("You have the latest version of this application.")); inProgress = false; return; } qSort( versions.begin(), versions.end(), versionCompare); // I should write Version class with right compare QString version = versions.first(); // operator and use QMap's auto sorting. if (versionCompare(version, QApplication::applicationVersion())) { QMessageBox msg; msg.addButton(tr("Yes"), QMessageBox::YesRole); msg.addButton(tr("No"), QMessageBox::NoRole); msg.setText(tr("Lastest version is %1. Do you want to update?").arg(version)); msg.setWindowTitle(tr("Update available")); msg.exec(); if (msg.buttonRole(msg.clickedButton()) == QMessageBox::YesRole) { QDesktopServices().openUrl(urls[version]); } } else { if (!workSilent) { QMessageBox::information(NULL, tr("No updates available"), tr("You have the latest version of this application.")); } } inProgress = false; }
QgsDelimitedTextFeatureIterator::QgsDelimitedTextFeatureIterator( QgsDelimitedTextFeatureSource* source, bool ownSource, const QgsFeatureRequest& request ) : QgsAbstractFeatureIteratorFromSource<QgsDelimitedTextFeatureSource>( source, ownSource, request ) , mTestGeometryExact( false ) { // Determine mode to use based on request... QgsDebugMsg( "Setting up QgsDelimitedTextIterator" ); // Does the layer have geometry - will revise later to determine if we actually need to // load it. bool hasGeometry = mSource->mGeomRep != QgsDelimitedTextProvider::GeomNone; // Does the layer have an explicit or implicit subset (implicit subset is if we have geometry which can // be invalid) mTestSubset = mSource->mSubsetExpression; mTestGeometry = false; mMode = FileScan; if ( !request.filterRect().isNull() && hasGeometry ) { QgsDebugMsg( "Configuring for rectangle select" ); mTestGeometry = true; // Exact intersection test only applies for WKT geometries mTestGeometryExact = mRequest.flags() & QgsFeatureRequest::ExactIntersect && mSource->mGeomRep == QgsDelimitedTextProvider::GeomAsWkt; QgsRectangle rect = request.filterRect(); // If request doesn't overlap extents, then nothing to return if ( ! rect.intersects( mSource->mExtent ) ) { QgsDebugMsg( "Rectangle outside layer extents - no features to return" ); mMode = FeatureIds; } // If the request extents include the entire layer, then revert to // a file scan else if ( rect.contains( mSource->mExtent ) ) { QgsDebugMsg( "Rectangle contains layer extents - bypass spatial filter" ); mTestGeometry = false; } // If we have a spatial index then use it. The spatial index already accounts // for the subset. Also means we don't have to test geometries unless doing exact // intersection else if ( mSource->mUseSpatialIndex ) { mFeatureIds = mSource->mSpatialIndex->intersects( rect ); // Sort for efficient sequential retrieval qSort( mFeatureIds.begin(), mFeatureIds.end() ); QgsDebugMsg( QString( "Layer has spatial index - selected %1 features from index" ).arg( mFeatureIds.size() ) ); mMode = FeatureIds; mTestSubset = false; mTestGeometry = mTestGeometryExact; } } if ( request.filterType() == QgsFeatureRequest::FilterFid ) { QgsDebugMsg( "Configuring for returning single id" ); if ( request.filterRect().isNull() || mFeatureIds.contains( request.filterFid() ) ) { mFeatureIds = QList<QgsFeatureId>() << request.filterFid(); } mMode = FeatureIds; mTestSubset = false; } // If have geometry and testing geometry then evaluate options... // If we don't have geometry then all records pass geometry filter. // CC: 2013-05-09 // Not sure about intended relationship between filtering on geometry and // requesting no geometry? Have preserved current logic of ignoring spatial filter // if not requesting geometry. else // If we have a subset index then use it.. if ( mMode == FileScan && mSource->mUseSubsetIndex ) { QgsDebugMsg( QString( "Layer has subset index - use %1 items from subset index" ).arg( mSource->mSubsetIndex.size() ) ); mTestSubset = false; mMode = SubsetIndex; } // Otherwise just have to scan the file if ( mMode == FileScan ) { QgsDebugMsg( "File will be scanned for desired features" ); } // If the layer has geometry, do we really need to load it? // We need it if it is asked for explicitly in the request, // if we are testing geometry (ie spatial filter), or // if testing the subset expression. if ( hasGeometry && ( !( mRequest.flags() & QgsFeatureRequest::NoGeometry ) || mTestGeometry || ( mTestSubset && mSource->mSubsetExpression->needsGeometry() ) ) ) { mLoadGeometry = true; } else { QgsDebugMsgLevel( "Feature geometries not required", 4 ); mLoadGeometry = false; } QgsDebugMsg( QString( "Iterator is scanning file: " ) + ( mMode == FileScan ? "Yes" : "No" ) ); QgsDebugMsg( QString( "Iterator is loading geometries: " ) + ( mLoadGeometry ? "Yes" : "No" ) ); QgsDebugMsg( QString( "Iterator is testing geometries: " ) + ( mTestGeometry ? "Yes" : "No" ) ); QgsDebugMsg( QString( "Iterator is testing subset: " ) + ( mTestSubset ? "Yes" : "No" ) ); rewind(); }
QList<T> sorted(const QList<T> &list) { QList<T> res = list; qSort(res); return res; }
QGradientStops SplineInformation::interpolateGradientStops(QGradientStops stops1, QGradientStops stops2, float frc) { QVector<float> pos; for(int i=0; i<stops1.size(); i++) pos.append(stops1[i].first); for(int i=0; i<stops2.size(); i++) { float pos2 = stops2[i].first; bool flag = true; for(int j=0; j<stops1.size(); j++) { if (fabs(pos[j] - pos2) < 0.0001) { flag = false; break; } } if (flag) pos.append(pos2); } qSort(pos.begin(), pos.end()); QGradientStops gradStops1 = StaticFunctions::resampleGradientStops(stops1); QGradientStops gradStops2 = StaticFunctions::resampleGradientStops(stops2); QGradientStops gradStops; int gsize = gradStops1.size()-1; for(int i=0; i<pos.size(); i++) { int idx = pos[i]*gsize; QColor color1 = gradStops1[idx].second; QColor color2 = gradStops2[idx].second; // linear interpolation of colors float rb,gb,bb,ab, re,ge,be,ae; rb = color1.red(); gb = color1.green(); bb = color1.blue(); ab = color1.alpha(); re = color2.red(); ge = color2.green(); be = color2.blue(); ae = color2.alpha(); float r,g,b,a; r = rb + frc*(re-rb); g = gb + frc*(ge-gb); b = bb + frc*(be-bb); a = ab + frc*(ae-ab); QColor color = QColor(r,g,b,a); gradStops << QGradientStop(pos[i], color); } return gradStops; }