void ContentBlockingInformationWidget::populateElementsMenu() { m_elementsMenu->clear(); if (!m_window) { return; } const QVector<NetworkManager::ResourceInformation> requests(m_window->getContentsWidget()->getBlockedRequests().mid(m_amount - 50)); for (int i = 0; i < requests.count(); ++i) { QString type; switch (requests.at(i).resourceType) { case NetworkManager::MainFrameType: type = tr("main frame"); break; case NetworkManager::SubFrameType: type = tr("subframe"); break; case NetworkManager::StyleSheetType: type = tr("stylesheet"); break; case NetworkManager::ScriptType: type = tr("script"); break; case NetworkManager::ImageType: type = tr("image"); break; case NetworkManager::ObjectType: type = tr("object"); break; case NetworkManager::ObjectSubrequestType: type = tr("object subrequest"); break; case NetworkManager::XmlHttpRequestType: type = tr("XHR"); break; case NetworkManager::WebSocketType: type = tr("WebSocket"); break; default: type = tr("other"); break; } QAction *action(m_elementsMenu->addAction(QStringLiteral("%1\t [%2]").arg(Utils::elideText(requests.at(i).url.toString(), m_elementsMenu)).arg(type))); action->setStatusTip(requests.at(i).url.toString()); } }
QTextHtmlImporter::Table QTextHtmlImporter::scanTable(int tableNodeIdx) { Table table; table.columns = 0; QVector<QTextLength> columnWidths; int tableHeaderRowCount = 0; QVector<int> rowNodes; rowNodes.reserve(at(tableNodeIdx).children.count()); foreach (int row, at(tableNodeIdx).children) switch (at(row).id) { case Html_tr: rowNodes += row; break; case Html_thead: case Html_tbody: case Html_tfoot: foreach (int potentialRow, at(row).children) if (at(potentialRow).id == Html_tr) { rowNodes += potentialRow; if (at(row).id == Html_thead) ++tableHeaderRowCount; } break; default: break; } QVector<RowColSpanInfo> rowColSpans; QVector<RowColSpanInfo> rowColSpanForColumn; int effectiveRow = 0; foreach (int row, rowNodes) { int colsInRow = 0; foreach (int cell, at(row).children) if (at(cell).isTableCell()) { // skip all columns with spans from previous rows while (colsInRow < rowColSpanForColumn.size()) { const RowColSpanInfo &spanInfo = rowColSpanForColumn[colsInRow]; if (spanInfo.row + spanInfo.rowSpan > effectiveRow) { Q_ASSERT(spanInfo.col == colsInRow); colsInRow += spanInfo.colSpan; } else break; } const QTextHtmlParserNode &c = at(cell); const int currentColumn = colsInRow; colsInRow += c.tableCellColSpan; RowColSpanInfo spanInfo; spanInfo.row = effectiveRow; spanInfo.col = currentColumn; spanInfo.colSpan = c.tableCellColSpan; spanInfo.rowSpan = c.tableCellRowSpan; if (spanInfo.colSpan > 1 || spanInfo.rowSpan > 1) rowColSpans.append(spanInfo); columnWidths.resize(qMax(columnWidths.count(), colsInRow)); rowColSpanForColumn.resize(columnWidths.size()); for (int i = currentColumn; i < currentColumn + c.tableCellColSpan; ++i) { if (columnWidths.at(i).type() == QTextLength::VariableLength) columnWidths[i] = c.width; rowColSpanForColumn[i] = spanInfo; } } table.columns = qMax(table.columns, colsInRow); ++effectiveRow; }
answersDialog::answersDialog(QWidget *parent, const QVector<userAnswer> &userAnswers, const QString &question, int correctAnswers) : QDialog(parent) { setWindowTitle(i18n("Your Answers Were")); QVBoxLayout *mainLayout = new QVBoxLayout; p_scrollArea = new QScrollArea(this); mainLayout->addWidget(p_scrollArea); p_container = new QWidget(this); p_scrollArea -> setWidget(p_container); p_scrollArea -> setWidgetResizable(true); uint totalAnswers = userAnswers.count(); QGridLayout *gridLayout = new QGridLayout(p_container); int spacing = gridLayout -> spacing(); gridLayout -> setSpacing(0); gridLayout -> setColumnStretch(0, 1); gridLayout -> setColumnStretch(4, 1); gridLayout -> setRowStretch(totalAnswers + 4, 1); p_container->setLayout(gridLayout); QFont titleFont = p_container -> font(); titleFont.setPointSize(24); QLabel *titleLabel = new QLabel(question); titleLabel -> setFont(titleFont); gridLayout -> addWidget(titleLabel, 0, 0, 1, 5, Qt::AlignHCenter); QLabel *correctAnswersInfoLabel = new QLabel(i18n("You answered correctly %1 out of %2 questions.", correctAnswers, totalAnswers)); correctAnswersInfoLabel -> setAlignment(Qt::AlignCenter); gridLayout -> addWidget(correctAnswersInfoLabel, 1, 0, 1, 5); QFont headerFont = p_container -> font(); headerFont.setBold(true); QLabel *questionHeaderLabel = new QLabel(i18n("Question")); questionHeaderLabel -> setFont(headerFont); questionHeaderLabel -> setMargin(spacing); gridLayout->addWidget(questionHeaderLabel, 2, 1); QLabel *userAnswerHeaderLabel = new QLabel(i18n("Your Answer")); userAnswerHeaderLabel -> setFont(headerFont); userAnswerHeaderLabel -> setMargin(spacing); gridLayout->addWidget(userAnswerHeaderLabel, 2, 2); QLabel *correctAnswerHeaderLabel = new QLabel(i18n("Correct Answer")); correctAnswerHeaderLabel -> setFont(headerFont); correctAnswerHeaderLabel -> setMargin(spacing); gridLayout->addWidget(correctAnswerHeaderLabel, 2, 3); for(uint i = 0; i < totalAnswers; i++) { userAnswers[i].putWidgets(p_container, gridLayout, i + 3, spacing); } QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); connect(buttonBox, &QDialogButtonBox::accepted, this, &answersDialog::accept); mainLayout->addWidget(buttonBox); setLayout(mainLayout); resize(500, 500); }
void AppearancePreferences::reset() { QSettings settings; // Empty this _ui->programTokenTable->clear(); // Declare some variables which will be used to populate the table QTextCharFormat format; QTableWidgetItem *item; int row = 0; int column = 0; QStringList headers; headers << "Token" << "Font" << "Foreground" << "Background"; _ui->programTokenTable->setHorizontalHeaderLabels(headers); QVector<int> tokens; // Default, identifiers, declaration identifiers, operators, keywords, // comments and errors tokens << ProgramLexeme_Default << ProgramLexeme_Identifier << ProgramLexeme_Declaration << ProgramLexeme_DeclarationOperator << ProgramLexeme_Keyword << ProgramLexeme_Comment << ProgramLexeme_Error; _ui->programTokenTable->setRowCount(tokens.count()); for(row = 0; row < tokens.count(); ++row) { format = _ui->plainTextEdit->highlighter()->format(tokens.at(row)); for(column = 0; column < 4; ++column) { item = new QTableWidgetItem(); switch(column) { case 0: // The name of this token type switch(tokens.at(row)) { case ProgramLexeme_Default: item->setText("Default"); break; case ProgramLexeme_Identifier: item->setText("Identifiers"); break; case ProgramLexeme_Declaration: item->setText("Macro Declarations"); break; case ProgramLexeme_DeclarationOperator: item->setText("Operators"); break; case ProgramLexeme_Keyword: item->setText("Keywords"); break; case ProgramLexeme_Comment: item->setText("Comments"); break; case ProgramLexeme_Error: item->setText("Errors"); break; default: qDebug() << "Unknown token type encountered in " "AppearancePreferences::reset(), passed " << tokens.at(row); break; } item->setFlags(Qt::ItemIsSelectable); item->setFont(format.font()); item->setForeground(format.foreground()); item->setBackground(format.background()); break; case 1: // The font item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); item->setText(format.font().family() + ", " + QVariant(format.fontPointSize()).toString()); break; case 2: // The foreground colour item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled); item->setText(QVariant(format.foreground().color()).toString()); break; case 3: // The background colour item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled); item->setText(QVariant(format.background().color()).toString()); break; default: qDebug() << "Unexpected column ID in " "AppearancePreferences::reset(), passed " << column; break; } _ui->programTokenTable->setItem(row, column, item); } } // Now have the table rejig to fit the items it now contains _ui->programTokenTable->resizeColumnsToContents(); }
void Plotter::drawCurves(QPainter *painter) { //printf("Inside DrawCurves\n"); static const QColor colorForIds[7] = {Qt::red,Qt::green,Qt::cyan,Qt::magenta,Qt::yellow,Qt::blue,Qt::white}; PlotSettings settings = zoomStack[curZoom]; if( m_moveFlag == true) { settings.maxX = m_ZoomSettings->maxX; settings.maxY = m_ZoomSettings->maxY; settings.minX = m_ZoomSettings->minX; settings.minY = m_ZoomSettings->minY; settings.m_nOffset = m_ZoomSettings->m_nOffset; settings.numXTicks = m_ZoomSettings->numXTicks; settings.numYTicks = m_ZoomSettings->numYTicks; } QRect rect(Margin,Margin,width()-(2*Margin),height()-(2*Margin)); //qDebug()<<"Draw Curves:"<< settings.m_nOffset; if(m_bshowZoomRect == true) { painter->setPen(colorForIds[6]); painter->drawRect(rubberBandRect); } if(!rect.isValid()) return; painter->setClipRect(rect.adjusted(+1,+1,-1,-1)); QMapIterator<int, QVector<QPointF> > i(curveMap); // printf("Rect Left: %d\n",rect.left()); // printf("Rect Height: %d\n",rect.height()); // printf("Rect width: %d\n",rect.width()); // printf("Rect Bottom: %d\n",rect.bottomLeft().y()); // printf("Rect Top: %d\n",rect.top()); double dx,dy; while(i.hasNext()){ i.next(); int id = i.key(); QVector<QPointF> data = i.value(); QPolygonF polyline(data.count()); double y =0.0,x=0.0; int l_nCounter =0; //printf("MinY:%f\n",settings.minY); //printf("Offset:%f\n",m_nOffset); for(int j=0; j< data.count();++j) { dx = data[j].x(); dy = data[j].y(); if(m_bUniPolar == true) { float l_nDiv = (dy/2.0); printf("UniPolar %f->%f\n",l_nDiv,dy - l_nDiv); } if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX)) { //printf("X:%f Y:%f\n",dx,dy); } y =0.0,x=0.0; if(m_ZoomFlag == false) { if(m_bVIMode == true) x = (rect.width()/2+ (dx*(((rect.width()-1)))/(settings.spanX()))); else x = (rect.left()+ (dx*(((rect.width()-1)))/(settings.spanX()))); if( m_bUniPolar == true){ y = ((Margin+rect.bottom()) - (((dy/2.0)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY()))); printf(" Coord-Y %f\n",dy/2.0); } else y = ((Margin+rect.height()) - (((dy-settings.minY)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY()))); //y = ((Margin+rect.height()/2) - ((dy*rect.height()-1)/4.096));/*((rect.height()-1))));*/ //y = (Margin+rect.height()/2) - (dy); // printf(" Coord- X & Y %f %f\n",x,y); // qDebug() << dy; } else if(m_ZoomFlag == true) { x = (rect.left() + ((dx-settings.minX)*(((rect.width()-1)))/(settings.spanX()))); y = ((Margin+rect.height()) - (((dy-settings.minY)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY()))); } if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX)&&(( data[j].y()>=settings.minY && data[j].y()<=settings.maxY))) { polyline[j] = QPointF(x,y); l_nCounter++; } } QPolygonF zoomPolyline(l_nCounter); y =0.0,x=0.0; int l_nIndex1 =0; for(int l_nIndex=0;l_nIndex< data.count();l_nIndex++) { QPointF(x,y); x = polyline.at(l_nIndex).x(); y = polyline.at(l_nIndex).y(); if(x!=0.0 || y!=0.0 ) { zoomPolyline[l_nIndex1] = QPointF(x,y); l_nIndex1++; } } painter->setPen(colorForIds[uint(id) %6]); if(m_ZoomFlag == false) painter->drawPolyline(polyline); else painter->drawPolyline(zoomPolyline); } }
/** * \brief Ctor */ ColumnReplaceValuesCmd::ColumnReplaceValuesCmd(ColumnPrivate * col, int first, const QVector<double>& new_values, QUndoCommand * parent ) : QUndoCommand( parent ), m_col(col), m_first(first), m_new_values(new_values) { setText(i18n("%1: replace the values for rows %2 to %3", col->name(), first, first + new_values.count() -1)); m_copied = false; }
/*! \reimp */ void QBoxLayout::setGeometry(const QRect &r) { Q_D(QBoxLayout); if (d->dirty || r != geometry()) { QRect oldRect = geometry(); QLayout::setGeometry(r); if (d->dirty) d->setupGeom(); QRect cr = alignment() ? alignmentRect(r) : r; int left, top, right, bottom; d->effectiveMargins(&left, &top, &right, &bottom); QRect s(cr.x() + left, cr.y() + top, cr.width() - (left + right), cr.height() - (top + bottom)); QVector<QLayoutStruct> a = d->geomArray; int pos = horz(d->dir) ? s.x() : s.y(); int space = horz(d->dir) ? s.width() : s.height(); int n = a.count(); if (d->hasHfw && !horz(d->dir)) { for (int i = 0; i < n; i++) { QBoxLayoutItem *box = d->list.at(i); if (box->item->hasHeightForWidth()) { int width = qBound(box->item->minimumSize().width(), s.width(), box->item->maximumSize().width()); a[i].sizeHint = a[i].minimumSize = box->item->heightForWidth(width); } } } Direction visualDir = d->dir; QWidget *parent = parentWidget(); if (parent && parent->isRightToLeft()) { if (d->dir == LeftToRight) visualDir = RightToLeft; else if (d->dir == RightToLeft) visualDir = LeftToRight; } qGeomCalc(a, 0, n, pos, space); bool reverse = (horz(visualDir) ? ((r.right() > oldRect.right()) != (visualDir == RightToLeft)) : r.bottom() > oldRect.bottom()); for (int j = 0; j < n; j++) { int i = reverse ? n-j-1 : j; QBoxLayoutItem *box = d->list.at(i); switch (visualDir) { case LeftToRight: box->item->setGeometry(QRect(a.at(i).pos, s.y(), a.at(i).size, s.height())); break; case RightToLeft: box->item->setGeometry(QRect(s.left() + s.right() - a.at(i).pos - a.at(i).size + 1, s.y(), a.at(i).size, s.height())); break; case TopToBottom: box->item->setGeometry(QRect(s.x(), a.at(i).pos, s.width(), a.at(i).size)); break; case BottomToTop: box->item->setGeometry(QRect(s.x(), s.top() + s.bottom() - a.at(i).pos - a.at(i).size + 1, s.width(), a.at(i).size)); } } } }
//The function receives the data from Add Filter and filters the data. The filtered sheet is then used to further processing Sheet* PivotMain::filter() { Sheet *const sheet1 = d->selection->lastSheet(); const QRect range2 = d->selection->lastRange(); Map *mymap=sheet1->map(); Sheet* sheet2=mymap->createSheet("Filtered Sheet"); int r= range2.right(); int b=range2.bottom(); int row=range2.top(); QVector<QString> vect; QVector<int> filtered; if(d->filterVect.count()<3) return sheet1; for(int k=row+1;k<=b;k++) { bool pass=true; if(d->filterVect.count()==3) { pass=checkCondition(d->filterVect.at(0),d->filterVect.at(1),d->filterVect.at(2),k); } else if(d->filterVect.count()==7) { if(d->filterVect.at(3)=="And") pass= checkCondition(d->filterVect.at(0),d->filterVect.at(1),d->filterVect.at(2),k) && checkCondition(d->filterVect.at(4),d->filterVect.at(5),d->filterVect.at(6),k); if(d->filterVect.at(3)=="Or") pass= checkCondition(d->filterVect.at(0),d->filterVect.at(1),d->filterVect.at(2),k) || checkCondition(d->filterVect.at(4),d->filterVect.at(5),d->filterVect.at(6),k); } else if(d->filterVect.count()==11) { if(d->filterVect.at(3)=="And") pass= checkCondition(d->filterVect.at(0),d->filterVect.at(1),d->filterVect.at(2),k) && checkCondition(d->filterVect.at(4),d->filterVect.at(5),d->filterVect.at(6),k); if(d->filterVect.at(3)=="Or") pass= checkCondition(d->filterVect.at(0),d->filterVect.at(1),d->filterVect.at(2),k) || checkCondition(d->filterVect.at(4),d->filterVect.at(5),d->filterVect.at(6),k); if(d->filterVect.at(7)=="And") pass= pass && checkCondition(d->filterVect.at(9),d->filterVect.at(10),d->filterVect.at(11),k); if(d->filterVect.at(7)=="Or") pass= pass || checkCondition(d->filterVect.at(4),d->filterVect.at(5),d->filterVect.at(6),k); } if(pass==true) filtered.append(k); } for(int j=1;j<=r;j++) Cell(sheet2,j,1).setValue(Cell(sheet1,j,1).value()); for(int i=0;i<filtered.count();i++) { for(int j=1;j<=r;j++) { Cell(sheet2,j,i+2).setValue(Cell(sheet1,j,filtered.at(i)).value()); } } d->filtersize=filtered.count()+1; return sheet2; }
//The core function which summarizes the data and forms the pivot table. void PivotMain::Summarize() { Map* myMap = d->selection->lastSheet()->map(); const QRect range3=d->selection->lastRange(); Sheet* sheet=myMap->createSheet("Filtered Sheet"); sheet=filter(); if(sheet==d->selection->lastSheet()) { d->filtersize=range3.bottom(); } const QRect range(1,1,d->selection->lastRange().right(),d->filtersize); QColor color,color2("lightGray"); color.setBlue(50); QPen pen(color); Style st,st2,st3,str,stl,stb,stt; st.setFontUnderline(true); st3.setBackgroundColor("lightGray"); st.setRightBorderPen(pen); st.setLeftBorderPen(pen); st.setTopBorderPen(pen); st.setBottomBorderPen(pen); str.setRightBorderPen(pen); stl.setLeftBorderPen(pen); stt.setTopBorderPen(pen); stb.setBottomBorderPen(pen); static int z=1; Sheet* mySheet=myMap->createSheet("Pivot Sheet"+QString::number(z++)); int r = range.right(); int row=range.top(); int bottom=range.bottom(); Cell cell; ValueConverter *c; Value res(0); ValueCalc *calc= new ValueCalc(c); QVector<Value> vect; for (int i = 1; i <= r; ++i) { cell= Cell(sheet,i,row); vect.append(Value(cell.value())); } d->func=d->mainWidget.selectOption->currentText();//check for the function to be performed //For Creating QLists for Rows,Columns,Values and PageField int counter; QListWidgetItem *item1; QList<QListWidgetItem *> rowList,columnList,valueList,pageList; counter= d->mainWidget.Rows->count(); for(int i=0;i<counter;i++) { item1=d->mainWidget.Rows->item(i); rowList.append(item1); } counter= d->mainWidget.Columns->count(); for(int i=0;i<counter;i++) { item1=d->mainWidget.Columns->item(i); columnList.append(item1); } /*counter= d->mainWidget.PageFields->count(); for(int i=0;i<counter;i++) { item1=d->mainWidget.PageFields->item(i); pageList.append(item1); }*/ counter= d->mainWidget.Values->count(); for(int i=0;i<counter;i++) { item1=d->mainWidget.Values->item(i); valueList.append(item1); } //Summarization using vectors int rowpos=-1,colpos=-1,valpos=-1; QVector<Value> rowVector; QVector<QVector<Value> > rowVectorArr(rowList.size()); QVector<QVector<Value> > columnVectorArr(columnList.size()); QVector<Value> columnVector,valueVector; QVector<int> rowposVect,colposVect,valposVect; for(int i=0;i<rowList.size();i++) { rowpos=vect.indexOf(Value(rowList.at(i)->text())); for(int j=row+1;j<=bottom;j++) { cell =Cell(sheet,rowpos+1,j); if(rowVector.contains(Value(cell.value()))==0) { rowVector.append(Value(cell.value())); rowVectorArr[i].append(Value(cell.value())); } } rowposVect.append(rowpos); } for(int i=0;i<columnList.size();i++) { colpos=vect.indexOf(Value(columnList.at(i)->text())); for(int j=row+1;j<=bottom;j++) { cell =Cell(sheet,colpos+1,j); if(columnVector.contains(Value(cell.value()))==0) { columnVector.append(Value(cell.value())); columnVectorArr[i].append(Value(cell.value())); } } colposVect.append(colpos); } int count=1,count2=0,prevcount=1; QVector<QVector<Value> > rowVect(rowposVect.count()); for(int i=0;i<rowposVect.count();i++) { for(int j=i+1;j<rowposVect.count();j++) { count*=rowVectorArr[j].count(); } for(int k=0;k<(rowVectorArr[i].count())*prevcount;k++) { Cell(mySheet,((k)*count)+1+colposVect.count(),i+1).setValue(rowVectorArr[i].at(k%rowVectorArr[i].count())); for(int l=0;l<count;l++) rowVect[i].append(rowVectorArr[i].at(k%rowVectorArr[i].count())); count2++; } prevcount=count2; count=1; count2=0; } count=1,count2=0,prevcount=1; QVector<QVector<Value> > colVect(colposVect.count()); for(int i=0;i<colposVect.count();i++) { for(int j=i+1;j<colposVect.count();j++) { count*=columnVectorArr[j].count(); } for(int k=0;k<(columnVectorArr[i].count())*prevcount;k++) { Cell(mySheet,i+1,((k)*count)+1+rowposVect.count()).setValue(columnVectorArr[i].at(k%columnVectorArr[i].count())); // Cell(mySheet,i+1,((k)*count)+1+rowposVect.count()).setStyle(st2); for(int l=0;l<count;l++) colVect[i].append(columnVectorArr[i].at(k%columnVectorArr[i].count())); count2++; } prevcount=count2; count=1; count2=0; } // Styling for(int m=0;m<colVect[0].count();m++) { Cell(mySheet,1,m+1+rowList.count()).setStyle(stl); Cell(mySheet,columnList.count(),m+1+rowList.count()).setStyle(str); Cell(mySheet,columnList.count()+rowVect[0].count(),m+1+rowList.count()).setStyle(str); } for(int m=0;m<rowVect[0].count();m++) { Cell(mySheet,m+1+columnList.count(),1).setStyle(stt); Cell(mySheet,m+1+columnList.count(),rowList.count()).setStyle(stb); Cell(mySheet,m+1+columnList.count(),rowList.count()+colVect[0].count()).setStyle(stb); } for(int m=0;m<rowList.count();m++) { Cell(mySheet,columnList.count()+1,m+1).setStyle(stl); Cell(mySheet,columnList.count()+rowVect[0].count(),m+1).setStyle(str); } for(int m=0;m<columnList.count();m++) { Cell(mySheet,m+1,rowList.count()+1).setStyle(stt); Cell(mySheet,m+1,rowList.count()+colVect[0].count()).setStyle(stb); } //Styling Done for(int i=0;i<valueList.size();i++) { valpos=vect.indexOf(Value(valueList.at(i)->text())); valposVect.append(valpos); } QString title=d->func + "-" + valueList.at(0)->text(); Cell(mySheet,1,1).setValue(Value(title)); Cell(mySheet,1,1).setStyle(st); for(int l=0;l<rowVect[0].count();l++) { for(int m=0;m<colVect[0].count();m++) { QVector<Value> aggregate; for(int k=row+1;k<=bottom;k++) { int flag=0; for(int i=0;i<rowposVect.count();i++) { for(int j=0;j<colposVect.count();j++) { if(!(Cell(sheet,rowposVect.at(i)+1,k).value()==rowVect[i].at(l) && Cell(sheet,colposVect.at(j)+1,k).value()==colVect[j].at(m))) flag=1; } } if(flag==0) aggregate.append(Cell(sheet,valpos+1,k).value()); } if(d->func!="average") calc->arrayWalk(aggregate,res,calc->awFunc(d->func),Value(0)); else { calc->arrayWalk(aggregate,res,calc->awFunc("sum"),Value(0)); if(aggregate.count()!=0) res=calc->div(res,aggregate.count()); } Cell(mySheet,l+colposVect.count()+1,m+rowposVect.count()+1).setValue(res); if(m%2==0) Cell(mySheet,l+colposVect.count()+1,m+rowposVect.count()+1).setStyle(st3); aggregate.clear(); res=Value(0); } } //For Adding the functions: Total Rows & Total Columns int colmult=1,rowmult=1; for(int x=0;x<columnList.size();x++) colmult*=columnVectorArr[x].count(); for(int x=0;x<rowList.size();x++) rowmult*=rowVectorArr[x].count(); //Totalling Columns if(d->mainWidget.TotalColumns->isChecked()) { Cell(mySheet,1,rowList.size()+colmult+1).setValue(Value("Total Column")); for(int z=columnList.size()+1;z<=rowmult+columnList.size();z++) { QVector<Value> vector; for(int y=rowList.size()+1;y<=colmult+rowList.size();y++) { vector.append(Cell(mySheet,z,y).value()); } if(d->func!="average") calc->arrayWalk(vector,res,calc->awFunc(d->func),Value(0)); else { calc->arrayWalk(vector,res,calc->awFunc("sum"),Value(0)); if(vector.count()!=0) res=calc->div(res,vector.count()); } Cell(mySheet,z,rowList.size()+colmult+1).setValue(res); res=Value(0); } } //Totalling Rows if(d->mainWidget.TotalRows->isChecked()) { Cell(mySheet,columnList.size()+rowmult+1,1).setValue(Value("Total Row")); for(int z=rowList.size()+1;z<=colmult+rowList.size();z++) { QVector<Value> vector; for(int y=columnList.size()+1;y<=rowmult+columnList.size();y++) { vector.append(Cell(mySheet,y,z).value()); } if(d->func!="average") calc->arrayWalk(vector,res,calc->awFunc(d->func),Value(0)); else { calc->arrayWalk(vector,res,calc->awFunc("sum"),Value(0)); if(vector.count()!=0) res=calc->div(res,vector.count()); } Cell(mySheet,columnList.size()+rowmult+1,z).setValue(res); res=Value(0); } } //Clearing Vectors rowVector.clear(); columnVector.clear(); valueVector.clear(); rowposVect.clear(); colposVect.clear(); valposVect.clear(); //Adding built sheet to myMap for viewing myMap->addSheet(mySheet); }//Summarize
int runMoc(int _argc, char **_argv) { bool autoInclude = true; Preprocessor pp; Moc moc; pp.macros["Q_MOC_RUN"]; pp.macros["__cplusplus"]; QByteArray filename; QByteArray output; FILE *in = 0; FILE *out = 0; bool ignoreConflictingOptions = false; QVector<QByteArray> argv; argv.resize(_argc - 1); for (int n = 1; n < _argc; ++n) argv[n - 1] = _argv[n]; int argc = argv.count(); for (int n = 0; n < argv.count(); ++n) { if (argv.at(n).startsWith('@')) { QByteArray optionsFile = argv.at(n); optionsFile.remove(0, 1); if (optionsFile.isEmpty()) error("The @ option requires an input file"); QFile f(QString::fromLatin1(optionsFile.constData())); if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) error("Cannot open options file specified with @"); argv.remove(n); while (!f.atEnd()) { QByteArray line = f.readLine().trimmed(); if (!line.isEmpty()) argv.insert(n++, line); } } } argc = argv.count(); for (int n = 0; n < argc; ++n) { QByteArray arg(argv[n]); if (arg[0] != '-') { if (filename.isEmpty()) { filename = arg; continue; } error("Too many input files specified"); } QByteArray opt = arg.mid(1); bool more = (opt.size() > 1); switch (opt[0]) { case 'o': // output redirection if (!more) { if (!(n < argc-1)) error("Missing output file name"); output = argv[++n]; } else output = opt.mid(1); break; case 'E': // only preprocessor pp.preprocessOnly = true; break; case 'i': // no #include statement if (more) error(); moc.noInclude = true; autoInclude = false; break; case 'f': // produce #include statement if (ignoreConflictingOptions) break; moc.noInclude = false; autoInclude = false; if (opt[1]) // -fsomething.h moc.includeFiles.append(opt.mid(1)); break; case 'p': // include file path if (ignoreConflictingOptions) break; if (!more) { if (!(n < argc-1)) error("Missing path name for the -p option."); moc.includePath = argv[++n]; } else { moc.includePath = opt.mid(1); } break; case 'I': // produce #include statement if (!more) { if (!(n < argc-1)) error("Missing path name for the -I option."); pp.includes += Preprocessor::IncludePath(argv[++n]); } else { pp.includes += Preprocessor::IncludePath(opt.mid(1)); } break; case 'F': // minimalistic framework support for the mac if (!more) { if (!(n < argc-1)) error("Missing path name for the -F option."); Preprocessor::IncludePath p(argv[++n]); p.isFrameworkPath = true; pp.includes += p; } else { Preprocessor::IncludePath p(opt.mid(1)); p.isFrameworkPath = true; pp.includes += p; } break; case 'D': // define macro { QByteArray name; QByteArray value("1"); if (!more) { if (n < argc-1) name = argv[++n]; } else name = opt.mid(1); int eq = name.indexOf('='); if (eq >= 0) { value = name.mid(eq + 1); name = name.left(eq); } if (name.isEmpty()) error("Missing macro name"); Macro macro; macro.symbols += Symbol(0, PP_IDENTIFIER, value); pp.macros.insert(name, macro); } break; case 'U': { QByteArray macro; if (!more) { if (n < argc-1) macro = argv[++n]; } else macro = opt.mid(1); if (macro.isEmpty()) error("Missing macro name"); pp.macros.remove(macro); } break; case 'v': // version number if (more && opt != "version") error(); fprintf(stderr, "Qt Meta Object Compiler version %d (Qt %s)\n", mocOutputRevision, QT_VERSION_STR); return 1; case 'n': // don't display warnings if (ignoreConflictingOptions) break; if (opt != "nw") error(); moc.displayWarnings = false; break; case 'h': // help if (more && opt != "help") error(); else error(0); // 0 means usage only break; case '-': if (more && arg == "--ignore-option-clashes") { // -- ignore all following moc specific options that conflict // with for example gcc, like -pthread conflicting with moc's // -p option. ignoreConflictingOptions = true; break; } // fall through default: error(); } } if (autoInclude) { int ppos = filename.lastIndexOf('.'); moc.noInclude = (ppos >= 0 && tolower(filename[ppos + 1]) != 'h' && tolower(filename[ppos + 1]) != QDir::separator().toLatin1() ); } if (moc.includeFiles.isEmpty()) { if (moc.includePath.isEmpty()) { if (filename.size()) { if (output.size()) moc.includeFiles.append(combinePath(filename, output)); else moc.includeFiles.append(filename); } } else { moc.includeFiles.append(combinePath(filename, filename)); } } if (filename.isEmpty()) { filename = "standard input"; in = stdin; } else { #if defined(_MSC_VER) && _MSC_VER >= 1400 if (fopen_s(&in, filename.data(), "rb")) { #else in = fopen(filename.data(), "rb"); if (!in) { #endif fprintf(stderr, "moc: %s: No such file\n", (const char*)filename); return 1; } moc.filename = filename; } moc.currentFilenames.push(filename); // 1. preprocess moc.symbols = pp.preprocessed(moc.filename, in); fclose(in); if (!pp.preprocessOnly) { // 2. parse moc.parse(); } // 3. and output meta object code if (output.size()) { // output file specified #if defined(_MSC_VER) && _MSC_VER >= 1400 if (fopen_s(&out, output.data(), "w")) #else out = fopen(output.data(), "w"); // create output file if (!out) #endif { fprintf(stderr, "moc: Cannot create %s\n", (const char*)output); return 1; } } else { // use stdout out = stdout; } if (pp.preprocessOnly) { fprintf(out, "%s\n", composePreprocessorOutput(moc.symbols).constData()); } else { if (moc.classList.isEmpty()) moc.warning("No relevant classes found. No output generated."); else moc.generate(out); } if (output.size()) fclose(out); return 0; } QT_END_NAMESPACE int main(int _argc, char **_argv) { return QT_PREPEND_NAMESPACE(runMoc)(_argc, _argv); }
bool parseStream(const char *stream, unsigned long streamLen) { //std::cout << "parseStream of length " << streamLen << std::endl; setlocale(LC_ALL, "C"); QStack<FloatText> stack; QVector<double> lastArray; unsigned long previousPosition = 0; unsigned long tokenPosition = 0; bool inArray = false; FloatText x1, y1, x2, y2, x3, y3; double capStyle, offset, joinStyle; QList<GraphicContext> contexts; GraphicContext currentContext; currentContext.brush.setStyle(Qt::SolidPattern); currentContext.brush.setColor(Qt::black); currentContext.pen.setStyle(Qt::SolidLine); currentContext.pen.setColor(Qt::black); QString currentPath; FloatText cur_x, cur_y; do { // Special case : array handling if (stream[tokenPosition] == '[') { inArray = true; tokenPosition++; previousPosition = tokenPosition; continue; } if ((stream[tokenPosition] != ' ') && (stream[tokenPosition] != '\n') && (stream[tokenPosition] != '\0') && (stream[tokenPosition] != '\t') && (stream[tokenPosition] != ']')) { tokenPosition++; continue; } if (previousPosition != tokenPosition) { switch (stream[previousPosition]) { case 'l': y1 = stack.pop(); x1 = stack.pop(); //currentPath.lineTo(x1, y1); std::cout << " L " << x1 << ',' << y1; cur_x = x1; cur_y = y1; break; case 'v': y3 = stack.pop(); x3 = stack.pop(); y2 = stack.pop(); x2 = stack.pop(); //currentPath.quadTo(x2, y2, x3, y3); WRONG, it's not a quad but a cubic command ! std::cout << " C " << cur_x << ',' << cur_y << ' ' << x2 << ',' << y2 << ' ' << x3 << ',' << y3; cur_x = x3; cur_y = y3; break; case 'y': y3 = stack.pop(); x3 = stack.pop(); y2 = stack.pop(); x2 = stack.pop(); std::cout << " C " << x2 << ',' << y2 << ' ' << x3 << ',' << y3 << ' ' << x3 << ',' << y3; cur_x = x3; cur_y = y3; break; case 'm': y1 = stack.pop(); x1 = stack.pop(); //currentPath.moveTo(x1, y1); std::cout << " M " << x1 << ',' << y1; cur_x = x1; cur_y = y1; break; case 'h': //currentPath.closeSubpath(); std::cout << " Z"; break; case 'W': //if (currentContext.clipPath.length() == 0) // currentContext.clipPath = currentPath.toPainterPath(); //if (stream[previousPosition+1] == '*') { // currentContext.clipPath.setFillRule(Qt::OddEvenFill); // currentPath.setFillRule(Qt::OddEvenFill); //} else { // currentContext.clipPath.setFillRule(Qt::WindingFill); // currentPath.setFillRule(Qt::WindingFill); //} //currentContext.clipPath = currentContext.clipPath.intersected(currentPath.toPainterPath()); break; case 'n': //currentPath = VectorPath(); std::cout << std::endl << "" << std::endl; break; case 'q': contexts.append(currentContext); break; case 'Q': currentContext = contexts.takeLast(); break; case 'S': //emit strikePath(currentPath, currentContext); //currentPath = VectorPath(); std::cout << std::endl << "fill:none;stroke:" << currentContext.pen.color().name().toStdString(); std::cout << ";stroke-opacity:1"; if (currentContext.pen.style() == Qt::SolidLine) { std::cout << ";stroke-dasharray:none"; } std::cout << ";stroke-width:" << currentContext.pen.widthF(); std::cout << std::endl; break; case 'w': currentContext.pen.setWidthF(stack.pop().value()); break; case 'R': if (stream[previousPosition+1] == 'G') { double b = stack.pop().value(); double g = stack.pop().value(); double r = stack.pop().value(); currentContext.pen.setColor(QColor(r*255, g*255, b*255)); } break; case 'J': capStyle = stack.pop().value(); if (capStyle == 0) currentContext.pen.setCapStyle(Qt::FlatCap); else if (capStyle == 1) currentContext.pen.setCapStyle(Qt::RoundCap); else currentContext.pen.setCapStyle(Qt::SquareCap); break; case 'M': currentContext.pen.setMiterLimit(stack.pop().value()); break; case 'f': std::cout << std::endl << "fill:" << currentContext.brush.color().name().toStdString(); std::cout << ";stroke:none"; if (stream[previousPosition+1] == '*') //emit fillPath(currentPath, currentContext, Qt::OddEvenFill); std::cout << ";fill-rule:evenodd"; else //emit fillPath(currentPath, currentContext, Qt::WindingFill); std::cout << ";fill-rule:nonzero"; //currentPath = VectorPath(); std::cout << std::endl; break; case 'd': offset = stack.pop().value(); if (lastArray.count() == 0) { currentContext.pen.setStyle(Qt::SolidLine); } else { currentContext.pen.setDashOffset(offset); currentContext.pen.setDashPattern(lastArray); lastArray.clear(); } break; case 'r': if (stream[previousPosition+1] == 'g') { double b = stack.pop().value(); double g = stack.pop().value(); double r = stack.pop().value(); currentContext.brush.setColor(QColor(r*255, g*255, b*255)); } break; case 'c': y3 = stack.pop(); x3 = stack.pop(); y2 = stack.pop(); x2 = stack.pop(); y1 = stack.pop(); x1 = stack.pop(); //currentPath.cubicTo(x1, y1, x2, y2, x3, y3); std::cout << " C " << x1 << ',' << y1 << ' ' << x2 << ',' << y2 << ' ' << x3 << ',' << y3; cur_x = x3; cur_y = y3; break; case 'j': joinStyle = stack.pop().value(); if (joinStyle == 0) currentContext.pen.setJoinStyle(Qt::MiterJoin); else if (joinStyle == 1) currentContext.pen.setJoinStyle(Qt::RoundJoin); else currentContext.pen.setJoinStyle(Qt::BevelJoin); break; default: // handle a number then errno = 0; //double d = strtod(stream + previousPosition, NULL); FloatText d = FloatText(stream + previousPosition); if (errno != 0) qFatal("Convertion to double failed !"); if (inArray) //lastArray << d; lastArray << d.value(); else stack.push(d); } } previousPosition = tokenPosition + 1; if (stream[tokenPosition] == ']') { inArray = false; } tokenPosition++; } while (tokenPosition <= streamLen); //std::cerr << "stack: " << stack.size() << std::endl; return true; }
void QmlProfilerStatisticsModel::loadData(qint64 rangeStart, qint64 rangeEnd) { clear(); qint64 qmlTime = 0; qint64 lastEndTime = 0; QHash <int, QVector<qint64> > durations; const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1); const QVector<QmlProfilerDataModel::QmlEventData> &eventList = d->modelManager->qmlModel()->getEvents(); const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList = d->modelManager->qmlModel()->getEventTypes(); // used by binding loop detection QStack<const QmlProfilerDataModel::QmlEventData*> callStack; callStack.push(0); // artificial root for (int i = 0; i < eventList.size(); ++i) { const QmlProfilerDataModel::QmlEventData *event = &eventList[i]; const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex()]; if (!d->acceptedTypes.contains(type->rangeType)) continue; if (checkRanges) { if ((event->startTime() + event->duration() < rangeStart) || (event->startTime() > rangeEnd)) continue; } // update stats QmlEventStats *stats = &d->data[event->typeIndex()]; stats->duration += event->duration(); stats->durationSelf += event->duration(); if (event->duration() < stats->minTime) stats->minTime = event->duration(); if (event->duration() > stats->maxTime) stats->maxTime = event->duration(); stats->calls++; // for median computing durations[event->typeIndex()].append(event->duration()); // qml time computation if (event->startTime() > lastEndTime) { // assume parent event if starts before last end qmlTime += event->duration(); lastEndTime = event->startTime() + event->duration(); } // // binding loop detection // const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top(); while (potentialParent && !(potentialParent->startTime() + potentialParent->duration() > event->startTime())) { callStack.pop(); potentialParent = callStack.top(); } // check whether event is already in stack for (int ii = 1; ii < callStack.size(); ++ii) { if (callStack.at(ii)->typeIndex() == event->typeIndex()) { d->eventsInBindingLoop.insert(event->typeIndex()); break; } } if (callStack.count() > 1) d->data[callStack.top()->typeIndex()].durationSelf -= event->duration(); callStack.push(event); d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2); } // post-process: calc mean time, median time, percentoftime int i = d->data.size(); int total = i * 2; for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) { QmlEventStats* stats = &it.value(); if (stats->calls > 0) stats->timePerCall = stats->duration / (double)stats->calls; QVector<qint64> eventDurations = durations[it.key()]; if (!eventDurations.isEmpty()) { Utils::sort(eventDurations); stats->medianTime = eventDurations.at(eventDurations.count()/2); } stats->percentOfTime = stats->duration * 100.0 / qmlTime; stats->percentSelf = stats->durationSelf * 100.0 / qmlTime; d->modelManager->modelProxyCountUpdated(d->modelId, i++, total); } // set binding loop flag foreach (int typeIndex, d->eventsInBindingLoop) d->data[typeIndex].isBindingLoop = true; // insert root event QmlEventStats rootEvent; rootEvent.duration = rootEvent.minTime = rootEvent.maxTime = rootEvent.timePerCall = rootEvent.medianTime = qmlTime + 1; rootEvent.durationSelf = 1; rootEvent.calls = 1; rootEvent.percentOfTime = 100.0; rootEvent.percentSelf = 1.0 / rootEvent.duration; d->data.insert(-1, rootEvent); d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1); emit dataAvailable(); }
bool ScanInfo::load( QTextStream &in, QVector<AMotor*> &AMotors, QVector<ASensor*> &ASensors ) { bool f = false; am = NULL; as = as0 = NULL; while( !in.atEnd() ) { QString line = in.readLine(); if ( line.count() < 2 ) break; if ( line.left( 1 ) != "#" ) break; if ( line.left( 2 ) != "# " ) continue; QStringList vals = line.mid( 2 ).split( "\t" ); if ( vals.count() < 2 ) continue; if ( vals[0] == UNITNAMES ) { f = true; if ( vals.count() > 1 ) amName = vals[1]; if ( vals.count() > 2 ) asName = vals[2]; if ( vals.count() > 3 ) as0Name = vals[3]; } if ( vals[0] == UNITIDS ) { if ( vals.count() >= 4 ) { for ( int j = 0; j < AMotors.count(); j++ ) { if ( AMotors[j]->uid() == vals[1] ) { am = AMotors[j]; break; } } for ( int j = 0; j < ASensors.count(); j++ ) { if ( ASensors[j]->uid() == vals[2] ) { as = ASensors[j]; break; } } for ( int j = 0; j < ASensors.count(); j++ ) { if ( ASensors[j]->uid() == vals[3] ) { as0 = ASensors[j]; break; } } } } if ( vals[0] == NORMALIZE ) normalize = ( vals[1].toInt() == 1 ); if ( vals[0] == METRICUNIT ) unitName = vals[1]; if ( vals[0] == UNIT_PULSE ) upp = vals[1].toDouble(); if ( vals[0] == ORIG_POINT ) origin = vals[1].toDouble(); if ( vals[0] == OFFSET ) offset = vals[1].toDouble(); if ( vals[0] == START_END_STEP ) { if ( vals.count() >= 4 ) { sx0 = vals[1]; ex0 = vals[2]; dx0 = vals[3]; } } if ( vals[0] == RELABSSEL ) relabs = (RELABS)(vals[1].toInt()); if ( vals[0] == SPEED ) speed = (MSPEED)(vals[1].toInt()); if ( vals[0] == SCANDWELLTIME ) dt0 = vals[1]; if ( vals[0] == USEMONITORS ) UseMonitors = ( vals[1].toInt() == 1 ); bool dummyF; mi.load0( line, ASensors, dummyF ); } if ( am != NULL ) { sx = am->any2p( sx0.toDouble(), showUnit, relabs ); ex = am->any2p( ex0.toDouble(), showUnit, relabs ); } if ( upp != 0 ) dx = fabs( dx0.toDouble() / upp ); if ( sx > ex ) dx = -dx; dt = dt0.toDouble(); return f; }
/*! \fn void QTextTable::removeColumns(int index, int columns) Removes a number of \a columns starting with the column at the specified \a index. \sa insertRows(), insertColumns(), removeRows(), resize(), appendRows(), appendColumns() */ void QTextTable::removeColumns(int pos, int num) { Q_D(QTextTable); // qDebug() << "-------- removeCols" << pos << num; if (num <= 0 || pos < 0) return; if (d->dirty) d->update(); if (pos >= d->nCols) return; if (pos + num > d->nCols) pos = d->nCols - num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *collection = p->formatCollection(); p->beginEditBlock(); // delete whole table? if (pos == 0 && num == d->nCols) { const int pos = p->fragmentMap().position(d->fragment_start); p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1); p->endEditBlock(); return; } p->aboutToRemoveCell(cellAt(0, pos).firstPosition(), cellAt(d->nRows - 1, pos + num - 1).lastPosition()); QList<int> touchedCells; for (int r = 0; r < d->nRows; ++r) { for (int c = pos; c < pos + num; ++c) { int cell = d->grid[r*d->nCols + c]; QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = collection->charFormat(it->format); int span = fmt.tableCellColumnSpan(); if (touchedCells.contains(cell) && span <= 1) continue; touchedCells << cell; if (span > 1) { fmt.setTableCellColumnSpan(span - 1); p->setCharFormat(it.position(), 1, fmt); } else { // remove cell int index = d->cells.indexOf(cell) + 1; int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end; p->remove(it.position(), p->fragmentMap().position(f_end) - it.position()); } } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()-num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (columnWidths.count() > pos) { columnWidths.remove(pos, num); tfmt.setColumnWidthConstraints (columnWidths); } QTextObject::setFormat(tfmt); p->endEditBlock(); // qDebug() << "-------- end removeCols" << pos << num; }
void cChannelSession::dataRX(const QVector<QByteArray> &data) { if (data.count() < 2) { qDebug() << "[ERROR]cChannelSession::dataRX-> Pocos campos... :" << data.count(); return; } int cmd = data[1].toInt(); //qDebug() << "[INFO]cChannelSession::dataRX-> Comando:" << cmd; if(cmd == CMD_JOIN_SESSION) { QString id = data[2]; emit join_session(id); } else if (cmd == CMD_SESSION_STATUS) { QString id = data[2]; bool status = data[3].toInt(); QString reason = data[4]; emit session_status(id,status,reason); } else if (cmd == CMD_GET_SESSION_USERLIST) { QString id = data[2]; emit get_session_userlist(id); } else if (cmd == CMD_SESSION_USERLIST) { QString id = data[2]; QByteArray array = data[3]; cUsersInfoList userslist(array); emit session_userlist(id,userslist); } else if (cmd == CMD_GET_CHATROOM_LIST) { QString id = data[2]; emit get_chatroom_list(id); } else if (cmd == CMD_CHATROOM_LIST) { QString id = data[2]; QVector<cChatInfo> chats; for ( int i = 3 ; i < data.count() ; i+=3 ) { cChatInfo chatroom(data[i],data[i+1],data[i+2].toInt()); chats.append(chatroom); } emit chatroom_list(id,chats); } else if(cmd == CMD_JOIN_CHATROOM) { QString id = data[2]; emit join_chatroom(id); } else if(cmd == CMD_CHATROOM_STATUS) { QString id = data[2]; bool status = data[3].toInt(); QString reason = data[4]; emit chatroom_status(id,status,reason); } else if(cmd == CMD_GET_CHATROOM_USERLIST) { QString chatroom_id = data[2]; emit get_chatroom_userlist(chatroom_id); } else if(cmd == CMD_CHATROOM_USERLIST) { QString id = data[2]; QByteArray array = data[3]; cUsersInfoList userslist(array); emit chatroom_userlist(id,userslist); } else if(cmd == CMD_CREATE_CHATROOM) { QString name = data[2]; bool persistent = data[3].toInt(); emit create_chatroom(name,persistent); } else if(cmd == CMD_CHATROOM_MSG) { QVector<cChatMsg> msgs; QString id = data[2]; for ( int i = 3 ; i < data.count() ; i+=3 ) { QDateTime timestamp; timestamp.fromMSecsSinceEpoch(data[i+2].toInt()); cChatMsg msg(data[i],data[i+1],timestamp); msgs.append(msg); } emit chatroom_msg(id,msgs); } else if(cmd == CMD_GET_FILELIST) { QString id = data[2]; emit get_file_list(id); } else if(cmd == CMD_FILELIST) { QString id = data[2]; } else if(cmd == CMD_GET_PAD_LIST) { QString id = data[2]; emit get_pad_list(id); } else if(cmd == CMD_PAD_LIST) { QString id = data[2]; QByteArray array(data[3]); cPadsInfoList padslist(array); emit pad_list(id,padslist); } else if(cmd == CMD_JOIN_PAD) { QString id = data[2]; emit join_pad(id); } else if(cmd == CMD_PAD_STATUS) { QString id = data[2]; bool status = data[3].toInt(); QString reason = data[4]; emit pad_status(id,status,reason); } else if(cmd == CMD_GET_PAD_USERLIST) { QString id = data[2]; emit get_pad_userlist(id); } else if(cmd == CMD_PAD_USERLIST) { QString id = data[2]; QByteArray array = data[3]; cUsersInfoList userslist(array); emit pad_userlist(id,userslist); } else if(cmd == CMD_GET_PAD_DOCUMENT) { QString id(data[2]); emit get_pad_document(id); } else if(cmd == CMD_PAD_DOCUMENT) { QString id(data[2]); QString padText(data[3]); emit pad_document(id,padText); } else if(cmd == CMD_PAD_CHANGES) { QString id(data[2]); QString sender = data[3]; int pos(data[4].toInt()); int del(data[5].toInt()); int add(data[6].toInt()); QString text(data[7]); emit pad_changes(id,sender,pos,del,add,text); } else { qDebug() << "[ERROR]cChannelSession::dataRX-> Comando desconocido:" << cmd; } }
void SOM::initializeTraining( QMap<QString, QVariant> somParameters, QVector<FeaturePtr> features ) { SOMError::requireCondition( features.count() > 0, "Cannot train with an empty feature set" ); int featureSize = features.front()->size(); SOMError::requireCondition( featureSize > 0 , "Feature size must be greater than 0" ); bool ok = true; // Describes the number of epochs of training the SOM will need SOMError::requireCondition( somParameters.contains( "maxEpochs" ), "SOM parameters doesn't contain epoch count" ); maxEpochs = somParameters["maxEpochs"].toInt( &ok ); SOMError::requireCondition( ok, "Couldn't convert maximum epoch count to an int" ); // Describes the inital training weight for the SOM SOMError::requireCondition( somParameters.contains( "initialAlpha" ), "SOM parameters doesn't contain initial alpha" ); initialAlpha = somParameters["initialAlpha"].toDouble( &ok ); /// @todo Add range check to alpha (hint on values) /// @todo Perhaps use default values if the parameters aren't specified SOMError::requireCondition( ok, "Couldn't convert initial alpha to a double" ); // Describes the inital radius of the training neighborhood for the SOM SOMError::requireCondition( somParameters.contains( "initialRadiusRatio" ), "SOM parameters doesn't contain initial radius ratio" ); double initialRadiusRatio = somParameters["initialRadiusRatio"].toDouble( &ok ); SOMError::requireCondition( ok, "Couldn't convvert initial radius ratio to a double" ); SOMError::requireCondition( initialRadiusRatio < 0.5, "Initial radius ratio may not exceed 0.5" ); SOMError::requireCondition( initialRadiusRatio > 0.0, "Initial radius ratio must be greater than 0" ); /// @todo determine if there should be other constraints to alpha and radius ratio (negatives, ffs!) alpha_tf = 0.10; // This is a tuning factor...should not be hardcoded alpha_Nf = 0.25; // This is a tuning factor...should not be hardcoded alpha_gamma = -log( alpha_Nf ) / ( alpha_tf * maxEpochs ); initialRadius = initialRadiusRatio * _grid->diagonal(); radius_tf = 0.25; // This is a tuning factor...should not be hardcoded radius_Nf = 0.50; // This is a tuning factor...should not be hardcoded radius_gamma = -log( radius_Nf ) / ( radius_tf * maxEpochs ); currentEpoch = -1; nextEpoch(); // Calculate the normalizer given the training features _normalizer->calculateNormalizer( features ); for( int i=0; i<_grid->capacity(); i++ ) { FeaturePtr newFeature( new Feature( featureSize ) ); _normalizer->setFeature( newFeature ); _grid->item(i) = newFeature; } // Normalize the input features _normalizer->normalizeAll( features ); }
void ScatterPlot::setData (ScatterSettings *settings) { // get application settings cranklength = appsettings->value(this, GC_CRANKLENGTH, 0.0).toDouble() / 1000.0; // if there are no settings or incomplete settings // create a null data plot if (settings == NULL || settings->ride == NULL || settings->ride->ride() == NULL || settings->x == 0 || settings->y == 0 ) { return; } // if its not setup or no settings exist default to 175mm cranks if (cranklength == 0.0) cranklength = 0.175; // // Create Main Plot dataset - used to frame intervals // int points=0; x.clear(); y.clear(); x.resize(settings->ride->ride()->dataPoints().count()); y.resize(settings->ride->ride()->dataPoints().count()); double maxY = maxX = -65535; double minY = minX = 65535; foreach(const RideFilePoint *point, settings->ride->ride()->dataPoints()) { double xv = x[points] = pointType(point, settings->x, context->athlete->useMetricUnits, cranklength); double yv = y[points] = pointType(point, settings->y, context->athlete->useMetricUnits, cranklength); // skip zeroes? if (!(settings->ignore && (x[points] == 0 || y[points] == 0))) { points++; if (yv > maxY) maxY = yv; if (yv < minY) minY = yv; if (xv > maxX) maxX = xv; if (xv < minX) minX = xv; } } QwtSymbol sym; sym.setStyle(QwtSymbol::Ellipse); sym.setSize(6); sym.setPen(GCColor::invert(GColor(CPLOTBACKGROUND))); sym.setBrush(QBrush(Qt::NoBrush)); QPen p; p.setColor(GColor(CPLOTSYMBOL)); sym.setPen(p); // wipe away existing if (all) { all->detach(); delete all; } // setup the framing curve if (settings->frame) { all = new QwtPlotCurve(); all->setSymbol(new QwtSymbol(sym)); all->setStyle(QwtPlotCurve::Dots); all->setRenderHint(QwtPlotItem::RenderAntialiased); all->setData(x.constData(), y.constData(), points); all->attach(this); } else { all = NULL; } QPen gridPen(GColor(CPLOTGRID)); gridPen.setStyle(Qt::DotLine); if (grid) { grid->detach(); delete grid; } if (settings->gridlines) { grid = new QwtPlotGrid(); grid->setPen(gridPen); grid->enableX(true); grid->enableY(true); grid->attach(this); } else { grid = NULL; } setAxisTitle(yLeft, describeType(settings->y, true, useMetricUnits)); setAxisTitle(xBottom, describeType(settings->x, true, useMetricUnits)); // truncate PfPv values to make easier to read if (settings->y == MODEL_AEPF) setAxisScale(yLeft, 0, 600); else setAxisScale(yLeft, minY, maxY); if (settings->x == MODEL_CPV) setAxisScale(xBottom, 0, 3); else setAxisScale(xBottom, minX, maxX); // // Create Interval Plot dataset - used to frame intervals // // clear out any interval curves which are presently defined if (intervalCurves.size()) { QListIterator<QwtPlotCurve *> i(intervalCurves); while (i.hasNext()) { QwtPlotCurve *curve = i.next(); curve->detach(); delete curve; } } intervalCurves.clear(); // which ones are highlighted then? QVector<int> intervals; QMap<int,int> displaySequence; for (int child=0; child<context->athlete->allIntervalItems()->childCount(); child++) { IntervalItem *current = dynamic_cast<IntervalItem *>(context->athlete->allIntervalItems()->child(child)); if ((current != NULL) && current->isSelected()) { intervals.append(child); displaySequence.insert(current->displaySequence, intervals.count()-1); } } if (intervals.count() > 0) { // interval data in here QVector<QVector<double> > xvals(intervals.count()); // array of curve x arrays QVector<QVector<double> > yvals(intervals.count()); // array of curve x arrays QVector<int> points(intervals.count()); // points in eac curve // extract interval data foreach(const RideFilePoint *point, settings->ride->ride()->dataPoints()) { double x = pointType(point, settings->x, useMetricUnits, cranklength); double y = pointType(point, settings->y, useMetricUnits, cranklength); if (!(settings->ignore && (x == 0 && y ==0))) { // which interval is it in? for (int idx=0; idx<intervals.count(); idx++) { IntervalItem *current = dynamic_cast<IntervalItem *>(context->athlete->allIntervalItems()->child(intervals[idx])); if (point->secs+settings->ride->ride()->recIntSecs() > current->start && point->secs< current->stop) { xvals[idx].append(x); yvals[idx].append(y); points[idx]++; } } } } // now we have the interval data lets create the curves QMapIterator<int, int> order(displaySequence); while (order.hasNext()) { order.next(); int idx = order.value(); QPen pen; QColor intervalColor; intervalColor.setHsv((255/context->athlete->allIntervalItems()->childCount()) * (intervals[idx]), 255,255); pen.setColor(intervalColor); sym.setPen(pen); QwtPlotCurve *curve = new QwtPlotCurve(); curve->setSymbol(new QwtSymbol(sym)); curve->setStyle(QwtPlotCurve::Dots); curve->setRenderHint(QwtPlotItem::RenderAntialiased); curve->setData(xvals[idx].constData(), yvals[idx].constData(), points[idx]); curve->attach(this); intervalCurves.append(curve); } }
void KDReports::SpreadsheetReportLayout::ensureLayouted() { if ( !m_layoutDirty ) return; if ( m_pageContentSize.isEmpty() ) { qWarning( "No paper size specified!" ); return; } m_tableLayout.setInitialFontScalingFactor( m_userRequestedFontScalingFactor ); m_pageRects.clear(); QAbstractItemModel* model = m_tableLayout.m_model; if ( !model ) return; // Here's the whole layouting logic // Step 1: determine "ideal" column widths, based on contents m_tableLayout.updateColumnWidths(); // Step 2: based on that and the number of horiz pages wanted, // determine actual column widths (horizontal table breaking) KDReports::TableBreakingLogic optimizer; optimizer.setColumnWidths( m_tableLayout.m_columnWidths ); optimizer.setPageCount( m_numHorizontalPages ); const QVector<int> columnsPerPage = optimizer.columnsPerPage(); QVector<qreal> widthPerPage = optimizer.widthPerPage( columnsPerPage ); const int horizPages = columnsPerPage.count(); bool scaled = false; // Step 3: check everything fits horizontally, otherwise calculate font scaling factor for this const qreal horizMargins = 0 /*m_leftMargin*/ + 0 /*m_rightMargin*/; const qreal verticalMargins = 0 /*m_topMargin*/ + 0 /*m_bottomMargin*/; const qreal usablePageWidth = m_pageContentSize.width() - horizMargins; const qreal usablePageHeight = m_pageContentSize.height() - verticalMargins - m_tableLayout.hHeaderHeight(); #ifdef DEBUG_LAYOUT qDebug() << "usablePageHeight=" << m_pageContentSize.height() << "minus hHeaderHeight" << m_tableLayout.hHeaderHeight(); #endif // for each page, if (sum of column widths) > usablePageWidth, // then we need to scale everything (font and padding) // by the ratio of those two numbers. qreal bestScalingFactor = 1000000; for ( int page = 0; page < horizPages; ++page ) { const qreal width = widthPerPage[page] + m_tableLayout.vHeaderWidth(); if ( width > usablePageWidth ) { const qreal scalingFactor = usablePageWidth / width; #ifdef DEBUG_LAYOUT qDebug() << "page" << page << "sum of column widths:" << width << "usablePageWidth=" << usablePageWidth; qDebug() << "scaling factor so that it fits horizontally:" << scalingFactor; #endif bestScalingFactor = qMin(bestScalingFactor, scalingFactor); scaled = true; } } if (scaled) { m_tableLayout.ensureScalingFactorForWidth( bestScalingFactor ); } // Step 4: check everything fits vertically, otherwise calculate font scaling factor for this const int rowCount = m_tableLayout.m_model->rowCount(); if ( m_numVerticalPages > 0 ) { const qreal rowHeight = m_tableLayout.rowHeight(); // We can't do a global division of heights, it assumes rows can be over page borders, partially truncated // const qreal maxTotalHeight = m_numVerticalPages * usablePageHeight; // const qreal maxRowHeight = maxTotalHeight / rowCount; // Example: 5 rows over 2 pages, and the usablePageHeight is 100. What do you do? // 2.5 rows per page means truncation. 2 rows per page (as in the division above) is not enough. // The right solution is qCeil, i.e. max 3 rows per page, and maxRowHeight = 100 / 3 = 33.3. const int maxRowsPerPage = qCeil( static_cast<qreal>(rowCount) / m_numVerticalPages ); const qreal maxRowHeight = usablePageHeight / maxRowsPerPage; #ifdef DEBUG_LAYOUT qDebug() << "usablePageHeight=" << usablePageHeight << "rowHeight=" << rowHeight << "maxRowsPerPage=" << maxRowsPerPage << "maxRowHeight=" << usablePageHeight << "/" << maxRowsPerPage << "=" << maxRowHeight; #endif if ( rowHeight > maxRowHeight ) { // more than authorized maximum m_tableLayout.ensureScalingFactorForHeight( maxRowHeight ); scaled = true; } } // Step 5: update font and calculations based on final font scaling if (scaled) { #ifdef DEBUG_LAYOUT qDebug() << "final scaling factor" << m_tableLayout.scalingFactor(); qDebug() << "final fonts: cells:" << m_tableLayout.scaledFont().pointSizeF() << "hHeader:" << m_tableLayout.horizontalHeaderScaledFont().pointSizeF() << "vHeader:" << m_tableLayout.verticalHeaderScaledFont().pointSizeF(); #endif // With this new scaling factor [when step 4 changed the factor], what should be the column widths? // If we just call // m_tableLayout.updateColumnWidthsByFactor( m_tableLayout.scalingFactor() / m_userRequestedFontScalingFactor ); // then we risk truncating column text (because fonts are not proportional). // Testcase: LongReport with font size 8, padding 3, 10 columns, 300 rows, and scaleTo(1,10) (or none); m_tableLayout.updateColumnWidths(); #ifdef DEBUG_LAYOUT qDebug() << "New total width:" << totalWidth(); #endif #if 0 // not used right now, but could be useful, especially if we want to goto step 3 again, to resize down // Update the widthPerPage array int column = 0; for ( int page = 0; page < horizPages; ++page ) { const int numColumnsInPage = columnsPerPage[page]; widthPerPage[page] = 0; for ( int col = column; col < column + numColumnsInPage; ++col) { widthPerPage[page] += m_tableLayout.m_columnWidths[col]; } const qreal width = widthPerPage[page] + m_tableLayout.vHeaderWidth(); if ( width > usablePageWidth ) { qWarning() << "Too much width on page" << page; } column += numColumnsInPage; } qDebug() << "widthPerPage:" << widthPerPage; #endif } const qreal rowHeight = m_tableLayout.rowHeight(); // do it now so that the scaling is included // Step 6: determine number of pages for all rows to fit const int maxRowsPerPage = qFloor(usablePageHeight / rowHeight); // no qCeil here, the last row would be truncated... int verticPages = qCeil( qreal( rowCount ) / qreal( maxRowsPerPage ) ); #ifdef DEBUG_LAYOUT qDebug() << "maxRowsPerPage=" << usablePageHeight << "/" << rowHeight << "=" << maxRowsPerPage; qDebug() << "pages:" << horizPages << "x" << verticPages; qDebug() << "verticPages = qCeil(" << rowCount << "/" << maxRowsPerPage << ") =" << verticPages; #endif // avoid rounding problems (or the font not zooming down enough vertically), // obey m_numVerticalPages in all cases if ( m_numVerticalPages > 0 ) { Q_ASSERT( verticPages <= m_numVerticalPages ); // verticPages = qMin( m_numVerticalPages, verticPages ); } // Step 7: now we can record all this in terms of cell areas if ( m_tableBreakingPageOrder == Report::RightThenDown ) { //qDebug() << "Doing right then down layout"; int row = 0; for ( int y = 0; y < verticPages; ++y ) { int column = 0; const int numRowsInPage = qMin( maxRowsPerPage, rowCount - row ); for ( int x = 0; x < horizPages; ++x ) { const int numColumnsInPage = columnsPerPage[x]; m_pageRects.append( QRect( column, row, numColumnsInPage, numRowsInPage ) ); column += numColumnsInPage; } row += maxRowsPerPage; } } else { //qDebug() << "Doing down then right layout"; int column = 0; for ( int x = 0; x < horizPages; ++x ) { int row = 0; const int numColumnsInPage = columnsPerPage[x]; for ( int y = 0; y < verticPages; ++y ) { const int numRowsInPage = qMin( maxRowsPerPage, rowCount - row ); m_pageRects.append( QRect( column, row, numColumnsInPage, numRowsInPage ) ); row += maxRowsPerPage; } column += numColumnsInPage; } } m_layoutDirty = false; }
void RDHeaderView::resizeSectionsWithHints() { if(m_sectionMinSizes.count() == 0) return; QVector<int> sizes = m_sectionMinSizes; int available = 0; if(orientation() == Qt::Horizontal) available = rect().width(); else available = rect().height(); // see if we even have any extra space to allocate if(available > m_sectionMinSizesTotal) { // this is how much space we can allocate to stretch sections available -= m_sectionMinSizesTotal; // distribute the available space between the sections. Dividing by the total stretch tells us // how many 'whole' multiples we can allocate: int wholeMultiples = available / m_sectionStretchHintTotal; if(wholeMultiples > 0) { for(int i = 0; i < sizes.count() && i < m_sectionStretchHints.count(); i++) { int hint = m_sectionStretchHints[i]; if(hint > 0) sizes[i] += wholeMultiples * hint; } } available -= wholeMultiples * m_sectionStretchHintTotal; // we now have a small amount (less than m_sectionStretchHintTotal) of extra space to allocate. // we still want to assign this leftover proportional to the hints, otherwise we'd end up with a // stair-stepping effect. // To do this we calculate hint/total for each section then loop around adding on fractional // components to the sizes until one is above 1, then it gets a pixel, and we keep going until // all the remainder is allocated QVector<float> fractions, increment; fractions.resize(sizes.count()); increment.resize(sizes.count()); // set up increments for(int i = 0; i < sizes.count(); i++) { // don't assign any space to sections with negative hints, or sections without hints if(i >= m_sectionStretchHints.count() || m_sectionStretchHints[i] <= 0) { increment[i] = 0.0f; continue; } increment[i] = float(m_sectionStretchHints[i]) / float(m_sectionStretchHintTotal); } while(available > 0) { // loop along each section incrementing it. for(int i = 0; i < fractions.count(); i++) { fractions[i] += increment[i]; // if we have a whole pixel now, assign it if(fractions[i] > 1.0f) { fractions[i] -= 1.0f; sizes[i]++; available--; // if we've assigned all pixels, stop if(available == 0) break; } } } for(int pix = 0; pix < available; pix++) { int minSection = 0; for(int i = 1; i < sizes.count(); i++) { // don't assign any space to sections with negative hints if(i < m_sectionStretchHints.count() && m_sectionStretchHints[i] <= 0) continue; if(sizes[i] < sizes[minSection]) minSection = i; } sizes[minSection]++; } } resizeSections(sizes.toList()); }
bool DiacriticRules::on_match() { double ambiguity_reduction = 0.0; int least_ambiguity_position = -1; /** Number of Morphemes **/ int number_of_morphemes = 0; /** letter count of unvocalized word **/ int length = 0; QString vocalizedWord; QString unvocalizedWord; QVector<QString> prefixPOSs; QVector<QString> prefixes; QString stemPOS; QVector<QString> suffixPOSs; QVector<QString> suffixes; int prefix_length = 0; /** letter count of stem **/ int stem_length = 0; int suffix_length = 0; /** Get vocalized and unvocalized words **/ int prefix_infos_size = prefix_infos->size(); for (int i= 0; i<prefix_infos_size;i++) { minimal_item_info & pre = (*prefix_infos)[i]; if(!(pre.raw_data.isEmpty())) { number_of_morphemes++; vocalizedWord.append(pre.raw_data); } } prefix_length = removeDiacritics(vocalizedWord).count(); number_of_morphemes++; vocalizedWord.append(stem_info->raw_data); stem_length = removeDiacritics(stem_info->raw_data).count(); int suffix_infos_size = suffix_infos->size(); for (int i=0;i<suffix_infos_size;i++) { minimal_item_info & suff = (*suffix_infos)[i]; if(!(suff.raw_data.isEmpty())) { number_of_morphemes++; vocalizedWord.append(suff.raw_data); } } unvocalizedWord = removeDiacritics(vocalizedWord); /** Unvocalized word Character Count **/ length = unvocalizedWord.count(); suffix_length = length - (prefix_length + stem_length); /** Ambiguity of the unvocalized word **/ int unvocalizedAmbiguity = 0; WordAmbiguity wa(&unvocalizedWord, &unvocalizedAmbiguity); wa(); /** Discard this morphological solution if the unvocalized word is not ambiguous (has 1 morpho. solution) **/ if(unvocalizedAmbiguity < 2) { return true; } /// Select required morphological features /** Prefix Features **/ int j = 0; for (int i = (prefix_infos_size-1); (i>=0) && (j<4);i--) { minimal_item_info & pre = (*prefix_infos)[i]; if(pre.POS.isEmpty() && pre.raw_data.isEmpty()) { continue; } QStringList pre_poss = pre.POS.split('/'); if(pre_poss.count() != 2) { continue; } QString unvoc_pre_data = removeDiacritics(pre.raw_data); if(!(unvoc_pre_data.isEmpty())) { prefixes.prepend(unvoc_pre_data); } if(!(pre_poss[1].isEmpty())) { prefixPOSs.prepend(pre_poss[1]); } j++; } while(prefixes.count() < 4) { prefixes.prepend("EPRE"); } while(prefixPOSs.count() < 4) { prefixPOSs.prepend("EPREPOS"); } /** Stem Features **/ minimal_item_info & stem = *stem_info; //stem_length = removeDiacritics(stem.raw_data).count(); QStringList stem_poss = stem.POS.split('/'); if(stem_poss.count() != 2) { return true; } stemPOS = stem_poss[1]; /** Suffix Features **/ j = 0; for (int i=0;(i<suffix_infos_size) && (j<4);i++) { minimal_item_info & suff = (*suffix_infos)[i]; if(suff.POS.isEmpty() && suff.raw_data.isEmpty()) { continue; } QStringList suff_poss = suff.POS.split('/'); if(suff_poss.count() != 2) { continue; } QString unvoc_suf_data = removeDiacritics(suff.raw_data); if(!(unvoc_suf_data.isEmpty())) { suffixes.append(unvoc_suf_data); } if(!(suff_poss[1].isEmpty())) { suffixPOSs.append(suff_poss[1]); } j++; } while(suffixes.count() < 4) { suffixes.append("ESUF"); } while(suffixPOSs.count() < 4) { suffixPOSs.append("ESUFPOS"); } /// Detach diacritics from raw_data and store in separate structure int diacritic_Counter = 0; QVector<QVector<QChar> > wordDiacritics(length); int letterIndex = 0; for(int i=1; i<vocalizedWord.count(); i++) { QChar currentLetter= vocalizedWord[i]; if(isDiacritic(currentLetter)) { wordDiacritics[letterIndex].append(currentLetter); diacritic_Counter++; } else { letterIndex++; } } if(diacritic_Counter == 0) { return true; } /// Get the number of solutions for each solution with one diacritic /// Select diacritic position leastambiguous = least number of morphological solutions QVector<QVector<int> > diacriticAmbiguity(length); int least_ambiguity = unvocalizedAmbiguity + 1; int diacritic_Index = -1; for(int i=0; i< wordDiacritics.count(); i++) { for(j=0; j< wordDiacritics.at(i).count(); j++) { QString one_diacritic_word = unvocalizedWord; one_diacritic_word.insert(i+1,wordDiacritics[i][j]); int one_diacritic_Ambiguity = 0; WordAmbiguity wa(&one_diacritic_word, &one_diacritic_Ambiguity); wa(); if(one_diacritic_Ambiguity == 0) { diacriticAmbiguity[i].append(unvocalizedAmbiguity); } else { diacriticAmbiguity[i].append(one_diacritic_Ambiguity); } if(diacriticAmbiguity[i][j] < least_ambiguity) { least_ambiguity = diacriticAmbiguity[i][j]; least_ambiguity_position = i; diacritic_Index = j; } } } /** This weirdly happens when a word partial diacritics has ambiguity more than the unvocalized word (ex. dAn) **/ if((least_ambiguity_position == -1) || (diacritic_Index == -1)) { if(number_of_solutions == -1) { return true; } else if(solution_counter != number_of_solutions) { solution_counter++; return true; } else { return false; } } ambiguity_reduction = ((unvocalizedAmbiguity- diacriticAmbiguity[least_ambiguity_position][diacritic_Index]) * 1.0) / unvocalizedAmbiguity; /** Filter data to extract high ambiguity reduction instances **/ if(ambiguity_reduction < 0.667) { if(number_of_solutions == -1) { return true; } else if(solution_counter != number_of_solutions) { solution_counter++; return true; } else { return false; } } filtered_items++; /** Print/Use data **/ theSarf->out << number_of_morphemes << " " << length << " " << stem_length << " "; // prefixPOSs for(int i=0; i<prefixPOSs.count(); i++) { theSarf->out << prefixPOSs[i] << " "; } // prefixes for(int i=0; i< prefixes.count(); i++) { theSarf->out << prefixes[i] << " "; } // stemPOS theSarf->out << stemPOS << " "; // suffixPOSs for(int i=0; i<suffixPOSs.count(); i++) { theSarf->out << suffixPOSs[i] << " "; } // suffixes for(int i=0; i<suffixes.count(); i++) { theSarf->out << suffixes[i] << " "; } // least_ambiguity_position // prefixs , prefixm, prefixe , stems , stemm, steme , suffixs , suffixm, suffixe //theSarf->out << least_ambiguity_position << " "; QString diacritic_position; if((prefix_length != 0) && (least_ambiguity_position == 0)) { diacritic_position = "prefixs"; } else if((prefix_length != 0) && (least_ambiguity_position > 0) && (least_ambiguity_position < (prefix_length-1))) { diacritic_position = "prefixm"; } else if((prefix_length != 0) && (least_ambiguity_position == (prefix_length-1))) { diacritic_position = "prefixe"; } else if(least_ambiguity_position == prefix_length) { diacritic_position = "stems"; } else if((least_ambiguity_position > (prefix_length)) && (least_ambiguity_position < (prefix_length + stem_length - 1))) { diacritic_position = "stemm"; } else if(least_ambiguity_position == (prefix_length + stem_length - 1)) { diacritic_position = "steme"; } else if((suffix_length != 0) && (least_ambiguity_position == (prefix_length + stem_length))) { diacritic_position = "suffixs"; } else if((suffix_length != 0) && (least_ambiguity_position > (prefix_length + stem_length)) && (least_ambiguity_position < (length - 1))) { diacritic_position = "suffixm"; } else if((suffix_length != 0) && (least_ambiguity_position == (length -1))) { diacritic_position = "suffixe"; } else { cout << "Couldn't set diacritic position!" << endl; return false; } theSarf->out << diacritic_position << '\n'; // ambiguity_reduction //theSarf->out << ambiguity_reduction << '\n'; /** Check for number of solutions requested **/ if(number_of_solutions == -1) { return true; } else if(solution_counter != number_of_solutions) { solution_counter++; return true; } else { return false; } };
void DownloadManager::timerEvent(QTimerEvent* e) { QVector<QTime> remTimes; QVector<int> progresses; QVector<double> speeds; if (e->timerId() == m_timer.timerId()) { if (!ui->list->count()) { ui->speedLabel->clear(); setWindowTitle(tr("Download Manager")); #ifdef Q_OS_WIN if (m_taskbarButton) { m_taskbarButton->progress()->hide(); } #endif return; } for (int i = 0; i < ui->list->count(); i++) { DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i))); if (!downItem || downItem->isCancelled() || !downItem->isDownloading()) { continue; } progresses.append(downItem->progress()); remTimes.append(downItem->remainingTime()); speeds.append(downItem->currentSpeed()); } if (remTimes.isEmpty()) { return; } QTime remaining; foreach (const QTime &time, remTimes) { if (time > remaining) { remaining = time; } } int progress = 0; foreach (int prog, progresses) { progress += prog; } progress = progress / progresses.count(); double speed = 0.00; foreach (double spee, speeds) { speed += spee; } #ifndef Q_OS_WIN ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()), DownloadItem::currentSpeedToString(speed), DownloadItem::remaingTimeToString(remaining))); #endif setWindowTitle(tr("%1% - Download Manager").arg(progress)); #ifdef Q_OS_WIN if (m_taskbarButton) { m_taskbarButton->progress()->show(); m_taskbarButton->progress()->setValue(progress); } #endif } QWidget::timerEvent(e); }
void ArgumentsEditor::setupCall() { m_model->clear(); QStringList headers; headers.append(tr("Argument")); headers.append(tr("Value")); m_model->setColumnCount(2); m_model->setHorizontalHeaderLabels(headers); m_ui.argsTabWidget->removeTab( m_ui.argsTabWidget->indexOf(m_ui.shaderTab)); if (!m_call) return; m_ui.callLabel->setText(m_call->name()); QStandardItem *rootItem = m_model->invisibleRootItem(); for (int i = 0; i < m_call->argNames().count(); ++i) { QString argName = m_call->argNames()[i]; QVariant val = m_call->arguments()[i]; QStandardItem *nameItem = new QStandardItem(argName); nameItem->setFlags(nameItem->flags() ^ Qt::ItemIsEditable); QList<QStandardItem*> topRow; topRow.append(nameItem); if (val.canConvert<ApiArray>()) { ApiArray array = val.value<ApiArray>(); QVector<QVariant> vals = array.values(); QVariant firstVal = vals.value(0); if (firstVal.userType() == QVariant::String) { m_ui.argsTabWidget->addTab( m_ui.shaderTab, argName); setupShaderEditor(vals); delete nameItem; continue; } else if (isVariantEditable(firstVal)) { for (int i = 0; i < vals.count(); ++i) { QList<QStandardItem*> row; QStandardItem *idx = new QStandardItem(); idx->setFlags(idx->flags() ^ Qt::ItemIsEditable); idx->setText(tr("%1)").arg(i)); QStandardItem *col = new QStandardItem(); col->setFlags(col->flags() | Qt::ItemIsEditable); col->setData(vals[i], Qt::EditRole); row.append(idx); row.append(col); nameItem->appendRow(row); } } else { qDebug()<<"\tUnsupported array = "<<firstVal; delete nameItem; continue; } } else if (val.canConvert<ApiPointer>()) { ApiPointer ptr = val.value<ApiPointer>(); QStandardItem *item = new QStandardItem(); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setText(ptr.toString()); QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setToolTip(tr("Argument is read-only")); topRow.append(item); } else if (val.canConvert<ApiEnum>()) { ApiEnum en = val.value<ApiEnum>(); QStandardItem *item = new QStandardItem(); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setText(en.toString()); QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setToolTip(tr("Argument is read-only")); topRow.append(item); } else if (val.canConvert<ApiBitmask>()) { ApiBitmask mask = val.value<ApiBitmask>(); QStandardItem *item = new QStandardItem(); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setText(mask.toString()); QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setToolTip(tr("Argument is read-only")); topRow.append(item); } else if (val.canConvert<ApiStruct>()) { ApiStruct str = val.value<ApiStruct>(); QStandardItem *item = new QStandardItem(); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setText(str.toString()); QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setToolTip(tr("Argument is read-only")); topRow.append(item); } else if (val.userType() == QVariant::ByteArray) { QByteArray ba = val.value<QByteArray>(); QStandardItem *item = new QStandardItem(); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setText( tr("<binary data, size = %1 bytes>").arg(ba.size())); QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setToolTip(tr("Argument is read-only")); topRow.append(item); } else { QStandardItem *item = new QStandardItem(); if (isVariantEditable(val)) { item->setFlags(item->flags() | Qt::ItemIsEditable); } else { QIcon icon(":/resources/emblem-locked.png"); item->setIcon(icon); item->setFlags(item->flags() ^ Qt::ItemIsEditable); item->setToolTip(tr("Argument is read-only")); } item->setData(val, Qt::EditRole); topRow.append(item); } rootItem->appendRow(topRow); } }
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints ) { results.clear(); if ( !mSnapper ) return 5; //topological editing on? int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); //snapping on intersection on? int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); if ( topologicalEditing == 0 ) { if ( intersectionSnapping == 0 ) mSnapper->setSnapMode( QgsSnapper::SnapWithOneResult ); else mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } else if ( intersectionSnapping == 0 ) { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsForSamePosition ); } else { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } QgsVectorLayer* currentVectorLayer = dynamic_cast<QgsVectorLayer*>( mMapCanvas->currentLayer() ); if ( !currentVectorLayer ) { return 1; } //read snapping settings from project QStringList layerIdList, enabledList, toleranceList, toleranceUnitList, snapToList; bool ok, snappingDefinedInProject; QSettings settings; QString snappingMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode", "current_layer", &snappingDefinedInProject ); QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapToleranceUnit" ) : settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", "0" ).toString(); QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType" ) : settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance" ) ) : settings.value( "/qgis/digitizing/default_snapping_tolerance", "0" ).toString(); if ( !snappingDefinedInProject && defaultSnapType == "off" ) { return 0; } if ( snappingMode == "current_layer" || !snappingDefinedInProject ) { layerIdList.append( currentVectorLayer->id() ); enabledList.append( "enabled" ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); } else if ( snappingMode == "all_layers" ) { QList<QgsMapLayer*> allLayers = mMapCanvas->layers(); QList<QgsMapLayer*>::const_iterator layerIt = allLayers.constBegin(); for ( ; layerIt != allLayers.constEnd(); ++layerIt ) { if ( !( *layerIt ) ) { continue; } layerIdList.append(( *layerIt )->id() ); enabledList.append( "enabled" ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); } } else //advanced { layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &ok ); enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); } if ( !( layerIdList.size() == enabledList.size() && layerIdList.size() == toleranceList.size() && layerIdList.size() == toleranceUnitList.size() && layerIdList.size() == snapToList.size() ) ) { // lists must have the same size, otherwise something is wrong return 1; } QList<QgsSnapper::SnapLayer> snapLayers; QgsSnapper::SnapLayer snapLayer; // set layers, tolerances, snap to segment/vertex to QgsSnapper QStringList::const_iterator layerIt( layerIdList.constBegin() ); QStringList::const_iterator tolIt( toleranceList.constBegin() ); QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() ); QStringList::const_iterator snapIt( snapToList.constBegin() ); QStringList::const_iterator enabledIt( enabledList.constBegin() ); for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) { if ( *enabledIt != "enabled" ) { // skip layer if snapping is not enabled continue; } //layer QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) ); if ( !vlayer || !vlayer->hasGeometryType() ) continue; snapLayer.mLayer = vlayer; //tolerance snapLayer.mTolerance = tolIt->toDouble(); snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt(); // segment or vertex if ( *snapIt == "to vertex" || *snapIt == "to_vertex" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertex; } else if ( *snapIt == "to segment" || *snapIt == "to_segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToSegment; } else if ( *snapIt == "to vertex and segment" || *snapIt == "to_vertex_and_segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment; } else //off { continue; } snapLayers.append( snapLayer ); } mSnapper->setSnapLayers( snapLayers ); if ( mSnapper->snapMapPoint( point, results, excludePoints ) != 0 ) return 4; if ( intersectionSnapping != 1 ) return 0; QVector<QgsSnappingResult> segments; QVector<QgsSnappingResult> points; for ( QList<QgsSnappingResult>::const_iterator it = results.constBegin(); it != results.constEnd(); ++it ) { if ( it->snappedVertexNr == -1 ) { QgsDebugMsg( "segment" ); segments.push_back( *it ); } else { QgsDebugMsg( "no segment" ); points.push_back( *it ); } } if ( segments.count() < 2 ) return 0; QList<QgsSnappingResult> myResults; for ( QVector<QgsSnappingResult>::const_iterator oSegIt = segments.constBegin(); oSegIt != segments.constEnd(); ++oSegIt ) { QgsDebugMsg( QString::number( oSegIt->beforeVertexNr ) ); QVector<QgsPoint> vertexPoints; vertexPoints.append( oSegIt->beforeVertex ); vertexPoints.append( oSegIt->afterVertex ); QgsGeometry* lineA = QgsGeometry::fromPolyline( vertexPoints ); for ( QVector<QgsSnappingResult>::iterator iSegIt = segments.begin(); iSegIt != segments.end(); ++iSegIt ) { QVector<QgsPoint> vertexPoints; vertexPoints.append( iSegIt->beforeVertex ); vertexPoints.append( iSegIt->afterVertex ); QgsGeometry* lineB = QgsGeometry::fromPolyline( vertexPoints ); QgsGeometry* intersectionPoint = lineA->intersection( lineB ); delete lineB; if ( intersectionPoint && intersectionPoint->type() == Qgis::Point ) { //We have to check the intersection point is inside the tolerance distance for both layers double toleranceA = 0; double toleranceB = 0; for ( int i = 0 ;i < snapLayers.size();++i ) { if ( snapLayers[i].mLayer == oSegIt->layer ) { toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } if ( snapLayers[i].mLayer == iSegIt->layer ) { toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } } QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point ); double distance = intersectionPoint->distance( *cursorPoint ); if ( distance < toleranceA && distance < toleranceB ) { iSegIt->snappedVertex = intersectionPoint->asPoint(); myResults.append( *iSegIt ); } delete cursorPoint; } delete intersectionPoint; } delete lineA; } if ( myResults.length() > 0 ) { results.clear(); results = myResults; } return 0; }
ErrorList topolTest::checkGaps( QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent ) { Q_UNUSED( layer2 ); int i = 0; ErrorList errorList; GEOSContextHandle_t geosctxt = QgsGeos::getGEOSHandler(); // could be enabled for lines and points too // so duplicate rule may be removed? if ( layer1->geometryType() != QgsWkbTypes::PolygonGeometry ) { return errorList; } QList<FeatureLayer>::iterator it; QgsGeometry g1; QList<GEOSGeometry *> geomList; qDebug() << mFeatureList1.count() << " features in list!"; for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it ) { qDebug() << "reading features-" << i; if ( !( ++i % 100 ) ) { emit progress( i ); } if ( testCanceled() ) { break; } g1 = it->feature.geometry(); if ( g1.isNull() ) { continue; } if ( !_canExportToGeos( g1 ) ) { continue; } if ( !g1.isGeosValid() ) { qDebug() << "invalid geometry found..skipping.." << it->feature.id(); continue; } if ( g1.isMultipart() ) { QgsMultiPolygonXY polys = g1.asMultiPolygon(); for ( int m = 0; m < polys.count(); m++ ) { QgsPolygonXY polygon = polys[m]; QgsGeometry polyGeom = QgsGeometry::fromPolygonXY( polygon ); geomList.push_back( QgsGeos::asGeos( polyGeom ).release() ); } } else { geomList.push_back( QgsGeos::asGeos( g1 ).release() ); } } GEOSGeometry **geomArray = new GEOSGeometry*[geomList.size()]; for ( int i = 0; i < geomList.size(); ++i ) { //qDebug() << "filling geometry array-" << i; geomArray[i] = geomList.at( i ); } qDebug() << "creating geometry collection-"; if ( geomList.isEmpty() ) { //qDebug() << "geometry list is empty!"; delete [] geomArray; return errorList; } GEOSGeometry *collection = nullptr; collection = GEOSGeom_createCollection_r( geosctxt, GEOS_MULTIPOLYGON, geomArray, geomList.size() ); qDebug() << "performing cascaded union..might take time..-"; GEOSGeometry *unionGeom = GEOSUnionCascaded_r( geosctxt, collection ); //delete[] geomArray; QgsGeometry test = QgsGeos::geometryFromGeos( unionGeom ); //qDebug() << "wktmerged - " << test.exportToWkt(); QString extentWkt = test.boundingBox().asWktPolygon(); QgsGeometry extentGeom = QgsGeometry::fromWkt( extentWkt ); QgsGeometry bufferExtent = extentGeom.buffer( 2, 3 ); //qDebug() << "extent wkt - " << bufferExtent->exportToWkt(); QgsGeometry diffGeoms = bufferExtent.difference( test ); if ( !diffGeoms ) { qDebug() << "difference result 0-"; return errorList; } //qDebug() << "difference gometry - " << diffGeoms->exportToWkt(); QVector<QgsGeometry> geomColl = diffGeoms.asGeometryCollection(); QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() ); for ( int i = 1; i < geomColl.count() ; ++i ) { QgsGeometry conflictGeom = geomColl[i]; if ( isExtent ) { if ( canvasExtentPoly.disjoint( conflictGeom ) ) { continue; } if ( canvasExtentPoly.crosses( conflictGeom ) ) { conflictGeom = conflictGeom.intersection( canvasExtentPoly ); } } QgsRectangle bBox = conflictGeom.boundingBox(); FeatureLayer ftrLayer1; ftrLayer1.layer = layer1; QList<FeatureLayer> errorFtrLayers; errorFtrLayers << ftrLayer1 << ftrLayer1; TopolErrorGaps *err = new TopolErrorGaps( bBox, conflictGeom, errorFtrLayers ); errorList << err; } return errorList; }
QString VariableEditor::updateFromPreprocessor(Parser::Preprocessor* pp, QString in, bool* showGUI) { if (spacer) { layout->removeItem(spacer); delete(spacer); spacer = 0; } QVector<Parser::GuiParameter*> ps = pp->getParameters(); QMap<QString, QString> substitutions; for (int i = 0; i < variables.count(); i++) { QString name = variables[i]->getName(); variables[i]->setUpdated(false); } for (int i = 0; i < ps.count(); i++) { bool found = false; for (int j = 0; j < variables.count(); j++) { QString name = variables[j]->getName(); if (name == ps[i]->getName()) { substitutions[name] = variables[j]->getValueAsText(); found = true; variables[j]->setUpdated(true); //INFO("Found existing: " + variables[j]->getName() + QString(" value: %1").arg(variables[j]->getValueAsText())); } } if (!found) { if (dynamic_cast<Parser::FloatParameter*>(ps[i])) { Parser::FloatParameter* fp = dynamic_cast<Parser::FloatParameter*>(ps[i]); QString name = fp->getName(); FloatWidget* fw = new FloatWidget(this, name, fp->getDefaultValue(), fp->getFrom(), fp->getTo()); variables.append(fw); fw->setUpdated(true); layout->addWidget(fw); substitutions[name] = fw->getValueAsText(); } if (dynamic_cast<Parser::IntParameter*>(ps[i])) { Parser::IntParameter* ip = dynamic_cast<Parser::IntParameter*>(ps[i]); QString name = ip->getName(); IntWidget* iw = new IntWidget(this, name, ip->getDefaultValue(), ip->getFrom(), ip->getTo()); variables.append(iw); iw->setUpdated(true); layout->addWidget(iw); substitutions[name] = iw->getValueAsText(); } } } for (int i = 0; i < variables.count(); ) { if (!variables[i]->isUpdated()) { //INFO("Deleting : " + variables[i]->getName()); delete(variables[i]); variables.remove(i); i = 0; } else { i++; } } if (showGUI) (*showGUI) = (variables.count() != 0); QMap<QString, QString>::const_iterator it2 = substitutions.constBegin(); int subst = 0; while (it2 != substitutions.constEnd()) { if (subst>100) { WARNING("More than 100 recursive preprocessor substitutions... breaking."); break; } if (in.contains(it2.key())) { //INFO("Replacing: " + it2.key() + " with " + it2.value()); in.replace(it2.key(), it2.value()); it2 = substitutions.constBegin(); subst++; } else { it2++; } } spacer = new QSpacerItem(1,1, QSizePolicy::Minimum,QSizePolicy::Expanding); layout->addItem(spacer); return in; }
bool QSQLite2ResultPrivate::fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch) { // may be caching. const char **fvals; const char **cnames; int colNum; int res; int i; if (skipRow) { // already fetched Q_ASSERT(!initialFetch); skipRow = false; for(int i=0;i<firstRow.count(); i++) values[i] = firstRow[i]; return skippedStatus; } skipRow = initialFetch; if (!currentMachine) return false; // keep trying while busy, wish I could implement this better. while ((res = sqlite_step(currentMachine, &colNum, &fvals, &cnames)) == SQLITE_BUSY) { // sleep instead requesting result again immidiately. #if defined Q_WS_WIN32 Sleep(1000); #else sleep(1); #endif } if(initialFetch) { firstRow.clear(); firstRow.resize(colNum); } switch(res) { case SQLITE_ROW: // check to see if should fill out columns if (rInf.isEmpty()) // must be first call. init(cnames, colNum); if (!fvals) return false; if (idx < 0 && !initialFetch) return true; for (i = 0; i < colNum; ++i) values[i + idx] = utf8 ? QString::fromUtf8(fvals[i]) : QString::fromAscii(fvals[i]); return true; case SQLITE_DONE: if (rInf.isEmpty()) // must be first call. init(cnames, colNum); q->setAt(QSql::AfterLastRow); return false; case SQLITE_ERROR: case SQLITE_MISUSE: default: // something wrong, don't get col info, but still return false finalize(); // finalize to get the error message. q->setAt(QSql::AfterLastRow); return false; } return false; }
inline bool validIndex(int index) { return index >= 0 && index < segments.count(); }
void Analisator::startOperation(const QString &path, Core::DataBaseManager *dbm, QVector<QPair<QListWidgetItem *, Marker *> > *markers, QString& answer) { if(path.isEmpty()) { qDebug() << "path" << path; return; } QVector<MorphData*>* currentData = new QVector<MorphData*>; QMap<qint64, QVector<MorphData*>* > *storedData = new QMap<qint64, QVector<MorphData*>* >; qDebug() << "readMorphology " << dbm->readMorphology(storedData); qDebug() << *storedData; for(auto it = storedData->begin(); it != storedData->end(); ++it) { if(it.value() == NULL) continue; qDebug() << it.key() << *(it.value()); } qDebug("1"); QImage image; qDebug("2"); image.load(path + "/Morph/morph.png"); for(int i = 0; i < markers->count(); ++ i) { qDebug() << i; qDebug() << (long long) (*markers)[i].first; Marker* marker = (*markers)[i].second; qDebug() << (long long) marker; if(marker == NULL || marker->name == "Arrow") continue; QPoint p1, p2; if(marker->name != "Polygon") { p1 = (marker->item->firstPoint) / ((qreal)marker->item->currentScale); p2 = (marker->item->secondPoint) / ( (qreal)marker->item->currentScale); } else { p1 = (marker->advancedItem->bRect.topLeft()) / ( (qreal)marker->advancedItem->currentScale); p2 = (marker->advancedItem->bRect.bottomRight()) / ((qreal)marker->advancedItem->currentScale); } QRect tmp(p1,p2); qDebug() << "tmp" << tmp; tmp = tmp.normalized(); MorphData* data = new MorphData; qDebug() << "lalsad" << (*data = mediator->calculate(tmp,image)).AverageRadius; currentData->push_back(data); } if(currentData->count() != 1) pirsonCorrelation(dbm,currentData, storedData, answer); else answer = "Мало данных 1 маркрера не достаточно"; qDebug() << "ВСЁ"; for(auto it = storedData->begin(); it != storedData->end(); ++it) { if(it.value()->count()) qDeleteAll(*it.value()); } qDebug() << "ВСЁ"; qDeleteAll(*storedData); qDebug() << "ВСЁ"; qDeleteAll(*currentData); qDebug() << "ВСЁ"; delete storedData; qDebug() << "ВСЁ"; delete currentData; }
void QSoftKeyDesignToolWidget::updateUIButtonState( int nSelectKeyCount, GroupStatus eGroupStatus, QVector<CSoftkey*>& SelectKeys ) { bool bEnableRemove; if ( nSelectKeyCount >= 1 ) bEnableRemove = true; else bEnableRemove = false; if ( s_bEnableRemove != bEnableRemove ) { ui->BtnRemove->setEnabled( bEnableRemove ); s_bEnableRemove = bEnableRemove; } m_pLayoutToolWidget->updateUIButtonState( nSelectKeyCount ); switch ( eGroupStatus ) { case EnableGroup: ui->BtnGroup->setEnabled( true ); ui->BtnUngroup->setEnabled( false ); break; case EnableUngroup: ui->BtnGroup->setEnabled( false ); ui->BtnUngroup->setEnabled( true ); break; case DisableGroup: ui->BtnGroup->setEnabled( false ); ui->BtnUngroup->setEnabled( false ); break; } if ( SelectKeys.count() == 0 ) { m_rcOld.setRect( 0,0,0,0 ); ui->EditName->clear(); ui->CBVisible->setCurrentIndex( -1 ); ui->CBVisible->setEnabled( false ); ui->EditName->setEnabled( false ); ui->EditPosX->setEnabled( false ); ui->EditPosY->setEnabled( false ); ui->EditWidth->setEnabled( false ); ui->EditHeight->setEnabled( false ); ui->BtnReorder->setEnabled( false ); ui->EditPosX->clear(); ui->EditPosY->clear(); ui->EditWidth->clear(); ui->EditHeight->clear(); } else if ( SelectKeys.count() == 1 ) { CSoftkey* key = SelectKeys.at(0); ui->EditName->setText( key->getName() ); ui->CBVisible->setCurrentIndex( key->getShow() ? 0 : 1 ); QRect rc( key->getPosition() ); if( m_eUnit == UnitMM ) { double dPX = rc.left() * m_dD2PScaleWidth; double dPY = rc.top() * m_dD2PScaleHeight; double dW = rc.width() * m_dD2PScaleWidth; double dH = rc.height() * m_dD2PScaleHeight; qDebug() << "MM : " << dH << "," << rc.height(); ui->EditPosX->setText( QString("%1").arg(dPX, 0, 'f', 1) ); ui->EditPosY->setText( QString("%1").arg(dPY, 0, 'f', 1) ); ui->EditWidth->setText( QString("%1").arg(dW, 0, 'f', 1) ); ui->EditHeight->setText( QString("%1").arg(dH, 0, 'f', 1) ); m_rcOld.setRect( dPX / m_dD2PScaleWidth, dPY / m_dD2PScaleWidth, dW / m_dD2PScaleWidth, dH / m_dD2PScaleWidth ); } else { qDebug() << QString("%1,%2,%3,%4").arg(rc.left()).arg(rc.top()).arg(rc.width()).arg(rc.height()); ui->EditPosX->setText( QString::number( rc.left() ) ); ui->EditPosY->setText( QString::number( rc.top() ) ); ui->EditWidth->setText( QString::number( rc.width() ) ); ui->EditHeight->setText( QString::number( rc.height() ) ); m_rcOld.setRect( ui->EditPosX->text().toDouble(), ui->EditPosY->text().toDouble(), ui->EditWidth->text().toDouble(), ui->EditHeight->text().toDouble() ); } ui->CBVisible->setEnabled( true ); ui->EditName->setEnabled( true ); ui->EditPosX->setEnabled( true ); ui->EditPosY->setEnabled( true ); ui->EditWidth->setEnabled( true ); ui->EditHeight->setEnabled( true ); } else if( SelectKeys.count() > 1 ) { int nVisible = -1; QRect rcMerge; for ( int nI=0 ; nI<SelectKeys.count() ; nI++ ) { CSoftkey* key = SelectKeys.at(nI); rcMerge = rcMerge.united( key->getPosition() ); if ( nVisible < 0 ) nVisible = key->getShow(); else { if ( nVisible != key->getShow() ) { nVisible = 2; } } } if( m_eUnit == UnitMM ) { double dPX = rcMerge.left() * m_dD2PScaleWidth; double dPY = rcMerge.top() * m_dD2PScaleHeight; double dW = rcMerge.width() * m_dD2PScaleWidth; double dH = rcMerge.height() * m_dD2PScaleHeight; ui->EditPosX->setText( QString("%1").arg(dPX, 0, 'f', 1) ); ui->EditPosY->setText( QString("%1").arg(dPY, 0, 'f', 1) ); ui->EditWidth->setText( QString("%1").arg(dW, 0, 'f', 1) ); ui->EditHeight->setText( QString("%1").arg(dH, 0, 'f', 1) ); m_rcOld.setRect( dPX / m_dD2PScaleWidth, dPY / m_dD2PScaleWidth, dW / m_dD2PScaleWidth, dH / m_dD2PScaleWidth ); } else { ui->EditPosX->setText( QString::number( rcMerge.left() ) ); ui->EditPosY->setText( QString::number( rcMerge.top() ) ); ui->EditWidth->setText( QString::number( rcMerge.width() ) ); ui->EditHeight->setText( QString::number( rcMerge.height() ) ); m_rcOld.setRect( ui->EditPosX->text().toDouble(), ui->EditPosY->text().toDouble(), ui->EditWidth->text().toDouble(), ui->EditHeight->text().toDouble() ); } switch ( nVisible ) { case 0: ui->CBVisible->setCurrentIndex( 0 ); break; case 1: ui->CBVisible->setCurrentIndex( 1 ); break; case -1: case 2: ui->CBVisible->setCurrentIndex( -1 ); break; } ui->EditName->clear(); ui->CBVisible->setEnabled( true ); ui->EditName->setEnabled( true ); ui->EditPosX->setEnabled( true ); ui->EditPosY->setEnabled( true ); ui->EditWidth->setEnabled( true ); ui->EditHeight->setEnabled( true ); ui->BtnReorder->setEnabled( true ); } }
void Cube::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glTranslatef(0.0, 0.0, -3.0); //glRotatef(91, 0, 1, 0); glRotated(y_angle, 1.0, 0.0, 0.0);glRotatef(x_angle, 0.0, 1.0, 0.0); #define rgbVertex(X, Y, Z) {glColor3d(X,Y,Z);glVertex3d(X,Y,Z);} glCallList(m_cube); double vx,vy,vz,zx,zy,zz,D,x,y,z; vx=sin(x_angle*M_PI/180)*cos(y_angle*M_PI/180); vy=-sin(y_angle*M_PI/180); vz=-cos(x_angle*M_PI/180)*cos(y_angle*M_PI/180); zx=zy=zz=0.5; zx+=0.01*vx*d; zy+=0.01*vy*d; zz+=0.01*vz*d; D=-zx*vx-zy*vy-zz*vz; QVector <point> p; char w[4][2]={{0,0}, {1,0}, {1,1}, {0,1}}; int i; for (i=0; i<4; i++) { if (abs(vx)>0.000001) { x=(-D-vy*w[i][0]-vz*w[i][1])/vx; if (x>=0 && x<=1) p.push_back(pnt3(x,w[i][0],w[i][1])); } if (abs(vy)>0.000001) { y=(-D-vx*w[i][0]-vz*w[i][1])/vy; if (y>=0 && y<=1) p.push_back(pnt3(w[i][0],y,w[i][1])); } if (abs(vz)>0.000001) { z=(-D-vx*w[i][0]-vy*w[i][1])/vz; if (z>=0 && z<=1) p.push_back(pnt3(w[i][0],w[i][1],z)); } } #define sqr(_X) ((_X)*(_X)) #define len(_V) (sqrt(sqr(_V.x-zx)+sqr(_V.y-zy)+sqr(_V.z-zz))) if (p.size()<3) return; int j; QVector <double> v; double pv; v.resize(p.size()); v[0]=0; for (i=1; i<p.size(); i++) { v[i]=acos(pv=((p[i].x-zx)*(p[0].x-zx)+ (p[i].y-zy)*(p[0].y-zy)+ (p[i].z-zz)*(p[0].z-zz))/(len(p[0])*len(p[i]))); if (pv==-1) v[i]=M_PI; else if (vx*((p[0].y-zy)*(p[i].z-zz)-(p[0].z-zz)*(p[i].y-zy))+ vy*((p[0].x-zx)*(p[i].z-zz)-(p[0].z-zz)*(p[i].x-zx))+ vz*((p[0].x-zx)*(p[i].y-zy)-(p[0].y-zy)*(p[i].x-zx)) >= 0) v[i]=M_PI*2-v[i]; } qDebug() << v; for (i=0; i<p.size()-1; i++) for (j=0; j<p.size()-i-1; j++) { if (v[j]>v[j+1]) { swap(v[j], v[j+1]); swap(p[j], p[j+1]); } } qDebug() << v; glBegin(GL_LINE_STRIP); //glBegin(GL_POLYGON); for (i=0; i<p.count(); i++) rgbVertex(p[i].x, p[i].y, p[i].z); glEnd(); }