/**
      * Redimensionne la taille des tableaux de chunk.
      * Positionne aussi la position des chunk nouvellement conçus.
      * @return La liste des chunk à générer
      */
    QList<Chunk::Chunk*> WorldGenerator::_redim(qint32 x, qint32 y)
    {
        QList<Chunk::Chunk*> list;
        int oldSize;
        if (y < 0)
        {
            if (x < 0)
            {
                x = abs(x);
                if (abs(y) >= _world->_chunkTL.size())
                {
                    _world->_chunkTL.resize(abs(y) + 2);
                }
                for (int i = 0; i <= abs(y) + 1; i++)
                {
                    oldSize = _world->_chunkTL[i].size();
                    oldSize = oldSize == 0 ? 1 : oldSize;
                    _world->_chunkTL[i].resize(abs(x) + 2);
                    for (int j = oldSize; j <= x + 1; j++)
                    {
                        _world->_chunkTL[i][j] = new Chunk::Chunk(-1 * (j - 1) * BaseConfig::CHUNK_SIZE - 1, -1 * (i - 1) * BaseConfig::CHUNK_SIZE - 1);
                        list.push_back(_world->_chunkTL[i][j]);
                    }
                }
            }
            else
            {
                if (abs(y) >= _world->_chunkTR.size())
                {
                    _world->_chunkTR.resize(abs(y) + 2);
                }
                for (int i = 0; i <= abs(y) + 1; i++)
                {
                    oldSize = _world->_chunkTR[i].size();
                    oldSize = oldSize == 0 ? 1 : oldSize;
                    _world->_chunkTR[i].resize(x + 2);
                    for (int j = oldSize; j <= x + 1; j++)
                    {                      
                        _world->_chunkTR[i][j] = new Chunk::Chunk((j - 1) * BaseConfig::CHUNK_SIZE, -1 * (i - 1) * BaseConfig::CHUNK_SIZE - 1);
                        list.push_back(_world->_chunkTR[i][j]);
                    }

                }

            }
        }
        else
        {
            if (x < 0)
            {
                x = abs(x);
                if (y >= _world->_chunkBL.size())
                {
                    _world->_chunkBL.resize(y + 2);
                }
                for (int i = 0; i <= y + 1; i++)
                {
                    oldSize = _world->_chunkBL[i].size();
                    oldSize = oldSize == 0 ? 1 : oldSize;
                    _world->_chunkBL[i].resize(abs(x) + 2);
                    for (int j = oldSize; j <= abs(x) + 1; j++)
                    {                        
                        _world->_chunkBL[i][j] = new Chunk::Chunk(-1 * (j - 1) * BaseConfig::CHUNK_SIZE - 1, (i - 1)  * BaseConfig::CHUNK_SIZE);
                        list.push_back(_world->_chunkBL[i][j]);
                    }
                }
            }
            else
            {
                if (y >= _world->_chunkBR.size())
                {
                    _world->_chunkBR.resize(y + 2);
                }
                for (int i = 0; i <= y + 1; i++)
                {
                    oldSize = _world->_chunkBR[i].size();
                    oldSize = oldSize == 0 ? 1 : oldSize;
                    _world->_chunkBR[i].resize(x + 2);
                    for (int j = oldSize; j <= x + 1; j++)
                    {
                        _world->_chunkBR[i][j] = new Chunk::Chunk((j - 1) * BaseConfig::CHUNK_SIZE, (i - 1) * BaseConfig::CHUNK_SIZE);
                        list.push_back(_world->_chunkBR[i][j]);
                    }
                }

            }
        }
        return list;

    }
QList< QList< int > > QgsCoordinateTransform::datumTransformations( const QgsCoordinateReferenceSystem& srcCRS, const QgsCoordinateReferenceSystem& destCRS )
{
  QList< QList< int > > transformations;

  QString srcGeoId = srcCRS.geographicCRSAuthId();
  QString destGeoId = destCRS.geographicCRSAuthId();

  if ( srcGeoId.isEmpty() || destGeoId.isEmpty() )
  {
    return transformations;
  }

  QStringList srcSplit = srcGeoId.split( ":" );
  QStringList destSplit = destGeoId.split( ":" );

  if ( srcSplit.size() < 2 || destSplit.size() < 2 )
  {
    return transformations;
  }

  int srcAuthCode = srcSplit.at( 1 ).toInt();
  int destAuthCode = destSplit.at( 1 ).toInt();

  if ( srcAuthCode == destAuthCode )
  {
    return transformations; //crs have the same datum
  }

  QList<int> directTransforms;
  searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code=%1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( destAuthCode ),
                        directTransforms );
  QList<int> reverseDirectTransforms;
  searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code = %1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( srcAuthCode ),
                        reverseDirectTransforms );
  QList<int> srcToWgs84;
  searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( 4326 ),
                        srcToWgs84 );
  QList<int> destToWgs84;
  searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( 4326 ),
                        destToWgs84 );

  //add direct datum transformations
  QList<int>::const_iterator directIt = directTransforms.constBegin();
  for ( ; directIt != directTransforms.constEnd(); ++directIt )
  {
    transformations.push_back( QList<int>() << *directIt << -1 );
  }

  //add direct datum transformations
  directIt = reverseDirectTransforms.constBegin();
  for ( ; directIt != reverseDirectTransforms.constEnd(); ++directIt )
  {
    transformations.push_back( QList<int>() << -1 << *directIt );
  }

  QList<int>::const_iterator srcWgsIt = srcToWgs84.constBegin();
  for ( ; srcWgsIt != srcToWgs84.constEnd(); ++srcWgsIt )
  {
    QList<int>::const_iterator dstWgsIt = destToWgs84.constBegin();
    for ( ; dstWgsIt != destToWgs84.constEnd(); ++dstWgsIt )
    {
      transformations.push_back( QList<int>() << *srcWgsIt << *dstWgsIt );
    }
  }

  return transformations;
}
Exemple #3
0
/**
 * @brief Creates tokens from a single GDB output row.
 */
QList<Token*> GdbMiParser::tokenizeVarString(QString str)
{
    enum { IDLE, BLOCK, BLOCK_COLON, STRING, VAR} state = IDLE;
    QList<Token*> list;
    Token *cur = NULL;
    QChar prevC = ' ';
    
    if(str.isEmpty())
        return list;

    for(int i = 0;i < str.size();i++)
    {
        QChar c = str[i];
        switch(state)
        {
            case IDLE:
            {
                if(c == '"')
                {
                    cur = new Token(Token::C_STRING);
                    list.push_back(cur);
                    state = STRING;
                }
                else if(c == '<')
                {
                    cur = new Token(Token::VAR);
                    list.push_back(cur);
                    cur->text += c;
                    state = BLOCK;
                }
                else if(c == '(')
                {
                    cur = new Token(Token::VAR);
                    list.push_back(cur);
                    cur->text += c;
                    state = BLOCK_COLON;
                }
                else if(c == '=' || c == '{' || c == '}' || c == ',' ||
                    c == '[' || c == ']' || c == '+' || c == '^' ||
                    c == '~' || c == '@' || c == '&' || c == '*')
                {
                    Token::Type type = Token::UNKNOWN;
                    if(c == '=')
                        type = Token::KEY_EQUAL;
                    if(c == '{')
                        type = Token::KEY_LEFT_BRACE;
                    if(c == '}')
                        type = Token::KEY_RIGHT_BRACE;
                    if(c == '[')
                        type = Token::KEY_LEFT_BAR;
                    if(c == ']')
                        type = Token::KEY_RIGHT_BAR;
                    if(c == ',')
                        type = Token::KEY_COMMA;
                    if(c == '^')
                        type = Token::KEY_UP;
                    if(c == '+')
                        type = Token::KEY_PLUS;
                    if(c == '~')
                        type = Token::KEY_TILDE;
                    if(c == '@')
                        type = Token::KEY_SNABEL;
                    if(c == '&')
                        type = Token::KEY_AND;
                    if(c == '*')
                        type = Token::KEY_STAR;
                    cur = new Token(type);
                    list.push_back(cur);
                    cur->text += c;
                    state = IDLE;
                }
                else if( c != ' ')
                {
                    cur = new Token(Token::VAR);
                    list.push_back(cur);
                    cur->text = c;
                    state = VAR;
                }
                
            };break;
            case STRING:
            {
                if(prevC != '\\' && c == '\\')
                {
                }
                else if(prevC == '\\')
                {
                    if(c == 'n')
                        cur->text += '\n';
                    else
                        cur->text += c;
                }
                else if(c == '"')
                    state = IDLE;
                else
                    cur->text += c;
            };break;
            case BLOCK_COLON:
            case BLOCK:
            {
                if(prevC != '\\' && c == '\\')
                {
                }
                else if(prevC == '\\')
                {
                    if(c == 'n')
                        cur->text += '\n';
                    else
                        cur->text += c;
                }
                else if((c == '>' && state == BLOCK) ||
                        (c == ')' && state == BLOCK_COLON))
                {
                    cur->text += c;
                    state = IDLE;
                }
                else
                    cur->text += c;
            };break;
            case VAR:
            {
                if(c == ' ' || c == '=' || c == ',' || c == '{' || c == '}')
                {
                    i--;
                    cur->text = cur->text.trimmed();
                    state = IDLE;
                }
                else
                    cur->text += c;
            };break;
            
        }
        prevC = c;
    }
    if(cur)
    {
        if(cur->getType() == Token::VAR)
            cur->text = cur->text.trimmed();
    }
    return list;
}
Exemple #4
0
void Plots::changeOrder(QList<std::tuple<int, int> > orderedFilterInfo)
{
    if(orderedFilterInfo.empty())
    {
        qDebug() << "orderedFilterInfo is empty, do not reorder..";
        return;
    }

    qDebug() << "changeOrder: items = " << orderedFilterInfo.count();

    auto gridLayout = static_cast<QGridLayout*> (layout());
    auto rowsCount = gridLayout->rowCount();

    Q_ASSERT(m_plotsCount <= rowsCount);

    qDebug() << "plotsCount: " << m_plotsCount;

    QList <std::tuple<size_t, size_t, size_t>> currentOrderedPlotsInfo;
    QList <std::tuple<size_t, size_t, size_t>> expectedOrderedPlotsInfo;

    for(auto row = 0; row < m_plotsCount; ++row)
    {
        auto plotItem = gridLayout->itemAtPosition(row, 0);
        auto legendItem = gridLayout->itemAtPosition(row, 1);

        Q_ASSERT(plotItem);
        Q_ASSERT(legendItem);

        auto plot = qobject_cast<Plot*> (plotItem->widget());
        Q_ASSERT(plot);

        currentOrderedPlotsInfo.push_back(std::make_tuple(plot->group(), plot->type(), plot->streamPos()));
    }

    for(auto filterInfo : orderedFilterInfo)
    {
        for(auto plotInfo : currentOrderedPlotsInfo)
        {
            if(std::get<0>(plotInfo) == std::get<0>(filterInfo) && std::get<1>(plotInfo) == std::get<1>(filterInfo))
            {
                expectedOrderedPlotsInfo.push_back(plotInfo);
            }
        }
    }

    Q_ASSERT(currentOrderedPlotsInfo.length() == expectedOrderedPlotsInfo.length());
    if(currentOrderedPlotsInfo.length() != expectedOrderedPlotsInfo.length())
        return;

    for(auto i = 0; i < expectedOrderedPlotsInfo.length(); ++i)
    {
        qDebug() << "cg: " << std::get<0>(currentOrderedPlotsInfo[i])
                 << ", "
                 << "ct: " << std::get<1>(currentOrderedPlotsInfo[i])
                 << ", "
                 << "cp: " << std::get<2>(currentOrderedPlotsInfo[i])
                 << ", "
                 << "eg: " << std::get<0>(expectedOrderedPlotsInfo[i])
                 << ", "
                 << "et: " << std::get<1>(expectedOrderedPlotsInfo[i])
                 << ", "
                 << "ep: " << std::get<2>(expectedOrderedPlotsInfo[i]);
    }

    for(auto i = 0; i < expectedOrderedPlotsInfo.length(); ++i)
    {
        if(expectedOrderedPlotsInfo[i] != currentOrderedPlotsInfo[i])
        {
            // search current item which we should put at expected position
            for(auto j = 0; j < expectedOrderedPlotsInfo.length(); ++j)
            {
                if(expectedOrderedPlotsInfo[i] == currentOrderedPlotsInfo[j])
                {
                    qDebug() << "i: " << i << ", j: " << j;

                    auto plotWidget = gridLayout->itemAtPosition(j, 0)->widget();
                    auto legendWidget = gridLayout->itemAtPosition(j, 1)->widget();

                    {
                        auto plot = qobject_cast<Plot*> (plotWidget);
                        qDebug() << "jg: " << plot->group() << ", t: " << plot->type() << ", p: " << plot->streamPos() << ", ptr = " << plot;
                    }

                    auto swapPlotWidget = gridLayout->itemAtPosition(i, 0)->widget();
                    auto swapLegendWidget = gridLayout->itemAtPosition(i, 1)->widget();

                    {
                        auto plot = qobject_cast<Plot*> (swapPlotWidget);
                        qDebug() << "ig: " << plot->group() << ", t: " << plot->type() << ", p: " << plot->streamPos() << ", ptr = " << plot;
                    }

                    gridLayout->removeWidget(plotWidget);
                    gridLayout->removeWidget(legendWidget);

                    gridLayout->removeWidget(swapPlotWidget);
                    gridLayout->removeWidget(swapLegendWidget);

                    gridLayout->addWidget(plotWidget, i, 0);
                    gridLayout->addWidget(legendWidget, i, 1);

                    gridLayout->addWidget(swapPlotWidget, j, 0);
                    gridLayout->addWidget(swapLegendWidget, j, 1);

                    currentOrderedPlotsInfo[j] = currentOrderedPlotsInfo[i];
                    currentOrderedPlotsInfo[i] = expectedOrderedPlotsInfo[i];

                    break;
                }
            }
        }
    }

    Q_ASSERT(rowsCount == gridLayout->rowCount());

    for(auto row = 0; row < m_plotsCount; ++row)
    {
        auto plotItem = gridLayout->itemAtPosition(row, 0);
        auto legendItem = gridLayout->itemAtPosition(row, 1);

        Q_ASSERT(plotItem);
        Q_ASSERT(legendItem);

        auto plot = qobject_cast<Plot*> (plotItem->widget());
        Q_ASSERT(plot);

        Q_ASSERT(plot->group() == std::get<0>(expectedOrderedPlotsInfo[row]) &&
                 plot->type() == std::get<1>(expectedOrderedPlotsInfo[row]));
    }
}
Exemple #5
0
void SceneLoader::appendMesh(const QDomElement & meshNode) {
    string name = meshNode.attribute("name").toStdString();
    LogDebug << "Mesh name:" << name;
    Mesh *mesh = NULL;

    if (meshNode.tagName() == "File") {
        string meshUrl = meshNode.attribute("url").toStdString();
        QList<string> attributes;
        attributes.push_back("normal");
        attributes.push_back("tangent");
        attributes.push_back("bitangent");
        attributes.push_back("uv");
            mesh = MeshLoader::load(attributes, meshUrl);
    } else if (meshNode.tagName() == "Procedural") {
        if (meshNode.attribute("type") == "Sponge") {
          QList<string> attributes;
          attributes.push_back("normal");
          MengerSponge * sponge = new MengerSponge(attributes, meshNode.attribute(
                    "recursion").toUInt());
          mesh = sponge->getMesh();
        } else if (meshNode.attribute("type") == "Stars") {
          QList<string> attributes;
          attributes.push_back("color");
          float resolution = meshNode.attribute("resolution").toFloat();
          QVector3D resolutionVec =
                  QVector3D(resolution, resolution, resolution);
            mesh = Geometry::stars(
                attributes,
                    resolutionVec,
                    meshNode.attribute("density").toFloat(),
                    meshNode.attribute("randomness").toFloat(),
                    meshNode.attribute("colorIntensity").toFloat());
        } else if (meshNode.attribute("type") == "Tetrahedron") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::tetrahedron(attributes);
        } else if (meshNode.attribute("type") == "Cube") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::cube(attributes);
        } else if (meshNode.attribute("type") == "Plane") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::plane(
                attributes,
                QRectF(
                    meshNode.attribute("left").toFloat(),
                    meshNode.attribute("top").toFloat(),
                    meshNode.attribute("width").toFloat(),
                    meshNode.attribute("height").toFloat()));
        } else if (meshNode.attribute("type") == "Sphere") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::sphere(
                attributes,
                    meshNode.attribute("radius").toFloat(),
                    meshNode.attribute("slices").toInt(),
                    meshNode.attribute("stacks").toInt());
        } else if (meshNode.attribute("type") == "Icosahedron") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::icosahedron(attributes);
        } else if (meshNode.attribute("type") == "Spiral") {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::spiral(
                attributes,
                    meshNode.attribute("resolution").toInt());
        } else {
          QList<string> attributes;
          attributes.push_back("color");
            mesh = Geometry::cube(attributes);
          LogError << "Unknown Mesh Type" << meshNode.attribute("type").toStdString();
        }

    }
    if (meshNode.hasAttribute("drawType")) {
      GLenum drawType = GL_TRIANGLES;
      string drawTypeString = meshNode.attribute("drawType").toStdString();

      if (drawTypeString == "PATCHES")
        drawType = GL_PATCHES;
      else if (drawTypeString == "POINTS")
        drawType = GL_POINTS;
      else if (drawTypeString == "TRIANGLE_STRIP")
        drawType = GL_TRIANGLE_STRIP;
      else if (drawTypeString == "TRIANGLES")
        drawType = GL_TRIANGLES;
      else if (drawTypeString == "LINES")
        drawType = GL_LINES;

      mesh->setDrawType(drawType);
    }

    Scene::Instance().meshes.insert(name, mesh);
}
Exemple #6
0
    void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        mp->save();
        QStyleOptionViewItem o = option;
        QPalette palette = o.palette;
        MUCItem::Role r = index.data(GCUserModel::StatusRole).value<Status>().mucItem().role();
        QRect rect = o.rect;

        if(nickColoring_) {
            if(r == MUCItem::Moderator)
                palette.setColor(QPalette::Text, colorModerator_);
            else if(r == MUCItem::Participant)
                palette.setColor(QPalette::Text, colorParticipant_);
            else if(r == MUCItem::Visitor)
                palette.setColor(QPalette::Text, colorVisitor_);
            else
                palette.setColor(QPalette::Text, colorNoRole_);
        }

        mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base));

        if(showAvatar_) {
            QPixmap ava = index.data(GCUserModel::AvatarRole).value<QPixmap>();
            if(ava.isNull()) {
                ava = IconsetFactory::iconPixmap("psi/default_avatar");
            }
            ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_);
            QRect avaRect(rect);
            avaRect.setWidth(ava.width());
            avaRect.setHeight(ava.height());
            if(!avatarAtLeft_) {
                avaRect.moveTopRight(rect.topRight());
                avaRect.translate(-1, 1);
                rect.setRight(avaRect.left() - 1);
            }
            else {
                avaRect.translate(1, 1);
                rect.setLeft(avaRect.right() + 1);
            }
            mp->drawPixmap(avaRect, ava);
        }

        QPixmap status = showStatusIcons_? PsiIconset::instance()->status(index.data(GCUserModel::StatusRole).value<Status>()).pixmap() : QPixmap();
        int h = rect.height();
        int sh = status.isNull() ? 0 : status.height();
        rect.setHeight(qMax(sh, fontHeight_));
        rect.moveTop(rect.top() + (h - rect.height())/2);
        if(!status.isNull()) {
            QRect statusRect(rect);
            statusRect.setWidth(status.width());
            statusRect.setHeight(status.height());
            statusRect.translate(1, 1);
            mp->drawPixmap(statusRect, status);
            rect.setLeft(statusRect.right() + 2);
        }
        else
            rect.setLeft(rect.left() + 2);

        mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text)));
        mp->setFont(o.font);
        mp->setClipRect(rect);
        QTextOption to;
        to.setWrapMode(QTextOption::NoWrap);
        mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to);

        QList<QPixmap> rightPixs;

        if(showAffiliations_) {
            QPixmap pix = index.data(GCUserModel::AffilationIconRole).value<QPixmap>();;
            if(!pix.isNull())
                rightPixs.push_back(pix);
        }

        if(showClients_) {
            QPixmap clientPix = index.data(GCUserModel::ClientIconRole).value<QPixmap>();
            if(!clientPix.isNull())
                rightPixs.push_back(clientPix);
        }

        mp->restore();

        if(rightPixs.isEmpty())
            return;

        int sumWidth = 0;
        foreach (const QPixmap& pix, rightPixs) {
                sumWidth += pix.width();
        }
        sumWidth += rightPixs.count();

        QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base);
        QColor tbgc = bgc;
        tbgc.setAlpha(0);
        QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0);
        grad.setColorAt(0, tbgc);
        grad.setColorAt(1, bgc);
        QBrush tbakBr(grad);
        QRect gradRect(rect);
        gradRect.setLeft(gradRect.right() - sumWidth - 20);
        mp->fillRect(gradRect, tbakBr);

        QRect iconRect(rect);
        for (int i=0; i<rightPixs.size(); i++) {
            const QPixmap pix = rightPixs[i];
            iconRect.setRight(iconRect.right() - pix.width() -1);
            mp->drawPixmap(iconRect.topRight(), pix);
        }

    }
QList<double> Skeleton::vectorization(int type) {
    QList<double> result;

    int count = getDim(type);
    int endCount = getEndCount(type);
    int junctionCount = getJunctionCount(type);
    int holeCount = getHoleCount(type);
    int massCenterCount = getMassCenterCount(type);
    int totalCount = getTotalCount(type);
    int partCount = getPartCount(type);

    int index = 0;

    for (int i = 0; i < count; i++){
        result.push_back(0.0001);
    }



    for (int i = 0; i < listLineEnds.size() && i < endCount; i++){
        result[index] = (listLineEnds[i].x);
        index++;

        result[index] = (listLineEnds[i].y);
        index++;
    }

    for (int i = 0; i < listJunctions.size() && i < junctionCount; i++){
        result[index] = (listJunctions[i].x);
        index++;

        result[index] = (listJunctions[i].y);
        index++;
    }

    for (int i = 0; i < listHoles.size() && i < holeCount; i++){
        result[index] = (listHoles[i].x);
        index++;

        result[index] = (listHoles[i].y);
        index++;
    }

    for (int i = 0; i < massCenterCount; i++){
        result[index] = (massCenter.x);
        index++;

        result[index] = (massCenter.y);
        index++;
    }



    for (int i = 0; i < totalCount; i++){
        result[index] = (total);
        index++;
    }

    for (int i = 0; i < partCount; i++){
        for (int x = 0; x < PART_X; x++){
            for (int y = 0; y < PART_Y; y++){
                result[index] = parts[x][y];
                index++;
            }
        }
    }

    return result;
}
void QgsHistogramDiagram::renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, const QPointF& position )
{
  QPainter* p = c.painter();
  if ( !p )
  {
    return;
  }

  QList<double> values;
  double maxValue = 0;

  QgsExpressionContext expressionContext = c.expressionContext();
  expressionContext.setFeature( feature );
  if ( feature.fields() )
    expressionContext.setFields( *feature.fields() );

  Q_FOREACH ( const QString& cat, s.categoryAttributes )
  {
    QgsExpression* expression = getExpression( cat, expressionContext );
    double currentVal = expression->evaluate( &expressionContext ).toDouble();
    values.push_back( currentVal );
    maxValue = qMax( currentVal, maxValue );
  }

  double scaledMaxVal = sizePainterUnits( maxValue * mScaleFactor, s, c );

  double currentOffset = 0;
  double scaledWidth = sizePainterUnits( s.barWidth, s, c );

  double baseX = position.x();
  double baseY = position.y();

  mPen.setColor( s.penColor );
  setPenWidth( mPen, s, c );
  p->setPen( mPen );

  QList<double>::const_iterator valIt = values.constBegin();
  QList< QColor >::const_iterator colIt = s.categoryColors.constBegin();
  for ( ; valIt != values.constEnd(); ++valIt, ++colIt )
  {
    double length = sizePainterUnits( *valIt * mScaleFactor, s, c );

    mCategoryBrush.setColor( *colIt );
    p->setBrush( mCategoryBrush );

    switch ( s.diagramOrientation )
    {
      case QgsDiagramSettings::Up:
        p->drawRect( baseX + currentOffset, baseY, scaledWidth, length * -1 );
        break;

      case QgsDiagramSettings::Down:
        p->drawRect( baseX + currentOffset, baseY - scaledMaxVal, scaledWidth, length );
        break;

      case QgsDiagramSettings::Right:
        p->drawRect( baseX, baseY - currentOffset, length, scaledWidth * -1 );
        break;

      case QgsDiagramSettings::Left:
        p->drawRect( baseX + scaledMaxVal, baseY - currentOffset, 0 - length, scaledWidth * -1 );
        break;
    }

    currentOffset += scaledWidth;
  }
}
Exemple #9
0
Data::Graph* SpecialMatrix::FileParser::addSpecialCase2NodesToGraph( Data::Graph* matrixGraph, QStringList fields, SpecialMatrix::NodeConnections* connections, int& nodeCounter )
{
	//cases: E - I - I, I - E - I, I - I - E || N - I - I, I - N - I, I - I - N
	int separator = Util::ApplicationConfig::get()->getValue( "Viewer.Display.MatrixNodeSeparator" ).toInt();
	osg::Vec3f nodePos;
	QString edgeName;
	qlonglong edgeId;
	osg::ref_ptr<Data::Node> startGraphNode, midGraphNode, endGraphNode;

	QList<qlonglong>* xAxisNodes = connections->getXAxisNodes();
	QList<qlonglong>* yAxisNodes = connections->getYAxisNodes();
	QList<qlonglong>* iNodes = connections->getINodes();

	//=====================start node (E||N||I)=====================
	ParsedNode startNode;
	startNode.nodeName = fields.at( 0 );
	startNode.nodeId = qHash( startNode.nodeName );

	if ( startNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
		if ( !xAxisNodes->contains( startNode.nodeId ) ) {
			//insert node into xAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			xAxisNodes->push_back( startNode.nodeId );
			startNode.nodePos = xAxisNodes->indexOf( startNode.nodeId )+1;
			nodePos = osg::Vec3f( static_cast<float>( startNode.nodePos )*separator, 0.0f, 0.0f );
			startGraphNode = matrixGraph->addNode( startNode.nodeId, startNode.nodeName, nNodeType, nodePos );
			connections->setNodePositionsArrayField( startNode.nodePos, 0, startNode.nodeId );
		}
		else {
			startGraphNode = matrixGraph->findNodeById( startNode.nodeId );
		}
	}

	else if ( startNode.nodeName.contains( QRegExp( "[Ee]" ) ) ) {
		if ( !yAxisNodes->contains( startNode.nodeId ) ) {
			//insert node into yAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			yAxisNodes->push_back( startNode.nodeId );
			startNode.nodePos = yAxisNodes->indexOf( startNode.nodeId )+1;
			nodePos = osg::Vec3f( 0.0f, static_cast<float>( startNode.nodePos )*separator, 0.0f );
			startGraphNode = matrixGraph->addNode( startNode.nodeId, startNode.nodeName, eNodeType, nodePos );
			connections->setNodePositionsArrayField( 0, startNode.nodePos, startNode.nodeId );
		}
		else {
			startGraphNode = matrixGraph->findNodeById( startNode.nodeId );
		}
	}

	//=====================mid node (E||N||I)=====================
	ParsedNode midNode;
	midNode.nodeName = fields.at( 1 );
	midNode.nodeId = qHash( midNode.nodeName );

	if ( midNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
		if ( !xAxisNodes->contains( midNode.nodeId ) ) {
			//insert node into xAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			xAxisNodes->push_back( midNode.nodeId );
			midNode.nodePos = xAxisNodes->indexOf( midNode.nodeId )+1;
			nodePos = osg::Vec3f( static_cast<float>( midNode.nodePos )*separator, 0.0f, 0.0f );
			midGraphNode = matrixGraph->addNode( midNode.nodeId, midNode.nodeName, nNodeType, nodePos );
			connections->setNodePositionsArrayField( midNode.nodePos, 0, midNode.nodeId );
		}
		else {
			midGraphNode = matrixGraph->findNodeById( midNode.nodeId );
		}
	}

	else if ( midNode.nodeName.contains( QRegExp( "[Ee]" ) ) ) {
		if ( !yAxisNodes->contains( midNode.nodeId ) ) {
			//insert node into yAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			yAxisNodes->push_back( midNode.nodeId );
			midNode.nodePos = yAxisNodes->indexOf( midNode.nodeId )+1;
			nodePos = osg::Vec3f( 0.0f, static_cast<float>( midNode.nodePos )*separator, 0.0f );
			midGraphNode = matrixGraph->addNode( midNode.nodeId, midNode.nodeName, eNodeType, nodePos );
			connections->setNodePositionsArrayField( 0, midNode.nodePos, midNode.nodeId );
		}
		else {
			midGraphNode = matrixGraph->findNodeById( midNode.nodeId );
		}
	}

	//=====================end node (E||N||I)=====================
	ParsedNode endNode;
	endNode.nodeName = fields.at( 2 );
	endNode.nodeId = qHash( endNode.nodeName );

	if ( endNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
		if ( !xAxisNodes->contains( endNode.nodeId ) ) {
			//insert node into xAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			xAxisNodes->push_back( endNode.nodeId );
			endNode.nodePos = xAxisNodes->indexOf( endNode.nodeId )+1;
			nodePos = osg::Vec3f( static_cast<float>( endNode.nodePos )*separator, 0.0f, 0.0f );
			endGraphNode = matrixGraph->addNode( endNode.nodeId, endNode.nodeName, nNodeType, nodePos );
			connections->setNodePositionsArrayField( endNode.nodePos, 0, endNode.nodeId );
		}
		else {
			endGraphNode = matrixGraph->findNodeById( endNode.nodeId );
		}
	}

	else if ( endNode.nodeName.contains( QRegExp( "[Ee]" ) ) ) {
		if ( !yAxisNodes->contains( endNode.nodeId ) ) {
			//insert node into yAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			yAxisNodes->push_back( endNode.nodeId );
			endNode.nodePos = yAxisNodes->indexOf( endNode.nodeId )+1;
			nodePos = osg::Vec3f( 0.0f, static_cast<float>( endNode.nodePos )*separator, 0.0f );
			endGraphNode = matrixGraph->addNode( endNode.nodeId, endNode.nodeName, eNodeType, nodePos );
			connections->setNodePositionsArrayField( 0, endNode.nodePos, endNode.nodeId );
		}
		else {
			endGraphNode = matrixGraph->findNodeById( endNode.nodeId );
		}
	}

	//=====================calculate I node=====================
	if ( startNode.nodeName.contains( QRegExp( "[EeNn]" ) ) ) {
		//case: E/N - I - I
		osg::Vec2f pos;
		if ( startNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
			//case: N - I - I
			pos.x() = static_cast<float>( xAxisNodes->indexOf( startNode.nodeId )+1 );
			pos.y() = pos.x();
		}
		else {
			//case: E - I - I
			pos.y() = static_cast<float>( yAxisNodes->indexOf( startNode.nodeId )+1 );
			pos.x() = pos.y();
		}

		if ( !iNodes->contains( endNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( endNode.nodeId );

			pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() ) );
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			endGraphNode = matrixGraph->addNode( endNode.nodeId, endNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), endNode.nodeId );
		}
		else {
			endGraphNode = matrixGraph->findNodeById( endNode.nodeId );
		}

		if ( !iNodes->contains( midNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( midNode.nodeId );

			if ( startNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() )/2 );
			}
			else {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() )/2, static_cast<int>( pos.y() ) );
			}
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			midGraphNode = matrixGraph->addNode( midNode.nodeId, midNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), midNode.nodeId );
		}
		else {
			midGraphNode = matrixGraph->findNodeById( midNode.nodeId );
		}

	}
	else if ( midNode.nodeName.contains( QRegExp( "[EeNn]" ) ) ) {
		//case: I - E/N - I
		osg::Vec2f pos;
		if ( midNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
			//case: I - N - I
			pos.x() = static_cast<float>( xAxisNodes->indexOf( midNode.nodeId )+1 );
			pos.y() = pos.x();
		}
		else {
			//case: I - E - I
			pos.y() = static_cast<float>( yAxisNodes->indexOf( midNode.nodeId )+1 );
			pos.x() = pos.y();
		}

		if ( !iNodes->contains( endNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( endNode.nodeId );

			pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() ) );
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			endGraphNode = matrixGraph->addNode( endNode.nodeId, endNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), endNode.nodeId );
		}
		else {
			endGraphNode = matrixGraph->findNodeById( endNode.nodeId );
		}

		if ( !iNodes->contains( startNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( startNode.nodeId );

			if ( midNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() )/2 );
			}
			else {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() )/2, static_cast<int>( pos.y() ) );
			}
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			startGraphNode = matrixGraph->addNode( startNode.nodeId, startNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), startNode.nodeId );
		}
		else {
			startGraphNode = matrixGraph->findNodeById( startNode.nodeId );
		}

	}
	else if ( endNode.nodeName.contains( QRegExp( "[EeNn]" ) ) ) {
		//case: I - I - E/N
		osg::Vec2f pos;
		if ( endNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
			//case: I - I - N
			pos.x() = static_cast<float>( xAxisNodes->indexOf( endNode.nodeId )+1 );
			pos.y() = pos.x();
		}
		else {
			//case: I - I - E
			pos.y() = static_cast<float>( yAxisNodes->indexOf( endNode.nodeId )+1 );
			pos.x() = pos.y();
		}

		if ( !iNodes->contains( midNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( midNode.nodeId );

			pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() ) );
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			midGraphNode = matrixGraph->addNode( midNode.nodeId, midNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), midNode.nodeId );
		}
		else {
			midGraphNode = matrixGraph->findNodeById( midNode.nodeId );
		}

		if ( !iNodes->contains( startNode.nodeId ) ) {
			//insert node into iNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			iNodes->push_back( startNode.nodeId );

			if ( midNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() )/2 );
			}
			else {
				pos = getAvailablePosition( connections, static_cast<int>( pos.x() )/2, static_cast<int>( pos.y() ) );
			}
			nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator, pos.y()*separator, 0.0f ) );
			startGraphNode = matrixGraph->addNode( startNode.nodeId, startNode.nodeName, iHalfNodeType, nodePos );
			connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), startNode.nodeId );
		}
		else {
			startGraphNode = matrixGraph->findNodeById( startNode.nodeId );
		}
	}

	//same in every condition
	edgeName = midNode.nodeName;
	edgeName.append( startNode.nodeName );
	edgeId = qHash( edgeName );
	matrixGraph->addEdge( edgeId, edgeName, midGraphNode, startGraphNode, iEdgeType, false );

	edgeName = midNode.nodeName;
	edgeName.append( endNode.nodeName );
	edgeId = qHash( edgeName );
	matrixGraph->addEdge( edgeId, edgeName, midGraphNode, endGraphNode, iEdgeType, false );

	return matrixGraph;
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo> RimLegendConfig::calculateValueOptions(const caf::PdmFieldHandle* fieldNeedingOptions, bool* useOptionsOnly)
{

    bool isCategoryResult = false;
    {
        RimEclipseCellColors* eclCellColors = nullptr;
        this->firstAncestorOrThisOfType(eclCellColors);
        RimGeoMechResultDefinition* gmCellColors = nullptr;
        this->firstAncestorOrThisOfType(gmCellColors);
        RimCellEdgeColors* eclCellEdgColors = nullptr;
        this->firstAncestorOrThisOfType(eclCellEdgColors);

        if (   ( eclCellColors && eclCellColors->hasCategoryResult()) 
            || ( gmCellColors && gmCellColors->hasCategoryResult()) 
            || ( eclCellEdgColors && eclCellEdgColors->hasCategoryResult()) )
        {
            isCategoryResult = true;
        }
    }

    QList<caf::PdmOptionItemInfo> optionList;

    if (fieldNeedingOptions == &m_mappingMode)
    {
        // This is an app enum field, see cafInternalPdmFieldTypeSpecializations.h for the default specialization of this type
        std::vector<MappingType> mappingTypes;
        mappingTypes.push_back(LINEAR_DISCRETE);
        mappingTypes.push_back(LINEAR_CONTINUOUS);
        mappingTypes.push_back(LOG10_CONTINUOUS);
        mappingTypes.push_back(LOG10_DISCRETE);

        if (isCategoryResult)
        {
            mappingTypes.push_back(CATEGORY_INTEGER);
        }

        for(MappingType mapType: mappingTypes)
        {
            optionList.push_back(caf::PdmOptionItemInfo(MappingEnum::uiText(mapType), mapType));
        }
    }
    else if (fieldNeedingOptions == &m_colorRangeMode)
    {
        // This is an app enum field, see cafInternalPdmFieldTypeSpecializations.h for the default specialization of this type
        std::vector<ColorRangesType> rangeTypes;
        rangeTypes.push_back(NORMAL);
        rangeTypes.push_back(OPPOSITE_NORMAL);
        rangeTypes.push_back(WHITE_PINK);
        rangeTypes.push_back(PINK_WHITE);
        rangeTypes.push_back(BLUE_WHITE_RED);
        rangeTypes.push_back(RED_WHITE_BLUE);
        rangeTypes.push_back(WHITE_BLACK);
        rangeTypes.push_back(BLACK_WHITE);
        rangeTypes.push_back(ANGULAR);

        if (isCategoryResult)
        {
            rangeTypes.push_back(CATEGORY);
        }

        for(ColorRangesType colType: rangeTypes)
        {
            optionList.push_back(caf::PdmOptionItemInfo(ColorRangeEnum::uiText(colType), colType));
        }
    }
 
    return optionList;
}
KisPropertiesConfigurationTest::KisPropertiesConfigurationTest() :
        v1(10), v2("hello"), v3(1242.0), v4(true)
{
    QList<QPointF> pts; pts.push_back(QPointF(0.2, 0.3)); pts.push_back(QPointF(0.5, 0.7));
    v5.setPoints(pts);
}
void QgsInterpolationDialog::on_buttonBox_accepted()
{
  if ( !mInterpolatorDialog )
  {
    return;
  }

  QgsRectangle outputBBox = currentBoundingBox();
  if ( outputBBox.isEmpty() )
  {
    return;
  }

  //warn the user if there isn't any input layer
  if ( mLayersTreeWidget->topLevelItemCount() < 1 )
  {
    QMessageBox::information( nullptr, tr( "No input data for interpolation" ), tr( "Please add one or more input layers" ) );
    return;
  }

  //read file name
  QString fileName = mOutputFileLineEdit->text();
  QFileInfo theFileInfo( fileName );
  if ( fileName.isEmpty() || !theFileInfo.dir().exists() )
  {
    QMessageBox::information( nullptr, tr( "Output file name invalid" ), tr( "Please enter a valid output file name" ) );
    return;
  }

  //add .asc suffix if the user did not provider it already
  QString suffix = theFileInfo.suffix();
  if ( suffix.isEmpty() )
  {
    fileName.append( ".asc" );
  }

  int nLayers = mLayersTreeWidget->topLevelItemCount();
  QList< QgsInterpolator::LayerData > inputLayerList;

  for ( int i = 0; i < nLayers; ++i )
  {
    QString layerName = mLayersTreeWidget->topLevelItem( i )->text( 0 );
    QgsVectorLayer* theVectorLayer = vectorLayerFromName( layerName );
    if ( !theVectorLayer )
    {
      continue;
    }

    QgsVectorDataProvider* theProvider = theVectorLayer->dataProvider();
    if ( !theProvider )
    {
      continue;
    }

    QgsInterpolator::LayerData currentLayerData;
    currentLayerData.vectorLayer = theVectorLayer;

    QString interpolationAttString = mLayersTreeWidget->topLevelItem( i )->text( 1 );
    if ( interpolationAttString == "Z_COORD" )
    {
      currentLayerData.zCoordInterpolation = true;
      currentLayerData.interpolationAttribute = -1;
    }
    else
    {
      currentLayerData.zCoordInterpolation = false;
      int attributeIndex = theProvider->fieldNameIndex( interpolationAttString );
      currentLayerData.interpolationAttribute = attributeIndex;
    }

    //type (point/structure line/ breakline)
    QComboBox* itemCombo = qobject_cast<QComboBox *>( mLayersTreeWidget->itemWidget( mLayersTreeWidget->topLevelItem( i ), 2 ) );
    if ( itemCombo )
    {
      QString typeString = itemCombo->currentText();
      if ( typeString == tr( "Break lines" ) )
      {
        currentLayerData.mInputType = QgsInterpolator::BREAK_LINES;
      }
      else if ( typeString == tr( "Structure lines" ) )
      {
        currentLayerData.mInputType = QgsInterpolator::STRUCTURE_LINES;
      }
      else //Points
      {
        currentLayerData.mInputType = QgsInterpolator::POINTS;
      }
    }
    else
    {
      currentLayerData.mInputType = QgsInterpolator::POINTS;
    }
    inputLayerList.push_back( currentLayerData );
  }

  mInterpolatorDialog->setInputData( inputLayerList );
  QgsInterpolator* theInterpolator = mInterpolatorDialog->createInterpolator();

  if ( !theInterpolator )
  {
    return;
  }

  //create grid file writer
  QgsGridFileWriter theWriter( theInterpolator, fileName, outputBBox, mNumberOfColumnsSpinBox->value(),
                               mNumberOfRowsSpinBox->value(), mCellsizeXSpinBox->value(), mCellSizeYSpinBox->value() );
  if ( theWriter.writeFile( true ) == 0 )
  {
    if ( mAddResultToProjectCheckBox->isChecked() )
    {
      mIface->addRasterLayer( fileName, QFileInfo( fileName ).baseName() );
    }
    accept();
  }

  delete theInterpolator;
}
Exemple #13
0
/**
 init tbl and table model and attch to tableview
*/
void CMDSimMW::initTbl() {
    //set table sytle
    if(_ptbl == NULL) {
        return;
    }
   //use right click
    _ptbl->setContextMenuPolicy (Qt::CustomContextMenu);

    QPushButton *tbtn;
    tbl_model = new QStandardItemModel(TBL_ROW, TBL_COL + 1);


    _ptbl->setModel(tbl_model);

    tbl_model->setHeaderData(0, Qt::Horizontal, cvcp936("类型"));
    tbl_model->setHeaderData(1, Qt::Horizontal, cvcp936("名称"));
    tbl_model->setHeaderData(2, Qt::Horizontal, cvcp936("关联通道号"));
    tbl_model->setHeaderData(3, Qt::Horizontal, cvcp936("设置"));
    tbl_model->setHeaderData(4, Qt::Horizontal, cvcp936("启动"));

    _ptbl->setEditTriggers (QAbstractItemView::NoEditTriggers);
    QHeaderView *header = new QHeaderView(Qt::Horizontal, _ptbl);
#if !defined(Q_OS_DARWIN)
    header->setMovable (true);                  /* move cols */
#endif
    _ptbl->setHorizontalHeader (header);
    //_ptbl->horizontalHeader ()->setStretchLastSection ();
    int trow = tbl_model->rowCount() ,tcol = tbl_model->columnCount();
    for(int i = 0; i < trow; i++) {
        for(int j = 0; j < tcol; j++) {
            QModelIndex idx = tbl_model->index(i, j);
            //test the first col...
            if(j == tcol - 2) {
                tbl_model->setData(idx, "btncol");
                tbtn = new QPushButton(cvcp936 ("设置"));
                _ptbl->setIndexWidget(tbl_model->index(i, j), tbtn);
                connect (tbtn, SIGNAL(clicked()), _pSigMaper, SLOT(map()));
                _pSigMaper->setMapping (tbtn, i + 1); /* row start 0 */
            }
            if(j == tcol - 1) {
                //tbl_model->setData(idx, "chkstart");
                QCheckBox *chk = new QCheckBox(cvcp936("启动"));
                _ptbl->setIndexWidget(tbl_model->index(i, j), chk);
                //connect(chk, SIGNAL(clicked()), _pSigMaper, SLOT(map()));
                //_pSigMaper->setMapping(chk, i + 1);
            }else {
                tbl_model->setData(idx, "test");
            }
        }
    }
    connect (_pSigMaper, SIGNAL(mapped(int)), this, SLOT(mslot_tableClick(int)));



    // test for insert data
#if 1
    QList <QStandardItem *> items;
    for (int i = 0; i < 5; ++i) {
        items.push_back(new QStandardItem(QString::number(i)));
    }
    tbl_model->appendRow(items);
#endif


}
Exemple #14
0
void DkConnection::checkState() {
	
	if (mState == WaitingForGreeting) {
		if (mCurrentDataType != Greeting) {
			abort();
			return;
		}

		if (!hasEnoughData())
			return;

		mBuffer = read(mNumBytesForCurrentDataType);
		if (mBuffer.size() != mNumBytesForCurrentDataType) {
			abort();
			return;
		}

		if (!isValid()) {
			abort();
			return;
		}

		if (!mIsGreetingMessageSent)
			sendGreetingMessage(mCurrentTitle);

		mState = ReadyForUse;
		mPortOfPeer = peerPort(); // save peer port ... otherwise connections where this instance is server can not be removed from peerList

		readGreetingMessage();

		mBuffer.clear();
		mNumBytesForCurrentDataType = 0;
		mCurrentDataType = Undefined;
		return;
	}

	if (mState==ReadyForUse && mCurrentDataType == startSynchronize) {
		if (!hasEnoughData())
			return;

		mBuffer = read(mNumBytesForCurrentDataType);
		if (mBuffer.size() != mNumBytesForCurrentDataType) {
			abort();
			return;
		}

		QDataStream ds(mBuffer);
		QList<quint16> synchronizedPeersOfOtherInstance;
		quint16 numberOfSynchronizedPeers;
		ds >> numberOfSynchronizedPeers;

		//qDebug() << "other client is sychronized with: ";
		for (int i=0; i < numberOfSynchronizedPeers; i++) {
			quint16 peerId;
			ds >> peerId;
			synchronizedPeersOfOtherInstance.push_back(peerId);
			//qDebug() << peerId;
		}
		mCurrentDataType = Undefined;
		mNumBytesForCurrentDataType = 0;
		mBuffer.clear();

		if (!isValid()) {
			abort();
			return;
		}

		mState = Synchronized;
		if (!mIsSynchronizeMessageSent)
			sendStartSynchronizeMessage();

		mSynchronizedTimer->stop();
		emit connectionStartSynchronize(synchronizedPeersOfOtherInstance, this);
		return;
	}

	if (mState==Synchronized && mCurrentDataType == stopSynchronize) {
		mState=ReadyForUse;
		this->mIsSynchronizeMessageSent=false;
		emit connectionStopSynchronize(this);
		mBuffer = read(mNumBytesForCurrentDataType);
		if (mBuffer.size() != mNumBytesForCurrentDataType) {
			abort();
			return;
		}

		mCurrentDataType = Undefined;
		mNumBytesForCurrentDataType = 0;
		mBuffer.clear();

		return;
	}

	if (mCurrentDataType == GoodBye) {
		//qDebug() << "received GoodBye from " << peerAddress() << ":" << peerPort();
		emit connectionGoodBye(this);
		mCurrentDataType = Undefined;
		mNumBytesForCurrentDataType = 0;
		mBuffer.clear();
		abort();
		return;
	}
}
Exemple #15
0
bool patternPrinter::printListDescription(int* yUsed, int fontHeight) {

  QList<flossType> flossTypes = flossType::allFlossTypes();
  QList<QPair<QString, QString> > abbreviations;
  for (int i = 0, size = flossTypes.size(); i < size; ++i) {
    const flossType thisType = flossTypes[i];
    if (::colorsContainType(colors_, thisType)) {
      abbreviations.push_back(qMakePair(thisType.shortText(),
                                        thisType.prefix()));
    }
  }
  QString flossString;
  bool useCodeAbbreviations = false;
  if (abbreviations.size() == 1) { // only one type of floss
    if (abbreviations[0].first == "") { // flossVariable only
      flossString =
        QObject::tr("The Code column gives the RGB value of a color and the Name "
                    "column gives the code and DMC name of the nearest DMC color.");
    }
    else if (abbreviations[0].second != "d") { // not DMC
      flossString =
        //: %1 is "DMC" or "Anchor" or...
        QObject::tr("All codes are for %1 floss.  The Name column gives the code "
                    "and DMC name of the nearest DMC color.")
                   .arg(abbreviations[0].first);
    }
    else { // DMC only
      flossString =
        //: %1 is "DMC" or "Anchor" or...
        QObject::tr("All codes are for %1 floss.").arg(abbreviations[0].first);
    }
  }
  else { // more than one type of floss
    QString abbreviationsText;
    int numberOfAbbreviations = 0;
    for (int i = 0, size = abbreviations.size(); i < size; ++i) {
      const QString shortText = abbreviations[i].first;
      const QString prefix = abbreviations[i].second;
      if (shortText != "") { // don't include flossVariable
        abbreviationsText += prefix + " = " + shortText + ", ";
        ++numberOfAbbreviations;
      }
    }
    abbreviationsText.chop(2);
    if (numberOfAbbreviations > 1) {
      useCodeAbbreviations = true;
      flossString = QObject::tr("For colors available as floss the Code column "
                                "gives an abbreviation for the floss type (%1), "
                                "otherwise the RGB code of the color is given.  "
                                "The Name column gives the code and DMC name of "
                                "the nearest DMC color.").arg(abbreviationsText);
    }
    else { // variable plus one other type
        //: %1 is "DMC" or "Anchor" or...
      flossString = QObject::tr("For non-%1 colors the Code column gives the RGB "
                                "value of the color and the Name column gives the "
                                "code and DMC name of the nearest DMC color.")
                               .arg(abbreviations[0].first);
    }        
  }
  QRect textBoundingRect;
  painter_.drawText(QRect(0, *yUsed, printerWidth_, 4 * fontHeight),
                    Qt::TextWordWrap, flossString,
                    &textBoundingRect);
  *yUsed += textBoundingRect.height() + fontHeight;
  return useCodeAbbreviations;
}
Exemple #16
0
Data::Graph* SpecialMatrix::FileParser::addNormalNodesToGraph( Data::Graph* matrixGraph, QStringList fields, SpecialMatrix::NodeConnections* connections, int& nodeCounter )
{
	//cases: E - I - N, N - I - E
	float separator = Util::ApplicationConfig::get()->getValue( "Viewer.Display.MatrixNodeSeparator" ).toFloat();
	osg::Vec3f nodePos;
	osg::ref_ptr<Data::Node> foundNode;
	qlonglong foundNodeId;

	QList<qlonglong>* xAxisNodes = connections->getXAxisNodes();
	QList<qlonglong>* yAxisNodes = connections->getYAxisNodes();
	QList<qlonglong>* iNodes = connections->getINodes();
	QMap<qlonglong, QList<qlonglong>* >* connectedNodes = connections->getConnectedNodes();
	QList<qlonglong>* tempList;

	//=====================start node (E||N)=====================
	ParsedNode startNode;
	startNode.nodeName = fields.at( 0 );
	startNode.nodeId = qHash( startNode.nodeName );

	if ( startNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
		if ( !xAxisNodes->contains( startNode.nodeId ) ) {
			//insert node into xAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			xAxisNodes->push_back( startNode.nodeId );
			startNode.nodePos = xAxisNodes->indexOf( startNode.nodeId )+1;
			nodePos = osg::Vec3f( static_cast<float>( startNode.nodePos )*separator, 0.0f, 0.0f );
			matrixGraph->addNode( startNode.nodeId, startNode.nodeName, nNodeType, nodePos );
			connections->setNodePositionsArrayField( startNode.nodePos, 0, startNode.nodeId );
		}
		//get list from Qmap where key is xFrstNodeId and insert I node into connectedNodes list
		tempList = connectedNodes->value( startNode.nodeId );
		if ( tempList == nullptr ) {
			tempList = new QList<qlonglong>;
		}
		tempList->push_back( qHash( fields.at( 1 ) ) );
		connectedNodes->insert( startNode.nodeId, tempList );
	}

	else if ( startNode.nodeName.contains( QRegExp( "[Ee]" ) ) ) {
		if ( !yAxisNodes->contains( startNode.nodeId ) ) {
			//insert node into yAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			yAxisNodes->push_back( startNode.nodeId );
			startNode.nodePos = yAxisNodes->indexOf( startNode.nodeId )+1;
			nodePos = osg::Vec3f( 0.0f, static_cast<float>( startNode.nodePos )*separator, 0.0f );
			matrixGraph->addNode( startNode.nodeId, startNode.nodeName, eNodeType, nodePos );
			connections->setNodePositionsArrayField( 0, startNode.nodePos, startNode.nodeId );
		}
		//get list from Qmap where key is xFrstNodeId and insert I node into connectedNodes list
		tempList = connectedNodes->value( startNode.nodeId );
		if ( tempList == nullptr ) {
			tempList = new QList<qlonglong>;
		}
		tempList->push_back( qHash( fields.at( 1 ) ) );
		connectedNodes->insert( startNode.nodeId, tempList );
	}

	//=====================end node (E||N)=====================
	ParsedNode endNode;
	endNode.nodeName = fields.at( 2 );
	endNode.nodeId = qHash( endNode.nodeName );

	if ( endNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
		if ( !xAxisNodes->contains( endNode.nodeId ) ) {
			//insert node into xAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			xAxisNodes->push_back( endNode.nodeId );
			endNode.nodePos = xAxisNodes->indexOf( endNode.nodeId )+1;
			nodePos = osg::Vec3f( static_cast<float>( endNode.nodePos )*separator, 0.0f, 0.0f );
			matrixGraph->addNode( endNode.nodeId, endNode.nodeName, nNodeType, nodePos );
			connections->setNodePositionsArrayField( endNode.nodePos, 0, endNode.nodeId );
		}
		//get list from Qmap where key is xFrstNodeId and insert I node into connectedNodes list
		tempList = connectedNodes->value( endNode.nodeId );
		if ( tempList == nullptr ) {
			tempList = new QList<qlonglong>;
		}
		tempList->push_back( qHash( fields.at( 1 ) ) );
		connectedNodes->insert( endNode.nodeId, tempList );
	}

	else if ( endNode.nodeName.contains( QRegExp( "[Ee]" ) ) ) {
		if ( !yAxisNodes->contains( endNode.nodeId ) ) {
			//insert node into yAxisNodes list only if missing
			connections->setNodePositionsArray( ++nodeCounter );
			yAxisNodes->push_back( endNode.nodeId );
			endNode.nodePos = yAxisNodes->indexOf( endNode.nodeId )+1;
			nodePos = osg::Vec3f( 0.0f, static_cast<float>( endNode.nodePos )*separator, 0.0f );
			matrixGraph->addNode( endNode.nodeId, endNode.nodeName, eNodeType, nodePos );
			connections->setNodePositionsArrayField( 0, endNode.nodePos, endNode.nodeId );
		}
		//get list from Qmap where key is xFrstNodeId and insert I node into connectedNodes list
		tempList = connectedNodes->value( endNode.nodeId );
		if ( tempList == nullptr ) {
			tempList = new QList<qlonglong>;
		}
		tempList->push_back( qHash( fields.at( 1 ) ) );
		connectedNodes->insert( endNode.nodeId, tempList );
	}

	//=====================middle node (I)=====================
	ParsedNode midNode;
	midNode.nodeName = fields.at( 1 );
	midNode.nodeId = qHash( midNode.nodeName );

	if ( !iNodes->contains( midNode.nodeId ) ) {
		//insert node into iNodes list only if missing
		iNodes->push_back( midNode.nodeId );
		osg::Vec2f pos;
		if ( startNode.nodeName.contains( QRegExp( "[Nn]" ) ) ) {
			pos.x() = static_cast<float>( xAxisNodes->indexOf( startNode.nodeId )+1 );
			pos.y() = static_cast<float>( yAxisNodes->indexOf( endNode.nodeId )+1 );

		}
		else {
			pos.x() = static_cast<float>( xAxisNodes->indexOf( endNode.nodeId )+1 );
			pos.y() = static_cast<float>( yAxisNodes->indexOf( startNode.nodeId )+1 );
		}

		//CHECK AVAIBILITY - if there is a node, move it
		foundNodeId = connections->getNodePositionsArrayField( pos.x(), pos.y() );
		if ( foundNodeId ) {
			foundNode = matrixGraph->findNodeById( foundNodeId );
			osg::Vec2f foundNodePos = getAvailablePosition( connections, static_cast<int>( pos.x() ), static_cast<int>( pos.y() ) );
			foundNode->setTargetPosition( osg::Vec3f( foundNodePos.x()*separator , foundNodePos.y()*separator , 0.0f ) );
			connections->setNodePositionsArrayField( static_cast<int>( foundNodePos.x() ), static_cast<int>( foundNodePos.y() ), foundNodeId );
		}

		nodePos = osg::Vec3f( osg::Vec3f( pos.x()*separator,  pos.y()*separator, 0.0f ) );
		matrixGraph->addNode( midNode.nodeId, midNode.nodeName, iFullNodeType, nodePos );
		connections->setNodePositionsArrayField( static_cast<int>( pos.x() ), static_cast<int>( pos.y() ), midNode.nodeId );
	}
	return matrixGraph;
}
bool    TablePermissions::getRights(const QString &id_accessor, const QString &id_object, QStringList &allowed, QStringList &denied) const
{
    TableAccounts       *account = NULL;
    TableFiles          *file = NULL;
    TableDirectories    *directory = NULL;
    TableCollections    *collection = NULL;
    TableGroups         group;
    bool                inheritance;
    bool                ownerInheritance;
    bool                checked = false;
    QString             id;
    TableDirectories    dir;
    TableCollections    col;
    QStringList         accessors;
    QList<QStringList>  groups;

    allowed.clear();
    denied.clear();
    // If the permissions system is not activated, all the rights are granted
    if (!LightBird::c().permissions.activate)
    {
        allowed.push_back("");
        return (true);
    }
    ownerInheritance = LightBird::c().permissions.ownerInheritance;
    inheritance = LightBird::c().permissions.inheritance;
    QSharedPointer<TableAccessors> accessor(dynamic_cast<TableAccessors *>(Library::database().getTable(Table::Accessor, id_accessor)));
    if (accessor.isNull())
        return (false);
    if (accessor->isTable(Table::Accounts))
        account = dynamic_cast<TableAccounts *>(accessor.data());
    // If the accessor is an account, and the account is administrator, he has all the rights on all the objects
    if (account && account->isAdministrator())
    {
        allowed.push_back("");
        return (true);
    }
    QSharedPointer<TableObjects> object(dynamic_cast<TableObjects *>(Library::database().getTable(Table::Object, id_object)));
    // An empty id_object is the root directory
    if (!object && !id_object.isEmpty())
        return (false);
    // If the accessor is an account, and the account is the owner of the object, he has all the rights on it
    if (account && object && account->getId() == object->getIdAccount())
    {
        allowed.push_back("");
        return (true);
    }
    // Get all the accessors concerned by the permission
    if (account)
        accessors = account->getGroups();
    else if (group.setId(accessor->getId()) && !(id = group.getIdGroup()).isEmpty())
        accessors.push_back(id);
    // Get all the parent groups of the accessor
    if (!accessors.isEmpty())
    {
        groups.push_back(accessors);
        while (true)
        {
            QStringListIterator it(groups.back());
            QStringList parents;
            while (it.hasNext())
            {
                // A parent has been found
                if (group.setId(it.peekNext()) && !(id = group.getIdGroup()).isEmpty())
                {
                    parents.push_back(id);
                    accessors.push_back(id);
                }
                it.next();
            }
            // No parent remaining. We are at the root of the tree.
            if (parents.isEmpty())
                break;
            parents.removeDuplicates();
            groups.push_back(parents);
        }
        accessors.removeDuplicates();
        // If groupInheritance is disables, we don't need to keep the groups hierarchy
        if (!LightBird::c().permissions.groupInheritance)
            groups.clear();
    }
    accessors.push_front(accessor->getId());
    // Get the id of the first object in the hierarchy
    if (!object)
        ;
    else if (object->isTable(Table::Files))
    {
        file = dynamic_cast<TableFiles *>(object.data());
        id = file->getIdDirectory();
        this->_getRights(accessors, groups, file->getId(), allowed, denied);
        checked = true;
    }
    else if (object->isTable(Table::Directories))
    {
        directory = dynamic_cast<TableDirectories *>(object.data());
        id = directory->getId();
    }
    else if (object->isTable(Table::Collections))
    {
        collection = dynamic_cast<TableCollections *>(object.data());
        id = collection->getId();
    }
    // Run through the objects hierarchy to find the permissions
    if (file || directory)
        while (!id.isEmpty())
        {
            if (inheritance || !checked)
                this->_getRights(accessors, groups, id, allowed, denied);
            dir.setId(id);
            if (account && ownerInheritance && account->getId() == dir.getIdAccount())
            {
                allowed.clear();
                denied.clear();
                allowed.push_back("");
                return (true);
            }
            id = dir.getIdDirectory();
            checked = true;
        }
    else if (collection)
        while (!id.isEmpty())
        {
            if (inheritance || !checked)
                this->_getRights(accessors, groups, id, allowed, denied);
            col.setId(id);
            if (account && ownerInheritance && account->getId() == col.getIdAccount())
            {
                allowed.clear();
                denied.clear();
                allowed.push_back("");
                return (true);
            }
            id = col.getIdCollection();
            checked = true;
        }
    // The root directory of the server
    else if (!object)
        this->_getRights(accessors, groups, "", allowed, denied);
    // Check if there is a permission at the root of the server
    if (inheritance && object)
        this->_getRights(accessors, groups, "", allowed, denied);
    // If there is no global permission, the default is applied
    if (!allowed.contains("") && !denied.contains(""))
    {
        if (LightBird::c().permissions.default_)
        {
            allowed.clear();
            allowed.push_back("");
        }
        else
        {
            denied.clear();
            denied.push_back("");
        }
    }
    return (true);
}
void QgsSingleBandPseudoColorRendererWidget::on_mClassifyButton_clicked()
{
  int bandComboIndex = mBandComboBox->currentIndex();
  if ( bandComboIndex == -1 || !mRasterLayer )
  {
    return;
  }

  //int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt();
  //QgsRasterBandStats myRasterBandStats = mRasterLayer->dataProvider()->bandStatistics( bandNr );
  int numberOfEntries = 0;

  QList<double> entryValues;
  QList<QColor> entryColors;

  double min = lineEditValue( mMinLineEdit );
  double max = lineEditValue( mMaxLineEdit );

  QgsVectorColorRampV2* colorRamp = mColorRampComboBox->currentColorRamp();

  if ( mClassificationModeComboBox->itemData( mClassificationModeComboBox->currentIndex() ).toInt() == Continuous )
  {
    if ( colorRamp )
    {
      numberOfEntries = colorRamp->count();
      entryValues.reserve( colorRamp->count() );
      for ( int i = 0; i < colorRamp->count(); ++i )
      {
        double value = colorRamp->value( i );
        entryValues.push_back( min + value * ( max - min ) );
      }
    }
  }
  else // EqualInterval
  {
    numberOfEntries = mNumberOfEntriesSpinBox->value();
    //double currentValue = myRasterBandStats.minimumValue;
    double currentValue = min;
    double intervalDiff;
    if ( numberOfEntries > 1 )
    {
      //because the highest value is also an entry, there are (numberOfEntries - 1)
      //intervals
      //intervalDiff = ( myRasterBandStats.maximumValue - myRasterBandStats.minimumValue ) /
      intervalDiff = ( max - min ) / ( numberOfEntries - 1 );
    }
    else
    {
      //intervalDiff = myRasterBandStats.maximumValue - myRasterBandStats.minimumValue;
      intervalDiff = max - min;
    }

    entryValues.reserve( numberOfEntries );
    for ( int i = 0; i < numberOfEntries; ++i )
    {
      entryValues.push_back( currentValue );
      currentValue += intervalDiff;
    }
  }

#if 0
  //hard code color range from blue -> red for now. Allow choice of ramps in future
  int colorDiff = 0;
  if ( numberOfEntries != 0 )
  {
    colorDiff = ( int )( 255 / numberOfEntries );
  }
  for ( int i = 0; i < numberOfEntries; ++i )
  {
    QColor currentColor;
    currentColor.setRgb( colorDiff*i, 0, 255 - colorDiff * i );
    entryColors.push_back( currentColor );
  }
#endif

  if ( ! colorRamp )
  {
    //hard code color range from blue -> red (previous default)
    int colorDiff = 0;
    if ( numberOfEntries != 0 )
    {
      colorDiff = ( int )( 255 / numberOfEntries );
    }

    entryColors.reserve( numberOfEntries );
    for ( int i = 0; i < numberOfEntries; ++i )
    {
      QColor currentColor;
      int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i;
      currentColor.setRgb( colorDiff*idx, 0, 255 - colorDiff * idx );
      entryColors.push_back( currentColor );
    }
  }
  else
  {
    entryColors.reserve( numberOfEntries );
    for ( int i = 0; i < numberOfEntries; ++i )
    {
      int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i;
      entryColors.push_back( colorRamp->color((( double ) idx ) / ( numberOfEntries - 1 ) ) );
    }
  }

  mColormapTreeWidget->clear();

  QList<double>::const_iterator value_it = entryValues.begin();
  QList<QColor>::const_iterator color_it = entryColors.begin();

  for ( ; value_it != entryValues.end(); ++value_it, ++color_it )
  {
    QTreeWidgetItem* newItem = new QTreeWidgetItem( mColormapTreeWidget );
    newItem->setText( 0, QString::number( *value_it, 'f' ) );
    newItem->setBackground( 1, QBrush( *color_it ) );
    newItem->setText( 2, QString::number( *value_it, 'f' ) );
    newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable );
  }
}
QList<int> Skeleton::possibleNumbers(QList<int> digitsOnField){
    QList<int> list;

    /*if (listHoles.size() > 2 || listJunctions.size() > 5 || listLineEnds.size() > 5){
        // certainly a bad 'catch'
    }
    if (listHoles.size() == 0){
        if (listLineEnds.size() >= 2){
            if (listLineEnds[0].x < 0.3 && listLineEnds[0].y < 0.3 && listLineEnds[1].x > 0.7 && listLineEnds[1].y > 0.7){
                list.push_back(2);
            }
            else if (listLineEnds[0].x > 0.7 && listLineEnds[0].y < 0.3 && listLineEnds[1].y > 0.5){
                list.push_back(5);
            }
            else if (listLineEnds[1].x < 0.4){
                list.push_back(7);
            }
            else {
                list.push_back(1);
            }
        }
        else {
            list.push_back(1);
            list.push_back(2);
            list.push_back(5);
            list.push_back(7);
        }
    }
    else if (listHoles.size() == 1){
        if (listHoles[0].x > 0.35 && listHoles[0].x < 0.65 && listHoles[0].y > 0.35 && listHoles[0].y < 0.65){
            if (listJunctions.size() + listLineEnds.size() < 3){
                list.push_back(0);
            }
            else {
                list.push_back(4);
            }
        }
        else if (listHoles.size() == 1 && listJunctions.size() >= 1 && listLineEnds.size() >= 1){
            if (listHoles[0].y > listLineEnds[0].y){
                list.push_back(6);
            }
            else {
                list.push_back(9);
            }
        }
        else {
            list.push_back(0);
            list.push_back(4);
            list.push_back(6);
            list.push_back(9);
        }
    }
    else if (listHoles.size() == 2){
        list.push_back(8);
    }
    else { // if the 'number' is close to a 'normal' number, but not a perfect match, we try all of them
        for (int i = 0; i < TEMPLATES_COUNT; i++){
            list.push_back(i);
        }
    }*/

    if (HOLE_SEPARATION){
        if (listHoles.size() == 0){
            QList<int> zeroHole;
            zeroHole.push_back(1);
            zeroHole.push_back(2);
            zeroHole.push_back(3);
            zeroHole.push_back(5);
            zeroHole.push_back(7);

            int dim = Skeleton::getDim(M0);

            QList<double> vect = vectorization(M0);

            float sampleData[dim];

            for (int i = 0; i < dim; i++){
                sampleData[i] = vect[i];
            }

            cv::Mat sampleMat(1, dim, CV_32FC1, sampleData);

            int maxVote = 0;
            int intMaxVote = -1;

            for (int i = 0; i < 10; i++){
                int vote = 0;
                for (int j = 0; j < 10; j++){
                    if (i != j && zeroHole.contains(i) && zeroHole.contains(j)){
                        float response = Skeleton::machines.m[min(i,j)][max(i,j)]->predict(sampleMat);

                        if ((response == 0.0 && i == min(i,j)) || (response == 1.0 && i == max(i,j))){
                            vote++;
                        }
                    }
                }

                //qDebug() << i << ": " << vote;

                if (vote > maxVote){
                    maxVote = vote;
                    intMaxVote = i;
                }
            }

            if (intMaxVote == -1){
                qDebug() << "Error : No vote is greater than 0";
            }
            else {
                list.push_back(intMaxVote);
            }
        }
        else if (listHoles.size() == 1){
            QList<int> oneHole;
            oneHole.push_back(0);
            oneHole.push_back(4);
            oneHole.push_back(6);
            oneHole.push_back(9);

            int dim = Skeleton::getDim(M1);

            QList<double> vect = vectorization(M1);

            float sampleData[dim];

            for (int i = 0; i < dim; i++){
                sampleData[i] = vect[i];
            }

            cv::Mat sampleMat(1, dim, CV_32FC1, sampleData);

            int maxVote = 0;
            int intMaxVote = -1;

            for (int i = 0; i < 10; i++){
                int vote = 0;
                for (int j = 0; j < 10; j++){
                    if (i != j && oneHole.contains(i) && oneHole.contains(j)){
                        float response = Skeleton::machines.m[min(i,j)][max(i,j)]->predict(sampleMat);

                        if ((response == 0.0 && i == min(i,j)) || (response == 1.0 && i == max(i,j))){
                            vote++;
                        }
                    }
                }

                //qDebug() << i << ": " << vote;

                if (vote > maxVote){
                    maxVote = vote;
                    intMaxVote = i;
                }
            }

            if (intMaxVote == -1){
                qDebug() << "Error : No vote is greater than 0";
            }
            else {
                list.push_back(intMaxVote);
            }
        }
        else if (listHoles.size() == 2){
            list.push_back(8);
        }
        else { // if the 'number' is close to a 'normal' number, but not a perfect match, we try all of them
            for (int i = 0; i < TEMPLATES_COUNT; i++){
                list.push_back(i);
            }
        }
    }
    else {


        int dim = Skeleton::getDim(M0);
        QList<double> vect = vectorization(M0);

        float sampleData[dim];

        for (int i = 0; i < dim; i++){
            sampleData[i] = vect[i];
        }

        cv::Mat sampleMat(1, dim, CV_32FC1, sampleData);

        int maxVote = 0;
        int intMaxVote = -1;

        for (int i = 0; i < 10; i++){
            int vote = 0;
            for (int j = 0; j < 10; j++){
                if (i != j && digitsOnField.contains(i) && digitsOnField.contains(j)) {
                    float response = Skeleton::machines.m[min(i,j)][max(i,j)]->predict(sampleMat);

                    if ((response == 0.0 && i == min(i,j)) || (response == 1.0 && i == max(i,j))){
                        vote++;
                    }
                }
            }

            //qDebug() << i << ": " << vote;

            if (vote > maxVote){
                maxVote = vote;
                intMaxVote = i;
            }
        }

        if (intMaxVote == -1){
            qDebug() << "Error : No vote is greater than 0";
        }
        else {
            list.push_back(intMaxVote);
        }
    }

    return list;
}
void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked()
{
  int lineCounter = 0;
  bool importError = false;
  QString badLines;
  QSettings settings;
  QString lastDir = settings.value( "lastRasterFileFilterDir", QDir::homePath() ).toString();
  QString fileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), lastDir, tr( "Textfile (*.txt)" ) );
  QFile inputFile( fileName );
  if ( inputFile.open( QFile::ReadOnly ) )
  {
    //clear the current tree
    mColormapTreeWidget->clear();

    QTextStream inputStream( &inputFile );
    QString inputLine;
    QStringList inputStringComponents;
    QList<QgsColorRampShader::ColorRampItem> colorRampItems;

    //read through the input looking for valid data
    while ( !inputStream.atEnd() )
    {
      lineCounter++;
      inputLine = inputStream.readLine();
      if ( !inputLine.isEmpty() )
      {
        if ( !inputLine.simplified().startsWith( '#' ) )
        {
          if ( inputLine.contains( "INTERPOLATION", Qt::CaseInsensitive ) )
          {
            inputStringComponents = inputLine.split( ':' );
            if ( inputStringComponents.size() == 2 )
            {
              if ( inputStringComponents[1].trimmed().toUpper().compare( "INTERPOLATED", Qt::CaseInsensitive ) == 0 )
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Linear" ) ) );
              }
              else if ( inputStringComponents[1].trimmed().toUpper().compare( "DISCRETE", Qt::CaseInsensitive ) == 0 )
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Discrete" ) ) );
              }
              else
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Exact" ) ) );
              }
            }
            else
            {
              importError = true;
              badLines = badLines + QString::number( lineCounter ) + ":\t[" + inputLine + "]\n";
            }
          }
          else
          {
            inputStringComponents = inputLine.split( ',' );
            if ( inputStringComponents.size() == 6 )
            {
              QgsColorRampShader::ColorRampItem currentItem( inputStringComponents[0].toDouble(),
                  QColor::fromRgb( inputStringComponents[1].toInt(), inputStringComponents[2].toInt(),
                                   inputStringComponents[3].toInt(), inputStringComponents[4].toInt() ),
                  inputStringComponents[5] );
              colorRampItems.push_back( currentItem );
            }
            else
            {
              importError = true;
              badLines = badLines + QString::number( lineCounter ) + ":\t[" + inputLine + "]\n";
            }
          }
        }
      }
      lineCounter++;
    }
    populateColormapTreeWidget( colorRampItems );

    if ( importError )
    {
      QMessageBox::warning( this, tr( "Import Error" ), tr( "The following lines contained errors\n\n" ) + badLines );
    }
  }
  else if ( !fileName.isEmpty() )
  {
    QMessageBox::warning( this, tr( "Read access denied" ), tr( "Read access denied. Adjust the file permissions and try again.\n\n" ) );
  }
}
Exemple #21
0
void ColorPalette::drawPannel(QPainter &painter)
{
    QPen pen;
    pen.setColor(QColor(255,255,255));
    pen.setWidthF(0.01);
    painter.setPen(pen);

    float x = draw_erae_.left();
    float y = draw_erae_.top();

    float diff = draw_erae_.height()/1020;

    float l_x = draw_erae_.right();
    float l_y = draw_erae_.bottom();

    QRgb srgb = QRgb(0x660000);
    int sred = qRed(srgb);

    QRgb ergb = QRgb(0xff0000);
    int ered = qRed(ergb);

    int k = 0;
    while(k<919) //1020)
    {

        QRectF rect = QRectF(draw_erae_.left(),draw_erae_.top() + k*diff,draw_erae_.width() - 40,diff);
        painter.drawRect(rect);
        if (k<153)
        {
            painter.fillRect(rect,QBrush(QColor(sred + k,0,0)));
        }
        else if (k < 408 && k >= 153)
        {
            painter.fillRect(rect,QBrush(QColor(255,k - 153,0)));
        }
        else if ( k < 663 && k >= 408)
        {
            painter.fillRect(rect,QBrush(QColor(255 - (k - 408),255,0)));
        }
        else if (k < 918 && k>= 663)
        {
            painter.fillRect(rect,QBrush(QColor(0,255 - (k - 663),k - 663)));
        }
        else
        {
            painter.fillRect(rect,QBrush(QColor(0,0,255- (k - 918))));
        }
        k++;
    }




    QList<float> earthquk;
    for (int i = 0;i<locationpoints.size();i++)
    {
        earthquk.push_back(locationpoints.value(i).quk_level);
    }
    qSort(earthquk);
    //earthquk.sort(Complear);
    int num = earthquk.size() * 0.1;


    QList<float> templist;
    for (int i = num;i<earthquk.size() - num;i++)
    {
        templist.push_back(earthquk.value(i));
    }

    //从1020个色彩中选出与震级幅度相同的颜色
    //震级的最大值为第一个颜色,最小值为最后一个颜色

    //int colordiff = 1020/templist.size();

    float tempmin = earthquk.value(0);
    float tempmax = earthquk.value(earthquk.size() - 1);

    float temp  = (tempmax - tempmin) / 10;
    float colordiff = draw_erae_.height() / 9;

    QLineF line[10];

    pen.setColor(QColor(0,0,0));
    pen.setWidth(XCOORDINATERULERWIDTH);
    painter.setFont(QFont(QObject::tr("WenQuanYi"),6));
    painter.setPen(pen);

    for (int i = 0;i<10;i++)
    {
         line[i].setP1(QPointF(draw_erae_.left(),draw_erae_.top()+(i)*colordiff));
         line[i].setP2(QPointF(draw_erae_.right() -40,draw_erae_.top() + (i)*colordiff));
         QString str_earthquake;
         str_earthquake.sprintf("%0.1f",tempmax - i*temp);
         float width = painter.fontMetrics().width(str_earthquake);
         float height = painter.fontMetrics().height();
         QRectF rect;
         if (i == 0)
         {
            rect = QRectF(draw_erae_.right() -35,draw_erae_.top() + colordiff*(i),width,height + 5);
         }
         else if (i == 9)
         {
            rect = QRectF(draw_erae_.right() -35,draw_erae_.top()-10 + colordiff*(i),width,height + 5);
         }
         else
         {
            rect = QRectF(draw_erae_.right() -35,draw_erae_.top()-5 + colordiff*(i),width,height + 5);
         }

         painter.drawText(rect,str_earthquake,QTextOption(Qt::AlignRight));
    }

    painter.drawLines(line,10);
}
void UnfuddleAPIWrapper::requestFinished(QNetworkReply *reply)
{
    QVariant requestTypeV = reply->property("requestType");
    Q_ASSERT(requestTypeV.isValid());
    RequestType requestType = static_cast<RequestType>(requestTypeV.toInt());

    if (reply->error() == QNetworkReply::NoError) {
        if (!isOnline) {
            isOnline = true;
            emit wentOnline();
        }
        // the following block detects if we use wrong protocol - http instead of https
        // FIXME: what if SSL not available for our account and we use https?
        // probably should handle ssl errors too
        QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        if (statusCode.toInt() == 302) {
            this->setUseSsl(!this->getUseSsl());

            // FIXME: the request which is failed may not necessarily be /account
            // BUG POSSIBILITY IS HIGH!!!
            requestGetAccount();

            return;
        }

        QNetworkReply *nr;

        switch (requestType) {
        case ACCOUNT_LOAD:
            emit getAccountComplete(unf::Account::loadFromDom(rootElement(reply)));
            break;
        case CURRENT_PERSON_LOAD:
            emit getCurrentPersonComplete(unf::Person::loadFromDom(rootElement(reply)));
            break;
        case PERSON_INVOLVEMENTS_LOAD:
            {
                involvementsForProjectsForPerson =
                        unf::Involvement::loadListFromDom(rootElement(reply));
                nr = sendGetRequest("/projects");
                nr->setProperty("requestType", PROJECTS_LOAD);
                nr->setProperty("person_id", reply->property("person_id"));
            }
            break;
        case PROJECTS_LOAD:
            {
                QList<unf::Project> projects =
                        unf::Project::loadListFromDom(rootElement(reply));
                projects = unf::Project::filterProjectListWithInvolvements(
                        projects,
                        involvementsForProjectsForPerson);
                emit getProjectsForPersonComplete(projects,
                                                  reply->property("person_id").toInt());
            }
            break;
        case MILESTONES_LOAD: // Milestones are not used in the program
            break;
        case TICKETS_LOAD:
            {
                int person_id = reply->property("person_id").toInt();
                QList<unf::Ticket> tickets = unf::Ticket::loadListFromDom(rootElement(reply));
                QList<unf::Ticket> tmpTickets;  // filter tickets
                foreach (unf::Ticket t, tickets) {
                    if (t.assignee_id == person_id && t.status != "closed")
                        tmpTickets.push_back(t);
                }
                emit getTicketsForPersonComplete(tmpTickets, person_id,
                                                 reply->property("project_id").toInt());
            }
            break;
        case UPDATE_TIME_ENTRY:
            emit saveTimeEntryComplete(reply->property("project_id").toInt(),
                                       reply->property("ticket_id").toInt(),
                                       timeEntryForSaving);
            break;
        case LIST_TIME_ENTRIES:
        case LIST_AFTER_POST_TIME_ENTRY:
            {
                int project_id = reply->property("project_id").toInt();
                int ticket_id = reply->property("ticket_id").toInt();

                QList<unf::TimeEntry> timeEntries =
                        unf::TimeEntry::loadListFromDom(rootElement(reply));

                unf::TimeEntry curTimeEntry;
                bool found = false;
                foreach (unf::TimeEntry te, timeEntries) {
                    if (te.date == timeEntryForSaving.date &&
                        te.person_id == timeEntryForSaving.person_id) {
                            curTimeEntry = te;
                            found = true;
                            break;
                    }
                }

                if (found) {
                    if (requestType == LIST_TIME_ENTRIES) {
                        curTimeEntry.hours += reply->property("hoursAdd").toFloat();
                        requestSaveTimeEntry(project_id, ticket_id, curTimeEntry);
                    }
                    else if (requestType == LIST_AFTER_POST_TIME_ENTRY)
                        emit saveTimeEntryComplete(project_id, ticket_id, curTimeEntry);
                }
                else {
                    timeEntryForSaving.hours = reply->property("hoursAdd").toFloat();
                    nr = sendPostRequest(
                            QString("/projects/%1/tickets/%2/time_entries")
                                .arg(project_id)
                                .arg(ticket_id),
                            timeEntryForSaving.toXml().toUtf8());
                    nr->setProperty("requestType", POST_NEW_TIME_ENTRY);
                    nr->setProperty("project_id", project_id);
                    nr->setProperty("ticket_id", ticket_id);
                }
            }
            break;
        case POST_NEW_TIME_ENTRY:
            {
                int project_id = reply->property("project_id").toInt();
                int ticket_id = reply->property("ticket_id").toInt();

                nr = sendGetRequest(
                        QString("/projects/%1/tickets/%2/time_entries")
                            .arg(project_id)
                            .arg(ticket_id));
                nr->setProperty("requestType", LIST_AFTER_POST_TIME_ENTRY);
                nr->setProperty("project_id", project_id);
                nr->setProperty("ticket_id", ticket_id);
            }
            break;
        case CHANGE_TICKET:
            emit changeTicketComplete(reply->property("project_id").toInt(),
                                      reply->property("ticket_id").toInt());
            break;
        case ADD_TICKET_COMMENT:
            {
                int project_id = reply->property("project_id").toInt();
                int ticket_id = reply->property("ticket_id").toInt();

                nr = sendGetRequest(QString("/projects/%1/tickets/%2/comments")
                                        .arg(project_id).arg(ticket_id));
                nr->setProperty("requestType", LIST_TICKET_COMMENTS);
                nr->setProperty("project_id", project_id);
                nr->setProperty("ticket_id", ticket_id);
            }
            break;
        case LIST_TICKET_COMMENTS:
            {
                int comment_id = unf::Comment::loadFromDom(
                        rootElement(reply).lastChild().toElement()).id;
                emit addTicketCommentComplete(reply->property("project_id").toInt(),
                                              reply->property("ticket_id").toInt(),
                                              comment_id);
            }
            break;
        case UPLOAD_TICKET_COMMENT_ATTACHMENT:
            {
                int project_id = reply->property("project_id").toInt();
                int ticket_id = reply->property("ticket_id").toInt();
                int comment_id = reply->property("comment_id").toInt();

                unf::Attachment a;
                a.filename = reply->property("filename").toString();
                a.content_type = "application/octet-stream";
                a.upload_key = rootElement(reply).firstChildElement("key").text();

                nr = sendPostRequest(
                        QString("/projects/%1/tickets/%2/comments/%3/attachments")
                            .arg(project_id).arg(ticket_id).arg(comment_id),
                        a.toXml().toUtf8());
                nr->setProperty("requestType", ADD_ATTACHMENT_TO_TICKET_COMMENT);
                nr->setProperty("project_id", project_id);
                nr->setProperty("ticket_id", ticket_id);
                nr->setProperty("comment_id", comment_id);
            }
            break;
        case ADD_ATTACHMENT_TO_TICKET_COMMENT:
            emit addAttachmentToTicketCommentComplete(reply->property("project_id").toInt(),
                                                      reply->property("ticket_id").toInt(),
                                                      reply->property("comment_id").toInt());
            break;
        case TICKET_COMMENTS_LOAD:
            emit getCommentsForTicketComplete(
                    unf::Comment::loadListFromDom(rootElement(reply)),
                    reply->property("project_id").toInt(),
                    reply->property("ticket_id").toInt());
            break;
        case ALL_PEOPLE_LOAD:
            emit getAllPeopleComplete(unf::Person::loadListFromDom(rootElement(reply)));
            break;
        }
    }
    else
Exemple #23
0
void FileIndexThread::run()
{
    struct PathToIndex
    {
        QString path;
        bool    recursive;
        QStringList filter;
    };

#ifdef Q_OS_UNIX
    static const QList<PathToIndex> pathsToIndex = {
        { "/usr/share/applications", true, { "*.desktop" } },
        { QDir(QDir::homePath()).relativeFilePath(".local/share/applications"), true, { "*.desktop" } },
        { QDir(QDir::homePath()).relativeFilePath("Desktop"), true, { "*.desktop" } },
    };
#elif defined(Q_OS_WIN)
    QList<PathToIndex> pathsToIndex = {
        { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Desktop").toString(), true, { "*.lnk" } },
        { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Start Menu").toString(), true, { "*.lnk" } },
    };

    {
        // There are newer API functions for this; but they are only for Vista and newer
        WCHAR szPath[MAX_PATH];
        HRESULT hr = SHGetFolderPathW(0, CSIDL_STARTMENU, 0, 0, szPath);
        if (SUCCEEDED(hr))
            pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } });

        hr = SHGetFolderPathW(0, CSIDL_DESKTOPDIRECTORY, 0, 0, szPath);
        if (SUCCEEDED(hr))
            pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } });
    }
#else
#error "Not implemented for this operating system"
#endif

    for (const PathToIndex& pathInfo : pathsToIndex)
    {
        const QString pathString = expandEnvironmentPath(pathInfo.path);
        QStack<QString> dirstack;
        dirstack.push_back(expandEnvironmentPath(pathString));

        while (dirstack.empty() == false)
        {
            QDir path(dirstack.pop());
            path.setNameFilters(pathInfo.filter);

            for (const QString& filename : path.entryList())
            {
                int dot = filename.lastIndexOf('.');
                const QString basename = dot > 0 ? filename.left(dot) : filename;

                dbLock.lockForWrite();
                this->db.add(basename, basename, path.absoluteFilePath(filename), QStringList());
                dbLock.unlock();
            }

            // For now, no symlink traversal to avoid loops
            for (const QString& dirname : path.entryList(QStringList(), QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot))
            {
                dirstack.push_back(path.absoluteFilePath(dirname));
            }
        }
    }

#ifdef Q_OS_WIN
    const QString systemPath = getWindowsSystemPath();

    for (const QString& filename : QDir(systemPath).entryList({ "*.cpl" }))
    {
        readCpl(filename, this->db, this->dbLock);
    }
#endif

    emit indexDone();
}
Exemple #24
0
    foreach(QGraphicsItem *bullet, bullets) {
        bullet->moveBy(0, -bullet_sp_c);
        bool kill_bullet = false;
        if( bullet->pos().y() + bullet_size_c < 0 ) {
            kill_bullet = true;
        }
        else {
            // using QSceneGraphics to do collision detection is slow (on Nokia 5800), even with BSP - better to use our own hashmap
            //qDebug("n items: %d", scene->items().size());
            //QList<QGraphicsItem *> collideBullet = scene->collidingItems(bullet);
            //foreach(QGraphicsItem *item, scene->items()) {
            /*foreach(QGraphicsItem *item, this->blocks) {
                bool collide = item->collidesWithItem(bullet);
            }*/

            /*QList<QGraphicsItem *> collideBullet = scene->items(QPointF(bullet->pos().x(), bullet->pos().y()));
            if( collideBullet.size() > 0 ) {
                foreach(QGraphicsItem *item, collideBullet) {
                    if( item->type() == CUSTOMITEMTYPE_BLOCK ) {
                        qDebug("    bullet hit block");
                        kill_bullet = true;
                        BlockItem *blockItem = static_cast<BlockItem *>(item);
                        if( hitBlock(blockItem) ) {
                            deleted_any_blocks = true;
                        }
                    }
                }
            }*/
            /*foreach(BlockItem *blockItem, blocks) {
                if( blockItem->collidesWithItem(bullet) ) {
                    qDebug("    bullet hit block");
                    kill_bullet = true;
                    if( hitBlock(blockItem) ) {
                        deleted_any_blocks = true;
                    }
                }
            }*/
            BlockItem *blockItem = this->blockAt(bullet->pos().x(), bullet->pos().y());
            if( blockItem != NULL ) {
                //bool collide = blockItem->collidesWithItem(bullet);
                qDebug("    bullet hit block");
                kill_bullet = true;
                if( hitBlock(blockItem) ) {
                    deleted_any_blocks = true;
                }
            }
            else {
                blockItem = this->blockAt(bullet->pos().x() + bullet_size_c - 1, bullet->pos().y());
                if( blockItem != NULL ) {
                    //bool collide = blockItem->collidesWithItem(bullet);
                    qDebug("    bullet hit block");
                    kill_bullet = true;
                    if( hitBlock(blockItem) ) {
                        deleted_any_blocks = true;
                    }
                }
            }
        }
        if( kill_bullet ) {
            killList.push_back(bullet);
        }
    }
Exemple #25
0
Sakura::SpriteFile* SpriteFileReader::readFile()
{
    Sakura::SpriteFile* ret = NULL;

    atUint32 magic = readUint32();

    if (magic != Sakura::SpriteFile::Magic)
    {
        atError("Not a valid Sakura Sprite container");
        return nullptr;
    }

    atUint32 version = readUint32();

    // TODO: Make this more verbose
    if (version != Sakura::SpriteFile::Version)
    {
        atError("Unsupported version");
        return nullptr;
    }

    // After reading in the magic and version we need to load some
    // metadata about the file.
    // Such as the texture count, it's dimensions, and it's origin.
    // After that we have the number of sprites contained in this
    // sprite container.
    atUint16 textureCount = readUint16(); // Having it as a Uint16 gives us the ability to have up to 65536 different states
    // This is probably overkill, but it's better safe than sorry.
    atUint32 width        = readUint32();
    atUint32 height       = readUint32();
    float originX       = readFloat();
    float originY       = readFloat();
    atUint16 spriteCount  = readUint16();

    // Lets go ahead and create or new container.
    ret = new Sakura::SpriteFile(width, height, originX, originY);

    // The next four bytes are reserved to keep the header 32 byte aligned.
    // This isn't necessary for most systems, but it's eventually planned
    // to migrate this code to Big Endian based systems, such as the wii
    // which require data to be 32 byte aligned, or it causes some issues.
    // It's also convenient to have this, for later expansion.
    atUint32 reserved     = readUint32();
    UNUSED(reserved);

    // Next we have to load the textures
    // If we tried to add them one at a time to the sprite container
    // it will be slow as hell, so we store them in a vector locally
    // then give that vector the the container, this bypasses the de-reference
    // for each texture
#ifndef ATHENA_USE_QT
    std::vector<Sakura::STexture*> textures;
#else
    QList<Sakura::STexture*> textures;
#endif

    for (atUint16 i = 0; i < textureCount; i++)
    {
        Sakura::STexture* texture = new Sakura::STexture;
        texture->Filepath = readString();
        texture->Preload  = readBool();
        textures.push_back(texture);
    }

    ret->setTextures(textures);

    // Now for the sprites
    // The sprites are a bit more difficult, they are stored in an unordered_map
    // with it's name as the key, this means we can't have two sprites with the same name
    // Normally this isn't a problem, but someone may decide to copy and paste a sprite
    // and forget to change the name, that needs to be handled, but it's outside the scope
    // of this reader.
#ifndef ATHENA_USE_QT
    std::unordered_map <std::string, Sakura::Sprite*> sprites;
#else
    QMap<QString, Sakura::Sprite*> sprites;
#endif

    for (atUint16 i = 0; i < spriteCount; i++)
    {
        Sakura::Sprite* sprite = new Sakura::Sprite(ret);
#ifndef ATHENA_USE_QT
        std::string name = readString();
#else
        QString name = QString::fromStdString(readString());
#endif
        sprite->setName(name);
        atUint16 frameCount = readUint16();
        atUint16 stateCount = readUint16();

        // Each state id corresponds to a texture held in the parent class
        std::vector<int> stateIds;

        for (int j = 0; j < stateCount; j++)
            stateIds.push_back(readUint16());


        sprite->setStateIds(stateIds);

        // Now to read the sprite parts.
        // The parts allow us to build retro style sprites very easily
        // making it possible to use one texture atlas for all possible
        // frame combinations, this reduces the amount of memory overhead
        // and the storage footprint, while Sakura supports packs and zips
        // it's still a bad idea to have a metric ton of texture resources
        // littering the place
#ifndef ATHENA_USE_QT
        std::vector<Sakura::SpriteFrame*> frames;
#else
        QList<Sakura::SpriteFrame*> frames;
#endif

        for (atUint32 k = 0; k < frameCount; k++)
        {
            Sakura::SpriteFrame* frame = new Sakura::SpriteFrame(sprite);
            frame->setFrameTime(readFloat());
            atUint16 partCount = readUint16();


#ifndef ATHENA_USE_QT
            std::vector<Sakura::SpritePart*> parts;
#else
            QList<Sakura::SpritePart*> parts;
#endif

            for (atUint8 j = 0; j < partCount; j++)
            {
                Sakura::SpritePart* part = new Sakura::SpritePart(frame);
#ifndef ATHENA_USE_QT
                std::string name = readString();
#else
                QString name = QString::fromStdString(readString());
#endif
                part->setName(name);
                part->setCollision(readBool());

                float xOff = readFloat();
                float yOff = readFloat();
                part->setOffset(xOff, yOff);
                float texXOff = readFloat();
                float texYOff = readFloat();
                part->setTextureOffset(texXOff, texYOff);
                atUint32 width = readUint32();
                atUint32 height = readUint32();
                part->setSize(width, height);
                bool flippedH = readBool();
                part->setFlippedHorizontally(flippedH);
                bool flippedV = readBool();
                part->setFlippedVertically(flippedV);

                parts.push_back(part);
            }

            frame->setParts(parts);
            frames.push_back(frame);
        }

        sprite->setFrames(frames);
#ifndef ATHENA_USE_QT

        if (sprite->name() != std::string())
        {
            std::string nameLow(sprite->name());
            athena::utility::tolower(nameLow);
            sprites[nameLow] = sprite;
        }

#else

        if (!sprite->name().isEmpty())
            sprites[sprite->name().toLower()] = sprite;

#endif
        else
        {
            atError("Sprite names cannot be empty");
            return nullptr;
        }
    }

    ret->setSprites(sprites);

    return ret;
}
//--------------------------------------------------------------------------------------------------
/// Build meta data - get states and results info
//--------------------------------------------------------------------------------------------------
bool RifReaderEclipseOutput::buildMetaData(RigReservoir* reservoir)
{
    CVF_ASSERT(reservoir);
    CVF_ASSERT(m_fileSet.size() > 0);

    caf::ProgressInfo progInfo(m_fileSet.size() + 3,"");

    progInfo.setNextProgressIncrement(m_fileSet.size());

    // Create access object for dynamic results
    m_dynamicResultsAccess = dynamicResultsAccess(m_fileSet);
    if (m_dynamicResultsAccess.isNull())
    {
        return false;
    }

    progInfo.incrementProgress();

    RigReservoirCellResults* matrixModelResults = reservoir->mainGrid()->results(RifReaderInterface::MATRIX_RESULTS);
    RigReservoirCellResults* fractureModelResults = reservoir->mainGrid()->results(RifReaderInterface::FRACTURE_RESULTS);

    if (m_dynamicResultsAccess.notNull())
    {
        // Get time steps
        m_timeSteps = m_dynamicResultsAccess->timeSteps();

        QStringList resultNames;
        std::vector<size_t> resultNamesDataItemCounts;
        m_dynamicResultsAccess->resultNames(&resultNames, &resultNamesDataItemCounts);

        {
            QStringList matrixResultNames = validKeywordsForPorosityModel(resultNames, resultNamesDataItemCounts, RifReaderInterface::MATRIX_RESULTS, m_dynamicResultsAccess->timeStepCount());

            for (int i = 0; i < matrixResultNames.size(); ++i)
            {
                size_t resIndex = matrixModelResults->addEmptyScalarResult(RimDefines::DYNAMIC_NATIVE, matrixResultNames[i]);
                matrixModelResults->setTimeStepDates(resIndex, m_timeSteps);
            }
        }

        {
            QStringList fractureResultNames = validKeywordsForPorosityModel(resultNames, resultNamesDataItemCounts, RifReaderInterface::FRACTURE_RESULTS, m_dynamicResultsAccess->timeStepCount());

            for (int i = 0; i < fractureResultNames.size(); ++i)
            {
                size_t resIndex = fractureModelResults->addEmptyScalarResult(RimDefines::DYNAMIC_NATIVE, fractureResultNames[i]);
                fractureModelResults->setTimeStepDates(resIndex, m_timeSteps);
            }
        }

    }

    progInfo.incrementProgress();

    QString initFileName = RifEclipseOutputFileTools::fileNameByType(m_fileSet, ECL_INIT_FILE);
    if (initFileName.size() > 0)
    {
        ecl_file_type* ecl_file = ecl_file_open(initFileName.toAscii().data());
        if (!ecl_file) return false;

        progInfo.incrementProgress();

        QStringList resultNames;
        std::vector<size_t> resultNamesDataItemCounts;
        RifEclipseOutputFileTools::findKeywordsAndDataItemCounts(ecl_file, &resultNames, &resultNamesDataItemCounts);

        {
            QStringList matrixResultNames = validKeywordsForPorosityModel(resultNames, resultNamesDataItemCounts, RifReaderInterface::MATRIX_RESULTS, 1);

            QList<QDateTime> staticDate;
            if (m_timeSteps.size() > 0)
            {
                staticDate.push_back(m_timeSteps.front());
            }

            for (int i = 0; i < matrixResultNames.size(); ++i)
            {
                size_t resIndex = matrixModelResults->addEmptyScalarResult(RimDefines::STATIC_NATIVE, matrixResultNames[i]);
                matrixModelResults->setTimeStepDates(resIndex, staticDate);
            }
        }

        {
            QStringList fractureResultNames = validKeywordsForPorosityModel(resultNames, resultNamesDataItemCounts, RifReaderInterface::FRACTURE_RESULTS, 1);

            QList<QDateTime> staticDate;
            if (m_timeSteps.size() > 0)
            {
                staticDate.push_back(m_timeSteps.front());
            }

            for (int i = 0; i < fractureResultNames.size(); ++i)
            {
                size_t resIndex = fractureModelResults->addEmptyScalarResult(RimDefines::STATIC_NATIVE, fractureResultNames[i]);
                fractureModelResults->setTimeStepDates(resIndex, staticDate);
            }
        }

        m_ecl_file = ecl_file;
    }

    return true;
}
Exemple #27
0
void MapPage::variantToPointFList(const QVariant &aval, QList<QPointF> &pl) const {
    QVariantList vlist = aval.toList();
    for (int i=0; i<vlist.size(); i+=2) {
        pl.push_back(QPointF(vlist[i].toDouble(), vlist[i+1].toDouble()));
    }
}
void MercurialPlugin::parseLogOutputBasicVersionControl(DVcsJob *job) const
{
    QList<QVariant> events;
    static unsigned int entriesPerCommit = 10;
    auto items = job->output().split("\\_%");

    mercurialDebug() << items;
    /* remove trailing \\_% */
    items.removeLast();

    if ((items.count() % entriesPerCommit) != 0) {
        mercurialDebug() << "Cannot parse commit log: unexpected number of entries";
        return;
    }

    /* get revision data from items.
     * because there is continuous stream of \\_% separated strings,
     * incrementation will occur inside loop body
     *
     * "{desc}\\_%{date|rfc3339date}\\_%{author}\\_%{parents}\\_%{node}\\_%{rev}\\_%"
     * "{file_dels}\\_%{file_adds}\\_%{file_mods}\\_%{file_copies}\\_%'
     */
    for (auto it = items.constBegin(); it != items.constEnd();) {
        QString desc = *it++;
        mercurialDebug() << desc;
        Q_ASSERT(!desc.isEmpty());
        QString date = *it++;
        mercurialDebug() << date;
        Q_ASSERT(!date.isEmpty());
        QString author = *it++;
        mercurialDebug() << author;
        Q_ASSERT(!author.isEmpty());
        QString parents = *it++;
        QString node = *it++;
        QString rev = *it++;
        mercurialDebug() << rev;
        Q_ASSERT(!rev.isEmpty());

        VcsEvent event;
        event.setMessage(desc);
        event.setDate(QDateTime::fromString(date, Qt::ISODate));
        event.setAuthor(author);

        VcsRevision revision;
        revision.setRevisionValue(rev.toLongLong(), KDevelop::VcsRevision::GlobalNumber);
        event.setRevision(revision);

        QList<VcsItemEvent> items;

        const VcsItemEvent::Action actions[3] = {VcsItemEvent::Deleted, VcsItemEvent::Added, VcsItemEvent::ContentsModified};
        for (int i = 0; i < 3; i++) {
            const auto &files = *it++;
            if (files.isEmpty()) {
                continue;
            }

            foreach (const auto& file, files.split(' ')) {
                VcsItemEvent item;
                item.setActions(actions[i]);
                item.setRepositoryLocation(QUrl::fromPercentEncoding(file.toLocal8Bit()));
                items.push_back(item);
            }
        }

        const auto &copies = *it++;
        if (!copies.isEmpty()) {
            foreach (const auto & copy, copies.split(' ')) {
                auto files = copy.split('~');

                // TODO: What is it? Why it doesn't work
                if (files.size() >= 2) {
                    VcsItemEvent item;
                    item.setActions(VcsItemEvent::Copied);
                    item.setRepositoryCopySourceLocation(QUrl::fromPercentEncoding(files[0].toLocal8Bit()));
                    item.setRepositoryLocation(QUrl::fromPercentEncoding(files[1].toLocal8Bit()));
                    items.push_back(item);
                }
            }
        }

        event.setItems(items);
        events.push_back(QVariant::fromValue(event));
    }
//------------------------------------------------------------------------------
// Name:
// Desc:
//------------------------------------------------------------------------------
QList<IRegion::pointer> DebuggerCore::memory_regions() const {

#if 0
    static const char * inheritance_strings[] = {
		"SHARE", "COPY", "NONE", "DONATE_COPY",
	};

	static const char * behavior_strings[] = {
		"DEFAULT", "RANDOM", "SEQUENTIAL", "RESQNTL", "WILLNEED", "DONTNEED",
	};
#endif

	QList<IRegion::pointer> regions;
	if(pid_ != 0) {
		task_t the_task;
		kern_return_t kr = task_for_pid(mach_task_self(), pid_, &the_task);
		if(kr != KERN_SUCCESS) {
			qDebug("task_for_pid failed");
            return QList<IRegion::pointer>();
		}

		vm_size_t vmsize;
		vm_address_t address;
		vm_region_basic_info_data_64_t info;
		mach_msg_type_number_t info_count;
		vm_region_flavor_t flavor;
		memory_object_name_t object;

		kr = KERN_SUCCESS;
		address = 0;

		do {
			flavor     = VM_REGION_BASIC_INFO_64;
			info_count = VM_REGION_BASIC_INFO_COUNT_64;
			kr = vm_region_64(the_task, &address, &vmsize, flavor, (vm_region_info_64_t)&info, &info_count, &object);
			if(kr == KERN_SUCCESS) {

				const edb::address_t start               = address;
				const edb::address_t end                 = address + vmsize;
				const edb::address_t base                = address;
				const QString name                       = QString();
				const IRegion::permissions_t permissions =
					((info.protection & VM_PROT_READ)    ? PROT_READ  : 0) |
					((info.protection & VM_PROT_WRITE)   ? PROT_WRITE : 0) |
					((info.protection & VM_PROT_EXECUTE) ? PROT_EXEC  : 0);

				regions.push_back(std::make_shared<PlatformRegion>(start, end, base, name, permissions));

				/*
				printf("%016llx-%016llx %8uK %c%c%c/%c%c%c %11s %6s %10s uwir=%hu sub=%u\n",
				address, (address + vmsize), (vmsize >> 10),
				(info.protection & VM_PROT_READ)        ? 'r' : '-',
				(info.protection & VM_PROT_WRITE)       ? 'w' : '-',
				(info.protection & VM_PROT_EXECUTE)     ? 'x' : '-',
				(info.max_protection & VM_PROT_READ)    ? 'r' : '-',
				(info.max_protection & VM_PROT_WRITE)   ? 'w' : '-',
				(info.max_protection & VM_PROT_EXECUTE) ? 'x' : '-',
				inheritance_strings[info.inheritance],
				(info.shared) ? "shared" : "-",
				behavior_strings[info.behavior],
				info.user_wired_count,
				info.reserved);
				*/

				address += vmsize;
			} else if(kr != KERN_INVALID_ADDRESS) {
				if(the_task != MACH_PORT_NULL) {
					mach_port_deallocate(mach_task_self(), the_task);
				}
                return QList<IRegion::pointer>();
			}
		} while(kr != KERN_INVALID_ADDRESS);

		if(the_task != MACH_PORT_NULL) {
			mach_port_deallocate(mach_task_self(), the_task);
		}
	}

	return regions;
}
void QgsComposerLegend::drawLayerChildItems( QPainter* p, QStandardItem* layerItem, double& currentYCoord, double& maxXCoord, int layerOpacity )
{
  if ( !layerItem )
  {
    return;
  }

  //Draw all symbols first and the texts after (to find out the x coordinate to have the text aligned)
  QList<double> childYCoords;
  QList<double> realItemHeights;

  double textHeight = fontHeightCharacterMM( mItemFont, QChar( '0' ) );
  double itemHeight = qMax( mSymbolHeight, textHeight );

  double textAlignCoord = 0; //alignment for legend text

  QStandardItem* currentItem;

  int numChildren = layerItem->rowCount();

  for ( int i = 0; i < numChildren; ++i )
  {
    //real symbol height. Can be different from standard height in case of point symbols
    double realSymbolHeight;
    double realItemHeight = itemHeight; //will be adjusted if realSymbolHeight turns out to be larger

    currentYCoord += mSymbolSpace;
    double currentXCoord = mBoxSpace;

    currentItem = layerItem->child( i, 0 );

    if ( !currentItem )
    {
      continue;
    }

    QgsSymbol* symbol = 0;
    QgsComposerSymbolItem* symbolItem = dynamic_cast<QgsComposerSymbolItem*>( currentItem );
    if ( symbolItem )
    {
      symbol = symbolItem->symbol();
    }

    QgsSymbolV2* symbolNg = 0;
    QgsComposerSymbolV2Item* symbolV2Item = dynamic_cast<QgsComposerSymbolV2Item*>( currentItem );
    if ( symbolV2Item )
    {
      symbolNg = symbolV2Item->symbolV2();
    }
    QgsComposerRasterSymbolItem* rasterItem = dynamic_cast<QgsComposerRasterSymbolItem*>( currentItem );

    if ( symbol )  //item with symbol?
    {
      //draw symbol
      drawSymbol( p, symbol, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, currentXCoord, realSymbolHeight, layerOpacity );
      realItemHeight = qMax( realSymbolHeight, itemHeight );
      currentXCoord += mIconLabelSpace;
    }
    else if ( symbolNg ) //item with symbol NG?
    {
      drawSymbolV2( p, symbolNg, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, currentXCoord, realSymbolHeight, layerOpacity );
      realItemHeight = qMax( realSymbolHeight, itemHeight );
      currentXCoord += mIconLabelSpace;
    }
    else if ( rasterItem )
    {
      if ( p )
      {
        p->setBrush( rasterItem->color() );
        p->drawRect( QRectF( currentXCoord, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, mSymbolWidth, mSymbolHeight ) );
      }
      currentXCoord += mSymbolWidth;
      currentXCoord += mIconLabelSpace;
    }
    else //item with icon?
    {
      QIcon symbolIcon = currentItem->icon();
      if ( !symbolIcon.isNull() && p )
      {
        symbolIcon.paint( p, currentXCoord, currentYCoord + ( itemHeight - mSymbolHeight ) / 2, mSymbolWidth, mSymbolHeight );
        currentXCoord += mSymbolWidth;
        currentXCoord += mIconLabelSpace;
      }
    }

    childYCoords.push_back( currentYCoord );
    realItemHeights.push_back( realItemHeight );
    currentYCoord += realItemHeight;
    textAlignCoord = qMax( currentXCoord, textAlignCoord );
  }

  maxXCoord = qMax( maxXCoord, textAlignCoord );
  for ( int i = 0; i < numChildren; ++i )
  {
    if ( p )
    {
      p->setPen( QColor( 0, 0, 0 ) );
      drawText( p, textAlignCoord, childYCoords.at( i ) + textHeight + ( realItemHeights.at( i ) - textHeight ) / 2, layerItem->child( i, 0 )->text(), mItemFont );
      maxXCoord = qMax( maxXCoord, textAlignCoord + mBoxSpace + textWidthMillimeters( mItemFont,  layerItem->child( i, 0 )->text() ) );
    }
  }
}